mm: per device dirty threshold
[powerpc.git] / mm / page-writeback.c
1 /*
2  * mm/page-writeback.c
3  *
4  * Copyright (C) 2002, Linus Torvalds.
5  * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
6  *
7  * Contains functions related to writing back dirty pages at the
8  * address_space level.
9  *
10  * 10Apr2002    akpm@zip.com.au
11  *              Initial version
12  */
13
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/spinlock.h>
17 #include <linux/fs.h>
18 #include <linux/mm.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
38 /*
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.
44  */
45 #define MAX_WRITEBACK_PAGES     1024
46
47 /*
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.
50  */
51 static long ratelimit_pages = 32;
52
53 /*
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.
58  */
59 static inline long sync_writeback_pages(void)
60 {
61         return ratelimit_pages + ratelimit_pages / 2;
62 }
63
64 /* The following parameters are exported via /proc/sys/vm */
65
66 /*
67  * Start background writeback (via pdflush) at this percentage
68  */
69 int dirty_background_ratio = 5;
70
71 /*
72  * The generator of dirty data starts writeback at this percentage
73  */
74 int vm_dirty_ratio = 10;
75
76 /*
77  * The interval between `kupdate'-style writebacks, in jiffies
78  */
79 int dirty_writeback_interval = 5 * HZ;
80
81 /*
82  * The longest number of jiffies for which data is allowed to remain dirty
83  */
84 int dirty_expire_interval = 30 * HZ;
85
86 /*
87  * Flag that makes the machine dump writes/reads and block dirtyings.
88  */
89 int block_dump;
90
91 /*
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.
94  */
95 int laptop_mode;
96
97 EXPORT_SYMBOL(laptop_mode);
98
99 /* End of sysctl-exported parameters */
100
101
102 static void background_writeout(unsigned long _min_pages);
103
104 /*
105  * Scale the writeback cache size proportional to the relative writeout speeds.
106  *
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
110  * share.
111  *
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.
114  *
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.
118  *
119  */
120 static struct prop_descriptor vm_completions;
121
122 static unsigned long determine_dirtyable_memory(void);
123
124 /*
125  * couple the period to the dirty_ratio:
126  *
127  *   period/2 ~ roundup_pow_of_two(dirty limit)
128  */
129 static int calc_period_shift(void)
130 {
131         unsigned long dirty_total;
132
133         dirty_total = (vm_dirty_ratio * determine_dirtyable_memory()) / 100;
134         return 2 + ilog2(dirty_total - 1);
135 }
136
137 /*
138  * update the period when the dirty ratio changes.
139  */
140 int dirty_ratio_handler(struct ctl_table *table, int write,
141                 struct file *filp, void __user *buffer, size_t *lenp,
142                 loff_t *ppos)
143 {
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);
149         }
150         return ret;
151 }
152
153 /*
154  * Increment the BDI's writeout completion count and the global writeout
155  * completion count. Called from test_clear_page_writeback().
156  */
157 static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
158 {
159         __prop_inc_percpu(&vm_completions, &bdi->completions);
160 }
161
162 /*
163  * Obtain an accurate fraction of the BDI's portion.
164  */
165 static void bdi_writeout_fraction(struct backing_dev_info *bdi,
166                 long *numerator, long *denominator)
167 {
168         if (bdi_cap_writeback_dirty(bdi)) {
169                 prop_fraction_percpu(&vm_completions, &bdi->completions,
170                                 numerator, denominator);
171         } else {
172                 *numerator = 0;
173                 *denominator = 1;
174         }
175 }
176
177 /*
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.
181  */
182 static void
183 clip_bdi_dirty_limit(struct backing_dev_info *bdi, long dirty, long *pbdi_dirty)
184 {
185         long avail_dirty;
186
187         avail_dirty = dirty -
188                 (global_page_state(NR_FILE_DIRTY) +
189                  global_page_state(NR_WRITEBACK) +
190                  global_page_state(NR_UNSTABLE_NFS));
191
192         if (avail_dirty < 0)
193                 avail_dirty = 0;
194
195         avail_dirty += bdi_stat(bdi, BDI_RECLAIMABLE) +
196                 bdi_stat(bdi, BDI_WRITEBACK);
197
198         *pbdi_dirty = min(*pbdi_dirty, avail_dirty);
199 }
200
201 /*
202  * Work out the current dirty-memory clamping and background writeout
203  * thresholds.
204  *
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.
209  *
210  * We only allow 1/2 of the currently-unmapped memory to be dirtied.
211  *
212  * We don't permit the clamping level to fall below 5% - that is getting rather
213  * excessive.
214  *
215  * We make sure that the background writeout level is below the adjusted
216  * clamping level.
217  */
218
219 static unsigned long highmem_dirtyable_memory(unsigned long total)
220 {
221 #ifdef CONFIG_HIGHMEM
222         int node;
223         unsigned long x = 0;
224
225         for_each_node_state(node, N_HIGH_MEMORY) {
226                 struct zone *z =
227                         &NODE_DATA(node)->node_zones[ZONE_HIGHMEM];
228
229                 x += zone_page_state(z, NR_FREE_PAGES)
230                         + zone_page_state(z, NR_INACTIVE)
231                         + zone_page_state(z, NR_ACTIVE);
232         }
233         /*
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.
238          */
239         return min(x, total);
240 #else
241         return 0;
242 #endif
243 }
244
245 static unsigned long determine_dirtyable_memory(void)
246 {
247         unsigned long x;
248
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 */
254 }
255
256 static void
257 get_dirty_limits(long *pbackground, long *pdirty, long *pbdi_dirty,
258                  struct backing_dev_info *bdi)
259 {
260         int background_ratio;           /* Percentages */
261         int dirty_ratio;
262         int unmapped_ratio;
263         long background;
264         long dirty;
265         unsigned long available_memory = determine_dirtyable_memory();
266         struct task_struct *tsk;
267
268         unmapped_ratio = 100 - ((global_page_state(NR_FILE_MAPPED) +
269                                 global_page_state(NR_ANON_PAGES)) * 100) /
270                                         available_memory;
271
272         dirty_ratio = vm_dirty_ratio;
273         if (dirty_ratio > unmapped_ratio / 2)
274                 dirty_ratio = unmapped_ratio / 2;
275
276         if (dirty_ratio < 5)
277                 dirty_ratio = 5;
278
279         background_ratio = dirty_background_ratio;
280         if (background_ratio >= dirty_ratio)
281                 background_ratio = dirty_ratio / 2;
282
283         background = (background_ratio * available_memory) / 100;
284         dirty = (dirty_ratio * available_memory) / 100;
285         tsk = current;
286         if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
287                 background += background / 4;
288                 dirty += dirty / 4;
289         }
290         *pbackground = background;
291         *pdirty = dirty;
292
293         if (bdi) {
294                 u64 bdi_dirty = dirty;
295                 long numerator, denominator;
296
297                 /*
298                  * Calculate this BDI's share of the dirty ratio.
299                  */
300                 bdi_writeout_fraction(bdi, &numerator, &denominator);
301
302                 bdi_dirty *= numerator;
303                 do_div(bdi_dirty, denominator);
304
305                 *pbdi_dirty = bdi_dirty;
306                 clip_bdi_dirty_limit(bdi, dirty, pbdi_dirty);
307         }
308 }
309
310 /*
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
315  * writeout.
316  */
317 static void balance_dirty_pages(struct address_space *mapping)
318 {
319         long bdi_nr_reclaimable;
320         long bdi_nr_writeback;
321         long background_thresh;
322         long dirty_thresh;
323         long bdi_thresh;
324         unsigned long pages_written = 0;
325         unsigned long write_chunk = sync_writeback_pages();
326
327         struct backing_dev_info *bdi = mapping->backing_dev_info;
328
329         for (;;) {
330                 struct writeback_control wbc = {
331                         .bdi            = bdi,
332                         .sync_mode      = WB_SYNC_NONE,
333                         .older_than_this = NULL,
334                         .nr_to_write    = write_chunk,
335                         .range_cyclic   = 1,
336                 };
337
338                 get_dirty_limits(&background_thresh, &dirty_thresh,
339                                 &bdi_thresh, bdi);
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)
343                         break;
344
345                 if (!bdi->dirty_exceeded)
346                         bdi->dirty_exceeded = 1;
347
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.
353                  */
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,
358                                        &bdi_thresh, bdi);
359                 }
360
361                 /*
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.
365                  *
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
369                  * deltas.
370                  */
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);
377                 }
378
379                 if (bdi_nr_reclaimable + bdi_nr_writeback <= bdi_thresh)
380                         break;
381                 if (pages_written >= write_chunk)
382                         break;          /* We've done our duty */
383
384                 congestion_wait(WRITE, HZ/10);
385         }
386
387         if (bdi_nr_reclaimable + bdi_nr_writeback < bdi_thresh &&
388                         bdi->dirty_exceeded)
389                 bdi->dirty_exceeded = 0;
390
391         if (writeback_in_progress(bdi))
392                 return;         /* pdflush is already working this queue */
393
394         /*
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.
398          *
399          * In normal mode, we start background writeout at the lower
400          * background_thresh, to keep the amount of dirty memory low.
401          */
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);
407 }
408
409 void set_page_dirty_balance(struct page *page, int page_mkwrite)
410 {
411         if (set_page_dirty(page) || page_mkwrite) {
412                 struct address_space *mapping = page_mapping(page);
413
414                 if (mapping)
415                         balance_dirty_pages_ratelimited(mapping);
416         }
417 }
418
419 /**
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
423  *
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.
427  *
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.
432  */
433 void balance_dirty_pages_ratelimited_nr(struct address_space *mapping,
434                                         unsigned long nr_pages_dirtied)
435 {
436         static DEFINE_PER_CPU(unsigned long, ratelimits) = 0;
437         unsigned long ratelimit;
438         unsigned long *p;
439
440         ratelimit = ratelimit_pages;
441         if (mapping->backing_dev_info->dirty_exceeded)
442                 ratelimit = 8;
443
444         /*
445          * Check the rate limiting. Also, we do not want to throttle real-time
446          * tasks in balance_dirty_pages(). Period.
447          */
448         preempt_disable();
449         p =  &__get_cpu_var(ratelimits);
450         *p += nr_pages_dirtied;
451         if (unlikely(*p >= ratelimit)) {
452                 *p = 0;
453                 preempt_enable();
454                 balance_dirty_pages(mapping);
455                 return;
456         }
457         preempt_enable();
458 }
459 EXPORT_SYMBOL(balance_dirty_pages_ratelimited_nr);
460
461 void throttle_vm_writeout(gfp_t gfp_mask)
462 {
463         long background_thresh;
464         long dirty_thresh;
465
466         if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO)) {
467                 /*
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.
471                  */
472                 congestion_wait(WRITE, HZ/10);
473                 return;
474         }
475
476         for ( ; ; ) {
477                 get_dirty_limits(&background_thresh, &dirty_thresh, NULL, NULL);
478
479                 /*
480                  * Boost the allowable dirty threshold a bit for page
481                  * allocators so they don't get DoS'ed by heavy writers
482                  */
483                 dirty_thresh += dirty_thresh / 10;      /* wheeee... */
484
485                 if (global_page_state(NR_UNSTABLE_NFS) +
486                         global_page_state(NR_WRITEBACK) <= dirty_thresh)
487                                 break;
488                 congestion_wait(WRITE, HZ/10);
489         }
490 }
491
492 /*
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.
495  */
496 static void background_writeout(unsigned long _min_pages)
497 {
498         long min_pages = _min_pages;
499         struct writeback_control wbc = {
500                 .bdi            = NULL,
501                 .sync_mode      = WB_SYNC_NONE,
502                 .older_than_this = NULL,
503                 .nr_to_write    = 0,
504                 .nonblocking    = 1,
505                 .range_cyclic   = 1,
506         };
507
508         for ( ; ; ) {
509                 long background_thresh;
510                 long dirty_thresh;
511
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
515                                 && min_pages <= 0)
516                         break;
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)
526                                 break;
527                 }
528         }
529 }
530
531 /*
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.
535  */
536 int wakeup_pdflush(long nr_pages)
537 {
538         if (nr_pages == 0)
539                 nr_pages = global_page_state(NR_FILE_DIRTY) +
540                                 global_page_state(NR_UNSTABLE_NFS);
541         return pdflush_operation(background_writeout, nr_pages);
542 }
543
544 static void wb_timer_fn(unsigned long unused);
545 static void laptop_timer_fn(unsigned long unused);
546
547 static DEFINE_TIMER(wb_timer, wb_timer_fn, 0, 0);
548 static DEFINE_TIMER(laptop_mode_wb_timer, laptop_timer_fn, 0, 0);
549
550 /*
551  * Periodic writeback of "old" data.
552  *
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.
557  *
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
560  * one-second gap.
561  *
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.
564  */
565 static void wb_kupdate(unsigned long arg)
566 {
567         unsigned long oldest_jif;
568         unsigned long start_jif;
569         unsigned long next_jif;
570         long nr_to_write;
571         struct writeback_control wbc = {
572                 .bdi            = NULL,
573                 .sync_mode      = WB_SYNC_NONE,
574                 .older_than_this = &oldest_jif,
575                 .nr_to_write    = 0,
576                 .nonblocking    = 1,
577                 .for_kupdate    = 1,
578                 .range_cyclic   = 1,
579         };
580
581         sync_supers();
582
583         oldest_jif = jiffies - dirty_expire_interval;
584         start_jif = jiffies;
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);
596                         else
597                                 break;  /* All the old data is written */
598                 }
599                 nr_to_write -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
600         }
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);
605 }
606
607 /*
608  * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
609  */
610 int dirty_writeback_centisecs_handler(ctl_table *table, int write,
611         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
612 {
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);
616         else
617                 del_timer(&wb_timer);
618         return 0;
619 }
620
621 static void wb_timer_fn(unsigned long unused)
622 {
623         if (pdflush_operation(wb_kupdate, 0) < 0)
624                 mod_timer(&wb_timer, jiffies + HZ); /* delay 1 second */
625 }
626
627 static void laptop_flush(unsigned long unused)
628 {
629         sys_sync();
630 }
631
632 static void laptop_timer_fn(unsigned long unused)
633 {
634         pdflush_operation(laptop_flush, 0);
635 }
636
637 /*
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.
641  */
642 void laptop_io_completion(void)
643 {
644         mod_timer(&laptop_mode_wb_timer, jiffies + laptop_mode);
645 }
646
647 /*
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.
651  */
652 void laptop_sync_completion(void)
653 {
654         del_timer(&laptop_mode_wb_timer);
655 }
656
657 /*
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.
662  *
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.
666  *
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.
672  */
673
674 void writeback_set_ratelimit(void)
675 {
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;
681 }
682
683 static int __cpuinit
684 ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
685 {
686         writeback_set_ratelimit();
687         return NOTIFY_DONE;
688 }
689
690 static struct notifier_block __cpuinitdata ratelimit_nb = {
691         .notifier_call  = ratelimit_handler,
692         .next           = NULL,
693 };
694
695 /*
696  * Called early on to tune the page writeback dirty limits.
697  *
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.
701  *
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.
709  *
710  * But we might still want to scale the dirty_ratio by how
711  * much memory the box has..
712  */
713 void __init page_writeback_init(void)
714 {
715         int shift;
716
717         mod_timer(&wb_timer, jiffies + dirty_writeback_interval);
718         writeback_set_ratelimit();
719         register_cpu_notifier(&ratelimit_nb);
720
721         shift = calc_period_shift();
722         prop_descriptor_init(&vm_completions, shift);
723 }
724
725 /**
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
731  *
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.
739  */
740 int write_cache_pages(struct address_space *mapping,
741                       struct writeback_control *wbc, writepage_t writepage,
742                       void *data)
743 {
744         struct backing_dev_info *bdi = mapping->backing_dev_info;
745         int ret = 0;
746         int done = 0;
747         struct pagevec pvec;
748         int nr_pages;
749         pgoff_t index;
750         pgoff_t end;            /* Inclusive */
751         int scanned = 0;
752         int range_whole = 0;
753
754         if (wbc->nonblocking && bdi_write_congested(bdi)) {
755                 wbc->encountered_congestion = 1;
756                 return 0;
757         }
758
759         pagevec_init(&pvec, 0);
760         if (wbc->range_cyclic) {
761                 index = mapping->writeback_index; /* Start from prev offset */
762                 end = -1;
763         } else {
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)
767                         range_whole = 1;
768                 scanned = 1;
769         }
770 retry:
771         while (!done && (index <= end) &&
772                (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
773                                               PAGECACHE_TAG_DIRTY,
774                                               min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1))) {
775                 unsigned i;
776
777                 scanned = 1;
778                 for (i = 0; i < nr_pages; i++) {
779                         struct page *page = pvec.pages[i];
780
781                         /*
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
786                          * mapping
787                          */
788                         lock_page(page);
789
790                         if (unlikely(page->mapping != mapping)) {
791                                 unlock_page(page);
792                                 continue;
793                         }
794
795                         if (!wbc->range_cyclic && page->index > end) {
796                                 done = 1;
797                                 unlock_page(page);
798                                 continue;
799                         }
800
801                         if (wbc->sync_mode != WB_SYNC_NONE)
802                                 wait_on_page_writeback(page);
803
804                         if (PageWriteback(page) ||
805                             !clear_page_dirty_for_io(page)) {
806                                 unlock_page(page);
807                                 continue;
808                         }
809
810                         ret = (*writepage)(page, wbc, data);
811
812                         if (unlikely(ret == AOP_WRITEPAGE_ACTIVATE))
813                                 unlock_page(page);
814                         if (ret || (--(wbc->nr_to_write) <= 0))
815                                 done = 1;
816                         if (wbc->nonblocking && bdi_write_congested(bdi)) {
817                                 wbc->encountered_congestion = 1;
818                                 done = 1;
819                         }
820                 }
821                 pagevec_release(&pvec);
822                 cond_resched();
823         }
824         if (!scanned && !done) {
825                 /*
826                  * We hit the last page and there is more work to be done: wrap
827                  * back to the start of the file
828                  */
829                 scanned = 1;
830                 index = 0;
831                 goto retry;
832         }
833         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
834                 mapping->writeback_index = index;
835         return ret;
836 }
837 EXPORT_SYMBOL(write_cache_pages);
838
839 /*
840  * Function used by generic_writepages to call the real writepage
841  * function and set the mapping flags on error
842  */
843 static int __writepage(struct page *page, struct writeback_control *wbc,
844                        void *data)
845 {
846         struct address_space *mapping = data;
847         int ret = mapping->a_ops->writepage(page, wbc);
848         mapping_set_error(mapping, ret);
849         return ret;
850 }
851
852 /**
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
856  *
857  * This is a library function, which implements the writepages()
858  * address_space_operation.
859  */
860 int generic_writepages(struct address_space *mapping,
861                        struct writeback_control *wbc)
862 {
863         /* deal with chardevs and other special file */
864         if (!mapping->a_ops->writepage)
865                 return 0;
866
867         return write_cache_pages(mapping, wbc, __writepage, mapping);
868 }
869
870 EXPORT_SYMBOL(generic_writepages);
871
872 int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
873 {
874         int ret;
875
876         if (wbc->nr_to_write <= 0)
877                 return 0;
878         wbc->for_writepages = 1;
879         if (mapping->a_ops->writepages)
880                 ret = mapping->a_ops->writepages(mapping, wbc);
881         else
882                 ret = generic_writepages(mapping, wbc);
883         wbc->for_writepages = 0;
884         return ret;
885 }
886
887 /**
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
891  *
892  * The page must be locked by the caller and will be unlocked upon return.
893  *
894  * write_one_page() returns a negative error code if I/O failed.
895  */
896 int write_one_page(struct page *page, int wait)
897 {
898         struct address_space *mapping = page->mapping;
899         int ret = 0;
900         struct writeback_control wbc = {
901                 .sync_mode = WB_SYNC_ALL,
902                 .nr_to_write = 1,
903         };
904
905         BUG_ON(!PageLocked(page));
906
907         if (wait)
908                 wait_on_page_writeback(page);
909
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);
915                         if (PageError(page))
916                                 ret = -EIO;
917                 }
918                 page_cache_release(page);
919         } else {
920                 unlock_page(page);
921         }
922         return ret;
923 }
924 EXPORT_SYMBOL(write_one_page);
925
926 /*
927  * For address_spaces which do not use buffers nor write back.
928  */
929 int __set_page_dirty_no_writeback(struct page *page)
930 {
931         if (!PageDirty(page))
932                 SetPageDirty(page);
933         return 0;
934 }
935
936 /*
937  * For address_spaces which do not use buffers.  Just tag the page as dirty in
938  * its radix tree.
939  *
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.
943  *
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.
947  *
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.
950  */
951 int __set_page_dirty_nobuffers(struct page *page)
952 {
953         if (!TestSetPageDirty(page)) {
954                 struct address_space *mapping = page_mapping(page);
955                 struct address_space *mapping2;
956
957                 if (!mapping)
958                         return 1;
959
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,
968                                                 BDI_RECLAIMABLE);
969                                 task_io_account_write(PAGE_CACHE_SIZE);
970                         }
971                         radix_tree_tag_set(&mapping->page_tree,
972                                 page_index(page), PAGECACHE_TAG_DIRTY);
973                 }
974                 write_unlock_irq(&mapping->tree_lock);
975                 if (mapping->host) {
976                         /* !PageAnon && !swapper_space */
977                         __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
978                 }
979                 return 1;
980         }
981         return 0;
982 }
983 EXPORT_SYMBOL(__set_page_dirty_nobuffers);
984
985 /*
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
989  */
990 int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
991 {
992         wbc->pages_skipped++;
993         return __set_page_dirty_nobuffers(page);
994 }
995 EXPORT_SYMBOL(redirty_page_for_writepage);
996
997 /*
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.
1000  */
1001 int fastcall set_page_dirty(struct page *page)
1002 {
1003         struct address_space *mapping = page_mapping(page);
1004
1005         if (likely(mapping)) {
1006                 int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
1007 #ifdef CONFIG_BLOCK
1008                 if (!spd)
1009                         spd = __set_page_dirty_buffers;
1010 #endif
1011                 return (*spd)(page);
1012         }
1013         if (!PageDirty(page)) {
1014                 if (!TestSetPageDirty(page))
1015                         return 1;
1016         }
1017         return 0;
1018 }
1019 EXPORT_SYMBOL(set_page_dirty);
1020
1021 /*
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.
1025  *
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.
1028  *
1029  * In other cases, the page should be locked before running set_page_dirty().
1030  */
1031 int set_page_dirty_lock(struct page *page)
1032 {
1033         int ret;
1034
1035         lock_page_nosync(page);
1036         ret = set_page_dirty(page);
1037         unlock_page(page);
1038         return ret;
1039 }
1040 EXPORT_SYMBOL(set_page_dirty_lock);
1041
1042 /*
1043  * Clear a page's dirty flag, while caring for dirty memory accounting.
1044  * Returns true if the page was previously dirty.
1045  *
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
1051  * back into sync.
1052  *
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.
1055  */
1056 int clear_page_dirty_for_io(struct page *page)
1057 {
1058         struct address_space *mapping = page_mapping(page);
1059
1060         BUG_ON(!PageLocked(page));
1061
1062         ClearPageReclaim(page);
1063         if (mapping && mapping_cap_account_dirty(mapping)) {
1064                 /*
1065                  * Yes, Virginia, this is indeed insane.
1066                  *
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.
1074                  *
1075                  * This way we avoid all nasty races with the
1076                  * dirty bit in multiple places and clearing
1077                  * them concurrently from different threads.
1078                  *
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
1083                  * avoid races.
1084                  *
1085                  * We basically use the page "master dirty bit"
1086                  * as a serialization point for all the different
1087                  * threads doing their things.
1088                  */
1089                 if (page_mkclean(page))
1090                         set_page_dirty(page);
1091                 /*
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.
1100                  */
1101                 if (TestClearPageDirty(page)) {
1102                         dec_zone_page_state(page, NR_FILE_DIRTY);
1103                         dec_bdi_stat(mapping->backing_dev_info,
1104                                         BDI_RECLAIMABLE);
1105                         return 1;
1106                 }
1107                 return 0;
1108         }
1109         return TestClearPageDirty(page);
1110 }
1111 EXPORT_SYMBOL(clear_page_dirty_for_io);
1112
1113 int test_clear_page_writeback(struct page *page)
1114 {
1115         struct address_space *mapping = page_mapping(page);
1116         int ret;
1117
1118         if (mapping) {
1119                 struct backing_dev_info *bdi = mapping->backing_dev_info;
1120                 unsigned long flags;
1121
1122                 write_lock_irqsave(&mapping->tree_lock, flags);
1123                 ret = TestClearPageWriteback(page);
1124                 if (ret) {
1125                         radix_tree_tag_clear(&mapping->page_tree,
1126                                                 page_index(page),
1127                                                 PAGECACHE_TAG_WRITEBACK);
1128                         if (bdi_cap_writeback_dirty(bdi)) {
1129                                 __dec_bdi_stat(bdi, BDI_WRITEBACK);
1130                                 __bdi_writeout_inc(bdi);
1131                         }
1132                 }
1133                 write_unlock_irqrestore(&mapping->tree_lock, flags);
1134         } else {
1135                 ret = TestClearPageWriteback(page);
1136         }
1137         if (ret)
1138                 dec_zone_page_state(page, NR_WRITEBACK);
1139         return ret;
1140 }
1141
1142 int test_set_page_writeback(struct page *page)
1143 {
1144         struct address_space *mapping = page_mapping(page);
1145         int ret;
1146
1147         if (mapping) {
1148                 struct backing_dev_info *bdi = mapping->backing_dev_info;
1149                 unsigned long flags;
1150
1151                 write_lock_irqsave(&mapping->tree_lock, flags);
1152                 ret = TestSetPageWriteback(page);
1153                 if (!ret) {
1154                         radix_tree_tag_set(&mapping->page_tree,
1155                                                 page_index(page),
1156                                                 PAGECACHE_TAG_WRITEBACK);
1157                         if (bdi_cap_writeback_dirty(bdi))
1158                                 __inc_bdi_stat(bdi, BDI_WRITEBACK);
1159                 }
1160                 if (!PageDirty(page))
1161                         radix_tree_tag_clear(&mapping->page_tree,
1162                                                 page_index(page),
1163                                                 PAGECACHE_TAG_DIRTY);
1164                 write_unlock_irqrestore(&mapping->tree_lock, flags);
1165         } else {
1166                 ret = TestSetPageWriteback(page);
1167         }
1168         if (!ret)
1169                 inc_zone_page_state(page, NR_WRITEBACK);
1170         return ret;
1171
1172 }
1173 EXPORT_SYMBOL(test_set_page_writeback);
1174
1175 /*
1176  * Return true if any of the pages in the mapping are marked with the
1177  * passed tag.
1178  */
1179 int mapping_tagged(struct address_space *mapping, int tag)
1180 {
1181         int ret;
1182         rcu_read_lock();
1183         ret = radix_tree_tagged(&mapping->page_tree, tag);
1184         rcu_read_unlock();
1185         return ret;
1186 }
1187 EXPORT_SYMBOL(mapping_tagged);