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