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