page-writeback.c 23.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * mm/page-writeback.c.
 *
 * Copyright (C) 2002, Linus Torvalds.
 *
 * Contains functions related to writing back dirty pages at the
 * address_space level.
 *
 * 10Apr2002	akpm@zip.com.au
 *		Initial version
 */

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/fs.h>
#include <linux/mm.h>
18
#include <linux/swap.h>
19 20 21 22
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/writeback.h>
#include <linux/init.h>
Andrew Morton's avatar
Andrew Morton committed
23
#include <linux/backing-dev.h>
24
#include <linux/blkdev.h>
25
#include <linux/mpage.h>
26
#include <linux/percpu.h>
27 28
#include <linux/notifier.h>
#include <linux/smp.h>
29
#include <linux/sysctl.h>
30
#include <linux/cpu.h>
Andrew Morton's avatar
Andrew Morton committed
31
#include <linux/syscalls.h>
32

Andrew Morton's avatar
Andrew Morton committed
33 34 35 36
/*
 * The maximum number of pages to writeout in a single bdflush/kupdate
 * operation.  We do this so we don't hold I_LOCK against an inode for
 * enormous amounts of time, which would block a userspace task which has
Andrew Morton's avatar
Andrew Morton committed
37 38
 * been forced to throttle against that inode.  Also, the code reevaluates
 * the dirty each time it has written this many pages.
Andrew Morton's avatar
Andrew Morton committed
39 40 41
 */
#define MAX_WRITEBACK_PAGES	1024

42
/*
Andrew Morton's avatar
Andrew Morton committed
43
 * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
44
 * will look to see if it needs to force writeback or throttling.
Andrew Morton's avatar
Andrew Morton committed
45
 */
46 47
static long ratelimit_pages = 32;

48 49
static long total_pages;	/* The total number of pages in the machine. */
static int dirty_exceeded;	/* Dirty mem may be over limit */
Andrew Morton's avatar
Andrew Morton committed
50 51 52 53 54 55 56

/*
 * When balance_dirty_pages decides that the caller needs to perform some
 * non-background writeback, this is how many pages it will attempt to write.
 * It should be somewhat larger than RATELIMIT_PAGES to ensure that reasonably
 * large amounts of I/O are submitted.
 */
57
static inline long sync_writeback_pages(void)
58 59 60
{
	return ratelimit_pages + ratelimit_pages / 2;
}
Andrew Morton's avatar
Andrew Morton committed
61

Andrew Morton's avatar
Andrew Morton committed
62 63
/* The following parameters are exported via /proc/sys/vm */

Andrew Morton's avatar
Andrew Morton committed
64
/*
65
 * Start background writeback (via pdflush) at this percentage
66
 */
67
int dirty_background_ratio = 10;
68 69

/*
70
 * The generator of dirty data starts writeback at this percentage
71
 */
72
int vm_dirty_ratio = 40;
73

Andrew Morton's avatar
Andrew Morton committed
74
/*
Andrew Morton's avatar
Andrew Morton committed
75 76
 * The interval between `kupdate'-style writebacks, in centiseconds
 * (hundredths of a second)
Andrew Morton's avatar
Andrew Morton committed
77 78 79 80
 */
int dirty_writeback_centisecs = 5 * 100;

/*
81
 * The longest number of centiseconds for which data is allowed to remain dirty
Andrew Morton's avatar
Andrew Morton committed
82 83 84
 */
int dirty_expire_centisecs = 30 * 100;

Andrew Morton's avatar
Andrew Morton committed
85 86 87 88 89 90 91 92 93 94
/*
 * Flag that makes the machine dump writes/reads and block dirtyings.
 */
int block_dump;

/*
 * Flag that puts the machine in "laptop mode".
 */
int laptop_mode;

95 96
EXPORT_SYMBOL(laptop_mode);

Andrew Morton's avatar
Andrew Morton committed
97 98
/* End of sysctl-exported parameters */

99

100
static void background_writeout(unsigned long _min_pages);
Andrew Morton's avatar
Andrew Morton committed
101

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
struct writeback_state
{
	unsigned long nr_dirty;
	unsigned long nr_unstable;
	unsigned long nr_mapped;
	unsigned long nr_writeback;
};

static void get_writeback_state(struct writeback_state *wbs)
{
	wbs->nr_dirty = read_page_state(nr_dirty);
	wbs->nr_unstable = read_page_state(nr_unstable);
	wbs->nr_mapped = read_page_state(nr_mapped);
	wbs->nr_writeback = read_page_state(nr_writeback);
}

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
/*
 * Work out the current dirty-memory clamping and background writeout
 * thresholds.
 *
 * The main aim here is to lower them aggressively if there is a lot of mapped
 * memory around.  To avoid stressing page reclaim with lots of unreclaimable
 * pages.  It is better to clamp down on writers than to start swapping, and
 * performing lots of scanning.
 *
 * We only allow 1/2 of the currently-unmapped memory to be dirtied.
 *
 * We don't permit the clamping level to fall below 5% - that is getting rather
 * excessive.
 *
 * We make sure that the background writeout level is below the adjusted
 * clamping level.
 */
static void
136 137
get_dirty_limits(struct writeback_state *wbs, long *pbackground, long *pdirty,
		struct address_space *mapping)
138 139 140 141
{
	int background_ratio;		/* Percentages */
	int dirty_ratio;
	int unmapped_ratio;
142 143
	long background;
	long dirty;
144
	unsigned long available_memory = total_pages;
145
	struct task_struct *tsk;
146

147
	get_writeback_state(wbs);
148

149 150 151 152 153 154 155 156 157 158
#ifdef CONFIG_HIGHMEM
	/*
	 * If this mapping can only allocate from low memory,
	 * we exclude high memory from our count.
	 */
	if (mapping && !(mapping_gfp_mask(mapping) & __GFP_HIGHMEM))
		available_memory -= totalhigh_pages;
#endif


159
	unmapped_ratio = 100 - (wbs->nr_mapped * 100) / total_pages;
160 161 162 163 164 165 166 167

	dirty_ratio = vm_dirty_ratio;
	if (dirty_ratio > unmapped_ratio / 2)
		dirty_ratio = unmapped_ratio / 2;

	if (dirty_ratio < 5)
		dirty_ratio = 5;

168 169 170
	background_ratio = dirty_background_ratio;
	if (background_ratio >= dirty_ratio)
		background_ratio = dirty_ratio / 2;
171

172 173
	background = (background_ratio * available_memory) / 100;
	dirty = (dirty_ratio * available_memory) / 100;
174 175
	tsk = current;
	if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
176 177 178 179 180
		background += background / 4;
		dirty += dirty / 4;
	}
	*pbackground = background;
	*pdirty = dirty;
181 182
}

183
/*
184 185
 * balance_dirty_pages() must be called by processes which are generating dirty
 * data.  It looks at the number of dirty pages in the machine and will force
186
 * the caller to perform writeback if the system is over `vm_dirty_ratio'.
187 188
 * If we're over `background_thresh' then pdflush is woken to perform some
 * writeout.
189
 */
190
static void balance_dirty_pages(struct address_space *mapping)
191
{
192
	struct writeback_state wbs;
193
	long nr_reclaimable;
194
	long background_thresh;
195
	long dirty_thresh;
196 197 198
	unsigned long pages_written = 0;
	unsigned long write_chunk = sync_writeback_pages();

199
	struct backing_dev_info *bdi = mapping->backing_dev_info;
200

201
	for (;;) {
202 203 204 205
		struct writeback_control wbc = {
			.bdi		= bdi,
			.sync_mode	= WB_SYNC_NONE,
			.older_than_this = NULL,
206
			.nr_to_write	= write_chunk,
207
		};
208

209 210
		get_dirty_limits(&wbs, &background_thresh,
					&dirty_thresh, mapping);
211 212
		nr_reclaimable = wbs.nr_dirty + wbs.nr_unstable;
		if (nr_reclaimable + wbs.nr_writeback <= dirty_thresh)
213 214
			break;

215 216
		dirty_exceeded = 1;

217 218 219 220 221 222 223
		/* Note: nr_reclaimable denotes nr_dirty + nr_unstable.
		 * Unstable writes are a feature of certain networked
		 * filesystems (i.e. NFS) in which data may have been
		 * written to the server's write cache, but has not yet
		 * been flushed to permanent storage.
		 */
		if (nr_reclaimable) {
224
			writeback_inodes(&wbc);
225
			get_dirty_limits(&wbs, &background_thresh,
226
					&dirty_thresh, mapping);
227 228
			nr_reclaimable = wbs.nr_dirty + wbs.nr_unstable;
			if (nr_reclaimable + wbs.nr_writeback <= dirty_thresh)
229 230 231 232 233
				break;
			pages_written += write_chunk - wbc.nr_to_write;
			if (pages_written >= write_chunk)
				break;		/* We've done our duty */
		}
234
		blk_congestion_wait(WRITE, HZ/10);
235 236
	}

237
	if (nr_reclaimable + wbs.nr_writeback <= dirty_thresh)
238
		dirty_exceeded = 0;
239

Andrew Morton's avatar
Andrew Morton committed
240 241 242 243 244 245 246 247 248 249 250 251 252
	if (writeback_in_progress(bdi))
		return;		/* pdflush is already working this queue */

	/*
	 * In laptop mode, we wait until hitting the higher threshold before
	 * starting background writeout, and then write out all the way down
	 * to the lower threshold.  So slow writers cause minimal disk activity.
	 *
	 * In normal mode, we start background writeout at the lower
	 * background_thresh, to keep the amount of dirty memory low.
	 */
	if ((laptop_mode && pages_written) ||
	     (!laptop_mode && (nr_reclaimable > background_thresh)))
Andrew Morton's avatar
Andrew Morton committed
253
		pdflush_operation(background_writeout, 0);
254 255
}

Andrew Morton's avatar
Andrew Morton committed
256 257 258 259 260 261 262 263
/**
 * balance_dirty_pages_ratelimited - balance dirty memory state
 * @mapping - address_space which was dirtied
 *
 * Processes which are dirtying memory should call in here once for each page
 * which was newly dirtied.  The function will periodically check the system's
 * dirty state and will initiate writeback if needed.
 *
264 265 266 267
 * On really big machines, get_writeback_state is expensive, so try to avoid
 * calling it too often (ratelimiting).  But once we're over the dirty memory
 * limit we decrease the ratelimiting by a lot, to prevent individual processes
 * from overshooting the limit by (ratelimit_pages) each.
268 269 270
 */
void balance_dirty_pages_ratelimited(struct address_space *mapping)
{
271
	static DEFINE_PER_CPU(int, ratelimits) = 0;
272 273 274 275 276
	long ratelimit;

	ratelimit = ratelimit_pages;
	if (dirty_exceeded)
		ratelimit = 8;
277

278 279 280 281
	/*
	 * Check the rate limiting. Also, we do not want to throttle real-time
	 * tasks in balance_dirty_pages(). Period.
	 */
282 283 284
	if (get_cpu_var(ratelimits)++ >= ratelimit) {
		__get_cpu_var(ratelimits) = 0;
		put_cpu_var(ratelimits);
285 286 287
		balance_dirty_pages(mapping);
		return;
	}
288
	put_cpu_var(ratelimits);
289
}
290
EXPORT_SYMBOL(balance_dirty_pages_ratelimited);
291

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
void throttle_vm_writeout(void)
{
	struct writeback_state wbs;
	long background_thresh;
	long dirty_thresh;

        for ( ; ; ) {
		get_dirty_limits(&wbs, &background_thresh, &dirty_thresh, NULL);

                /*
                 * Boost the allowable dirty threshold a bit for page
                 * allocators so they don't get DoS'ed by heavy writers
                 */
                dirty_thresh += dirty_thresh / 10;      /* wheeee... */

                if (wbs.nr_unstable + wbs.nr_writeback <= dirty_thresh)
                        break;
                blk_congestion_wait(WRITE, HZ/10);
        }
}


314
/*
Andrew Morton's avatar
Andrew Morton committed
315 316
 * writeback at least _min_pages, and keep writing until the amount of dirty
 * memory is less than the background threshold, or until we're all clean.
317
 */
Andrew Morton's avatar
Andrew Morton committed
318
static void background_writeout(unsigned long _min_pages)
319
{
Andrew Morton's avatar
Andrew Morton committed
320
	long min_pages = _min_pages;
321 322 323 324 325
	struct writeback_control wbc = {
		.bdi		= NULL,
		.sync_mode	= WB_SYNC_NONE,
		.older_than_this = NULL,
		.nr_to_write	= 0,
326
		.nonblocking	= 1,
327
	};
328

329
	for ( ; ; ) {
330
		struct writeback_state wbs;
331 332
		long background_thresh;
		long dirty_thresh;
333

334
		get_dirty_limits(&wbs, &background_thresh, &dirty_thresh, NULL);
335
		if (wbs.nr_dirty + wbs.nr_unstable < background_thresh
336
				&& min_pages <= 0)
Andrew Morton's avatar
Andrew Morton committed
337
			break;
338
		wbc.encountered_congestion = 0;
339
		wbc.nr_to_write = MAX_WRITEBACK_PAGES;
340
		wbc.pages_skipped = 0;
341 342
		writeback_inodes(&wbc);
		min_pages -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
343
		if (wbc.nr_to_write > 0 || wbc.pages_skipped > 0) {
344
			/* Wrote less than expected */
345 346
			blk_congestion_wait(WRITE, HZ/10);
			if (!wbc.encountered_congestion)
347 348 349
				break;
		}
	}
350 351
}

Andrew Morton's avatar
Andrew Morton committed
352
/*
353 354 355
 * Start writeback of `nr_pages' pages.  If `nr_pages' is zero, write back
 * the whole world.  Returns 0 if a pdflush thread was dispatched.  Returns
 * -1 if all pdflush threads were busy.
Andrew Morton's avatar
Andrew Morton committed
356
 */
357
int wakeup_bdflush(long nr_pages)
358
{
359
	if (nr_pages == 0) {
360
		struct writeback_state wbs;
Andrew Morton's avatar
Andrew Morton committed
361

362 363
		get_writeback_state(&wbs);
		nr_pages = wbs.nr_dirty + wbs.nr_unstable;
364 365
	}
	return pdflush_operation(background_writeout, nr_pages);
366 367
}

Andrew Morton's avatar
Andrew Morton committed
368 369 370 371 372 373 374
static void wb_timer_fn(unsigned long unused);
static void laptop_timer_fn(unsigned long unused);

static struct timer_list wb_timer =
			TIMER_INITIALIZER(wb_timer_fn, 0, 0);
static struct timer_list laptop_mode_wb_timer =
			TIMER_INITIALIZER(laptop_timer_fn, 0, 0);
375 376 377 378 379 380 381 382 383

/*
 * Periodic writeback of "old" data.
 *
 * Define "old": the first time one of an inode's pages is dirtied, we mark the
 * dirtying-time in the inode's address_space.  So this periodic writeback code
 * just walks the superblock inode list, writing back any inodes which are
 * older than a specific point in time.
 *
Andrew Morton's avatar
Andrew Morton committed
384 385 386
 * Try to run once per dirty_writeback_centisecs.  But if a writeback event
 * takes longer than a dirty_writeback_centisecs interval, then leave a
 * one-second gap.
Andrew Morton's avatar
Andrew Morton committed
387 388 389
 *
 * older_than_this takes precedence over nr_to_write.  So we'll only write back
 * all dirty pages if they are all attached to "old" mappings.
390 391 392
 */
static void wb_kupdate(unsigned long arg)
{
Andrew Morton's avatar
Andrew Morton committed
393 394 395
	unsigned long oldest_jif;
	unsigned long start_jif;
	unsigned long next_jif;
396
	long nr_to_write;
397
	struct writeback_state wbs;
398 399 400 401 402
	struct writeback_control wbc = {
		.bdi		= NULL,
		.sync_mode	= WB_SYNC_NONE,
		.older_than_this = &oldest_jif,
		.nr_to_write	= 0,
403
		.nonblocking	= 1,
Andrew Morton's avatar
Andrew Morton committed
404
		.for_kupdate	= 1,
405
	};
406 407 408

	sync_supers();

409
	get_writeback_state(&wbs);
Andrew Morton's avatar
Andrew Morton committed
410
	oldest_jif = jiffies - (dirty_expire_centisecs * HZ) / 100;
Andrew Morton's avatar
Andrew Morton committed
411
	start_jif = jiffies;
Andrew Morton's avatar
Andrew Morton committed
412
	next_jif = start_jif + (dirty_writeback_centisecs * HZ) / 100;
413
	nr_to_write = wbs.nr_dirty + wbs.nr_unstable +
414
			(inodes_stat.nr_inodes - inodes_stat.nr_unused);
415 416 417 418
	while (nr_to_write > 0) {
		wbc.encountered_congestion = 0;
		wbc.nr_to_write = MAX_WRITEBACK_PAGES;
		writeback_inodes(&wbc);
Andrew Morton's avatar
Andrew Morton committed
419
		if (wbc.nr_to_write > 0) {
420
			if (wbc.encountered_congestion)
421
				blk_congestion_wait(WRITE, HZ/10);
422 423 424 425 426
			else
				break;	/* All the old data is written */
		}
		nr_to_write -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
	}
Andrew Morton's avatar
Andrew Morton committed
427 428
	if (time_before(next_jif, jiffies + HZ))
		next_jif = jiffies + HZ;
429 430 431 432 433 434 435 436
	if (dirty_writeback_centisecs)
		mod_timer(&wb_timer, next_jif);
}

/*
 * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
 */
int dirty_writeback_centisecs_handler(ctl_table *table, int write,
437
		struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
438
{
439
	proc_dointvec(table, write, file, buffer, length, ppos);
440 441 442 443 444 445 446
	if (dirty_writeback_centisecs) {
		mod_timer(&wb_timer,
			jiffies + (dirty_writeback_centisecs * HZ) / 100);
	} else {
		del_timer(&wb_timer);
	}
	return 0;
447 448 449 450
}

static void wb_timer_fn(unsigned long unused)
{
Andrew Morton's avatar
Andrew Morton committed
451
	if (pdflush_operation(wb_kupdate, 0) < 0)
Andrew Morton's avatar
Andrew Morton committed
452
		mod_timer(&wb_timer, jiffies + HZ); /* delay 1 second */
Andrew Morton's avatar
Andrew Morton committed
453 454 455 456 457 458 459 460 461 462 463
}

static void laptop_flush(unsigned long unused)
{
	sys_sync();
}

static void laptop_timer_fn(unsigned long unused)
{
	pdflush_operation(laptop_flush, 0);
}
Andrew Morton's avatar
Andrew Morton committed
464

Andrew Morton's avatar
Andrew Morton committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
/*
 * We've spun up the disk and we're in laptop mode: schedule writeback
 * of all dirty data a few seconds from now.  If the flush is already scheduled
 * then push it back - the user is still using the disk.
 */
void laptop_io_completion(void)
{
	mod_timer(&laptop_mode_wb_timer, jiffies + laptop_mode * HZ);
}

/*
 * We're in laptop mode and we've just synced. The sync's writes will have
 * caused another writeback to be scheduled by laptop_io_completion.
 * Nothing needs to be written back anymore, so we unschedule the writeback.
 */
void laptop_sync_completion(void)
{
	del_timer(&laptop_mode_wb_timer);
483 484
}

485 486 487
/*
 * If ratelimit_pages is too high then we can get into dirty-data overload
 * if a large number of processes all perform writes at the same time.
488 489
 * If it is too low then SMP machines will call the (expensive)
 * get_writeback_state too often.
490 491 492 493 494 495 496 497 498 499 500 501 502 503
 *
 * Here we set ratelimit_pages to a level which ensures that when all CPUs are
 * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
 * thresholds before writeback cuts in.
 *
 * But the limit should not be set too high.  Because it also controls the
 * amount of memory which the balance_dirty_pages() caller has to write back.
 * If this is too large then the caller will block on the IO queue all the
 * time.  So limit it to four megabytes - the balance_dirty_pages() caller
 * will write six megabyte chunks, max.
 */

static void set_ratelimit(void)
{
504
	ratelimit_pages = total_pages / (num_online_cpus() * 32);
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
	if (ratelimit_pages < 16)
		ratelimit_pages = 16;
	if (ratelimit_pages * PAGE_CACHE_SIZE > 4096 * 1024)
		ratelimit_pages = (4096 * 1024) / PAGE_CACHE_SIZE;
}

static int
ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
{
	set_ratelimit();
	return 0;
}

static struct notifier_block ratelimit_nb = {
	.notifier_call	= ratelimit_handler,
	.next		= NULL,
};

523 524 525 526 527
/*
 * If the machine has a large highmem:lowmem ratio then scale back the default
 * dirty memory thresholds: allowing too much dirty highmem pins an excessive
 * number of buffer_heads.
 */
528
void __init page_writeback_init(void)
529
{
530 531 532 533 534 535 536 537 538 539
	long buffer_pages = nr_free_buffer_pages();
	long correction;

	total_pages = nr_free_pagecache_pages();

	correction = (100 * 4 * buffer_pages) / total_pages;

	if (correction < 100) {
		dirty_background_ratio *= correction;
		dirty_background_ratio /= 100;
540 541
		vm_dirty_ratio *= correction;
		vm_dirty_ratio /= 100;
542 543 544 545 546

		if (dirty_background_ratio <= 0)
			dirty_background_ratio = 1;
		if (vm_dirty_ratio <= 0)
			vm_dirty_ratio = 1;
547
	}
Andrew Morton's avatar
Andrew Morton committed
548
	mod_timer(&wb_timer, jiffies + (dirty_writeback_centisecs * HZ) / 100);
549 550
	set_ratelimit();
	register_cpu_notifier(&ratelimit_nb);
551 552
}

553
int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
Andrew Morton's avatar
Andrew Morton committed
554
{
555 556
	if (wbc->nr_to_write <= 0)
		return 0;
557
	if (mapping->a_ops->writepages)
558 559
		return mapping->a_ops->writepages(mapping, wbc);
	return generic_writepages(mapping, wbc);
Andrew Morton's avatar
Andrew Morton committed
560 561
}

562 563 564 565 566 567
/**
 * write_one_page - write out a single page and optionally wait on I/O
 *
 * @page - the page to write
 * @wait - if true, wait on writeout
 *
Andrew Morton's avatar
Andrew Morton committed
568
 * The page must be locked by the caller and will be unlocked upon return.
569 570 571 572 573 574 575
 *
 * write_one_page() returns a negative error code if I/O failed.
 */
int write_one_page(struct page *page, int wait)
{
	struct address_space *mapping = page->mapping;
	int ret = 0;
Andrew Morton's avatar
Andrew Morton committed
576 577
	struct writeback_control wbc = {
		.sync_mode = WB_SYNC_ALL,
578
		.nr_to_write = 1,
Andrew Morton's avatar
Andrew Morton committed
579
	};
580 581 582

	BUG_ON(!PageLocked(page));

583
	if (wait)
584 585
		wait_on_page_writeback(page);

586
	if (clear_page_dirty_for_io(page)) {
587
		page_cache_get(page);
Andrew Morton's avatar
Andrew Morton committed
588
		ret = mapping->a_ops->writepage(page, &wbc);
589
		if (ret == 0 && wait) {
590
			wait_on_page_writeback(page);
591 592 593 594 595 596 597 598 599 600 601
			if (PageError(page))
				ret = -EIO;
		}
		page_cache_release(page);
	} else {
		unlock_page(page);
	}
	return ret;
}
EXPORT_SYMBOL(write_one_page);

602
/*
603 604
 * For address_spaces which do not use buffers.  Just tag the page as dirty in
 * its radix tree.
605 606 607 608
 *
 * This is also used when a single buffer is being dirtied: we want to set the
 * page dirty in that case, but not all the buffers.  This is a "bottom-up"
 * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
609 610 611 612 613 614 615
 *
 * Most callers have locked the page, which pins the address_space in memory.
 * But zap_pte_range() does not lock the page, however in that case the
 * mapping is pinned by the vma's ->vm_file reference.
 *
 * We take care to handle the case where the page was truncated from the
 * mapping by re-checking page_mapping() insode tree_lock.
616 617 618 619 620 621
 */
int __set_page_dirty_nobuffers(struct page *page)
{
	int ret = 0;

	if (!TestSetPageDirty(page)) {
622
		struct address_space *mapping = page_mapping(page);
623
		struct address_space *mapping2;
624 625

		if (mapping) {
626
			write_lock_irq(&mapping->tree_lock);
627 628 629
			mapping2 = page_mapping(page);
			if (mapping2) { /* Race with truncate? */
				BUG_ON(mapping2 != mapping);
630 631
				if (!mapping->backing_dev_info->memory_backed)
					inc_page_state(nr_dirty);
632
				radix_tree_tag_set(&mapping->page_tree,
633
					page_index(page), PAGECACHE_TAG_DIRTY);
634
			}
635
			write_unlock_irq(&mapping->tree_lock);
636 637
			if (mapping->host) {
				/* !PageAnon && !swapper_space */
Andrew Morton's avatar
Andrew Morton committed
638 639
				__mark_inode_dirty(mapping->host,
							I_DIRTY_PAGES);
640
			}
641 642 643 644 645
		}
	}
	return ret;
}
EXPORT_SYMBOL(__set_page_dirty_nobuffers);
646

647 648 649 650 651 652 653 654 655 656 657 658
/*
 * When a writepage implementation decides that it doesn't want to write this
 * page for some reason, it should redirty the locked page via
 * redirty_page_for_writepage() and it should then unlock the page and return 0
 */
int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
{
	wbc->pages_skipped++;
	return __set_page_dirty_nobuffers(page);
}
EXPORT_SYMBOL(redirty_page_for_writepage);

659 660 661 662 663 664 665 666
/*
 * If the mapping doesn't provide a set_page_dirty a_op, then
 * just fall through and assume that it wants buffer_heads.
 */
int fastcall set_page_dirty(struct page *page)
{
	struct address_space *mapping = page_mapping(page);

667 668 669 670 671
	if (likely(mapping)) {
		int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
		if (spd)
			return (*spd)(page);
		return __set_page_dirty_buffers(page);
672
	}
673 674 675
	if (!PageDirty(page))
		SetPageDirty(page);
	return 0;
676 677 678
}
EXPORT_SYMBOL(set_page_dirty);

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
/*
 * set_page_dirty() is racy if the caller has no reference against
 * page->mapping->host, and if the page is unlocked.  This is because another
 * CPU could truncate the page off the mapping and then free the mapping.
 *
 * Usually, the page _is_ locked, or the caller is a user-space process which
 * holds a reference on the inode by having an open file.
 *
 * In other cases, the page should be locked before running set_page_dirty().
 */
int set_page_dirty_lock(struct page *page)
{
	int ret;

	lock_page(page);
	ret = set_page_dirty(page);
	unlock_page(page);
	return ret;
}
698
EXPORT_SYMBOL(set_page_dirty_lock);
699

700 701 702 703 704 705
/*
 * Clear a page's dirty flag, while caring for dirty memory accounting. 
 * Returns true if the page was previously dirty.
 */
int test_clear_page_dirty(struct page *page)
{
706
	struct address_space *mapping = page_mapping(page);
707 708 709
	unsigned long flags;

	if (mapping) {
710
		write_lock_irqsave(&mapping->tree_lock, flags);
711
		if (TestClearPageDirty(page)) {
712 713
			radix_tree_tag_clear(&mapping->page_tree,
						page_index(page),
714
						PAGECACHE_TAG_DIRTY);
715
			write_unlock_irqrestore(&mapping->tree_lock, flags);
716 717 718 719
			if (!mapping->backing_dev_info->memory_backed)
				dec_page_state(nr_dirty);
			return 1;
		}
720
		write_unlock_irqrestore(&mapping->tree_lock, flags);
721
		return 0;
722
	}
723
	return TestClearPageDirty(page);
724
}
725
EXPORT_SYMBOL(test_clear_page_dirty);
726

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
/*
 * Clear a page's dirty flag, while caring for dirty memory accounting.
 * Returns true if the page was previously dirty.
 *
 * This is for preparing to put the page under writeout.  We leave the page
 * tagged as dirty in the radix tree so that a concurrent write-for-sync
 * can discover it via a PAGECACHE_TAG_DIRTY walk.  The ->writepage
 * implementation will run either set_page_writeback() or set_page_dirty(),
 * at which stage we bring the page's dirty flag and radix-tree dirty tag
 * back into sync.
 *
 * This incoherency between the page's dirty flag and radix-tree tag is
 * unfortunate, but it only exists while the page is locked.
 */
int clear_page_dirty_for_io(struct page *page)
{
743
	struct address_space *mapping = page_mapping(page);
744 745 746 747 748 749 750 751 752 753 754 755 756

	if (mapping) {
		if (TestClearPageDirty(page)) {
			if (!mapping->backing_dev_info->memory_backed)
				dec_page_state(nr_dirty);
			return 1;
		}
		return 0;
	}
	return TestClearPageDirty(page);
}
EXPORT_SYMBOL(clear_page_dirty_for_io);

757 758 759 760 761
/*
 * Clear a page's dirty flag while ignoring dirty memory accounting
 */
int __clear_page_dirty(struct page *page)
{
762
	struct address_space *mapping = page_mapping(page);
763 764 765 766

	if (mapping) {
		unsigned long flags;

767
		write_lock_irqsave(&mapping->tree_lock, flags);
768
		if (TestClearPageDirty(page)) {
769 770
			radix_tree_tag_clear(&mapping->page_tree,
						page_index(page),
771
						PAGECACHE_TAG_DIRTY);
772
			write_unlock_irqrestore(&mapping->tree_lock, flags);
773 774
			return 1;
		}
775
		write_unlock_irqrestore(&mapping->tree_lock, flags);
776 777 778 779
		return 0;
	}
	return TestClearPageDirty(page);
}
780 781 782

int test_clear_page_writeback(struct page *page)
{
783
	struct address_space *mapping = page_mapping(page);
784 785 786 787 788
	int ret;

	if (mapping) {
		unsigned long flags;

789
		write_lock_irqsave(&mapping->tree_lock, flags);
790 791
		ret = TestClearPageWriteback(page);
		if (ret)
792 793
			radix_tree_tag_clear(&mapping->page_tree,
						page_index(page),
794
						PAGECACHE_TAG_WRITEBACK);
795
		write_unlock_irqrestore(&mapping->tree_lock, flags);
796 797 798 799 800 801 802 803
	} else {
		ret = TestClearPageWriteback(page);
	}
	return ret;
}

int test_set_page_writeback(struct page *page)
{
804
	struct address_space *mapping = page_mapping(page);
805 806 807 808 809
	int ret;

	if (mapping) {
		unsigned long flags;

810
		write_lock_irqsave(&mapping->tree_lock, flags);
811 812
		ret = TestSetPageWriteback(page);
		if (!ret)
813 814
			radix_tree_tag_set(&mapping->page_tree,
						page_index(page),
815
						PAGECACHE_TAG_WRITEBACK);
816
		if (!PageDirty(page))
817 818
			radix_tree_tag_clear(&mapping->page_tree,
						page_index(page),
819
						PAGECACHE_TAG_DIRTY);
820
		write_unlock_irqrestore(&mapping->tree_lock, flags);
821 822 823 824 825 826 827
	} else {
		ret = TestSetPageWriteback(page);
	}
	return ret;

}
EXPORT_SYMBOL(test_set_page_writeback);
828 829 830 831 832 833 834 835 836 837

/*
 * Return true if any of the pages in the mapping are marged with the
 * passed tag.
 */
int mapping_tagged(struct address_space *mapping, int tag)
{
	unsigned long flags;
	int ret;

838
	read_lock_irqsave(&mapping->tree_lock, flags);
839
	ret = radix_tree_tagged(&mapping->page_tree, tag);
840
	read_unlock_irqrestore(&mapping->tree_lock, flags);
841 842 843
	return ret;
}
EXPORT_SYMBOL(mapping_tagged);