ide-scsi: use print_hex_dump from <linux/kernel.h>
[linux-2.6] / 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_SYNC 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 static struct prop_descriptor vm_dirties;
122
123 static unsigned long determine_dirtyable_memory(void);
124
125 /*
126  * couple the period to the dirty_ratio:
127  *
128  *   period/2 ~ roundup_pow_of_two(dirty limit)
129  */
130 static int calc_period_shift(void)
131 {
132         unsigned long dirty_total;
133
134         dirty_total = (vm_dirty_ratio * determine_dirtyable_memory()) / 100;
135         return 2 + ilog2(dirty_total - 1);
136 }
137
138 /*
139  * update the period when the dirty ratio changes.
140  */
141 int dirty_ratio_handler(struct ctl_table *table, int write,
142                 struct file *filp, void __user *buffer, size_t *lenp,
143                 loff_t *ppos)
144 {
145         int old_ratio = vm_dirty_ratio;
146         int ret = proc_dointvec_minmax(table, write, filp, buffer, lenp, ppos);
147         if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
148                 int shift = calc_period_shift();
149                 prop_change_shift(&vm_completions, shift);
150                 prop_change_shift(&vm_dirties, shift);
151         }
152         return ret;
153 }
154
155 /*
156  * Increment the BDI's writeout completion count and the global writeout
157  * completion count. Called from test_clear_page_writeback().
158  */
159 static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
160 {
161         __prop_inc_percpu(&vm_completions, &bdi->completions);
162 }
163
164 static inline void task_dirty_inc(struct task_struct *tsk)
165 {
166         prop_inc_single(&vm_dirties, &tsk->dirties);
167 }
168
169 /*
170  * Obtain an accurate fraction of the BDI's portion.
171  */
172 static void bdi_writeout_fraction(struct backing_dev_info *bdi,
173                 long *numerator, long *denominator)
174 {
175         if (bdi_cap_writeback_dirty(bdi)) {
176                 prop_fraction_percpu(&vm_completions, &bdi->completions,
177                                 numerator, denominator);
178         } else {
179                 *numerator = 0;
180                 *denominator = 1;
181         }
182 }
183
184 /*
185  * Clip the earned share of dirty pages to that which is actually available.
186  * This avoids exceeding the total dirty_limit when the floating averages
187  * fluctuate too quickly.
188  */
189 static void
190 clip_bdi_dirty_limit(struct backing_dev_info *bdi, long dirty, long *pbdi_dirty)
191 {
192         long avail_dirty;
193
194         avail_dirty = dirty -
195                 (global_page_state(NR_FILE_DIRTY) +
196                  global_page_state(NR_WRITEBACK) +
197                  global_page_state(NR_UNSTABLE_NFS));
198
199         if (avail_dirty < 0)
200                 avail_dirty = 0;
201
202         avail_dirty += bdi_stat(bdi, BDI_RECLAIMABLE) +
203                 bdi_stat(bdi, BDI_WRITEBACK);
204
205         *pbdi_dirty = min(*pbdi_dirty, avail_dirty);
206 }
207
208 static inline void task_dirties_fraction(struct task_struct *tsk,
209                 long *numerator, long *denominator)
210 {
211         prop_fraction_single(&vm_dirties, &tsk->dirties,
212                                 numerator, denominator);
213 }
214
215 /*
216  * scale the dirty limit
217  *
218  * task specific dirty limit:
219  *
220  *   dirty -= (dirty/8) * p_{t}
221  */
222 void task_dirty_limit(struct task_struct *tsk, long *pdirty)
223 {
224         long numerator, denominator;
225         long dirty = *pdirty;
226         u64 inv = dirty >> 3;
227
228         task_dirties_fraction(tsk, &numerator, &denominator);
229         inv *= numerator;
230         do_div(inv, denominator);
231
232         dirty -= inv;
233         if (dirty < *pdirty/2)
234                 dirty = *pdirty/2;
235
236         *pdirty = dirty;
237 }
238
239 /*
240  * Work out the current dirty-memory clamping and background writeout
241  * thresholds.
242  *
243  * The main aim here is to lower them aggressively if there is a lot of mapped
244  * memory around.  To avoid stressing page reclaim with lots of unreclaimable
245  * pages.  It is better to clamp down on writers than to start swapping, and
246  * performing lots of scanning.
247  *
248  * We only allow 1/2 of the currently-unmapped memory to be dirtied.
249  *
250  * We don't permit the clamping level to fall below 5% - that is getting rather
251  * excessive.
252  *
253  * We make sure that the background writeout level is below the adjusted
254  * clamping level.
255  */
256
257 static unsigned long highmem_dirtyable_memory(unsigned long total)
258 {
259 #ifdef CONFIG_HIGHMEM
260         int node;
261         unsigned long x = 0;
262
263         for_each_node_state(node, N_HIGH_MEMORY) {
264                 struct zone *z =
265                         &NODE_DATA(node)->node_zones[ZONE_HIGHMEM];
266
267                 x += zone_page_state(z, NR_FREE_PAGES)
268                         + zone_page_state(z, NR_INACTIVE)
269                         + zone_page_state(z, NR_ACTIVE);
270         }
271         /*
272          * Make sure that the number of highmem pages is never larger
273          * than the number of the total dirtyable memory. This can only
274          * occur in very strange VM situations but we want to make sure
275          * that this does not occur.
276          */
277         return min(x, total);
278 #else
279         return 0;
280 #endif
281 }
282
283 static unsigned long determine_dirtyable_memory(void)
284 {
285         unsigned long x;
286
287         x = global_page_state(NR_FREE_PAGES)
288                 + global_page_state(NR_INACTIVE)
289                 + global_page_state(NR_ACTIVE);
290         x -= highmem_dirtyable_memory(x);
291         return x + 1;   /* Ensure that we never return 0 */
292 }
293
294 static void
295 get_dirty_limits(long *pbackground, long *pdirty, long *pbdi_dirty,
296                  struct backing_dev_info *bdi)
297 {
298         int background_ratio;           /* Percentages */
299         int dirty_ratio;
300         long background;
301         long dirty;
302         unsigned long available_memory = determine_dirtyable_memory();
303         struct task_struct *tsk;
304
305         dirty_ratio = vm_dirty_ratio;
306         if (dirty_ratio < 5)
307                 dirty_ratio = 5;
308
309         background_ratio = dirty_background_ratio;
310         if (background_ratio >= dirty_ratio)
311                 background_ratio = dirty_ratio / 2;
312
313         background = (background_ratio * available_memory) / 100;
314         dirty = (dirty_ratio * available_memory) / 100;
315         tsk = current;
316         if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
317                 background += background / 4;
318                 dirty += dirty / 4;
319         }
320         *pbackground = background;
321         *pdirty = dirty;
322
323         if (bdi) {
324                 u64 bdi_dirty = dirty;
325                 long numerator, denominator;
326
327                 /*
328                  * Calculate this BDI's share of the dirty ratio.
329                  */
330                 bdi_writeout_fraction(bdi, &numerator, &denominator);
331
332                 bdi_dirty *= numerator;
333                 do_div(bdi_dirty, denominator);
334
335                 *pbdi_dirty = bdi_dirty;
336                 clip_bdi_dirty_limit(bdi, dirty, pbdi_dirty);
337                 task_dirty_limit(current, pbdi_dirty);
338         }
339 }
340
341 /*
342  * balance_dirty_pages() must be called by processes which are generating dirty
343  * data.  It looks at the number of dirty pages in the machine and will force
344  * the caller to perform writeback if the system is over `vm_dirty_ratio'.
345  * If we're over `background_thresh' then pdflush is woken to perform some
346  * writeout.
347  */
348 static void balance_dirty_pages(struct address_space *mapping)
349 {
350         long nr_reclaimable, bdi_nr_reclaimable;
351         long nr_writeback, bdi_nr_writeback;
352         long background_thresh;
353         long dirty_thresh;
354         long bdi_thresh;
355         unsigned long pages_written = 0;
356         unsigned long write_chunk = sync_writeback_pages();
357
358         struct backing_dev_info *bdi = mapping->backing_dev_info;
359
360         for (;;) {
361                 struct writeback_control wbc = {
362                         .bdi            = bdi,
363                         .sync_mode      = WB_SYNC_NONE,
364                         .older_than_this = NULL,
365                         .nr_to_write    = write_chunk,
366                         .range_cyclic   = 1,
367                 };
368
369                 get_dirty_limits(&background_thresh, &dirty_thresh,
370                                 &bdi_thresh, bdi);
371
372                 nr_reclaimable = global_page_state(NR_FILE_DIRTY) +
373                                         global_page_state(NR_UNSTABLE_NFS);
374                 nr_writeback = global_page_state(NR_WRITEBACK);
375
376                 bdi_nr_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
377                 bdi_nr_writeback = bdi_stat(bdi, BDI_WRITEBACK);
378
379                 if (bdi_nr_reclaimable + bdi_nr_writeback <= bdi_thresh)
380                         break;
381
382                 /*
383                  * Throttle it only when the background writeback cannot
384                  * catch-up. This avoids (excessively) small writeouts
385                  * when the bdi limits are ramping up.
386                  */
387                 if (nr_reclaimable + nr_writeback <
388                                 (background_thresh + dirty_thresh) / 2)
389                         break;
390
391                 if (!bdi->dirty_exceeded)
392                         bdi->dirty_exceeded = 1;
393
394                 /* Note: nr_reclaimable denotes nr_dirty + nr_unstable.
395                  * Unstable writes are a feature of certain networked
396                  * filesystems (i.e. NFS) in which data may have been
397                  * written to the server's write cache, but has not yet
398                  * been flushed to permanent storage.
399                  */
400                 if (bdi_nr_reclaimable) {
401                         writeback_inodes(&wbc);
402                         pages_written += write_chunk - wbc.nr_to_write;
403                         get_dirty_limits(&background_thresh, &dirty_thresh,
404                                        &bdi_thresh, bdi);
405                 }
406
407                 /*
408                  * In order to avoid the stacked BDI deadlock we need
409                  * to ensure we accurately count the 'dirty' pages when
410                  * the threshold is low.
411                  *
412                  * Otherwise it would be possible to get thresh+n pages
413                  * reported dirty, even though there are thresh-m pages
414                  * actually dirty; with m+n sitting in the percpu
415                  * deltas.
416                  */
417                 if (bdi_thresh < 2*bdi_stat_error(bdi)) {
418                         bdi_nr_reclaimable = bdi_stat_sum(bdi, BDI_RECLAIMABLE);
419                         bdi_nr_writeback = bdi_stat_sum(bdi, BDI_WRITEBACK);
420                 } else if (bdi_nr_reclaimable) {
421                         bdi_nr_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
422                         bdi_nr_writeback = bdi_stat(bdi, BDI_WRITEBACK);
423                 }
424
425                 if (bdi_nr_reclaimable + bdi_nr_writeback <= bdi_thresh)
426                         break;
427                 if (pages_written >= write_chunk)
428                         break;          /* We've done our duty */
429
430                 congestion_wait(WRITE, HZ/10);
431         }
432
433         if (bdi_nr_reclaimable + bdi_nr_writeback < bdi_thresh &&
434                         bdi->dirty_exceeded)
435                 bdi->dirty_exceeded = 0;
436
437         if (writeback_in_progress(bdi))
438                 return;         /* pdflush is already working this queue */
439
440         /*
441          * In laptop mode, we wait until hitting the higher threshold before
442          * starting background writeout, and then write out all the way down
443          * to the lower threshold.  So slow writers cause minimal disk activity.
444          *
445          * In normal mode, we start background writeout at the lower
446          * background_thresh, to keep the amount of dirty memory low.
447          */
448         if ((laptop_mode && pages_written) ||
449                         (!laptop_mode && (global_page_state(NR_FILE_DIRTY)
450                                           + global_page_state(NR_UNSTABLE_NFS)
451                                           > background_thresh)))
452                 pdflush_operation(background_writeout, 0);
453 }
454
455 void set_page_dirty_balance(struct page *page, int page_mkwrite)
456 {
457         if (set_page_dirty(page) || page_mkwrite) {
458                 struct address_space *mapping = page_mapping(page);
459
460                 if (mapping)
461                         balance_dirty_pages_ratelimited(mapping);
462         }
463 }
464
465 /**
466  * balance_dirty_pages_ratelimited_nr - balance dirty memory state
467  * @mapping: address_space which was dirtied
468  * @nr_pages_dirtied: number of pages which the caller has just dirtied
469  *
470  * Processes which are dirtying memory should call in here once for each page
471  * which was newly dirtied.  The function will periodically check the system's
472  * dirty state and will initiate writeback if needed.
473  *
474  * On really big machines, get_writeback_state is expensive, so try to avoid
475  * calling it too often (ratelimiting).  But once we're over the dirty memory
476  * limit we decrease the ratelimiting by a lot, to prevent individual processes
477  * from overshooting the limit by (ratelimit_pages) each.
478  */
479 void balance_dirty_pages_ratelimited_nr(struct address_space *mapping,
480                                         unsigned long nr_pages_dirtied)
481 {
482         static DEFINE_PER_CPU(unsigned long, ratelimits) = 0;
483         unsigned long ratelimit;
484         unsigned long *p;
485
486         ratelimit = ratelimit_pages;
487         if (mapping->backing_dev_info->dirty_exceeded)
488                 ratelimit = 8;
489
490         /*
491          * Check the rate limiting. Also, we do not want to throttle real-time
492          * tasks in balance_dirty_pages(). Period.
493          */
494         preempt_disable();
495         p =  &__get_cpu_var(ratelimits);
496         *p += nr_pages_dirtied;
497         if (unlikely(*p >= ratelimit)) {
498                 *p = 0;
499                 preempt_enable();
500                 balance_dirty_pages(mapping);
501                 return;
502         }
503         preempt_enable();
504 }
505 EXPORT_SYMBOL(balance_dirty_pages_ratelimited_nr);
506
507 void throttle_vm_writeout(gfp_t gfp_mask)
508 {
509         long background_thresh;
510         long dirty_thresh;
511
512         for ( ; ; ) {
513                 get_dirty_limits(&background_thresh, &dirty_thresh, NULL, NULL);
514
515                 /*
516                  * Boost the allowable dirty threshold a bit for page
517                  * allocators so they don't get DoS'ed by heavy writers
518                  */
519                 dirty_thresh += dirty_thresh / 10;      /* wheeee... */
520
521                 if (global_page_state(NR_UNSTABLE_NFS) +
522                         global_page_state(NR_WRITEBACK) <= dirty_thresh)
523                                 break;
524                 congestion_wait(WRITE, HZ/10);
525
526                 /*
527                  * The caller might hold locks which can prevent IO completion
528                  * or progress in the filesystem.  So we cannot just sit here
529                  * waiting for IO to complete.
530                  */
531                 if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO))
532                         break;
533         }
534 }
535
536 /*
537  * writeback at least _min_pages, and keep writing until the amount of dirty
538  * memory is less than the background threshold, or until we're all clean.
539  */
540 static void background_writeout(unsigned long _min_pages)
541 {
542         long min_pages = _min_pages;
543         struct writeback_control wbc = {
544                 .bdi            = NULL,
545                 .sync_mode      = WB_SYNC_NONE,
546                 .older_than_this = NULL,
547                 .nr_to_write    = 0,
548                 .nonblocking    = 1,
549                 .range_cyclic   = 1,
550         };
551
552         for ( ; ; ) {
553                 long background_thresh;
554                 long dirty_thresh;
555
556                 get_dirty_limits(&background_thresh, &dirty_thresh, NULL, NULL);
557                 if (global_page_state(NR_FILE_DIRTY) +
558                         global_page_state(NR_UNSTABLE_NFS) < background_thresh
559                                 && min_pages <= 0)
560                         break;
561                 wbc.more_io = 0;
562                 wbc.encountered_congestion = 0;
563                 wbc.nr_to_write = MAX_WRITEBACK_PAGES;
564                 wbc.pages_skipped = 0;
565                 writeback_inodes(&wbc);
566                 min_pages -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
567                 if (wbc.nr_to_write > 0 || wbc.pages_skipped > 0) {
568                         /* Wrote less than expected */
569                         if (wbc.encountered_congestion || wbc.more_io)
570                                 congestion_wait(WRITE, HZ/10);
571                         else
572                                 break;
573                 }
574         }
575 }
576
577 /*
578  * Start writeback of `nr_pages' pages.  If `nr_pages' is zero, write back
579  * the whole world.  Returns 0 if a pdflush thread was dispatched.  Returns
580  * -1 if all pdflush threads were busy.
581  */
582 int wakeup_pdflush(long nr_pages)
583 {
584         if (nr_pages == 0)
585                 nr_pages = global_page_state(NR_FILE_DIRTY) +
586                                 global_page_state(NR_UNSTABLE_NFS);
587         return pdflush_operation(background_writeout, nr_pages);
588 }
589
590 static void wb_timer_fn(unsigned long unused);
591 static void laptop_timer_fn(unsigned long unused);
592
593 static DEFINE_TIMER(wb_timer, wb_timer_fn, 0, 0);
594 static DEFINE_TIMER(laptop_mode_wb_timer, laptop_timer_fn, 0, 0);
595
596 /*
597  * Periodic writeback of "old" data.
598  *
599  * Define "old": the first time one of an inode's pages is dirtied, we mark the
600  * dirtying-time in the inode's address_space.  So this periodic writeback code
601  * just walks the superblock inode list, writing back any inodes which are
602  * older than a specific point in time.
603  *
604  * Try to run once per dirty_writeback_interval.  But if a writeback event
605  * takes longer than a dirty_writeback_interval interval, then leave a
606  * one-second gap.
607  *
608  * older_than_this takes precedence over nr_to_write.  So we'll only write back
609  * all dirty pages if they are all attached to "old" mappings.
610  */
611 static void wb_kupdate(unsigned long arg)
612 {
613         unsigned long oldest_jif;
614         unsigned long start_jif;
615         unsigned long next_jif;
616         long nr_to_write;
617         struct writeback_control wbc = {
618                 .bdi            = NULL,
619                 .sync_mode      = WB_SYNC_NONE,
620                 .older_than_this = &oldest_jif,
621                 .nr_to_write    = 0,
622                 .nonblocking    = 1,
623                 .for_kupdate    = 1,
624                 .range_cyclic   = 1,
625         };
626
627         sync_supers();
628
629         oldest_jif = jiffies - dirty_expire_interval;
630         start_jif = jiffies;
631         next_jif = start_jif + dirty_writeback_interval;
632         nr_to_write = global_page_state(NR_FILE_DIRTY) +
633                         global_page_state(NR_UNSTABLE_NFS) +
634                         (inodes_stat.nr_inodes - inodes_stat.nr_unused);
635         while (nr_to_write > 0) {
636                 wbc.more_io = 0;
637                 wbc.encountered_congestion = 0;
638                 wbc.nr_to_write = MAX_WRITEBACK_PAGES;
639                 writeback_inodes(&wbc);
640                 if (wbc.nr_to_write > 0) {
641                         if (wbc.encountered_congestion || wbc.more_io)
642                                 congestion_wait(WRITE, HZ/10);
643                         else
644                                 break;  /* All the old data is written */
645                 }
646                 nr_to_write -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
647         }
648         if (time_before(next_jif, jiffies + HZ))
649                 next_jif = jiffies + HZ;
650         if (dirty_writeback_interval)
651                 mod_timer(&wb_timer, next_jif);
652 }
653
654 /*
655  * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
656  */
657 int dirty_writeback_centisecs_handler(ctl_table *table, int write,
658         struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
659 {
660         proc_dointvec_userhz_jiffies(table, write, file, buffer, length, ppos);
661         if (dirty_writeback_interval)
662                 mod_timer(&wb_timer, jiffies + dirty_writeback_interval);
663         else
664                 del_timer(&wb_timer);
665         return 0;
666 }
667
668 static void wb_timer_fn(unsigned long unused)
669 {
670         if (pdflush_operation(wb_kupdate, 0) < 0)
671                 mod_timer(&wb_timer, jiffies + HZ); /* delay 1 second */
672 }
673
674 static void laptop_flush(unsigned long unused)
675 {
676         sys_sync();
677 }
678
679 static void laptop_timer_fn(unsigned long unused)
680 {
681         pdflush_operation(laptop_flush, 0);
682 }
683
684 /*
685  * We've spun up the disk and we're in laptop mode: schedule writeback
686  * of all dirty data a few seconds from now.  If the flush is already scheduled
687  * then push it back - the user is still using the disk.
688  */
689 void laptop_io_completion(void)
690 {
691         mod_timer(&laptop_mode_wb_timer, jiffies + laptop_mode);
692 }
693
694 /*
695  * We're in laptop mode and we've just synced. The sync's writes will have
696  * caused another writeback to be scheduled by laptop_io_completion.
697  * Nothing needs to be written back anymore, so we unschedule the writeback.
698  */
699 void laptop_sync_completion(void)
700 {
701         del_timer(&laptop_mode_wb_timer);
702 }
703
704 /*
705  * If ratelimit_pages is too high then we can get into dirty-data overload
706  * if a large number of processes all perform writes at the same time.
707  * If it is too low then SMP machines will call the (expensive)
708  * get_writeback_state too often.
709  *
710  * Here we set ratelimit_pages to a level which ensures that when all CPUs are
711  * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
712  * thresholds before writeback cuts in.
713  *
714  * But the limit should not be set too high.  Because it also controls the
715  * amount of memory which the balance_dirty_pages() caller has to write back.
716  * If this is too large then the caller will block on the IO queue all the
717  * time.  So limit it to four megabytes - the balance_dirty_pages() caller
718  * will write six megabyte chunks, max.
719  */
720
721 void writeback_set_ratelimit(void)
722 {
723         ratelimit_pages = vm_total_pages / (num_online_cpus() * 32);
724         if (ratelimit_pages < 16)
725                 ratelimit_pages = 16;
726         if (ratelimit_pages * PAGE_CACHE_SIZE > 4096 * 1024)
727                 ratelimit_pages = (4096 * 1024) / PAGE_CACHE_SIZE;
728 }
729
730 static int __cpuinit
731 ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
732 {
733         writeback_set_ratelimit();
734         return NOTIFY_DONE;
735 }
736
737 static struct notifier_block __cpuinitdata ratelimit_nb = {
738         .notifier_call  = ratelimit_handler,
739         .next           = NULL,
740 };
741
742 /*
743  * Called early on to tune the page writeback dirty limits.
744  *
745  * We used to scale dirty pages according to how total memory
746  * related to pages that could be allocated for buffers (by
747  * comparing nr_free_buffer_pages() to vm_total_pages.
748  *
749  * However, that was when we used "dirty_ratio" to scale with
750  * all memory, and we don't do that any more. "dirty_ratio"
751  * is now applied to total non-HIGHPAGE memory (by subtracting
752  * totalhigh_pages from vm_total_pages), and as such we can't
753  * get into the old insane situation any more where we had
754  * large amounts of dirty pages compared to a small amount of
755  * non-HIGHMEM memory.
756  *
757  * But we might still want to scale the dirty_ratio by how
758  * much memory the box has..
759  */
760 void __init page_writeback_init(void)
761 {
762         int shift;
763
764         mod_timer(&wb_timer, jiffies + dirty_writeback_interval);
765         writeback_set_ratelimit();
766         register_cpu_notifier(&ratelimit_nb);
767
768         shift = calc_period_shift();
769         prop_descriptor_init(&vm_completions, shift);
770         prop_descriptor_init(&vm_dirties, shift);
771 }
772
773 /**
774  * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
775  * @mapping: address space structure to write
776  * @wbc: subtract the number of written pages from *@wbc->nr_to_write
777  * @writepage: function called for each page
778  * @data: data passed to writepage function
779  *
780  * If a page is already under I/O, write_cache_pages() skips it, even
781  * if it's dirty.  This is desirable behaviour for memory-cleaning writeback,
782  * but it is INCORRECT for data-integrity system calls such as fsync().  fsync()
783  * and msync() need to guarantee that all the data which was dirty at the time
784  * the call was made get new I/O started against them.  If wbc->sync_mode is
785  * WB_SYNC_ALL then we were called for data integrity and we must wait for
786  * existing IO to complete.
787  */
788 int write_cache_pages(struct address_space *mapping,
789                       struct writeback_control *wbc, writepage_t writepage,
790                       void *data)
791 {
792         struct backing_dev_info *bdi = mapping->backing_dev_info;
793         int ret = 0;
794         int done = 0;
795         struct pagevec pvec;
796         int nr_pages;
797         pgoff_t index;
798         pgoff_t end;            /* Inclusive */
799         int scanned = 0;
800         int range_whole = 0;
801
802         if (wbc->nonblocking && bdi_write_congested(bdi)) {
803                 wbc->encountered_congestion = 1;
804                 return 0;
805         }
806
807         pagevec_init(&pvec, 0);
808         if (wbc->range_cyclic) {
809                 index = mapping->writeback_index; /* Start from prev offset */
810                 end = -1;
811         } else {
812                 index = wbc->range_start >> PAGE_CACHE_SHIFT;
813                 end = wbc->range_end >> PAGE_CACHE_SHIFT;
814                 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
815                         range_whole = 1;
816                 scanned = 1;
817         }
818 retry:
819         while (!done && (index <= end) &&
820                (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
821                                               PAGECACHE_TAG_DIRTY,
822                                               min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1))) {
823                 unsigned i;
824
825                 scanned = 1;
826                 for (i = 0; i < nr_pages; i++) {
827                         struct page *page = pvec.pages[i];
828
829                         /*
830                          * At this point we hold neither mapping->tree_lock nor
831                          * lock on the page itself: the page may be truncated or
832                          * invalidated (changing page->mapping to NULL), or even
833                          * swizzled back from swapper_space to tmpfs file
834                          * mapping
835                          */
836                         lock_page(page);
837
838                         if (unlikely(page->mapping != mapping)) {
839                                 unlock_page(page);
840                                 continue;
841                         }
842
843                         if (!wbc->range_cyclic && page->index > end) {
844                                 done = 1;
845                                 unlock_page(page);
846                                 continue;
847                         }
848
849                         if (wbc->sync_mode != WB_SYNC_NONE)
850                                 wait_on_page_writeback(page);
851
852                         if (PageWriteback(page) ||
853                             !clear_page_dirty_for_io(page)) {
854                                 unlock_page(page);
855                                 continue;
856                         }
857
858                         ret = (*writepage)(page, wbc, data);
859
860                         if (unlikely(ret == AOP_WRITEPAGE_ACTIVATE)) {
861                                 unlock_page(page);
862                                 ret = 0;
863                         }
864                         if (ret || (--(wbc->nr_to_write) <= 0))
865                                 done = 1;
866                         if (wbc->nonblocking && bdi_write_congested(bdi)) {
867                                 wbc->encountered_congestion = 1;
868                                 done = 1;
869                         }
870                 }
871                 pagevec_release(&pvec);
872                 cond_resched();
873         }
874         if (!scanned && !done) {
875                 /*
876                  * We hit the last page and there is more work to be done: wrap
877                  * back to the start of the file
878                  */
879                 scanned = 1;
880                 index = 0;
881                 goto retry;
882         }
883         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
884                 mapping->writeback_index = index;
885         return ret;
886 }
887 EXPORT_SYMBOL(write_cache_pages);
888
889 /*
890  * Function used by generic_writepages to call the real writepage
891  * function and set the mapping flags on error
892  */
893 static int __writepage(struct page *page, struct writeback_control *wbc,
894                        void *data)
895 {
896         struct address_space *mapping = data;
897         int ret = mapping->a_ops->writepage(page, wbc);
898         mapping_set_error(mapping, ret);
899         return ret;
900 }
901
902 /**
903  * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
904  * @mapping: address space structure to write
905  * @wbc: subtract the number of written pages from *@wbc->nr_to_write
906  *
907  * This is a library function, which implements the writepages()
908  * address_space_operation.
909  */
910 int generic_writepages(struct address_space *mapping,
911                        struct writeback_control *wbc)
912 {
913         /* deal with chardevs and other special file */
914         if (!mapping->a_ops->writepage)
915                 return 0;
916
917         return write_cache_pages(mapping, wbc, __writepage, mapping);
918 }
919
920 EXPORT_SYMBOL(generic_writepages);
921
922 int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
923 {
924         int ret;
925
926         if (wbc->nr_to_write <= 0)
927                 return 0;
928         wbc->for_writepages = 1;
929         if (mapping->a_ops->writepages)
930                 ret = mapping->a_ops->writepages(mapping, wbc);
931         else
932                 ret = generic_writepages(mapping, wbc);
933         wbc->for_writepages = 0;
934         return ret;
935 }
936
937 /**
938  * write_one_page - write out a single page and optionally wait on I/O
939  * @page: the page to write
940  * @wait: if true, wait on writeout
941  *
942  * The page must be locked by the caller and will be unlocked upon return.
943  *
944  * write_one_page() returns a negative error code if I/O failed.
945  */
946 int write_one_page(struct page *page, int wait)
947 {
948         struct address_space *mapping = page->mapping;
949         int ret = 0;
950         struct writeback_control wbc = {
951                 .sync_mode = WB_SYNC_ALL,
952                 .nr_to_write = 1,
953         };
954
955         BUG_ON(!PageLocked(page));
956
957         if (wait)
958                 wait_on_page_writeback(page);
959
960         if (clear_page_dirty_for_io(page)) {
961                 page_cache_get(page);
962                 ret = mapping->a_ops->writepage(page, &wbc);
963                 if (ret == 0 && wait) {
964                         wait_on_page_writeback(page);
965                         if (PageError(page))
966                                 ret = -EIO;
967                 }
968                 page_cache_release(page);
969         } else {
970                 unlock_page(page);
971         }
972         return ret;
973 }
974 EXPORT_SYMBOL(write_one_page);
975
976 /*
977  * For address_spaces which do not use buffers nor write back.
978  */
979 int __set_page_dirty_no_writeback(struct page *page)
980 {
981         if (!PageDirty(page))
982                 SetPageDirty(page);
983         return 0;
984 }
985
986 /*
987  * For address_spaces which do not use buffers.  Just tag the page as dirty in
988  * its radix tree.
989  *
990  * This is also used when a single buffer is being dirtied: we want to set the
991  * page dirty in that case, but not all the buffers.  This is a "bottom-up"
992  * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
993  *
994  * Most callers have locked the page, which pins the address_space in memory.
995  * But zap_pte_range() does not lock the page, however in that case the
996  * mapping is pinned by the vma's ->vm_file reference.
997  *
998  * We take care to handle the case where the page was truncated from the
999  * mapping by re-checking page_mapping() inside tree_lock.
1000  */
1001 int __set_page_dirty_nobuffers(struct page *page)
1002 {
1003         if (!TestSetPageDirty(page)) {
1004                 struct address_space *mapping = page_mapping(page);
1005                 struct address_space *mapping2;
1006
1007                 if (!mapping)
1008                         return 1;
1009
1010                 write_lock_irq(&mapping->tree_lock);
1011                 mapping2 = page_mapping(page);
1012                 if (mapping2) { /* Race with truncate? */
1013                         BUG_ON(mapping2 != mapping);
1014                         WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
1015                         if (mapping_cap_account_dirty(mapping)) {
1016                                 __inc_zone_page_state(page, NR_FILE_DIRTY);
1017                                 __inc_bdi_stat(mapping->backing_dev_info,
1018                                                 BDI_RECLAIMABLE);
1019                                 task_io_account_write(PAGE_CACHE_SIZE);
1020                         }
1021                         radix_tree_tag_set(&mapping->page_tree,
1022                                 page_index(page), PAGECACHE_TAG_DIRTY);
1023                 }
1024                 write_unlock_irq(&mapping->tree_lock);
1025                 if (mapping->host) {
1026                         /* !PageAnon && !swapper_space */
1027                         __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
1028                 }
1029                 return 1;
1030         }
1031         return 0;
1032 }
1033 EXPORT_SYMBOL(__set_page_dirty_nobuffers);
1034
1035 /*
1036  * When a writepage implementation decides that it doesn't want to write this
1037  * page for some reason, it should redirty the locked page via
1038  * redirty_page_for_writepage() and it should then unlock the page and return 0
1039  */
1040 int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
1041 {
1042         wbc->pages_skipped++;
1043         return __set_page_dirty_nobuffers(page);
1044 }
1045 EXPORT_SYMBOL(redirty_page_for_writepage);
1046
1047 /*
1048  * If the mapping doesn't provide a set_page_dirty a_op, then
1049  * just fall through and assume that it wants buffer_heads.
1050  */
1051 static int __set_page_dirty(struct page *page)
1052 {
1053         struct address_space *mapping = page_mapping(page);
1054
1055         if (likely(mapping)) {
1056                 int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
1057 #ifdef CONFIG_BLOCK
1058                 if (!spd)
1059                         spd = __set_page_dirty_buffers;
1060 #endif
1061                 return (*spd)(page);
1062         }
1063         if (!PageDirty(page)) {
1064                 if (!TestSetPageDirty(page))
1065                         return 1;
1066         }
1067         return 0;
1068 }
1069
1070 int fastcall set_page_dirty(struct page *page)
1071 {
1072         int ret = __set_page_dirty(page);
1073         if (ret)
1074                 task_dirty_inc(current);
1075         return ret;
1076 }
1077 EXPORT_SYMBOL(set_page_dirty);
1078
1079 /*
1080  * set_page_dirty() is racy if the caller has no reference against
1081  * page->mapping->host, and if the page is unlocked.  This is because another
1082  * CPU could truncate the page off the mapping and then free the mapping.
1083  *
1084  * Usually, the page _is_ locked, or the caller is a user-space process which
1085  * holds a reference on the inode by having an open file.
1086  *
1087  * In other cases, the page should be locked before running set_page_dirty().
1088  */
1089 int set_page_dirty_lock(struct page *page)
1090 {
1091         int ret;
1092
1093         lock_page_nosync(page);
1094         ret = set_page_dirty(page);
1095         unlock_page(page);
1096         return ret;
1097 }
1098 EXPORT_SYMBOL(set_page_dirty_lock);
1099
1100 /*
1101  * Clear a page's dirty flag, while caring for dirty memory accounting.
1102  * Returns true if the page was previously dirty.
1103  *
1104  * This is for preparing to put the page under writeout.  We leave the page
1105  * tagged as dirty in the radix tree so that a concurrent write-for-sync
1106  * can discover it via a PAGECACHE_TAG_DIRTY walk.  The ->writepage
1107  * implementation will run either set_page_writeback() or set_page_dirty(),
1108  * at which stage we bring the page's dirty flag and radix-tree dirty tag
1109  * back into sync.
1110  *
1111  * This incoherency between the page's dirty flag and radix-tree tag is
1112  * unfortunate, but it only exists while the page is locked.
1113  */
1114 int clear_page_dirty_for_io(struct page *page)
1115 {
1116         struct address_space *mapping = page_mapping(page);
1117
1118         BUG_ON(!PageLocked(page));
1119
1120         ClearPageReclaim(page);
1121         if (mapping && mapping_cap_account_dirty(mapping)) {
1122                 /*
1123                  * Yes, Virginia, this is indeed insane.
1124                  *
1125                  * We use this sequence to make sure that
1126                  *  (a) we account for dirty stats properly
1127                  *  (b) we tell the low-level filesystem to
1128                  *      mark the whole page dirty if it was
1129                  *      dirty in a pagetable. Only to then
1130                  *  (c) clean the page again and return 1 to
1131                  *      cause the writeback.
1132                  *
1133                  * This way we avoid all nasty races with the
1134                  * dirty bit in multiple places and clearing
1135                  * them concurrently from different threads.
1136                  *
1137                  * Note! Normally the "set_page_dirty(page)"
1138                  * has no effect on the actual dirty bit - since
1139                  * that will already usually be set. But we
1140                  * need the side effects, and it can help us
1141                  * avoid races.
1142                  *
1143                  * We basically use the page "master dirty bit"
1144                  * as a serialization point for all the different
1145                  * threads doing their things.
1146                  */
1147                 if (page_mkclean(page))
1148                         set_page_dirty(page);
1149                 /*
1150                  * We carefully synchronise fault handlers against
1151                  * installing a dirty pte and marking the page dirty
1152                  * at this point. We do this by having them hold the
1153                  * page lock at some point after installing their
1154                  * pte, but before marking the page dirty.
1155                  * Pages are always locked coming in here, so we get
1156                  * the desired exclusion. See mm/memory.c:do_wp_page()
1157                  * for more comments.
1158                  */
1159                 if (TestClearPageDirty(page)) {
1160                         dec_zone_page_state(page, NR_FILE_DIRTY);
1161                         dec_bdi_stat(mapping->backing_dev_info,
1162                                         BDI_RECLAIMABLE);
1163                         return 1;
1164                 }
1165                 return 0;
1166         }
1167         return TestClearPageDirty(page);
1168 }
1169 EXPORT_SYMBOL(clear_page_dirty_for_io);
1170
1171 int test_clear_page_writeback(struct page *page)
1172 {
1173         struct address_space *mapping = page_mapping(page);
1174         int ret;
1175
1176         if (mapping) {
1177                 struct backing_dev_info *bdi = mapping->backing_dev_info;
1178                 unsigned long flags;
1179
1180                 write_lock_irqsave(&mapping->tree_lock, flags);
1181                 ret = TestClearPageWriteback(page);
1182                 if (ret) {
1183                         radix_tree_tag_clear(&mapping->page_tree,
1184                                                 page_index(page),
1185                                                 PAGECACHE_TAG_WRITEBACK);
1186                         if (bdi_cap_writeback_dirty(bdi)) {
1187                                 __dec_bdi_stat(bdi, BDI_WRITEBACK);
1188                                 __bdi_writeout_inc(bdi);
1189                         }
1190                 }
1191                 write_unlock_irqrestore(&mapping->tree_lock, flags);
1192         } else {
1193                 ret = TestClearPageWriteback(page);
1194         }
1195         if (ret)
1196                 dec_zone_page_state(page, NR_WRITEBACK);
1197         return ret;
1198 }
1199
1200 int test_set_page_writeback(struct page *page)
1201 {
1202         struct address_space *mapping = page_mapping(page);
1203         int ret;
1204
1205         if (mapping) {
1206                 struct backing_dev_info *bdi = mapping->backing_dev_info;
1207                 unsigned long flags;
1208
1209                 write_lock_irqsave(&mapping->tree_lock, flags);
1210                 ret = TestSetPageWriteback(page);
1211                 if (!ret) {
1212                         radix_tree_tag_set(&mapping->page_tree,
1213                                                 page_index(page),
1214                                                 PAGECACHE_TAG_WRITEBACK);
1215                         if (bdi_cap_writeback_dirty(bdi))
1216                                 __inc_bdi_stat(bdi, BDI_WRITEBACK);
1217                 }
1218                 if (!PageDirty(page))
1219                         radix_tree_tag_clear(&mapping->page_tree,
1220                                                 page_index(page),
1221                                                 PAGECACHE_TAG_DIRTY);
1222                 write_unlock_irqrestore(&mapping->tree_lock, flags);
1223         } else {
1224                 ret = TestSetPageWriteback(page);
1225         }
1226         if (!ret)
1227                 inc_zone_page_state(page, NR_WRITEBACK);
1228         return ret;
1229
1230 }
1231 EXPORT_SYMBOL(test_set_page_writeback);
1232
1233 /*
1234  * Return true if any of the pages in the mapping are marked with the
1235  * passed tag.
1236  */
1237 int mapping_tagged(struct address_space *mapping, int tag)
1238 {
1239         int ret;
1240         rcu_read_lock();
1241         ret = radix_tree_tagged(&mapping->page_tree, tag);
1242         rcu_read_unlock();
1243         return ret;
1244 }
1245 EXPORT_SYMBOL(mapping_tagged);