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 Andrew Morton
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>
37 #include <linux/hrtimer.h>
40 * The maximum number of pages to writeout in a single bdflush/kupdate
41 * operation. We do this so we don't hold I_SYNC against an inode for
42 * enormous amounts of time, which would block a userspace task which has
43 * been forced to throttle against that inode. Also, the code reevaluates
44 * the dirty each time it has written this many pages.
46 #define MAX_WRITEBACK_PAGES 1024
49 * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
50 * will look to see if it needs to force writeback or throttling.
52 static long ratelimit_pages = 32;
55 * When balance_dirty_pages decides that the caller needs to perform some
56 * non-background writeback, this is how many pages it will attempt to write.
57 * It should be somewhat larger than RATELIMIT_PAGES to ensure that reasonably
58 * large amounts of I/O are submitted.
60 static inline long sync_writeback_pages(void)
62 return ratelimit_pages + ratelimit_pages / 2;
65 /* The following parameters are exported via /proc/sys/vm */
68 * Start background writeback (via pdflush) at this percentage
70 int dirty_background_ratio = 5;
73 * free highmem will not be subtracted from the total free memory
74 * for calculating free ratios if vm_highmem_is_dirtyable is true
76 int vm_highmem_is_dirtyable;
79 * The generator of dirty data starts writeback at this percentage
81 int vm_dirty_ratio = 10;
84 * The interval between `kupdate'-style writebacks, in jiffies
86 int dirty_writeback_interval = 5 * HZ;
89 * The longest number of jiffies for which data is allowed to remain dirty
91 int dirty_expire_interval = 30 * HZ;
94 * Flag that makes the machine dump writes/reads and block dirtyings.
99 * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
100 * a full sync is triggered after this time elapses without any disk activity.
104 EXPORT_SYMBOL(laptop_mode);
106 /* End of sysctl-exported parameters */
109 static void background_writeout(unsigned long _min_pages);
112 * Scale the writeback cache size proportional to the relative writeout speeds.
114 * We do this by keeping a floating proportion between BDIs, based on page
115 * writeback completions [end_page_writeback()]. Those devices that write out
116 * pages fastest will get the larger share, while the slower will get a smaller
119 * We use page writeout completions because we are interested in getting rid of
120 * dirty pages. Having them written out is the primary goal.
122 * We introduce a concept of time, a period over which we measure these events,
123 * because demand can/will vary over time. The length of this period itself is
124 * measured in page writeback completions.
127 static struct prop_descriptor vm_completions;
128 static struct prop_descriptor vm_dirties;
131 * couple the period to the dirty_ratio:
133 * period/2 ~ roundup_pow_of_two(dirty limit)
135 static int calc_period_shift(void)
137 unsigned long dirty_total;
139 dirty_total = (vm_dirty_ratio * determine_dirtyable_memory()) / 100;
140 return 2 + ilog2(dirty_total - 1);
144 * update the period when the dirty ratio changes.
146 int dirty_ratio_handler(struct ctl_table *table, int write,
147 struct file *filp, void __user *buffer, size_t *lenp,
150 int old_ratio = vm_dirty_ratio;
151 int ret = proc_dointvec_minmax(table, write, filp, buffer, lenp, ppos);
152 if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
153 int shift = calc_period_shift();
154 prop_change_shift(&vm_completions, shift);
155 prop_change_shift(&vm_dirties, shift);
161 * Increment the BDI's writeout completion count and the global writeout
162 * completion count. Called from test_clear_page_writeback().
164 static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
166 __prop_inc_percpu_max(&vm_completions, &bdi->completions,
170 void bdi_writeout_inc(struct backing_dev_info *bdi)
174 local_irq_save(flags);
175 __bdi_writeout_inc(bdi);
176 local_irq_restore(flags);
178 EXPORT_SYMBOL_GPL(bdi_writeout_inc);
180 static inline void task_dirty_inc(struct task_struct *tsk)
182 prop_inc_single(&vm_dirties, &tsk->dirties);
186 * Obtain an accurate fraction of the BDI's portion.
188 static void bdi_writeout_fraction(struct backing_dev_info *bdi,
189 long *numerator, long *denominator)
191 if (bdi_cap_writeback_dirty(bdi)) {
192 prop_fraction_percpu(&vm_completions, &bdi->completions,
193 numerator, denominator);
201 * Clip the earned share of dirty pages to that which is actually available.
202 * This avoids exceeding the total dirty_limit when the floating averages
203 * fluctuate too quickly.
206 clip_bdi_dirty_limit(struct backing_dev_info *bdi, long dirty, long *pbdi_dirty)
210 avail_dirty = dirty -
211 (global_page_state(NR_FILE_DIRTY) +
212 global_page_state(NR_WRITEBACK) +
213 global_page_state(NR_UNSTABLE_NFS) +
214 global_page_state(NR_WRITEBACK_TEMP));
219 avail_dirty += bdi_stat(bdi, BDI_RECLAIMABLE) +
220 bdi_stat(bdi, BDI_WRITEBACK);
222 *pbdi_dirty = min(*pbdi_dirty, avail_dirty);
225 static inline void task_dirties_fraction(struct task_struct *tsk,
226 long *numerator, long *denominator)
228 prop_fraction_single(&vm_dirties, &tsk->dirties,
229 numerator, denominator);
233 * scale the dirty limit
235 * task specific dirty limit:
237 * dirty -= (dirty/8) * p_{t}
239 static void task_dirty_limit(struct task_struct *tsk, long *pdirty)
241 long numerator, denominator;
242 long dirty = *pdirty;
243 u64 inv = dirty >> 3;
245 task_dirties_fraction(tsk, &numerator, &denominator);
247 do_div(inv, denominator);
250 if (dirty < *pdirty/2)
259 static DEFINE_SPINLOCK(bdi_lock);
260 static unsigned int bdi_min_ratio;
262 int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio)
267 spin_lock_irqsave(&bdi_lock, flags);
268 if (min_ratio > bdi->max_ratio) {
271 min_ratio -= bdi->min_ratio;
272 if (bdi_min_ratio + min_ratio < 100) {
273 bdi_min_ratio += min_ratio;
274 bdi->min_ratio += min_ratio;
279 spin_unlock_irqrestore(&bdi_lock, flags);
284 int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio)
292 spin_lock_irqsave(&bdi_lock, flags);
293 if (bdi->min_ratio > max_ratio) {
296 bdi->max_ratio = max_ratio;
297 bdi->max_prop_frac = (PROP_FRAC_BASE * max_ratio) / 100;
299 spin_unlock_irqrestore(&bdi_lock, flags);
303 EXPORT_SYMBOL(bdi_set_max_ratio);
306 * Work out the current dirty-memory clamping and background writeout
309 * The main aim here is to lower them aggressively if there is a lot of mapped
310 * memory around. To avoid stressing page reclaim with lots of unreclaimable
311 * pages. It is better to clamp down on writers than to start swapping, and
312 * performing lots of scanning.
314 * We only allow 1/2 of the currently-unmapped memory to be dirtied.
316 * We don't permit the clamping level to fall below 5% - that is getting rather
319 * We make sure that the background writeout level is below the adjusted
323 static unsigned long highmem_dirtyable_memory(unsigned long total)
325 #ifdef CONFIG_HIGHMEM
329 for_each_node_state(node, N_HIGH_MEMORY) {
331 &NODE_DATA(node)->node_zones[ZONE_HIGHMEM];
333 x += zone_page_state(z, NR_FREE_PAGES) + zone_lru_pages(z);
336 * Make sure that the number of highmem pages is never larger
337 * than the number of the total dirtyable memory. This can only
338 * occur in very strange VM situations but we want to make sure
339 * that this does not occur.
341 return min(x, total);
348 * determine_dirtyable_memory - amount of memory that may be used
350 * Returns the numebr of pages that can currently be freed and used
351 * by the kernel for direct mappings.
353 unsigned long determine_dirtyable_memory(void)
357 x = global_page_state(NR_FREE_PAGES) + global_lru_pages();
359 if (!vm_highmem_is_dirtyable)
360 x -= highmem_dirtyable_memory(x);
362 return x + 1; /* Ensure that we never return 0 */
366 get_dirty_limits(long *pbackground, long *pdirty, long *pbdi_dirty,
367 struct backing_dev_info *bdi)
369 int background_ratio; /* Percentages */
373 unsigned long available_memory = determine_dirtyable_memory();
374 struct task_struct *tsk;
376 dirty_ratio = vm_dirty_ratio;
380 background_ratio = dirty_background_ratio;
381 if (background_ratio >= dirty_ratio)
382 background_ratio = dirty_ratio / 2;
384 background = (background_ratio * available_memory) / 100;
385 dirty = (dirty_ratio * available_memory) / 100;
387 if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
388 background += background / 4;
391 *pbackground = background;
396 long numerator, denominator;
399 * Calculate this BDI's share of the dirty ratio.
401 bdi_writeout_fraction(bdi, &numerator, &denominator);
403 bdi_dirty = (dirty * (100 - bdi_min_ratio)) / 100;
404 bdi_dirty *= numerator;
405 do_div(bdi_dirty, denominator);
406 bdi_dirty += (dirty * bdi->min_ratio) / 100;
407 if (bdi_dirty > (dirty * bdi->max_ratio) / 100)
408 bdi_dirty = dirty * bdi->max_ratio / 100;
410 *pbdi_dirty = bdi_dirty;
411 clip_bdi_dirty_limit(bdi, dirty, pbdi_dirty);
412 task_dirty_limit(current, pbdi_dirty);
417 * balance_dirty_pages() must be called by processes which are generating dirty
418 * data. It looks at the number of dirty pages in the machine and will force
419 * the caller to perform writeback if the system is over `vm_dirty_ratio'.
420 * If we're over `background_thresh' then pdflush is woken to perform some
423 static void balance_dirty_pages(struct address_space *mapping)
425 long nr_reclaimable, bdi_nr_reclaimable;
426 long nr_writeback, bdi_nr_writeback;
427 long background_thresh;
430 unsigned long pages_written = 0;
431 unsigned long write_chunk = sync_writeback_pages();
433 struct backing_dev_info *bdi = mapping->backing_dev_info;
436 struct writeback_control wbc = {
438 .sync_mode = WB_SYNC_NONE,
439 .older_than_this = NULL,
440 .nr_to_write = write_chunk,
444 get_dirty_limits(&background_thresh, &dirty_thresh,
447 nr_reclaimable = global_page_state(NR_FILE_DIRTY) +
448 global_page_state(NR_UNSTABLE_NFS);
449 nr_writeback = global_page_state(NR_WRITEBACK);
451 bdi_nr_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
452 bdi_nr_writeback = bdi_stat(bdi, BDI_WRITEBACK);
454 if (bdi_nr_reclaimable + bdi_nr_writeback <= bdi_thresh)
458 * Throttle it only when the background writeback cannot
459 * catch-up. This avoids (excessively) small writeouts
460 * when the bdi limits are ramping up.
462 if (nr_reclaimable + nr_writeback <
463 (background_thresh + dirty_thresh) / 2)
466 if (!bdi->dirty_exceeded)
467 bdi->dirty_exceeded = 1;
469 /* Note: nr_reclaimable denotes nr_dirty + nr_unstable.
470 * Unstable writes are a feature of certain networked
471 * filesystems (i.e. NFS) in which data may have been
472 * written to the server's write cache, but has not yet
473 * been flushed to permanent storage.
475 if (bdi_nr_reclaimable) {
476 writeback_inodes(&wbc);
477 pages_written += write_chunk - wbc.nr_to_write;
478 get_dirty_limits(&background_thresh, &dirty_thresh,
483 * In order to avoid the stacked BDI deadlock we need
484 * to ensure we accurately count the 'dirty' pages when
485 * the threshold is low.
487 * Otherwise it would be possible to get thresh+n pages
488 * reported dirty, even though there are thresh-m pages
489 * actually dirty; with m+n sitting in the percpu
492 if (bdi_thresh < 2*bdi_stat_error(bdi)) {
493 bdi_nr_reclaimable = bdi_stat_sum(bdi, BDI_RECLAIMABLE);
494 bdi_nr_writeback = bdi_stat_sum(bdi, BDI_WRITEBACK);
495 } else if (bdi_nr_reclaimable) {
496 bdi_nr_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
497 bdi_nr_writeback = bdi_stat(bdi, BDI_WRITEBACK);
500 if (bdi_nr_reclaimable + bdi_nr_writeback <= bdi_thresh)
502 if (pages_written >= write_chunk)
503 break; /* We've done our duty */
505 congestion_wait(WRITE, HZ/10);
508 if (bdi_nr_reclaimable + bdi_nr_writeback < bdi_thresh &&
510 bdi->dirty_exceeded = 0;
512 if (writeback_in_progress(bdi))
513 return; /* pdflush is already working this queue */
516 * In laptop mode, we wait until hitting the higher threshold before
517 * starting background writeout, and then write out all the way down
518 * to the lower threshold. So slow writers cause minimal disk activity.
520 * In normal mode, we start background writeout at the lower
521 * background_thresh, to keep the amount of dirty memory low.
523 if ((laptop_mode && pages_written) ||
524 (!laptop_mode && (global_page_state(NR_FILE_DIRTY)
525 + global_page_state(NR_UNSTABLE_NFS)
526 > background_thresh)))
527 pdflush_operation(background_writeout, 0);
530 void set_page_dirty_balance(struct page *page, int page_mkwrite)
532 if (set_page_dirty(page) || page_mkwrite) {
533 struct address_space *mapping = page_mapping(page);
536 balance_dirty_pages_ratelimited(mapping);
541 * balance_dirty_pages_ratelimited_nr - balance dirty memory state
542 * @mapping: address_space which was dirtied
543 * @nr_pages_dirtied: number of pages which the caller has just dirtied
545 * Processes which are dirtying memory should call in here once for each page
546 * which was newly dirtied. The function will periodically check the system's
547 * dirty state and will initiate writeback if needed.
549 * On really big machines, get_writeback_state is expensive, so try to avoid
550 * calling it too often (ratelimiting). But once we're over the dirty memory
551 * limit we decrease the ratelimiting by a lot, to prevent individual processes
552 * from overshooting the limit by (ratelimit_pages) each.
554 void balance_dirty_pages_ratelimited_nr(struct address_space *mapping,
555 unsigned long nr_pages_dirtied)
557 static DEFINE_PER_CPU(unsigned long, ratelimits) = 0;
558 unsigned long ratelimit;
561 ratelimit = ratelimit_pages;
562 if (mapping->backing_dev_info->dirty_exceeded)
566 * Check the rate limiting. Also, we do not want to throttle real-time
567 * tasks in balance_dirty_pages(). Period.
570 p = &__get_cpu_var(ratelimits);
571 *p += nr_pages_dirtied;
572 if (unlikely(*p >= ratelimit)) {
575 balance_dirty_pages(mapping);
580 EXPORT_SYMBOL(balance_dirty_pages_ratelimited_nr);
582 void throttle_vm_writeout(gfp_t gfp_mask)
584 long background_thresh;
588 get_dirty_limits(&background_thresh, &dirty_thresh, NULL, NULL);
591 * Boost the allowable dirty threshold a bit for page
592 * allocators so they don't get DoS'ed by heavy writers
594 dirty_thresh += dirty_thresh / 10; /* wheeee... */
596 if (global_page_state(NR_UNSTABLE_NFS) +
597 global_page_state(NR_WRITEBACK) <= dirty_thresh)
599 congestion_wait(WRITE, HZ/10);
602 * The caller might hold locks which can prevent IO completion
603 * or progress in the filesystem. So we cannot just sit here
604 * waiting for IO to complete.
606 if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO))
612 * writeback at least _min_pages, and keep writing until the amount of dirty
613 * memory is less than the background threshold, or until we're all clean.
615 static void background_writeout(unsigned long _min_pages)
617 long min_pages = _min_pages;
618 struct writeback_control wbc = {
620 .sync_mode = WB_SYNC_NONE,
621 .older_than_this = NULL,
628 long background_thresh;
631 get_dirty_limits(&background_thresh, &dirty_thresh, NULL, NULL);
632 if (global_page_state(NR_FILE_DIRTY) +
633 global_page_state(NR_UNSTABLE_NFS) < background_thresh
637 wbc.encountered_congestion = 0;
638 wbc.nr_to_write = MAX_WRITEBACK_PAGES;
639 wbc.pages_skipped = 0;
640 writeback_inodes(&wbc);
641 min_pages -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
642 if (wbc.nr_to_write > 0 || wbc.pages_skipped > 0) {
643 /* Wrote less than expected */
644 if (wbc.encountered_congestion || wbc.more_io)
645 congestion_wait(WRITE, HZ/10);
653 * Start writeback of `nr_pages' pages. If `nr_pages' is zero, write back
654 * the whole world. Returns 0 if a pdflush thread was dispatched. Returns
655 * -1 if all pdflush threads were busy.
657 int wakeup_pdflush(long nr_pages)
660 nr_pages = global_page_state(NR_FILE_DIRTY) +
661 global_page_state(NR_UNSTABLE_NFS);
662 return pdflush_operation(background_writeout, nr_pages);
665 static enum hrtimer_restart wb_timer_fn(struct hrtimer *timer);
666 static void laptop_timer_fn(unsigned long unused);
668 struct hrtimer wb_timer;
669 static DEFINE_TIMER(laptop_mode_wb_timer, laptop_timer_fn, 0, 0);
670 static DEFINE_SPINLOCK(wb_timer_lock);
672 /* Whether the atomic write-back is enabled or not */
673 atomic_t periodic_wb_enabled;
676 * This is a helper function which sets up the next periodic write-back timer
677 * event. The @wb_timer is set up as a range timer with soft limit 25% less
678 * than @expires and the hard limit equivalent to @expires. This means that the
679 * kernel may group this timer with other events and lessen number of
682 static void setup_wb_timer(unsigned long expires)
684 u64 hardlimit, delta;
686 hardlimit = jiffies_to_usecs(expires) * 1000LLU;
687 delta = hardlimit >> 2;
688 if (delta > ULONG_MAX)
691 hrtimer_start_range_ns(&wb_timer, ns_to_ktime(hardlimit - delta), delta,
696 * Enable the periodic write-back. This function is usually called when
697 * an inode or a super block becomes dirty.
699 void enable_periodic_wb(void)
701 if (dirty_writeback_interval) {
702 spin_lock(&wb_timer_lock);
703 setup_wb_timer(dirty_writeback_interval);
704 spin_unlock(&wb_timer_lock);
708 static int sb_supports_wb(struct super_block *sb)
711 struct backing_dev_info *bdi;
714 spin_lock(&inode_lock);
715 inode = list_entry(sb->s_inodes.next, struct inode, i_sb_list);
716 bdi = inode->i_mapping->backing_dev_info;
717 res = bdi_cap_writeback_dirty(bdi);
718 spin_unlock(&inode_lock);
722 static void set_next_wb_timer(unsigned long expires)
725 struct super_block *sb;
727 atomic_set(&periodic_wb_enabled, 0);
731 list_for_each_entry(sb, &super_blocks, s_list) {
733 spin_unlock(&sb_lock);
735 if (down_read_trylock(&sb->s_umount)) {
739 else if (sb->s_root && sb_supports_wb(sb) &&
740 sb_has_dirty_inodes(sb))
742 up_read(&sb->s_umount);
748 if (__put_super_and_need_restart(sb))
754 spin_unlock(&sb_lock);
756 spin_lock(&wb_timer_lock);
757 if (all_clean && !atomic_read(&periodic_wb_enabled)) {
759 * There are no dirty data, and no one marked an inode or
760 * super block as dirty. The periodic update timer may be
761 * deleted. Note, if we race with some other task which has
762 * just marked something as dirty and just set
763 * 'periodic_wb_enabled' to 1, then this task will call
764 * 'enable_periodic_wb()' which will re-enable the 'wb_timer'.
766 hrtimer_cancel(&wb_timer);
768 atomic_set(&periodic_wb_enabled, 1);
769 setup_wb_timer(expires);
771 spin_unlock(&wb_timer_lock);
775 * Periodic writeback of "old" data.
777 * Define "old": the first time one of an inode's pages is dirtied, we mark the
778 * dirtying-time in the inode's address_space. So this periodic writeback code
779 * just walks the superblock inode list, writing back any inodes which are
780 * older than a specific point in time.
782 * Try to run once per dirty_writeback_interval. But if a writeback event
783 * takes longer than a dirty_writeback_interval interval, then leave a
786 * older_than_this takes precedence over nr_to_write. So we'll only write back
787 * all dirty pages if they are all attached to "old" mappings.
789 static void wb_kupdate(unsigned long arg)
791 unsigned long oldest_jif;
792 unsigned long start_jif;
793 unsigned long next_jif;
795 struct writeback_control wbc = {
797 .sync_mode = WB_SYNC_NONE,
798 .older_than_this = &oldest_jif,
807 oldest_jif = jiffies - dirty_expire_interval;
809 next_jif = start_jif + dirty_writeback_interval;
810 nr_to_write = global_page_state(NR_FILE_DIRTY) +
811 global_page_state(NR_UNSTABLE_NFS) +
812 (inodes_stat.nr_inodes - inodes_stat.nr_unused);
813 while (nr_to_write > 0) {
815 wbc.encountered_congestion = 0;
816 wbc.nr_to_write = MAX_WRITEBACK_PAGES;
817 writeback_inodes(&wbc);
818 if (wbc.nr_to_write > 0) {
819 if (wbc.encountered_congestion || wbc.more_io)
820 congestion_wait(WRITE, HZ/10);
822 break; /* All the old data is written */
824 nr_to_write -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
827 if (dirty_writeback_interval) {
828 unsigned long expires;
830 if (time_before(next_jif, jiffies + HZ))
833 expires = next_jif - jiffies;
834 set_next_wb_timer(expires);
839 * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
841 int dirty_writeback_centisecs_handler(ctl_table *table, int write,
842 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
844 proc_dointvec_userhz_jiffies(table, write, file, buffer, length, ppos);
845 if (dirty_writeback_interval)
846 setup_wb_timer(dirty_writeback_interval);
848 hrtimer_cancel(&wb_timer);
852 static enum hrtimer_restart wb_timer_fn(struct hrtimer *timer)
854 if (pdflush_operation(wb_kupdate, 0) < 0)
855 setup_wb_timer(HZ); /* delay 1 second */
856 return HRTIMER_NORESTART;
859 static void laptop_flush(unsigned long unused)
864 static void laptop_timer_fn(unsigned long unused)
866 pdflush_operation(laptop_flush, 0);
870 * We've spun up the disk and we're in laptop mode: schedule writeback
871 * of all dirty data a few seconds from now. If the flush is already scheduled
872 * then push it back - the user is still using the disk.
874 void laptop_io_completion(void)
876 mod_timer(&laptop_mode_wb_timer, jiffies + laptop_mode);
880 * We're in laptop mode and we've just synced. The sync's writes will have
881 * caused another writeback to be scheduled by laptop_io_completion.
882 * Nothing needs to be written back anymore, so we unschedule the writeback.
884 void laptop_sync_completion(void)
886 del_timer(&laptop_mode_wb_timer);
890 * If ratelimit_pages is too high then we can get into dirty-data overload
891 * if a large number of processes all perform writes at the same time.
892 * If it is too low then SMP machines will call the (expensive)
893 * get_writeback_state too often.
895 * Here we set ratelimit_pages to a level which ensures that when all CPUs are
896 * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
897 * thresholds before writeback cuts in.
899 * But the limit should not be set too high. Because it also controls the
900 * amount of memory which the balance_dirty_pages() caller has to write back.
901 * If this is too large then the caller will block on the IO queue all the
902 * time. So limit it to four megabytes - the balance_dirty_pages() caller
903 * will write six megabyte chunks, max.
906 void writeback_set_ratelimit(void)
908 ratelimit_pages = vm_total_pages / (num_online_cpus() * 32);
909 if (ratelimit_pages < 16)
910 ratelimit_pages = 16;
911 if (ratelimit_pages * PAGE_CACHE_SIZE > 4096 * 1024)
912 ratelimit_pages = (4096 * 1024) / PAGE_CACHE_SIZE;
916 ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
918 writeback_set_ratelimit();
922 static struct notifier_block __cpuinitdata ratelimit_nb = {
923 .notifier_call = ratelimit_handler,
928 * Called early on to tune the page writeback dirty limits.
930 * We used to scale dirty pages according to how total memory
931 * related to pages that could be allocated for buffers (by
932 * comparing nr_free_buffer_pages() to vm_total_pages.
934 * However, that was when we used "dirty_ratio" to scale with
935 * all memory, and we don't do that any more. "dirty_ratio"
936 * is now applied to total non-HIGHPAGE memory (by subtracting
937 * totalhigh_pages from vm_total_pages), and as such we can't
938 * get into the old insane situation any more where we had
939 * large amounts of dirty pages compared to a small amount of
940 * non-HIGHMEM memory.
942 * But we might still want to scale the dirty_ratio by how
943 * much memory the box has..
945 void __init page_writeback_init(void)
949 hrtimer_init(&wb_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
950 wb_timer.function = wb_timer_fn;
951 writeback_set_ratelimit();
952 register_cpu_notifier(&ratelimit_nb);
954 shift = calc_period_shift();
955 prop_descriptor_init(&vm_completions, shift);
956 prop_descriptor_init(&vm_dirties, shift);
960 * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
961 * @mapping: address space structure to write
962 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
963 * @writepage: function called for each page
964 * @data: data passed to writepage function
966 * If a page is already under I/O, write_cache_pages() skips it, even
967 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
968 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
969 * and msync() need to guarantee that all the data which was dirty at the time
970 * the call was made get new I/O started against them. If wbc->sync_mode is
971 * WB_SYNC_ALL then we were called for data integrity and we must wait for
972 * existing IO to complete.
974 int write_cache_pages(struct address_space *mapping,
975 struct writeback_control *wbc, writepage_t writepage,
978 struct backing_dev_info *bdi = mapping->backing_dev_info;
984 pgoff_t end; /* Inclusive */
987 long nr_to_write = wbc->nr_to_write;
989 if (wbc->nonblocking && bdi_write_congested(bdi)) {
990 wbc->encountered_congestion = 1;
994 pagevec_init(&pvec, 0);
995 if (wbc->range_cyclic) {
996 index = mapping->writeback_index; /* Start from prev offset */
999 index = wbc->range_start >> PAGE_CACHE_SHIFT;
1000 end = wbc->range_end >> PAGE_CACHE_SHIFT;
1001 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
1006 while (!done && (index <= end) &&
1007 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
1008 PAGECACHE_TAG_DIRTY,
1009 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1))) {
1013 for (i = 0; i < nr_pages; i++) {
1014 struct page *page = pvec.pages[i];
1017 * At this point we hold neither mapping->tree_lock nor
1018 * lock on the page itself: the page may be truncated or
1019 * invalidated (changing page->mapping to NULL), or even
1020 * swizzled back from swapper_space to tmpfs file
1025 if (unlikely(page->mapping != mapping)) {
1030 if (!wbc->range_cyclic && page->index > end) {
1036 if (wbc->sync_mode != WB_SYNC_NONE)
1037 wait_on_page_writeback(page);
1039 if (PageWriteback(page) ||
1040 !clear_page_dirty_for_io(page)) {
1045 ret = (*writepage)(page, wbc, data);
1047 if (unlikely(ret == AOP_WRITEPAGE_ACTIVATE)) {
1051 if (ret || (--nr_to_write <= 0))
1053 if (wbc->nonblocking && bdi_write_congested(bdi)) {
1054 wbc->encountered_congestion = 1;
1058 pagevec_release(&pvec);
1061 if (!scanned && !done) {
1063 * We hit the last page and there is more work to be done: wrap
1064 * back to the start of the file
1070 if (!wbc->no_nrwrite_index_update) {
1071 if (wbc->range_cyclic || (range_whole && nr_to_write > 0))
1072 mapping->writeback_index = index;
1073 wbc->nr_to_write = nr_to_write;
1078 EXPORT_SYMBOL(write_cache_pages);
1081 * Function used by generic_writepages to call the real writepage
1082 * function and set the mapping flags on error
1084 static int __writepage(struct page *page, struct writeback_control *wbc,
1087 struct address_space *mapping = data;
1088 int ret = mapping->a_ops->writepage(page, wbc);
1089 mapping_set_error(mapping, ret);
1094 * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
1095 * @mapping: address space structure to write
1096 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
1098 * This is a library function, which implements the writepages()
1099 * address_space_operation.
1101 int generic_writepages(struct address_space *mapping,
1102 struct writeback_control *wbc)
1104 /* deal with chardevs and other special file */
1105 if (!mapping->a_ops->writepage)
1108 return write_cache_pages(mapping, wbc, __writepage, mapping);
1111 EXPORT_SYMBOL(generic_writepages);
1113 int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
1117 if (wbc->nr_to_write <= 0)
1119 wbc->for_writepages = 1;
1120 if (mapping->a_ops->writepages)
1121 ret = mapping->a_ops->writepages(mapping, wbc);
1123 ret = generic_writepages(mapping, wbc);
1124 wbc->for_writepages = 0;
1129 * write_one_page - write out a single page and optionally wait on I/O
1130 * @page: the page to write
1131 * @wait: if true, wait on writeout
1133 * The page must be locked by the caller and will be unlocked upon return.
1135 * write_one_page() returns a negative error code if I/O failed.
1137 int write_one_page(struct page *page, int wait)
1139 struct address_space *mapping = page->mapping;
1141 struct writeback_control wbc = {
1142 .sync_mode = WB_SYNC_ALL,
1146 BUG_ON(!PageLocked(page));
1149 wait_on_page_writeback(page);
1151 if (clear_page_dirty_for_io(page)) {
1152 page_cache_get(page);
1153 ret = mapping->a_ops->writepage(page, &wbc);
1154 if (ret == 0 && wait) {
1155 wait_on_page_writeback(page);
1156 if (PageError(page))
1159 page_cache_release(page);
1165 EXPORT_SYMBOL(write_one_page);
1168 * For address_spaces which do not use buffers nor write back.
1170 int __set_page_dirty_no_writeback(struct page *page)
1172 if (!PageDirty(page))
1178 * For address_spaces which do not use buffers. Just tag the page as dirty in
1181 * This is also used when a single buffer is being dirtied: we want to set the
1182 * page dirty in that case, but not all the buffers. This is a "bottom-up"
1183 * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
1185 * Most callers have locked the page, which pins the address_space in memory.
1186 * But zap_pte_range() does not lock the page, however in that case the
1187 * mapping is pinned by the vma's ->vm_file reference.
1189 * We take care to handle the case where the page was truncated from the
1190 * mapping by re-checking page_mapping() inside tree_lock.
1192 int __set_page_dirty_nobuffers(struct page *page)
1194 if (!TestSetPageDirty(page)) {
1195 struct address_space *mapping = page_mapping(page);
1196 struct address_space *mapping2;
1201 spin_lock_irq(&mapping->tree_lock);
1202 mapping2 = page_mapping(page);
1203 if (mapping2) { /* Race with truncate? */
1204 BUG_ON(mapping2 != mapping);
1205 WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
1206 if (mapping_cap_account_dirty(mapping)) {
1207 __inc_zone_page_state(page, NR_FILE_DIRTY);
1208 __inc_bdi_stat(mapping->backing_dev_info,
1210 task_io_account_write(PAGE_CACHE_SIZE);
1212 radix_tree_tag_set(&mapping->page_tree,
1213 page_index(page), PAGECACHE_TAG_DIRTY);
1215 spin_unlock_irq(&mapping->tree_lock);
1216 if (mapping->host) {
1217 /* !PageAnon && !swapper_space */
1218 __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
1224 EXPORT_SYMBOL(__set_page_dirty_nobuffers);
1227 * When a writepage implementation decides that it doesn't want to write this
1228 * page for some reason, it should redirty the locked page via
1229 * redirty_page_for_writepage() and it should then unlock the page and return 0
1231 int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
1233 wbc->pages_skipped++;
1234 return __set_page_dirty_nobuffers(page);
1236 EXPORT_SYMBOL(redirty_page_for_writepage);
1239 * If the mapping doesn't provide a set_page_dirty a_op, then
1240 * just fall through and assume that it wants buffer_heads.
1242 static int __set_page_dirty(struct page *page)
1244 struct address_space *mapping = page_mapping(page);
1246 if (likely(mapping)) {
1247 int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
1250 spd = __set_page_dirty_buffers;
1252 return (*spd)(page);
1254 if (!PageDirty(page)) {
1255 if (!TestSetPageDirty(page))
1261 int set_page_dirty(struct page *page)
1263 int ret = __set_page_dirty(page);
1265 task_dirty_inc(current);
1268 EXPORT_SYMBOL(set_page_dirty);
1271 * set_page_dirty() is racy if the caller has no reference against
1272 * page->mapping->host, and if the page is unlocked. This is because another
1273 * CPU could truncate the page off the mapping and then free the mapping.
1275 * Usually, the page _is_ locked, or the caller is a user-space process which
1276 * holds a reference on the inode by having an open file.
1278 * In other cases, the page should be locked before running set_page_dirty().
1280 int set_page_dirty_lock(struct page *page)
1284 lock_page_nosync(page);
1285 ret = set_page_dirty(page);
1289 EXPORT_SYMBOL(set_page_dirty_lock);
1292 * Clear a page's dirty flag, while caring for dirty memory accounting.
1293 * Returns true if the page was previously dirty.
1295 * This is for preparing to put the page under writeout. We leave the page
1296 * tagged as dirty in the radix tree so that a concurrent write-for-sync
1297 * can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
1298 * implementation will run either set_page_writeback() or set_page_dirty(),
1299 * at which stage we bring the page's dirty flag and radix-tree dirty tag
1302 * This incoherency between the page's dirty flag and radix-tree tag is
1303 * unfortunate, but it only exists while the page is locked.
1305 int clear_page_dirty_for_io(struct page *page)
1307 struct address_space *mapping = page_mapping(page);
1309 BUG_ON(!PageLocked(page));
1311 ClearPageReclaim(page);
1312 if (mapping && mapping_cap_account_dirty(mapping)) {
1314 * Yes, Virginia, this is indeed insane.
1316 * We use this sequence to make sure that
1317 * (a) we account for dirty stats properly
1318 * (b) we tell the low-level filesystem to
1319 * mark the whole page dirty if it was
1320 * dirty in a pagetable. Only to then
1321 * (c) clean the page again and return 1 to
1322 * cause the writeback.
1324 * This way we avoid all nasty races with the
1325 * dirty bit in multiple places and clearing
1326 * them concurrently from different threads.
1328 * Note! Normally the "set_page_dirty(page)"
1329 * has no effect on the actual dirty bit - since
1330 * that will already usually be set. But we
1331 * need the side effects, and it can help us
1334 * We basically use the page "master dirty bit"
1335 * as a serialization point for all the different
1336 * threads doing their things.
1338 if (page_mkclean(page))
1339 set_page_dirty(page);
1341 * We carefully synchronise fault handlers against
1342 * installing a dirty pte and marking the page dirty
1343 * at this point. We do this by having them hold the
1344 * page lock at some point after installing their
1345 * pte, but before marking the page dirty.
1346 * Pages are always locked coming in here, so we get
1347 * the desired exclusion. See mm/memory.c:do_wp_page()
1348 * for more comments.
1350 if (TestClearPageDirty(page)) {
1351 dec_zone_page_state(page, NR_FILE_DIRTY);
1352 dec_bdi_stat(mapping->backing_dev_info,
1358 return TestClearPageDirty(page);
1360 EXPORT_SYMBOL(clear_page_dirty_for_io);
1362 int test_clear_page_writeback(struct page *page)
1364 struct address_space *mapping = page_mapping(page);
1368 struct backing_dev_info *bdi = mapping->backing_dev_info;
1369 unsigned long flags;
1371 spin_lock_irqsave(&mapping->tree_lock, flags);
1372 ret = TestClearPageWriteback(page);
1374 radix_tree_tag_clear(&mapping->page_tree,
1376 PAGECACHE_TAG_WRITEBACK);
1377 if (bdi_cap_account_writeback(bdi)) {
1378 __dec_bdi_stat(bdi, BDI_WRITEBACK);
1379 __bdi_writeout_inc(bdi);
1382 spin_unlock_irqrestore(&mapping->tree_lock, flags);
1384 ret = TestClearPageWriteback(page);
1387 dec_zone_page_state(page, NR_WRITEBACK);
1391 int test_set_page_writeback(struct page *page)
1393 struct address_space *mapping = page_mapping(page);
1397 struct backing_dev_info *bdi = mapping->backing_dev_info;
1398 unsigned long flags;
1400 spin_lock_irqsave(&mapping->tree_lock, flags);
1401 ret = TestSetPageWriteback(page);
1403 radix_tree_tag_set(&mapping->page_tree,
1405 PAGECACHE_TAG_WRITEBACK);
1406 if (bdi_cap_account_writeback(bdi))
1407 __inc_bdi_stat(bdi, BDI_WRITEBACK);
1409 if (!PageDirty(page))
1410 radix_tree_tag_clear(&mapping->page_tree,
1412 PAGECACHE_TAG_DIRTY);
1413 spin_unlock_irqrestore(&mapping->tree_lock, flags);
1415 ret = TestSetPageWriteback(page);
1418 inc_zone_page_state(page, NR_WRITEBACK);
1422 EXPORT_SYMBOL(test_set_page_writeback);
1425 * Return true if any of the pages in the mapping are marked with the
1428 int mapping_tagged(struct address_space *mapping, int tag)
1432 ret = radix_tree_tagged(&mapping->page_tree, tag);
1436 EXPORT_SYMBOL(mapping_tagged);