4 * Copyright (C) 2002, Linus Torvalds.
6 * Contains functions related to writing back dirty pages at the
9 * 10Apr2002 akpm@zip.com.au
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/spinlock.h>
18 #include <linux/swap.h>
19 #include <linux/slab.h>
20 #include <linux/pagemap.h>
21 #include <linux/writeback.h>
22 #include <linux/init.h>
23 #include <linux/backing-dev.h>
24 #include <linux/blkdev.h>
25 #include <linux/mpage.h>
26 #include <linux/percpu.h>
27 #include <linux/notifier.h>
28 #include <linux/smp.h>
29 #include <linux/sysctl.h>
30 #include <linux/cpu.h>
31 #include <linux/syscalls.h>
34 * The maximum number of pages to writeout in a single bdflush/kupdate
35 * operation. We do this so we don't hold I_LOCK against an inode for
36 * enormous amounts of time, which would block a userspace task which has
37 * been forced to throttle against that inode. Also, the code reevaluates
38 * the dirty each time it has written this many pages.
40 #define MAX_WRITEBACK_PAGES 1024
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.
46 static long ratelimit_pages = 32;
48 static long total_pages; /* The total number of pages in the machine. */
49 static int dirty_exceeded; /* Dirty mem may be over limit */
52 * When balance_dirty_pages decides that the caller needs to perform some
53 * non-background writeback, this is how many pages it will attempt to write.
54 * It should be somewhat larger than RATELIMIT_PAGES to ensure that reasonably
55 * large amounts of I/O are submitted.
57 static inline long sync_writeback_pages(void)
59 return ratelimit_pages + ratelimit_pages / 2;
62 /* The following parameters are exported via /proc/sys/vm */
65 * Start background writeback (via pdflush) at this percentage
67 int dirty_background_ratio = 10;
70 * The generator of dirty data starts writeback at this percentage
72 int vm_dirty_ratio = 40;
75 * The interval between `kupdate'-style writebacks, in centiseconds
76 * (hundredths of a second)
78 int dirty_writeback_centisecs = 5 * 100;
81 * The longest number of centiseconds for which data is allowed to remain dirty
83 int dirty_expire_centisecs = 30 * 100;
86 * Flag that makes the machine dump writes/reads and block dirtyings.
91 * Flag that puts the machine in "laptop mode".
95 EXPORT_SYMBOL(laptop_mode);
97 /* End of sysctl-exported parameters */
100 static void background_writeout(unsigned long _min_pages);
103 * Work out the current dirty-memory clamping and background writeout
106 * The main aim here is to lower them aggressively if there is a lot of mapped
107 * memory around. To avoid stressing page reclaim with lots of unreclaimable
108 * pages. It is better to clamp down on writers than to start swapping, and
109 * performing lots of scanning.
111 * We only allow 1/2 of the currently-unmapped memory to be dirtied.
113 * We don't permit the clamping level to fall below 5% - that is getting rather
116 * We make sure that the background writeout level is below the adjusted
120 get_dirty_limits(struct page_state *ps, long *pbackground, long *pdirty)
122 int background_ratio; /* Percentages */
127 struct task_struct *tsk;
131 unmapped_ratio = 100 - (ps->nr_mapped * 100) / total_pages;
133 dirty_ratio = vm_dirty_ratio;
134 if (dirty_ratio > unmapped_ratio / 2)
135 dirty_ratio = unmapped_ratio / 2;
140 background_ratio = dirty_background_ratio;
141 if (background_ratio >= dirty_ratio)
142 background_ratio = dirty_ratio / 2;
144 background = (background_ratio * total_pages) / 100;
145 dirty = (dirty_ratio * total_pages) / 100;
147 if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
148 background += background / 4;
151 *pbackground = background;
156 * balance_dirty_pages() must be called by processes which are generating dirty
157 * data. It looks at the number of dirty pages in the machine and will force
158 * the caller to perform writeback if the system is over `vm_dirty_ratio'.
159 * If we're over `background_thresh' then pdflush is woken to perform some
162 static void balance_dirty_pages(struct address_space *mapping)
164 struct page_state ps;
166 long background_thresh;
168 unsigned long pages_written = 0;
169 unsigned long write_chunk = sync_writeback_pages();
171 struct backing_dev_info *bdi = mapping->backing_dev_info;
174 struct writeback_control wbc = {
176 .sync_mode = WB_SYNC_NONE,
177 .older_than_this = NULL,
178 .nr_to_write = write_chunk,
181 get_dirty_limits(&ps, &background_thresh, &dirty_thresh);
182 nr_reclaimable = ps.nr_dirty + ps.nr_unstable;
183 if (nr_reclaimable + ps.nr_writeback <= dirty_thresh)
188 /* Note: nr_reclaimable denotes nr_dirty + nr_unstable.
189 * Unstable writes are a feature of certain networked
190 * filesystems (i.e. NFS) in which data may have been
191 * written to the server's write cache, but has not yet
192 * been flushed to permanent storage.
194 if (nr_reclaimable) {
195 writeback_inodes(&wbc);
196 get_dirty_limits(&ps, &background_thresh,
198 nr_reclaimable = ps.nr_dirty + ps.nr_unstable;
199 if (nr_reclaimable + ps.nr_writeback <= dirty_thresh)
201 pages_written += write_chunk - wbc.nr_to_write;
202 if (pages_written >= write_chunk)
203 break; /* We've done our duty */
205 blk_congestion_wait(WRITE, HZ/10);
208 if (nr_reclaimable + ps.nr_writeback <= dirty_thresh)
211 if (writeback_in_progress(bdi))
212 return; /* pdflush is already working this queue */
215 * In laptop mode, we wait until hitting the higher threshold before
216 * starting background writeout, and then write out all the way down
217 * to the lower threshold. So slow writers cause minimal disk activity.
219 * In normal mode, we start background writeout at the lower
220 * background_thresh, to keep the amount of dirty memory low.
222 if ((laptop_mode && pages_written) ||
223 (!laptop_mode && (nr_reclaimable > background_thresh)))
224 pdflush_operation(background_writeout, 0);
228 * balance_dirty_pages_ratelimited - balance dirty memory state
229 * @mapping - address_space which was dirtied
231 * Processes which are dirtying memory should call in here once for each page
232 * which was newly dirtied. The function will periodically check the system's
233 * dirty state and will initiate writeback if needed.
235 * On really big machines, get_page_state is expensive, so try to avoid calling
236 * it too often (ratelimiting). But once we're over the dirty memory limit we
237 * decrease the ratelimiting by a lot, to prevent individual processes from
238 * overshooting the limit by (ratelimit_pages) each.
240 void balance_dirty_pages_ratelimited(struct address_space *mapping)
242 static DEFINE_PER_CPU(int, ratelimits) = 0;
245 ratelimit = ratelimit_pages;
250 * Check the rate limiting. Also, we do not want to throttle real-time
251 * tasks in balance_dirty_pages(). Period.
253 if (get_cpu_var(ratelimits)++ >= ratelimit) {
254 __get_cpu_var(ratelimits) = 0;
255 put_cpu_var(ratelimits);
256 balance_dirty_pages(mapping);
259 put_cpu_var(ratelimits);
261 EXPORT_SYMBOL(balance_dirty_pages_ratelimited);
264 * writeback at least _min_pages, and keep writing until the amount of dirty
265 * memory is less than the background threshold, or until we're all clean.
267 static void background_writeout(unsigned long _min_pages)
269 long min_pages = _min_pages;
270 struct writeback_control wbc = {
272 .sync_mode = WB_SYNC_NONE,
273 .older_than_this = NULL,
279 struct page_state ps;
280 long background_thresh;
283 get_dirty_limits(&ps, &background_thresh, &dirty_thresh);
284 if (ps.nr_dirty + ps.nr_unstable < background_thresh
287 wbc.encountered_congestion = 0;
288 wbc.nr_to_write = MAX_WRITEBACK_PAGES;
289 wbc.pages_skipped = 0;
290 writeback_inodes(&wbc);
291 min_pages -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
292 if (wbc.nr_to_write > 0 || wbc.pages_skipped > 0) {
293 /* Wrote less than expected */
294 blk_congestion_wait(WRITE, HZ/10);
295 if (!wbc.encountered_congestion)
302 * Start writeback of `nr_pages' pages. If `nr_pages' is zero, write back
303 * the whole world. Returns 0 if a pdflush thread was dispatched. Returns
304 * -1 if all pdflush threads were busy.
306 int wakeup_bdflush(long nr_pages)
309 struct page_state ps;
312 nr_pages = ps.nr_dirty + ps.nr_unstable;
314 return pdflush_operation(background_writeout, nr_pages);
317 static void wb_timer_fn(unsigned long unused);
318 static void laptop_timer_fn(unsigned long unused);
320 static struct timer_list wb_timer =
321 TIMER_INITIALIZER(wb_timer_fn, 0, 0);
322 static struct timer_list laptop_mode_wb_timer =
323 TIMER_INITIALIZER(laptop_timer_fn, 0, 0);
326 * Periodic writeback of "old" data.
328 * Define "old": the first time one of an inode's pages is dirtied, we mark the
329 * dirtying-time in the inode's address_space. So this periodic writeback code
330 * just walks the superblock inode list, writing back any inodes which are
331 * older than a specific point in time.
333 * Try to run once per dirty_writeback_centisecs. But if a writeback event
334 * takes longer than a dirty_writeback_centisecs interval, then leave a
337 * older_than_this takes precedence over nr_to_write. So we'll only write back
338 * all dirty pages if they are all attached to "old" mappings.
340 static void wb_kupdate(unsigned long arg)
342 unsigned long oldest_jif;
343 unsigned long start_jif;
344 unsigned long next_jif;
346 struct page_state ps;
347 struct writeback_control wbc = {
349 .sync_mode = WB_SYNC_NONE,
350 .older_than_this = &oldest_jif,
359 oldest_jif = jiffies - (dirty_expire_centisecs * HZ) / 100;
361 next_jif = start_jif + (dirty_writeback_centisecs * HZ) / 100;
362 nr_to_write = ps.nr_dirty + ps.nr_unstable +
363 (inodes_stat.nr_inodes - inodes_stat.nr_unused);
364 while (nr_to_write > 0) {
365 wbc.encountered_congestion = 0;
366 wbc.nr_to_write = MAX_WRITEBACK_PAGES;
367 writeback_inodes(&wbc);
368 if (wbc.nr_to_write > 0) {
369 if (wbc.encountered_congestion)
370 blk_congestion_wait(WRITE, HZ/10);
372 break; /* All the old data is written */
374 nr_to_write -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
376 if (time_before(next_jif, jiffies + HZ))
377 next_jif = jiffies + HZ;
378 if (dirty_writeback_centisecs)
379 mod_timer(&wb_timer, next_jif);
383 * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
385 int dirty_writeback_centisecs_handler(ctl_table *table, int write,
386 struct file *file, void __user *buffer, size_t *length)
388 proc_dointvec(table, write, file, buffer, length);
389 if (dirty_writeback_centisecs) {
391 jiffies + (dirty_writeback_centisecs * HZ) / 100);
393 del_timer(&wb_timer);
398 static void wb_timer_fn(unsigned long unused)
400 if (pdflush_operation(wb_kupdate, 0) < 0)
401 mod_timer(&wb_timer, jiffies + HZ); /* delay 1 second */
404 static void laptop_flush(unsigned long unused)
409 static void laptop_timer_fn(unsigned long unused)
411 pdflush_operation(laptop_flush, 0);
415 * We've spun up the disk and we're in laptop mode: schedule writeback
416 * of all dirty data a few seconds from now. If the flush is already scheduled
417 * then push it back - the user is still using the disk.
419 void laptop_io_completion(void)
421 mod_timer(&laptop_mode_wb_timer, jiffies + laptop_mode * HZ);
425 * We're in laptop mode and we've just synced. The sync's writes will have
426 * caused another writeback to be scheduled by laptop_io_completion.
427 * Nothing needs to be written back anymore, so we unschedule the writeback.
429 void laptop_sync_completion(void)
431 del_timer(&laptop_mode_wb_timer);
435 * If ratelimit_pages is too high then we can get into dirty-data overload
436 * if a large number of processes all perform writes at the same time.
437 * If it is too low then SMP machines will call the (expensive) get_page_state
440 * Here we set ratelimit_pages to a level which ensures that when all CPUs are
441 * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
442 * thresholds before writeback cuts in.
444 * But the limit should not be set too high. Because it also controls the
445 * amount of memory which the balance_dirty_pages() caller has to write back.
446 * If this is too large then the caller will block on the IO queue all the
447 * time. So limit it to four megabytes - the balance_dirty_pages() caller
448 * will write six megabyte chunks, max.
451 static void set_ratelimit(void)
453 ratelimit_pages = total_pages / (num_online_cpus() * 32);
454 if (ratelimit_pages < 16)
455 ratelimit_pages = 16;
456 if (ratelimit_pages * PAGE_CACHE_SIZE > 4096 * 1024)
457 ratelimit_pages = (4096 * 1024) / PAGE_CACHE_SIZE;
461 ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
467 static struct notifier_block ratelimit_nb = {
468 .notifier_call = ratelimit_handler,
473 * If the machine has a large highmem:lowmem ratio then scale back the default
474 * dirty memory thresholds: allowing too much dirty highmem pins an excessive
475 * number of buffer_heads.
477 void __init page_writeback_init(void)
479 long buffer_pages = nr_free_buffer_pages();
482 total_pages = nr_free_pagecache_pages();
484 correction = (100 * 4 * buffer_pages) / total_pages;
486 if (correction < 100) {
487 dirty_background_ratio *= correction;
488 dirty_background_ratio /= 100;
489 vm_dirty_ratio *= correction;
490 vm_dirty_ratio /= 100;
492 mod_timer(&wb_timer, jiffies + (dirty_writeback_centisecs * HZ) / 100);
494 register_cpu_notifier(&ratelimit_nb);
497 int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
499 if (wbc->nr_to_write <= 0)
501 if (mapping->a_ops->writepages)
502 return mapping->a_ops->writepages(mapping, wbc);
503 return generic_writepages(mapping, wbc);
507 * write_one_page - write out a single page and optionally wait on I/O
509 * @page - the page to write
510 * @wait - if true, wait on writeout
512 * The page must be locked by the caller and will be unlocked upon return.
514 * write_one_page() returns a negative error code if I/O failed.
516 int write_one_page(struct page *page, int wait)
518 struct address_space *mapping = page->mapping;
520 struct writeback_control wbc = {
521 .sync_mode = WB_SYNC_ALL,
525 BUG_ON(!PageLocked(page));
528 wait_on_page_writeback(page);
530 if (clear_page_dirty_for_io(page)) {
531 page_cache_get(page);
532 ret = mapping->a_ops->writepage(page, &wbc);
533 if (ret == 0 && wait) {
534 wait_on_page_writeback(page);
538 page_cache_release(page);
544 EXPORT_SYMBOL(write_one_page);
547 * For address_spaces which do not use buffers. Just tag the page as dirty in
550 * This is also used when a single buffer is being dirtied: we want to set the
551 * page dirty in that case, but not all the buffers. This is a "bottom-up"
552 * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
554 * Most callers have locked the page, which pins the address_space in memory.
555 * But zap_pte_range() does not lock the page, however in that case the
556 * mapping is pinned by the vma's ->vm_file reference.
558 * We take care to handle the case where the page was truncated from the
559 * mapping by re-checking page_mapping() insode tree_lock.
561 int __set_page_dirty_nobuffers(struct page *page)
565 if (!TestSetPageDirty(page)) {
566 struct address_space *mapping = page_mapping(page);
569 spin_lock_irq(&mapping->tree_lock);
570 mapping = page_mapping(page);
571 if (page_mapping(page)) { /* Race with truncate? */
572 BUG_ON(page_mapping(page) != mapping);
573 if (!mapping->backing_dev_info->memory_backed)
574 inc_page_state(nr_dirty);
575 radix_tree_tag_set(&mapping->page_tree,
576 page_index(page), PAGECACHE_TAG_DIRTY);
578 spin_unlock_irq(&mapping->tree_lock);
580 /* !PageAnon && !swapper_space */
581 __mark_inode_dirty(mapping->host,
588 EXPORT_SYMBOL(__set_page_dirty_nobuffers);
591 * When a writepage implementation decides that it doesn't want to write this
592 * page for some reason, it should redirty the locked page via
593 * redirty_page_for_writepage() and it should then unlock the page and return 0
595 int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
597 wbc->pages_skipped++;
598 return __set_page_dirty_nobuffers(page);
600 EXPORT_SYMBOL(redirty_page_for_writepage);
603 * If the mapping doesn't provide a set_page_dirty a_op, then
604 * just fall through and assume that it wants buffer_heads.
606 int fastcall set_page_dirty(struct page *page)
608 struct address_space *mapping = page_mapping(page);
610 if (likely(mapping)) {
611 int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
614 return __set_page_dirty_buffers(page);
616 if (!PageDirty(page))
620 EXPORT_SYMBOL(set_page_dirty);
623 * set_page_dirty() is racy if the caller has no reference against
624 * page->mapping->host, and if the page is unlocked. This is because another
625 * CPU could truncate the page off the mapping and then free the mapping.
627 * Usually, the page _is_ locked, or the caller is a user-space process which
628 * holds a reference on the inode by having an open file.
630 * In other cases, the page should be locked before running set_page_dirty().
632 int set_page_dirty_lock(struct page *page)
637 ret = set_page_dirty(page);
641 EXPORT_SYMBOL(set_page_dirty_lock);
644 * Clear a page's dirty flag, while caring for dirty memory accounting.
645 * Returns true if the page was previously dirty.
647 int test_clear_page_dirty(struct page *page)
649 struct address_space *mapping = page_mapping(page);
653 spin_lock_irqsave(&mapping->tree_lock, flags);
654 if (TestClearPageDirty(page)) {
655 radix_tree_tag_clear(&mapping->page_tree,
657 PAGECACHE_TAG_DIRTY);
658 spin_unlock_irqrestore(&mapping->tree_lock, flags);
659 if (!mapping->backing_dev_info->memory_backed)
660 dec_page_state(nr_dirty);
663 spin_unlock_irqrestore(&mapping->tree_lock, flags);
666 return TestClearPageDirty(page);
668 EXPORT_SYMBOL(test_clear_page_dirty);
671 * Clear a page's dirty flag, while caring for dirty memory accounting.
672 * Returns true if the page was previously dirty.
674 * This is for preparing to put the page under writeout. We leave the page
675 * tagged as dirty in the radix tree so that a concurrent write-for-sync
676 * can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
677 * implementation will run either set_page_writeback() or set_page_dirty(),
678 * at which stage we bring the page's dirty flag and radix-tree dirty tag
681 * This incoherency between the page's dirty flag and radix-tree tag is
682 * unfortunate, but it only exists while the page is locked.
684 int clear_page_dirty_for_io(struct page *page)
686 struct address_space *mapping = page_mapping(page);
689 if (TestClearPageDirty(page)) {
690 if (!mapping->backing_dev_info->memory_backed)
691 dec_page_state(nr_dirty);
696 return TestClearPageDirty(page);
698 EXPORT_SYMBOL(clear_page_dirty_for_io);
701 * Clear a page's dirty flag while ignoring dirty memory accounting
703 int __clear_page_dirty(struct page *page)
705 struct address_space *mapping = page_mapping(page);
710 spin_lock_irqsave(&mapping->tree_lock, flags);
711 if (TestClearPageDirty(page)) {
712 radix_tree_tag_clear(&mapping->page_tree,
714 PAGECACHE_TAG_DIRTY);
715 spin_unlock_irqrestore(&mapping->tree_lock, flags);
718 spin_unlock_irqrestore(&mapping->tree_lock, flags);
721 return TestClearPageDirty(page);
724 int test_clear_page_writeback(struct page *page)
726 struct address_space *mapping = page_mapping(page);
732 spin_lock_irqsave(&mapping->tree_lock, flags);
733 ret = TestClearPageWriteback(page);
735 radix_tree_tag_clear(&mapping->page_tree,
737 PAGECACHE_TAG_WRITEBACK);
738 spin_unlock_irqrestore(&mapping->tree_lock, flags);
740 ret = TestClearPageWriteback(page);
745 int test_set_page_writeback(struct page *page)
747 struct address_space *mapping = page_mapping(page);
753 spin_lock_irqsave(&mapping->tree_lock, flags);
754 ret = TestSetPageWriteback(page);
756 radix_tree_tag_set(&mapping->page_tree,
758 PAGECACHE_TAG_WRITEBACK);
759 if (!PageDirty(page))
760 radix_tree_tag_clear(&mapping->page_tree,
762 PAGECACHE_TAG_DIRTY);
763 spin_unlock_irqrestore(&mapping->tree_lock, flags);
765 ret = TestSetPageWriteback(page);
770 EXPORT_SYMBOL(test_set_page_writeback);
773 * Return true if any of the pages in the mapping are marged with the
776 int mapping_tagged(struct address_space *mapping, int tag)
781 spin_lock_irqsave(&mapping->tree_lock, flags);
782 ret = radix_tree_tagged(&mapping->page_tree, tag);
783 spin_unlock_irqrestore(&mapping->tree_lock, flags);
786 EXPORT_SYMBOL(mapping_tagged);