4 * Copyright (C) 2002, Linus Torvalds.
5 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
7 * Contains functions related to writing back dirty pages at the
10 * 10Apr2002 akpm@zip.com.au
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/spinlock.h>
19 #include <linux/swap.h>
20 #include <linux/slab.h>
21 #include <linux/pagemap.h>
22 #include <linux/writeback.h>
23 #include <linux/init.h>
24 #include <linux/backing-dev.h>
25 #include <linux/task_io_accounting_ops.h>
26 #include <linux/blkdev.h>
27 #include <linux/mpage.h>
28 #include <linux/rmap.h>
29 #include <linux/percpu.h>
30 #include <linux/notifier.h>
31 #include <linux/smp.h>
32 #include <linux/sysctl.h>
33 #include <linux/cpu.h>
34 #include <linux/syscalls.h>
35 #include <linux/buffer_head.h>
36 #include <linux/pagevec.h>
39 * The maximum number of pages to writeout in a single bdflush/kupdate
40 * operation. We do this so we don't hold I_LOCK against an inode for
41 * enormous amounts of time, which would block a userspace task which has
42 * been forced to throttle against that inode. Also, the code reevaluates
43 * the dirty each time it has written this many pages.
45 #define MAX_WRITEBACK_PAGES 1024
48 * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
49 * will look to see if it needs to force writeback or throttling.
51 static long ratelimit_pages = 32;
54 * When balance_dirty_pages decides that the caller needs to perform some
55 * non-background writeback, this is how many pages it will attempt to write.
56 * It should be somewhat larger than RATELIMIT_PAGES to ensure that reasonably
57 * large amounts of I/O are submitted.
59 static inline long sync_writeback_pages(void)
61 return ratelimit_pages + ratelimit_pages / 2;
64 /* The following parameters are exported via /proc/sys/vm */
67 * Start background writeback (via pdflush) at this percentage
69 int dirty_background_ratio = 5;
72 * The generator of dirty data starts writeback at this percentage
74 int vm_dirty_ratio = 10;
77 * The interval between `kupdate'-style writebacks, in jiffies
79 int dirty_writeback_interval = 5 * HZ;
82 * The longest number of jiffies for which data is allowed to remain dirty
84 int dirty_expire_interval = 30 * HZ;
87 * Flag that makes the machine dump writes/reads and block dirtyings.
92 * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
93 * a full sync is triggered after this time elapses without any disk activity.
97 EXPORT_SYMBOL(laptop_mode);
99 /* End of sysctl-exported parameters */
102 static void background_writeout(unsigned long _min_pages);
105 * Scale the writeback cache size proportional to the relative writeout speeds.
107 * We do this by keeping a floating proportion between BDIs, based on page
108 * writeback completions [end_page_writeback()]. Those devices that write out
109 * pages fastest will get the larger share, while the slower will get a smaller
112 * We use page writeout completions because we are interested in getting rid of
113 * dirty pages. Having them written out is the primary goal.
115 * We introduce a concept of time, a period over which we measure these events,
116 * because demand can/will vary over time. The length of this period itself is
117 * measured in page writeback completions.
120 static struct prop_descriptor vm_completions;
122 static unsigned long determine_dirtyable_memory(void);
125 * couple the period to the dirty_ratio:
127 * period/2 ~ roundup_pow_of_two(dirty limit)
129 static int calc_period_shift(void)
131 unsigned long dirty_total;
133 dirty_total = (vm_dirty_ratio * determine_dirtyable_memory()) / 100;
134 return 2 + ilog2(dirty_total - 1);
138 * update the period when the dirty ratio changes.
140 int dirty_ratio_handler(struct ctl_table *table, int write,
141 struct file *filp, void __user *buffer, size_t *lenp,
144 int old_ratio = vm_dirty_ratio;
145 int ret = proc_dointvec_minmax(table, write, filp, buffer, lenp, ppos);
146 if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
147 int shift = calc_period_shift();
148 prop_change_shift(&vm_completions, shift);
154 * Increment the BDI's writeout completion count and the global writeout
155 * completion count. Called from test_clear_page_writeback().
157 static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
159 __prop_inc_percpu(&vm_completions, &bdi->completions);
163 * Obtain an accurate fraction of the BDI's portion.
165 static void bdi_writeout_fraction(struct backing_dev_info *bdi,
166 long *numerator, long *denominator)
168 if (bdi_cap_writeback_dirty(bdi)) {
169 prop_fraction_percpu(&vm_completions, &bdi->completions,
170 numerator, denominator);
178 * Clip the earned share of dirty pages to that which is actually available.
179 * This avoids exceeding the total dirty_limit when the floating averages
180 * fluctuate too quickly.
183 clip_bdi_dirty_limit(struct backing_dev_info *bdi, long dirty, long *pbdi_dirty)
187 avail_dirty = dirty -
188 (global_page_state(NR_FILE_DIRTY) +
189 global_page_state(NR_WRITEBACK) +
190 global_page_state(NR_UNSTABLE_NFS));
195 avail_dirty += bdi_stat(bdi, BDI_RECLAIMABLE) +
196 bdi_stat(bdi, BDI_WRITEBACK);
198 *pbdi_dirty = min(*pbdi_dirty, avail_dirty);
202 * Work out the current dirty-memory clamping and background writeout
205 * The main aim here is to lower them aggressively if there is a lot of mapped
206 * memory around. To avoid stressing page reclaim with lots of unreclaimable
207 * pages. It is better to clamp down on writers than to start swapping, and
208 * performing lots of scanning.
210 * We only allow 1/2 of the currently-unmapped memory to be dirtied.
212 * We don't permit the clamping level to fall below 5% - that is getting rather
215 * We make sure that the background writeout level is below the adjusted
219 static unsigned long highmem_dirtyable_memory(unsigned long total)
221 #ifdef CONFIG_HIGHMEM
225 for_each_node_state(node, N_HIGH_MEMORY) {
227 &NODE_DATA(node)->node_zones[ZONE_HIGHMEM];
229 x += zone_page_state(z, NR_FREE_PAGES)
230 + zone_page_state(z, NR_INACTIVE)
231 + zone_page_state(z, NR_ACTIVE);
234 * Make sure that the number of highmem pages is never larger
235 * than the number of the total dirtyable memory. This can only
236 * occur in very strange VM situations but we want to make sure
237 * that this does not occur.
239 return min(x, total);
245 static unsigned long determine_dirtyable_memory(void)
249 x = global_page_state(NR_FREE_PAGES)
250 + global_page_state(NR_INACTIVE)
251 + global_page_state(NR_ACTIVE);
252 x -= highmem_dirtyable_memory(x);
253 return x + 1; /* Ensure that we never return 0 */
257 get_dirty_limits(long *pbackground, long *pdirty, long *pbdi_dirty,
258 struct backing_dev_info *bdi)
260 int background_ratio; /* Percentages */
265 unsigned long available_memory = determine_dirtyable_memory();
266 struct task_struct *tsk;
268 unmapped_ratio = 100 - ((global_page_state(NR_FILE_MAPPED) +
269 global_page_state(NR_ANON_PAGES)) * 100) /
272 dirty_ratio = vm_dirty_ratio;
273 if (dirty_ratio > unmapped_ratio / 2)
274 dirty_ratio = unmapped_ratio / 2;
279 background_ratio = dirty_background_ratio;
280 if (background_ratio >= dirty_ratio)
281 background_ratio = dirty_ratio / 2;
283 background = (background_ratio * available_memory) / 100;
284 dirty = (dirty_ratio * available_memory) / 100;
286 if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
287 background += background / 4;
290 *pbackground = background;
294 u64 bdi_dirty = dirty;
295 long numerator, denominator;
298 * Calculate this BDI's share of the dirty ratio.
300 bdi_writeout_fraction(bdi, &numerator, &denominator);
302 bdi_dirty *= numerator;
303 do_div(bdi_dirty, denominator);
305 *pbdi_dirty = bdi_dirty;
306 clip_bdi_dirty_limit(bdi, dirty, pbdi_dirty);
311 * balance_dirty_pages() must be called by processes which are generating dirty
312 * data. It looks at the number of dirty pages in the machine and will force
313 * the caller to perform writeback if the system is over `vm_dirty_ratio'.
314 * If we're over `background_thresh' then pdflush is woken to perform some
317 static void balance_dirty_pages(struct address_space *mapping)
319 long bdi_nr_reclaimable;
320 long bdi_nr_writeback;
321 long background_thresh;
324 unsigned long pages_written = 0;
325 unsigned long write_chunk = sync_writeback_pages();
327 struct backing_dev_info *bdi = mapping->backing_dev_info;
330 struct writeback_control wbc = {
332 .sync_mode = WB_SYNC_NONE,
333 .older_than_this = NULL,
334 .nr_to_write = write_chunk,
338 get_dirty_limits(&background_thresh, &dirty_thresh,
340 bdi_nr_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
341 bdi_nr_writeback = bdi_stat(bdi, BDI_WRITEBACK);
342 if (bdi_nr_reclaimable + bdi_nr_writeback <= bdi_thresh)
345 if (!bdi->dirty_exceeded)
346 bdi->dirty_exceeded = 1;
348 /* Note: nr_reclaimable denotes nr_dirty + nr_unstable.
349 * Unstable writes are a feature of certain networked
350 * filesystems (i.e. NFS) in which data may have been
351 * written to the server's write cache, but has not yet
352 * been flushed to permanent storage.
354 if (bdi_nr_reclaimable) {
355 writeback_inodes(&wbc);
356 pages_written += write_chunk - wbc.nr_to_write;
357 get_dirty_limits(&background_thresh, &dirty_thresh,
362 * In order to avoid the stacked BDI deadlock we need
363 * to ensure we accurately count the 'dirty' pages when
364 * the threshold is low.
366 * Otherwise it would be possible to get thresh+n pages
367 * reported dirty, even though there are thresh-m pages
368 * actually dirty; with m+n sitting in the percpu
371 if (bdi_thresh < 2*bdi_stat_error(bdi)) {
372 bdi_nr_reclaimable = bdi_stat_sum(bdi, BDI_RECLAIMABLE);
373 bdi_nr_writeback = bdi_stat_sum(bdi, BDI_WRITEBACK);
374 } else if (bdi_nr_reclaimable) {
375 bdi_nr_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
376 bdi_nr_writeback = bdi_stat(bdi, BDI_WRITEBACK);
379 if (bdi_nr_reclaimable + bdi_nr_writeback <= bdi_thresh)
381 if (pages_written >= write_chunk)
382 break; /* We've done our duty */
384 congestion_wait(WRITE, HZ/10);
387 if (bdi_nr_reclaimable + bdi_nr_writeback < bdi_thresh &&
389 bdi->dirty_exceeded = 0;
391 if (writeback_in_progress(bdi))
392 return; /* pdflush is already working this queue */
395 * In laptop mode, we wait until hitting the higher threshold before
396 * starting background writeout, and then write out all the way down
397 * to the lower threshold. So slow writers cause minimal disk activity.
399 * In normal mode, we start background writeout at the lower
400 * background_thresh, to keep the amount of dirty memory low.
402 if ((laptop_mode && pages_written) ||
403 (!laptop_mode && (global_page_state(NR_FILE_DIRTY)
404 + global_page_state(NR_UNSTABLE_NFS)
405 > background_thresh)))
406 pdflush_operation(background_writeout, 0);
409 void set_page_dirty_balance(struct page *page, int page_mkwrite)
411 if (set_page_dirty(page) || page_mkwrite) {
412 struct address_space *mapping = page_mapping(page);
415 balance_dirty_pages_ratelimited(mapping);
420 * balance_dirty_pages_ratelimited_nr - balance dirty memory state
421 * @mapping: address_space which was dirtied
422 * @nr_pages_dirtied: number of pages which the caller has just dirtied
424 * Processes which are dirtying memory should call in here once for each page
425 * which was newly dirtied. The function will periodically check the system's
426 * dirty state and will initiate writeback if needed.
428 * On really big machines, get_writeback_state is expensive, so try to avoid
429 * calling it too often (ratelimiting). But once we're over the dirty memory
430 * limit we decrease the ratelimiting by a lot, to prevent individual processes
431 * from overshooting the limit by (ratelimit_pages) each.
433 void balance_dirty_pages_ratelimited_nr(struct address_space *mapping,
434 unsigned long nr_pages_dirtied)
436 static DEFINE_PER_CPU(unsigned long, ratelimits) = 0;
437 unsigned long ratelimit;
440 ratelimit = ratelimit_pages;
441 if (mapping->backing_dev_info->dirty_exceeded)
445 * Check the rate limiting. Also, we do not want to throttle real-time
446 * tasks in balance_dirty_pages(). Period.
449 p = &__get_cpu_var(ratelimits);
450 *p += nr_pages_dirtied;
451 if (unlikely(*p >= ratelimit)) {
454 balance_dirty_pages(mapping);
459 EXPORT_SYMBOL(balance_dirty_pages_ratelimited_nr);
461 void throttle_vm_writeout(gfp_t gfp_mask)
463 long background_thresh;
466 if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO)) {
468 * The caller might hold locks which can prevent IO completion
469 * or progress in the filesystem. So we cannot just sit here
470 * waiting for IO to complete.
472 congestion_wait(WRITE, HZ/10);
477 get_dirty_limits(&background_thresh, &dirty_thresh, NULL, NULL);
480 * Boost the allowable dirty threshold a bit for page
481 * allocators so they don't get DoS'ed by heavy writers
483 dirty_thresh += dirty_thresh / 10; /* wheeee... */
485 if (global_page_state(NR_UNSTABLE_NFS) +
486 global_page_state(NR_WRITEBACK) <= dirty_thresh)
488 congestion_wait(WRITE, HZ/10);
493 * writeback at least _min_pages, and keep writing until the amount of dirty
494 * memory is less than the background threshold, or until we're all clean.
496 static void background_writeout(unsigned long _min_pages)
498 long min_pages = _min_pages;
499 struct writeback_control wbc = {
501 .sync_mode = WB_SYNC_NONE,
502 .older_than_this = NULL,
509 long background_thresh;
512 get_dirty_limits(&background_thresh, &dirty_thresh, NULL, NULL);
513 if (global_page_state(NR_FILE_DIRTY) +
514 global_page_state(NR_UNSTABLE_NFS) < background_thresh
517 wbc.encountered_congestion = 0;
518 wbc.nr_to_write = MAX_WRITEBACK_PAGES;
519 wbc.pages_skipped = 0;
520 writeback_inodes(&wbc);
521 min_pages -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
522 if (wbc.nr_to_write > 0 || wbc.pages_skipped > 0) {
523 /* Wrote less than expected */
524 congestion_wait(WRITE, HZ/10);
525 if (!wbc.encountered_congestion)
532 * Start writeback of `nr_pages' pages. If `nr_pages' is zero, write back
533 * the whole world. Returns 0 if a pdflush thread was dispatched. Returns
534 * -1 if all pdflush threads were busy.
536 int wakeup_pdflush(long nr_pages)
539 nr_pages = global_page_state(NR_FILE_DIRTY) +
540 global_page_state(NR_UNSTABLE_NFS);
541 return pdflush_operation(background_writeout, nr_pages);
544 static void wb_timer_fn(unsigned long unused);
545 static void laptop_timer_fn(unsigned long unused);
547 static DEFINE_TIMER(wb_timer, wb_timer_fn, 0, 0);
548 static DEFINE_TIMER(laptop_mode_wb_timer, laptop_timer_fn, 0, 0);
551 * Periodic writeback of "old" data.
553 * Define "old": the first time one of an inode's pages is dirtied, we mark the
554 * dirtying-time in the inode's address_space. So this periodic writeback code
555 * just walks the superblock inode list, writing back any inodes which are
556 * older than a specific point in time.
558 * Try to run once per dirty_writeback_interval. But if a writeback event
559 * takes longer than a dirty_writeback_interval interval, then leave a
562 * older_than_this takes precedence over nr_to_write. So we'll only write back
563 * all dirty pages if they are all attached to "old" mappings.
565 static void wb_kupdate(unsigned long arg)
567 unsigned long oldest_jif;
568 unsigned long start_jif;
569 unsigned long next_jif;
571 struct writeback_control wbc = {
573 .sync_mode = WB_SYNC_NONE,
574 .older_than_this = &oldest_jif,
583 oldest_jif = jiffies - dirty_expire_interval;
585 next_jif = start_jif + dirty_writeback_interval;
586 nr_to_write = global_page_state(NR_FILE_DIRTY) +
587 global_page_state(NR_UNSTABLE_NFS) +
588 (inodes_stat.nr_inodes - inodes_stat.nr_unused);
589 while (nr_to_write > 0) {
590 wbc.encountered_congestion = 0;
591 wbc.nr_to_write = MAX_WRITEBACK_PAGES;
592 writeback_inodes(&wbc);
593 if (wbc.nr_to_write > 0) {
594 if (wbc.encountered_congestion)
595 congestion_wait(WRITE, HZ/10);
597 break; /* All the old data is written */
599 nr_to_write -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
601 if (time_before(next_jif, jiffies + HZ))
602 next_jif = jiffies + HZ;
603 if (dirty_writeback_interval)
604 mod_timer(&wb_timer, next_jif);
608 * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
610 int dirty_writeback_centisecs_handler(ctl_table *table, int write,
611 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
613 proc_dointvec_userhz_jiffies(table, write, file, buffer, length, ppos);
614 if (dirty_writeback_interval)
615 mod_timer(&wb_timer, jiffies + dirty_writeback_interval);
617 del_timer(&wb_timer);
621 static void wb_timer_fn(unsigned long unused)
623 if (pdflush_operation(wb_kupdate, 0) < 0)
624 mod_timer(&wb_timer, jiffies + HZ); /* delay 1 second */
627 static void laptop_flush(unsigned long unused)
632 static void laptop_timer_fn(unsigned long unused)
634 pdflush_operation(laptop_flush, 0);
638 * We've spun up the disk and we're in laptop mode: schedule writeback
639 * of all dirty data a few seconds from now. If the flush is already scheduled
640 * then push it back - the user is still using the disk.
642 void laptop_io_completion(void)
644 mod_timer(&laptop_mode_wb_timer, jiffies + laptop_mode);
648 * We're in laptop mode and we've just synced. The sync's writes will have
649 * caused another writeback to be scheduled by laptop_io_completion.
650 * Nothing needs to be written back anymore, so we unschedule the writeback.
652 void laptop_sync_completion(void)
654 del_timer(&laptop_mode_wb_timer);
658 * If ratelimit_pages is too high then we can get into dirty-data overload
659 * if a large number of processes all perform writes at the same time.
660 * If it is too low then SMP machines will call the (expensive)
661 * get_writeback_state too often.
663 * Here we set ratelimit_pages to a level which ensures that when all CPUs are
664 * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
665 * thresholds before writeback cuts in.
667 * But the limit should not be set too high. Because it also controls the
668 * amount of memory which the balance_dirty_pages() caller has to write back.
669 * If this is too large then the caller will block on the IO queue all the
670 * time. So limit it to four megabytes - the balance_dirty_pages() caller
671 * will write six megabyte chunks, max.
674 void writeback_set_ratelimit(void)
676 ratelimit_pages = vm_total_pages / (num_online_cpus() * 32);
677 if (ratelimit_pages < 16)
678 ratelimit_pages = 16;
679 if (ratelimit_pages * PAGE_CACHE_SIZE > 4096 * 1024)
680 ratelimit_pages = (4096 * 1024) / PAGE_CACHE_SIZE;
684 ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
686 writeback_set_ratelimit();
690 static struct notifier_block __cpuinitdata ratelimit_nb = {
691 .notifier_call = ratelimit_handler,
696 * Called early on to tune the page writeback dirty limits.
698 * We used to scale dirty pages according to how total memory
699 * related to pages that could be allocated for buffers (by
700 * comparing nr_free_buffer_pages() to vm_total_pages.
702 * However, that was when we used "dirty_ratio" to scale with
703 * all memory, and we don't do that any more. "dirty_ratio"
704 * is now applied to total non-HIGHPAGE memory (by subtracting
705 * totalhigh_pages from vm_total_pages), and as such we can't
706 * get into the old insane situation any more where we had
707 * large amounts of dirty pages compared to a small amount of
708 * non-HIGHMEM memory.
710 * But we might still want to scale the dirty_ratio by how
711 * much memory the box has..
713 void __init page_writeback_init(void)
717 mod_timer(&wb_timer, jiffies + dirty_writeback_interval);
718 writeback_set_ratelimit();
719 register_cpu_notifier(&ratelimit_nb);
721 shift = calc_period_shift();
722 prop_descriptor_init(&vm_completions, shift);
726 * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
727 * @mapping: address space structure to write
728 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
729 * @writepage: function called for each page
730 * @data: data passed to writepage function
732 * If a page is already under I/O, write_cache_pages() skips it, even
733 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
734 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
735 * and msync() need to guarantee that all the data which was dirty at the time
736 * the call was made get new I/O started against them. If wbc->sync_mode is
737 * WB_SYNC_ALL then we were called for data integrity and we must wait for
738 * existing IO to complete.
740 int write_cache_pages(struct address_space *mapping,
741 struct writeback_control *wbc, writepage_t writepage,
744 struct backing_dev_info *bdi = mapping->backing_dev_info;
750 pgoff_t end; /* Inclusive */
754 if (wbc->nonblocking && bdi_write_congested(bdi)) {
755 wbc->encountered_congestion = 1;
759 pagevec_init(&pvec, 0);
760 if (wbc->range_cyclic) {
761 index = mapping->writeback_index; /* Start from prev offset */
764 index = wbc->range_start >> PAGE_CACHE_SHIFT;
765 end = wbc->range_end >> PAGE_CACHE_SHIFT;
766 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
771 while (!done && (index <= end) &&
772 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
774 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1))) {
778 for (i = 0; i < nr_pages; i++) {
779 struct page *page = pvec.pages[i];
782 * At this point we hold neither mapping->tree_lock nor
783 * lock on the page itself: the page may be truncated or
784 * invalidated (changing page->mapping to NULL), or even
785 * swizzled back from swapper_space to tmpfs file
790 if (unlikely(page->mapping != mapping)) {
795 if (!wbc->range_cyclic && page->index > end) {
801 if (wbc->sync_mode != WB_SYNC_NONE)
802 wait_on_page_writeback(page);
804 if (PageWriteback(page) ||
805 !clear_page_dirty_for_io(page)) {
810 ret = (*writepage)(page, wbc, data);
812 if (unlikely(ret == AOP_WRITEPAGE_ACTIVATE))
814 if (ret || (--(wbc->nr_to_write) <= 0))
816 if (wbc->nonblocking && bdi_write_congested(bdi)) {
817 wbc->encountered_congestion = 1;
821 pagevec_release(&pvec);
824 if (!scanned && !done) {
826 * We hit the last page and there is more work to be done: wrap
827 * back to the start of the file
833 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
834 mapping->writeback_index = index;
837 EXPORT_SYMBOL(write_cache_pages);
840 * Function used by generic_writepages to call the real writepage
841 * function and set the mapping flags on error
843 static int __writepage(struct page *page, struct writeback_control *wbc,
846 struct address_space *mapping = data;
847 int ret = mapping->a_ops->writepage(page, wbc);
848 mapping_set_error(mapping, ret);
853 * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
854 * @mapping: address space structure to write
855 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
857 * This is a library function, which implements the writepages()
858 * address_space_operation.
860 int generic_writepages(struct address_space *mapping,
861 struct writeback_control *wbc)
863 /* deal with chardevs and other special file */
864 if (!mapping->a_ops->writepage)
867 return write_cache_pages(mapping, wbc, __writepage, mapping);
870 EXPORT_SYMBOL(generic_writepages);
872 int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
876 if (wbc->nr_to_write <= 0)
878 wbc->for_writepages = 1;
879 if (mapping->a_ops->writepages)
880 ret = mapping->a_ops->writepages(mapping, wbc);
882 ret = generic_writepages(mapping, wbc);
883 wbc->for_writepages = 0;
888 * write_one_page - write out a single page and optionally wait on I/O
889 * @page: the page to write
890 * @wait: if true, wait on writeout
892 * The page must be locked by the caller and will be unlocked upon return.
894 * write_one_page() returns a negative error code if I/O failed.
896 int write_one_page(struct page *page, int wait)
898 struct address_space *mapping = page->mapping;
900 struct writeback_control wbc = {
901 .sync_mode = WB_SYNC_ALL,
905 BUG_ON(!PageLocked(page));
908 wait_on_page_writeback(page);
910 if (clear_page_dirty_for_io(page)) {
911 page_cache_get(page);
912 ret = mapping->a_ops->writepage(page, &wbc);
913 if (ret == 0 && wait) {
914 wait_on_page_writeback(page);
918 page_cache_release(page);
924 EXPORT_SYMBOL(write_one_page);
927 * For address_spaces which do not use buffers nor write back.
929 int __set_page_dirty_no_writeback(struct page *page)
931 if (!PageDirty(page))
937 * For address_spaces which do not use buffers. Just tag the page as dirty in
940 * This is also used when a single buffer is being dirtied: we want to set the
941 * page dirty in that case, but not all the buffers. This is a "bottom-up"
942 * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
944 * Most callers have locked the page, which pins the address_space in memory.
945 * But zap_pte_range() does not lock the page, however in that case the
946 * mapping is pinned by the vma's ->vm_file reference.
948 * We take care to handle the case where the page was truncated from the
949 * mapping by re-checking page_mapping() insode tree_lock.
951 int __set_page_dirty_nobuffers(struct page *page)
953 if (!TestSetPageDirty(page)) {
954 struct address_space *mapping = page_mapping(page);
955 struct address_space *mapping2;
960 write_lock_irq(&mapping->tree_lock);
961 mapping2 = page_mapping(page);
962 if (mapping2) { /* Race with truncate? */
963 BUG_ON(mapping2 != mapping);
964 WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
965 if (mapping_cap_account_dirty(mapping)) {
966 __inc_zone_page_state(page, NR_FILE_DIRTY);
967 __inc_bdi_stat(mapping->backing_dev_info,
969 task_io_account_write(PAGE_CACHE_SIZE);
971 radix_tree_tag_set(&mapping->page_tree,
972 page_index(page), PAGECACHE_TAG_DIRTY);
974 write_unlock_irq(&mapping->tree_lock);
976 /* !PageAnon && !swapper_space */
977 __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
983 EXPORT_SYMBOL(__set_page_dirty_nobuffers);
986 * When a writepage implementation decides that it doesn't want to write this
987 * page for some reason, it should redirty the locked page via
988 * redirty_page_for_writepage() and it should then unlock the page and return 0
990 int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
992 wbc->pages_skipped++;
993 return __set_page_dirty_nobuffers(page);
995 EXPORT_SYMBOL(redirty_page_for_writepage);
998 * If the mapping doesn't provide a set_page_dirty a_op, then
999 * just fall through and assume that it wants buffer_heads.
1001 int fastcall set_page_dirty(struct page *page)
1003 struct address_space *mapping = page_mapping(page);
1005 if (likely(mapping)) {
1006 int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
1009 spd = __set_page_dirty_buffers;
1011 return (*spd)(page);
1013 if (!PageDirty(page)) {
1014 if (!TestSetPageDirty(page))
1019 EXPORT_SYMBOL(set_page_dirty);
1022 * set_page_dirty() is racy if the caller has no reference against
1023 * page->mapping->host, and if the page is unlocked. This is because another
1024 * CPU could truncate the page off the mapping and then free the mapping.
1026 * Usually, the page _is_ locked, or the caller is a user-space process which
1027 * holds a reference on the inode by having an open file.
1029 * In other cases, the page should be locked before running set_page_dirty().
1031 int set_page_dirty_lock(struct page *page)
1035 lock_page_nosync(page);
1036 ret = set_page_dirty(page);
1040 EXPORT_SYMBOL(set_page_dirty_lock);
1043 * Clear a page's dirty flag, while caring for dirty memory accounting.
1044 * Returns true if the page was previously dirty.
1046 * This is for preparing to put the page under writeout. We leave the page
1047 * tagged as dirty in the radix tree so that a concurrent write-for-sync
1048 * can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
1049 * implementation will run either set_page_writeback() or set_page_dirty(),
1050 * at which stage we bring the page's dirty flag and radix-tree dirty tag
1053 * This incoherency between the page's dirty flag and radix-tree tag is
1054 * unfortunate, but it only exists while the page is locked.
1056 int clear_page_dirty_for_io(struct page *page)
1058 struct address_space *mapping = page_mapping(page);
1060 BUG_ON(!PageLocked(page));
1062 ClearPageReclaim(page);
1063 if (mapping && mapping_cap_account_dirty(mapping)) {
1065 * Yes, Virginia, this is indeed insane.
1067 * We use this sequence to make sure that
1068 * (a) we account for dirty stats properly
1069 * (b) we tell the low-level filesystem to
1070 * mark the whole page dirty if it was
1071 * dirty in a pagetable. Only to then
1072 * (c) clean the page again and return 1 to
1073 * cause the writeback.
1075 * This way we avoid all nasty races with the
1076 * dirty bit in multiple places and clearing
1077 * them concurrently from different threads.
1079 * Note! Normally the "set_page_dirty(page)"
1080 * has no effect on the actual dirty bit - since
1081 * that will already usually be set. But we
1082 * need the side effects, and it can help us
1085 * We basically use the page "master dirty bit"
1086 * as a serialization point for all the different
1087 * threads doing their things.
1089 if (page_mkclean(page))
1090 set_page_dirty(page);
1092 * We carefully synchronise fault handlers against
1093 * installing a dirty pte and marking the page dirty
1094 * at this point. We do this by having them hold the
1095 * page lock at some point after installing their
1096 * pte, but before marking the page dirty.
1097 * Pages are always locked coming in here, so we get
1098 * the desired exclusion. See mm/memory.c:do_wp_page()
1099 * for more comments.
1101 if (TestClearPageDirty(page)) {
1102 dec_zone_page_state(page, NR_FILE_DIRTY);
1103 dec_bdi_stat(mapping->backing_dev_info,
1109 return TestClearPageDirty(page);
1111 EXPORT_SYMBOL(clear_page_dirty_for_io);
1113 int test_clear_page_writeback(struct page *page)
1115 struct address_space *mapping = page_mapping(page);
1119 struct backing_dev_info *bdi = mapping->backing_dev_info;
1120 unsigned long flags;
1122 write_lock_irqsave(&mapping->tree_lock, flags);
1123 ret = TestClearPageWriteback(page);
1125 radix_tree_tag_clear(&mapping->page_tree,
1127 PAGECACHE_TAG_WRITEBACK);
1128 if (bdi_cap_writeback_dirty(bdi)) {
1129 __dec_bdi_stat(bdi, BDI_WRITEBACK);
1130 __bdi_writeout_inc(bdi);
1133 write_unlock_irqrestore(&mapping->tree_lock, flags);
1135 ret = TestClearPageWriteback(page);
1138 dec_zone_page_state(page, NR_WRITEBACK);
1142 int test_set_page_writeback(struct page *page)
1144 struct address_space *mapping = page_mapping(page);
1148 struct backing_dev_info *bdi = mapping->backing_dev_info;
1149 unsigned long flags;
1151 write_lock_irqsave(&mapping->tree_lock, flags);
1152 ret = TestSetPageWriteback(page);
1154 radix_tree_tag_set(&mapping->page_tree,
1156 PAGECACHE_TAG_WRITEBACK);
1157 if (bdi_cap_writeback_dirty(bdi))
1158 __inc_bdi_stat(bdi, BDI_WRITEBACK);
1160 if (!PageDirty(page))
1161 radix_tree_tag_clear(&mapping->page_tree,
1163 PAGECACHE_TAG_DIRTY);
1164 write_unlock_irqrestore(&mapping->tree_lock, flags);
1166 ret = TestSetPageWriteback(page);
1169 inc_zone_page_state(page, NR_WRITEBACK);
1173 EXPORT_SYMBOL(test_set_page_writeback);
1176 * Return true if any of the pages in the mapping are marked with the
1179 int mapping_tagged(struct address_space *mapping, int tag)
1183 ret = radix_tree_tagged(&mapping->page_tree, tag);
1187 EXPORT_SYMBOL(mapping_tagged);