]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - mm/page-writeback.c
Merge branch 'master' of master.kernel.org:/pub/scm/linux/kernel/git/mchehab/v4l-dvb
[linux-2.6-omap-h63xx.git] / mm / page-writeback.c
1 /*
2  * mm/page-writeback.c
3  *
4  * Copyright (C) 2002, Linus Torvalds.
5  *
6  * Contains functions related to writing back dirty pages at the
7  * address_space level.
8  *
9  * 10Apr2002    akpm@zip.com.au
10  *              Initial version
11  */
12
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/spinlock.h>
16 #include <linux/fs.h>
17 #include <linux/mm.h>
18 #include <linux/swap.h>
19 #include <linux/slab.h>
20 #include <linux/pagemap.h>
21 #include <linux/writeback.h>
22 #include <linux/init.h>
23 #include <linux/backing-dev.h>
24 #include <linux/task_io_accounting_ops.h>
25 #include <linux/blkdev.h>
26 #include <linux/mpage.h>
27 #include <linux/rmap.h>
28 #include <linux/percpu.h>
29 #include <linux/notifier.h>
30 #include <linux/smp.h>
31 #include <linux/sysctl.h>
32 #include <linux/cpu.h>
33 #include <linux/syscalls.h>
34 #include <linux/buffer_head.h>
35 #include <linux/pagevec.h>
36
37 /*
38  * The maximum number of pages to writeout in a single bdflush/kupdate
39  * operation.  We do this so we don't hold I_LOCK against an inode for
40  * enormous amounts of time, which would block a userspace task which has
41  * been forced to throttle against that inode.  Also, the code reevaluates
42  * the dirty each time it has written this many pages.
43  */
44 #define MAX_WRITEBACK_PAGES     1024
45
46 /*
47  * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
48  * will look to see if it needs to force writeback or throttling.
49  */
50 static long ratelimit_pages = 32;
51
52 static int dirty_exceeded __cacheline_aligned_in_smp;   /* Dirty mem may be over limit */
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 = 10;
71
72 /*
73  * The generator of dirty data starts writeback at this percentage
74  */
75 int vm_dirty_ratio = 40;
76
77 /*
78  * The interval between `kupdate'-style writebacks, in jiffies
79  */
80 int dirty_writeback_interval = 5 * HZ;
81
82 /*
83  * The longest number of jiffies for which data is allowed to remain dirty
84  */
85 int dirty_expire_interval = 30 * HZ;
86
87 /*
88  * Flag that makes the machine dump writes/reads and block dirtyings.
89  */
90 int block_dump;
91
92 /*
93  * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
94  * a full sync is triggered after this time elapses without any disk activity.
95  */
96 int laptop_mode;
97
98 EXPORT_SYMBOL(laptop_mode);
99
100 /* End of sysctl-exported parameters */
101
102
103 static void background_writeout(unsigned long _min_pages);
104
105 /*
106  * Work out the current dirty-memory clamping and background writeout
107  * thresholds.
108  *
109  * The main aim here is to lower them aggressively if there is a lot of mapped
110  * memory around.  To avoid stressing page reclaim with lots of unreclaimable
111  * pages.  It is better to clamp down on writers than to start swapping, and
112  * performing lots of scanning.
113  *
114  * We only allow 1/2 of the currently-unmapped memory to be dirtied.
115  *
116  * We don't permit the clamping level to fall below 5% - that is getting rather
117  * excessive.
118  *
119  * We make sure that the background writeout level is below the adjusted
120  * clamping level.
121  */
122 static void
123 get_dirty_limits(long *pbackground, long *pdirty,
124                                         struct address_space *mapping)
125 {
126         int background_ratio;           /* Percentages */
127         int dirty_ratio;
128         int unmapped_ratio;
129         long background;
130         long dirty;
131         unsigned long available_memory = vm_total_pages;
132         struct task_struct *tsk;
133
134 #ifdef CONFIG_HIGHMEM
135         /*
136          * If this mapping can only allocate from low memory,
137          * we exclude high memory from our count.
138          */
139         if (mapping && !(mapping_gfp_mask(mapping) & __GFP_HIGHMEM))
140                 available_memory -= totalhigh_pages;
141 #endif
142
143
144         unmapped_ratio = 100 - ((global_page_state(NR_FILE_MAPPED) +
145                                 global_page_state(NR_ANON_PAGES)) * 100) /
146                                         vm_total_pages;
147
148         dirty_ratio = vm_dirty_ratio;
149         if (dirty_ratio > unmapped_ratio / 2)
150                 dirty_ratio = unmapped_ratio / 2;
151
152         if (dirty_ratio < 5)
153                 dirty_ratio = 5;
154
155         background_ratio = dirty_background_ratio;
156         if (background_ratio >= dirty_ratio)
157                 background_ratio = dirty_ratio / 2;
158
159         background = (background_ratio * available_memory) / 100;
160         dirty = (dirty_ratio * available_memory) / 100;
161         tsk = current;
162         if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
163                 background += background / 4;
164                 dirty += dirty / 4;
165         }
166         *pbackground = background;
167         *pdirty = dirty;
168 }
169
170 /*
171  * balance_dirty_pages() must be called by processes which are generating dirty
172  * data.  It looks at the number of dirty pages in the machine and will force
173  * the caller to perform writeback if the system is over `vm_dirty_ratio'.
174  * If we're over `background_thresh' then pdflush is woken to perform some
175  * writeout.
176  */
177 static void balance_dirty_pages(struct address_space *mapping)
178 {
179         long nr_reclaimable;
180         long background_thresh;
181         long dirty_thresh;
182         unsigned long pages_written = 0;
183         unsigned long write_chunk = sync_writeback_pages();
184
185         struct backing_dev_info *bdi = mapping->backing_dev_info;
186
187         for (;;) {
188                 struct writeback_control wbc = {
189                         .bdi            = bdi,
190                         .sync_mode      = WB_SYNC_NONE,
191                         .older_than_this = NULL,
192                         .nr_to_write    = write_chunk,
193                         .range_cyclic   = 1,
194                 };
195
196                 get_dirty_limits(&background_thresh, &dirty_thresh, mapping);
197                 nr_reclaimable = global_page_state(NR_FILE_DIRTY) +
198                                         global_page_state(NR_UNSTABLE_NFS);
199                 if (nr_reclaimable + global_page_state(NR_WRITEBACK) <=
200                         dirty_thresh)
201                                 break;
202
203                 if (!dirty_exceeded)
204                         dirty_exceeded = 1;
205
206                 /* Note: nr_reclaimable denotes nr_dirty + nr_unstable.
207                  * Unstable writes are a feature of certain networked
208                  * filesystems (i.e. NFS) in which data may have been
209                  * written to the server's write cache, but has not yet
210                  * been flushed to permanent storage.
211                  */
212                 if (nr_reclaimable) {
213                         writeback_inodes(&wbc);
214                         get_dirty_limits(&background_thresh,
215                                                 &dirty_thresh, mapping);
216                         nr_reclaimable = global_page_state(NR_FILE_DIRTY) +
217                                         global_page_state(NR_UNSTABLE_NFS);
218                         if (nr_reclaimable +
219                                 global_page_state(NR_WRITEBACK)
220                                         <= dirty_thresh)
221                                                 break;
222                         pages_written += write_chunk - wbc.nr_to_write;
223                         if (pages_written >= write_chunk)
224                                 break;          /* We've done our duty */
225                 }
226                 congestion_wait(WRITE, HZ/10);
227         }
228
229         if (nr_reclaimable + global_page_state(NR_WRITEBACK)
230                 <= dirty_thresh && dirty_exceeded)
231                         dirty_exceeded = 0;
232
233         if (writeback_in_progress(bdi))
234                 return;         /* pdflush is already working this queue */
235
236         /*
237          * In laptop mode, we wait until hitting the higher threshold before
238          * starting background writeout, and then write out all the way down
239          * to the lower threshold.  So slow writers cause minimal disk activity.
240          *
241          * In normal mode, we start background writeout at the lower
242          * background_thresh, to keep the amount of dirty memory low.
243          */
244         if ((laptop_mode && pages_written) ||
245              (!laptop_mode && (nr_reclaimable > background_thresh)))
246                 pdflush_operation(background_writeout, 0);
247 }
248
249 void set_page_dirty_balance(struct page *page)
250 {
251         if (set_page_dirty(page)) {
252                 struct address_space *mapping = page_mapping(page);
253
254                 if (mapping)
255                         balance_dirty_pages_ratelimited(mapping);
256         }
257 }
258
259 /**
260  * balance_dirty_pages_ratelimited_nr - balance dirty memory state
261  * @mapping: address_space which was dirtied
262  * @nr_pages_dirtied: number of pages which the caller has just dirtied
263  *
264  * Processes which are dirtying memory should call in here once for each page
265  * which was newly dirtied.  The function will periodically check the system's
266  * dirty state and will initiate writeback if needed.
267  *
268  * On really big machines, get_writeback_state is expensive, so try to avoid
269  * calling it too often (ratelimiting).  But once we're over the dirty memory
270  * limit we decrease the ratelimiting by a lot, to prevent individual processes
271  * from overshooting the limit by (ratelimit_pages) each.
272  */
273 void balance_dirty_pages_ratelimited_nr(struct address_space *mapping,
274                                         unsigned long nr_pages_dirtied)
275 {
276         static DEFINE_PER_CPU(unsigned long, ratelimits) = 0;
277         unsigned long ratelimit;
278         unsigned long *p;
279
280         ratelimit = ratelimit_pages;
281         if (dirty_exceeded)
282                 ratelimit = 8;
283
284         /*
285          * Check the rate limiting. Also, we do not want to throttle real-time
286          * tasks in balance_dirty_pages(). Period.
287          */
288         preempt_disable();
289         p =  &__get_cpu_var(ratelimits);
290         *p += nr_pages_dirtied;
291         if (unlikely(*p >= ratelimit)) {
292                 *p = 0;
293                 preempt_enable();
294                 balance_dirty_pages(mapping);
295                 return;
296         }
297         preempt_enable();
298 }
299 EXPORT_SYMBOL(balance_dirty_pages_ratelimited_nr);
300
301 void throttle_vm_writeout(void)
302 {
303         long background_thresh;
304         long dirty_thresh;
305
306         for ( ; ; ) {
307                 get_dirty_limits(&background_thresh, &dirty_thresh, NULL);
308
309                 /*
310                  * Boost the allowable dirty threshold a bit for page
311                  * allocators so they don't get DoS'ed by heavy writers
312                  */
313                 dirty_thresh += dirty_thresh / 10;      /* wheeee... */
314
315                 if (global_page_state(NR_UNSTABLE_NFS) +
316                         global_page_state(NR_WRITEBACK) <= dirty_thresh)
317                                 break;
318                 congestion_wait(WRITE, HZ/10);
319         }
320 }
321
322
323 /*
324  * writeback at least _min_pages, and keep writing until the amount of dirty
325  * memory is less than the background threshold, or until we're all clean.
326  */
327 static void background_writeout(unsigned long _min_pages)
328 {
329         long min_pages = _min_pages;
330         struct writeback_control wbc = {
331                 .bdi            = NULL,
332                 .sync_mode      = WB_SYNC_NONE,
333                 .older_than_this = NULL,
334                 .nr_to_write    = 0,
335                 .nonblocking    = 1,
336                 .range_cyclic   = 1,
337         };
338
339         for ( ; ; ) {
340                 long background_thresh;
341                 long dirty_thresh;
342
343                 get_dirty_limits(&background_thresh, &dirty_thresh, NULL);
344                 if (global_page_state(NR_FILE_DIRTY) +
345                         global_page_state(NR_UNSTABLE_NFS) < background_thresh
346                                 && min_pages <= 0)
347                         break;
348                 wbc.encountered_congestion = 0;
349                 wbc.nr_to_write = MAX_WRITEBACK_PAGES;
350                 wbc.pages_skipped = 0;
351                 writeback_inodes(&wbc);
352                 min_pages -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
353                 if (wbc.nr_to_write > 0 || wbc.pages_skipped > 0) {
354                         /* Wrote less than expected */
355                         congestion_wait(WRITE, HZ/10);
356                         if (!wbc.encountered_congestion)
357                                 break;
358                 }
359         }
360 }
361
362 /*
363  * Start writeback of `nr_pages' pages.  If `nr_pages' is zero, write back
364  * the whole world.  Returns 0 if a pdflush thread was dispatched.  Returns
365  * -1 if all pdflush threads were busy.
366  */
367 int wakeup_pdflush(long nr_pages)
368 {
369         if (nr_pages == 0)
370                 nr_pages = global_page_state(NR_FILE_DIRTY) +
371                                 global_page_state(NR_UNSTABLE_NFS);
372         return pdflush_operation(background_writeout, nr_pages);
373 }
374
375 static void wb_timer_fn(unsigned long unused);
376 static void laptop_timer_fn(unsigned long unused);
377
378 static DEFINE_TIMER(wb_timer, wb_timer_fn, 0, 0);
379 static DEFINE_TIMER(laptop_mode_wb_timer, laptop_timer_fn, 0, 0);
380
381 /*
382  * Periodic writeback of "old" data.
383  *
384  * Define "old": the first time one of an inode's pages is dirtied, we mark the
385  * dirtying-time in the inode's address_space.  So this periodic writeback code
386  * just walks the superblock inode list, writing back any inodes which are
387  * older than a specific point in time.
388  *
389  * Try to run once per dirty_writeback_interval.  But if a writeback event
390  * takes longer than a dirty_writeback_interval interval, then leave a
391  * one-second gap.
392  *
393  * older_than_this takes precedence over nr_to_write.  So we'll only write back
394  * all dirty pages if they are all attached to "old" mappings.
395  */
396 static void wb_kupdate(unsigned long arg)
397 {
398         unsigned long oldest_jif;
399         unsigned long start_jif;
400         unsigned long next_jif;
401         long nr_to_write;
402         struct writeback_control wbc = {
403                 .bdi            = NULL,
404                 .sync_mode      = WB_SYNC_NONE,
405                 .older_than_this = &oldest_jif,
406                 .nr_to_write    = 0,
407                 .nonblocking    = 1,
408                 .for_kupdate    = 1,
409                 .range_cyclic   = 1,
410         };
411
412         sync_supers();
413
414         oldest_jif = jiffies - dirty_expire_interval;
415         start_jif = jiffies;
416         next_jif = start_jif + dirty_writeback_interval;
417         nr_to_write = global_page_state(NR_FILE_DIRTY) +
418                         global_page_state(NR_UNSTABLE_NFS) +
419                         (inodes_stat.nr_inodes - inodes_stat.nr_unused);
420         while (nr_to_write > 0) {
421                 wbc.encountered_congestion = 0;
422                 wbc.nr_to_write = MAX_WRITEBACK_PAGES;
423                 writeback_inodes(&wbc);
424                 if (wbc.nr_to_write > 0) {
425                         if (wbc.encountered_congestion)
426                                 congestion_wait(WRITE, HZ/10);
427                         else
428                                 break;  /* All the old data is written */
429                 }
430                 nr_to_write -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
431         }
432         if (time_before(next_jif, jiffies + HZ))
433                 next_jif = jiffies + HZ;
434         if (dirty_writeback_interval)
435                 mod_timer(&wb_timer, next_jif);
436 }
437
438 /*
439  * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
440  */
441 int dirty_writeback_centisecs_handler(ctl_table *table, int write,
442                 struct file *file, void __user *buffer, size_t *length, loff_t *ppos)
443 {
444         proc_dointvec_userhz_jiffies(table, write, file, buffer, length, ppos);
445         if (dirty_writeback_interval) {
446                 mod_timer(&wb_timer,
447                         jiffies + dirty_writeback_interval);
448                 } else {
449                 del_timer(&wb_timer);
450         }
451         return 0;
452 }
453
454 static void wb_timer_fn(unsigned long unused)
455 {
456         if (pdflush_operation(wb_kupdate, 0) < 0)
457                 mod_timer(&wb_timer, jiffies + HZ); /* delay 1 second */
458 }
459
460 static void laptop_flush(unsigned long unused)
461 {
462         sys_sync();
463 }
464
465 static void laptop_timer_fn(unsigned long unused)
466 {
467         pdflush_operation(laptop_flush, 0);
468 }
469
470 /*
471  * We've spun up the disk and we're in laptop mode: schedule writeback
472  * of all dirty data a few seconds from now.  If the flush is already scheduled
473  * then push it back - the user is still using the disk.
474  */
475 void laptop_io_completion(void)
476 {
477         mod_timer(&laptop_mode_wb_timer, jiffies + laptop_mode);
478 }
479
480 /*
481  * We're in laptop mode and we've just synced. The sync's writes will have
482  * caused another writeback to be scheduled by laptop_io_completion.
483  * Nothing needs to be written back anymore, so we unschedule the writeback.
484  */
485 void laptop_sync_completion(void)
486 {
487         del_timer(&laptop_mode_wb_timer);
488 }
489
490 /*
491  * If ratelimit_pages is too high then we can get into dirty-data overload
492  * if a large number of processes all perform writes at the same time.
493  * If it is too low then SMP machines will call the (expensive)
494  * get_writeback_state too often.
495  *
496  * Here we set ratelimit_pages to a level which ensures that when all CPUs are
497  * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
498  * thresholds before writeback cuts in.
499  *
500  * But the limit should not be set too high.  Because it also controls the
501  * amount of memory which the balance_dirty_pages() caller has to write back.
502  * If this is too large then the caller will block on the IO queue all the
503  * time.  So limit it to four megabytes - the balance_dirty_pages() caller
504  * will write six megabyte chunks, max.
505  */
506
507 void writeback_set_ratelimit(void)
508 {
509         ratelimit_pages = vm_total_pages / (num_online_cpus() * 32);
510         if (ratelimit_pages < 16)
511                 ratelimit_pages = 16;
512         if (ratelimit_pages * PAGE_CACHE_SIZE > 4096 * 1024)
513                 ratelimit_pages = (4096 * 1024) / PAGE_CACHE_SIZE;
514 }
515
516 static int __cpuinit
517 ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
518 {
519         writeback_set_ratelimit();
520         return 0;
521 }
522
523 static struct notifier_block __cpuinitdata ratelimit_nb = {
524         .notifier_call  = ratelimit_handler,
525         .next           = NULL,
526 };
527
528 /*
529  * If the machine has a large highmem:lowmem ratio then scale back the default
530  * dirty memory thresholds: allowing too much dirty highmem pins an excessive
531  * number of buffer_heads.
532  */
533 void __init page_writeback_init(void)
534 {
535         long buffer_pages = nr_free_buffer_pages();
536         long correction;
537
538         correction = (100 * 4 * buffer_pages) / vm_total_pages;
539
540         if (correction < 100) {
541                 dirty_background_ratio *= correction;
542                 dirty_background_ratio /= 100;
543                 vm_dirty_ratio *= correction;
544                 vm_dirty_ratio /= 100;
545
546                 if (dirty_background_ratio <= 0)
547                         dirty_background_ratio = 1;
548                 if (vm_dirty_ratio <= 0)
549                         vm_dirty_ratio = 1;
550         }
551         mod_timer(&wb_timer, jiffies + dirty_writeback_interval);
552         writeback_set_ratelimit();
553         register_cpu_notifier(&ratelimit_nb);
554 }
555
556 /**
557  * generic_writepages - walk the list of dirty pages of the given
558  *                      address space and writepage() all of them.
559  *
560  * @mapping: address space structure to write
561  * @wbc: subtract the number of written pages from *@wbc->nr_to_write
562  *
563  * This is a library function, which implements the writepages()
564  * address_space_operation.
565  *
566  * If a page is already under I/O, generic_writepages() skips it, even
567  * if it's dirty.  This is desirable behaviour for memory-cleaning writeback,
568  * but it is INCORRECT for data-integrity system calls such as fsync().  fsync()
569  * and msync() need to guarantee that all the data which was dirty at the time
570  * the call was made get new I/O started against them.  If wbc->sync_mode is
571  * WB_SYNC_ALL then we were called for data integrity and we must wait for
572  * existing IO to complete.
573  *
574  * Derived from mpage_writepages() - if you fix this you should check that
575  * also!
576  */
577 int generic_writepages(struct address_space *mapping,
578                        struct writeback_control *wbc)
579 {
580         struct backing_dev_info *bdi = mapping->backing_dev_info;
581         int ret = 0;
582         int done = 0;
583         int (*writepage)(struct page *page, struct writeback_control *wbc);
584         struct pagevec pvec;
585         int nr_pages;
586         pgoff_t index;
587         pgoff_t end;            /* Inclusive */
588         int scanned = 0;
589         int range_whole = 0;
590
591         if (wbc->nonblocking && bdi_write_congested(bdi)) {
592                 wbc->encountered_congestion = 1;
593                 return 0;
594         }
595
596         writepage = mapping->a_ops->writepage;
597
598         /* deal with chardevs and other special file */
599         if (!writepage)
600                 return 0;
601
602         pagevec_init(&pvec, 0);
603         if (wbc->range_cyclic) {
604                 index = mapping->writeback_index; /* Start from prev offset */
605                 end = -1;
606         } else {
607                 index = wbc->range_start >> PAGE_CACHE_SHIFT;
608                 end = wbc->range_end >> PAGE_CACHE_SHIFT;
609                 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
610                         range_whole = 1;
611                 scanned = 1;
612         }
613 retry:
614         while (!done && (index <= end) &&
615                (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
616                                               PAGECACHE_TAG_DIRTY,
617                                               min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1))) {
618                 unsigned i;
619
620                 scanned = 1;
621                 for (i = 0; i < nr_pages; i++) {
622                         struct page *page = pvec.pages[i];
623
624                         /*
625                          * At this point we hold neither mapping->tree_lock nor
626                          * lock on the page itself: the page may be truncated or
627                          * invalidated (changing page->mapping to NULL), or even
628                          * swizzled back from swapper_space to tmpfs file
629                          * mapping
630                          */
631                         lock_page(page);
632
633                         if (unlikely(page->mapping != mapping)) {
634                                 unlock_page(page);
635                                 continue;
636                         }
637
638                         if (!wbc->range_cyclic && page->index > end) {
639                                 done = 1;
640                                 unlock_page(page);
641                                 continue;
642                         }
643
644                         if (wbc->sync_mode != WB_SYNC_NONE)
645                                 wait_on_page_writeback(page);
646
647                         if (PageWriteback(page) ||
648                             !clear_page_dirty_for_io(page)) {
649                                 unlock_page(page);
650                                 continue;
651                         }
652
653                         ret = (*writepage)(page, wbc);
654                         if (ret) {
655                                 if (ret == -ENOSPC)
656                                         set_bit(AS_ENOSPC, &mapping->flags);
657                                 else
658                                         set_bit(AS_EIO, &mapping->flags);
659                         }
660
661                         if (unlikely(ret == AOP_WRITEPAGE_ACTIVATE))
662                                 unlock_page(page);
663                         if (ret || (--(wbc->nr_to_write) <= 0))
664                                 done = 1;
665                         if (wbc->nonblocking && bdi_write_congested(bdi)) {
666                                 wbc->encountered_congestion = 1;
667                                 done = 1;
668                         }
669                 }
670                 pagevec_release(&pvec);
671                 cond_resched();
672         }
673         if (!scanned && !done) {
674                 /*
675                  * We hit the last page and there is more work to be done: wrap
676                  * back to the start of the file
677                  */
678                 scanned = 1;
679                 index = 0;
680                 goto retry;
681         }
682         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
683                 mapping->writeback_index = index;
684         return ret;
685 }
686
687 EXPORT_SYMBOL(generic_writepages);
688
689 int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
690 {
691         int ret;
692
693         if (wbc->nr_to_write <= 0)
694                 return 0;
695         wbc->for_writepages = 1;
696         if (mapping->a_ops->writepages)
697                 ret = mapping->a_ops->writepages(mapping, wbc);
698         else
699                 ret = generic_writepages(mapping, wbc);
700         wbc->for_writepages = 0;
701         return ret;
702 }
703
704 /**
705  * write_one_page - write out a single page and optionally wait on I/O
706  *
707  * @page: the page to write
708  * @wait: if true, wait on writeout
709  *
710  * The page must be locked by the caller and will be unlocked upon return.
711  *
712  * write_one_page() returns a negative error code if I/O failed.
713  */
714 int write_one_page(struct page *page, int wait)
715 {
716         struct address_space *mapping = page->mapping;
717         int ret = 0;
718         struct writeback_control wbc = {
719                 .sync_mode = WB_SYNC_ALL,
720                 .nr_to_write = 1,
721         };
722
723         BUG_ON(!PageLocked(page));
724
725         if (wait)
726                 wait_on_page_writeback(page);
727
728         if (clear_page_dirty_for_io(page)) {
729                 page_cache_get(page);
730                 ret = mapping->a_ops->writepage(page, &wbc);
731                 if (ret == 0 && wait) {
732                         wait_on_page_writeback(page);
733                         if (PageError(page))
734                                 ret = -EIO;
735                 }
736                 page_cache_release(page);
737         } else {
738                 unlock_page(page);
739         }
740         return ret;
741 }
742 EXPORT_SYMBOL(write_one_page);
743
744 /*
745  * For address_spaces which do not use buffers.  Just tag the page as dirty in
746  * its radix tree.
747  *
748  * This is also used when a single buffer is being dirtied: we want to set the
749  * page dirty in that case, but not all the buffers.  This is a "bottom-up"
750  * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
751  *
752  * Most callers have locked the page, which pins the address_space in memory.
753  * But zap_pte_range() does not lock the page, however in that case the
754  * mapping is pinned by the vma's ->vm_file reference.
755  *
756  * We take care to handle the case where the page was truncated from the
757  * mapping by re-checking page_mapping() insode tree_lock.
758  */
759 int __set_page_dirty_nobuffers(struct page *page)
760 {
761         if (!TestSetPageDirty(page)) {
762                 struct address_space *mapping = page_mapping(page);
763                 struct address_space *mapping2;
764
765                 if (!mapping)
766                         return 1;
767
768                 write_lock_irq(&mapping->tree_lock);
769                 mapping2 = page_mapping(page);
770                 if (mapping2) { /* Race with truncate? */
771                         BUG_ON(mapping2 != mapping);
772                         if (mapping_cap_account_dirty(mapping)) {
773                                 __inc_zone_page_state(page, NR_FILE_DIRTY);
774                                 task_io_account_write(PAGE_CACHE_SIZE);
775                         }
776                         radix_tree_tag_set(&mapping->page_tree,
777                                 page_index(page), PAGECACHE_TAG_DIRTY);
778                 }
779                 write_unlock_irq(&mapping->tree_lock);
780                 if (mapping->host) {
781                         /* !PageAnon && !swapper_space */
782                         __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
783                 }
784                 return 1;
785         }
786         return 0;
787 }
788 EXPORT_SYMBOL(__set_page_dirty_nobuffers);
789
790 /*
791  * When a writepage implementation decides that it doesn't want to write this
792  * page for some reason, it should redirty the locked page via
793  * redirty_page_for_writepage() and it should then unlock the page and return 0
794  */
795 int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
796 {
797         wbc->pages_skipped++;
798         return __set_page_dirty_nobuffers(page);
799 }
800 EXPORT_SYMBOL(redirty_page_for_writepage);
801
802 /*
803  * If the mapping doesn't provide a set_page_dirty a_op, then
804  * just fall through and assume that it wants buffer_heads.
805  */
806 int fastcall set_page_dirty(struct page *page)
807 {
808         struct address_space *mapping = page_mapping(page);
809
810         if (likely(mapping)) {
811                 int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
812 #ifdef CONFIG_BLOCK
813                 if (!spd)
814                         spd = __set_page_dirty_buffers;
815 #endif
816                 return (*spd)(page);
817         }
818         if (!PageDirty(page)) {
819                 if (!TestSetPageDirty(page))
820                         return 1;
821         }
822         return 0;
823 }
824 EXPORT_SYMBOL(set_page_dirty);
825
826 /*
827  * set_page_dirty() is racy if the caller has no reference against
828  * page->mapping->host, and if the page is unlocked.  This is because another
829  * CPU could truncate the page off the mapping and then free the mapping.
830  *
831  * Usually, the page _is_ locked, or the caller is a user-space process which
832  * holds a reference on the inode by having an open file.
833  *
834  * In other cases, the page should be locked before running set_page_dirty().
835  */
836 int set_page_dirty_lock(struct page *page)
837 {
838         int ret;
839
840         lock_page_nosync(page);
841         ret = set_page_dirty(page);
842         unlock_page(page);
843         return ret;
844 }
845 EXPORT_SYMBOL(set_page_dirty_lock);
846
847 /*
848  * Clear a page's dirty flag, while caring for dirty memory accounting. 
849  * Returns true if the page was previously dirty.
850  */
851 int test_clear_page_dirty(struct page *page)
852 {
853         struct address_space *mapping = page_mapping(page);
854         unsigned long flags;
855
856         if (!mapping)
857                 return TestClearPageDirty(page);
858
859         write_lock_irqsave(&mapping->tree_lock, flags);
860         if (TestClearPageDirty(page)) {
861                 radix_tree_tag_clear(&mapping->page_tree,
862                                 page_index(page), PAGECACHE_TAG_DIRTY);
863                 write_unlock_irqrestore(&mapping->tree_lock, flags);
864                 /*
865                  * We can continue to use `mapping' here because the
866                  * page is locked, which pins the address_space
867                  */
868                 if (mapping_cap_account_dirty(mapping)) {
869                         page_mkclean(page);
870                         dec_zone_page_state(page, NR_FILE_DIRTY);
871                 }
872                 return 1;
873         }
874         write_unlock_irqrestore(&mapping->tree_lock, flags);
875         return 0;
876 }
877 EXPORT_SYMBOL(test_clear_page_dirty);
878
879 /*
880  * Clear a page's dirty flag, while caring for dirty memory accounting.
881  * Returns true if the page was previously dirty.
882  *
883  * This is for preparing to put the page under writeout.  We leave the page
884  * tagged as dirty in the radix tree so that a concurrent write-for-sync
885  * can discover it via a PAGECACHE_TAG_DIRTY walk.  The ->writepage
886  * implementation will run either set_page_writeback() or set_page_dirty(),
887  * at which stage we bring the page's dirty flag and radix-tree dirty tag
888  * back into sync.
889  *
890  * This incoherency between the page's dirty flag and radix-tree tag is
891  * unfortunate, but it only exists while the page is locked.
892  */
893 int clear_page_dirty_for_io(struct page *page)
894 {
895         struct address_space *mapping = page_mapping(page);
896
897         if (!mapping)
898                 return TestClearPageDirty(page);
899
900         if (TestClearPageDirty(page)) {
901                 if (mapping_cap_account_dirty(mapping)) {
902                         page_mkclean(page);
903                         dec_zone_page_state(page, NR_FILE_DIRTY);
904                 }
905                 return 1;
906         }
907         return 0;
908 }
909 EXPORT_SYMBOL(clear_page_dirty_for_io);
910
911 int test_clear_page_writeback(struct page *page)
912 {
913         struct address_space *mapping = page_mapping(page);
914         int ret;
915
916         if (mapping) {
917                 unsigned long flags;
918
919                 write_lock_irqsave(&mapping->tree_lock, flags);
920                 ret = TestClearPageWriteback(page);
921                 if (ret)
922                         radix_tree_tag_clear(&mapping->page_tree,
923                                                 page_index(page),
924                                                 PAGECACHE_TAG_WRITEBACK);
925                 write_unlock_irqrestore(&mapping->tree_lock, flags);
926         } else {
927                 ret = TestClearPageWriteback(page);
928         }
929         return ret;
930 }
931
932 int test_set_page_writeback(struct page *page)
933 {
934         struct address_space *mapping = page_mapping(page);
935         int ret;
936
937         if (mapping) {
938                 unsigned long flags;
939
940                 write_lock_irqsave(&mapping->tree_lock, flags);
941                 ret = TestSetPageWriteback(page);
942                 if (!ret)
943                         radix_tree_tag_set(&mapping->page_tree,
944                                                 page_index(page),
945                                                 PAGECACHE_TAG_WRITEBACK);
946                 if (!PageDirty(page))
947                         radix_tree_tag_clear(&mapping->page_tree,
948                                                 page_index(page),
949                                                 PAGECACHE_TAG_DIRTY);
950                 write_unlock_irqrestore(&mapping->tree_lock, flags);
951         } else {
952                 ret = TestSetPageWriteback(page);
953         }
954         return ret;
955
956 }
957 EXPORT_SYMBOL(test_set_page_writeback);
958
959 /*
960  * Return true if any of the pages in the mapping are marged with the
961  * passed tag.
962  */
963 int mapping_tagged(struct address_space *mapping, int tag)
964 {
965         unsigned long flags;
966         int ret;
967
968         read_lock_irqsave(&mapping->tree_lock, flags);
969         ret = radix_tree_tagged(&mapping->page_tree, tag);
970         read_unlock_irqrestore(&mapping->tree_lock, flags);
971         return ret;
972 }
973 EXPORT_SYMBOL(mapping_tagged);