]> git.ipfire.org Git - thirdparty/kernel/linux.git/blame - mm/page-writeback.c
writeback: max, min and target dirty pause time
[thirdparty/kernel/linux.git] / mm / page-writeback.c
CommitLineData
1da177e4 1/*
f30c2269 2 * mm/page-writeback.c
1da177e4
LT
3 *
4 * Copyright (C) 2002, Linus Torvalds.
04fbfdc1 5 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
1da177e4
LT
6 *
7 * Contains functions related to writing back dirty pages at the
8 * address_space level.
9 *
e1f8e874 10 * 10Apr2002 Andrew Morton
1da177e4
LT
11 * Initial version
12 */
13
14#include <linux/kernel.h>
b95f1b31 15#include <linux/export.h>
1da177e4
LT
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>
55e829af 25#include <linux/task_io_accounting_ops.h>
1da177e4
LT
26#include <linux/blkdev.h>
27#include <linux/mpage.h>
d08b3851 28#include <linux/rmap.h>
1da177e4
LT
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>
cf9a2ae8 35#include <linux/buffer_head.h>
811d736f 36#include <linux/pagevec.h>
028c2dd1 37#include <trace/events/writeback.h>
1da177e4 38
ffd1f609
WF
39/*
40 * Sleep at most 200ms at a time in balance_dirty_pages().
41 */
42#define MAX_PAUSE max(HZ/5, 1)
43
e98be2d5
WF
44/*
45 * Estimate write bandwidth at 200ms intervals.
46 */
47#define BANDWIDTH_INTERVAL max(HZ/5, 1)
48
6c14ae1e
WF
49#define RATELIMIT_CALC_SHIFT 10
50
1da177e4
LT
51/*
52 * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
53 * will look to see if it needs to force writeback or throttling.
54 */
55static long ratelimit_pages = 32;
56
1da177e4
LT
57/* The following parameters are exported via /proc/sys/vm */
58
59/*
5b0830cb 60 * Start background writeback (via writeback threads) at this percentage
1da177e4 61 */
1b5e62b4 62int dirty_background_ratio = 10;
1da177e4 63
2da02997
DR
64/*
65 * dirty_background_bytes starts at 0 (disabled) so that it is a function of
66 * dirty_background_ratio * the amount of dirtyable memory
67 */
68unsigned long dirty_background_bytes;
69
195cf453
BG
70/*
71 * free highmem will not be subtracted from the total free memory
72 * for calculating free ratios if vm_highmem_is_dirtyable is true
73 */
74int vm_highmem_is_dirtyable;
75
1da177e4
LT
76/*
77 * The generator of dirty data starts writeback at this percentage
78 */
1b5e62b4 79int vm_dirty_ratio = 20;
1da177e4 80
2da02997
DR
81/*
82 * vm_dirty_bytes starts at 0 (disabled) so that it is a function of
83 * vm_dirty_ratio * the amount of dirtyable memory
84 */
85unsigned long vm_dirty_bytes;
86
1da177e4 87/*
704503d8 88 * The interval between `kupdate'-style writebacks
1da177e4 89 */
22ef37ee 90unsigned int dirty_writeback_interval = 5 * 100; /* centiseconds */
1da177e4
LT
91
92/*
704503d8 93 * The longest time for which data is allowed to remain dirty
1da177e4 94 */
22ef37ee 95unsigned int dirty_expire_interval = 30 * 100; /* centiseconds */
1da177e4
LT
96
97/*
98 * Flag that makes the machine dump writes/reads and block dirtyings.
99 */
100int block_dump;
101
102/*
ed5b43f1
BS
103 * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
104 * a full sync is triggered after this time elapses without any disk activity.
1da177e4
LT
105 */
106int laptop_mode;
107
108EXPORT_SYMBOL(laptop_mode);
109
110/* End of sysctl-exported parameters */
111
c42843f2 112unsigned long global_dirty_limit;
1da177e4 113
04fbfdc1
PZ
114/*
115 * Scale the writeback cache size proportional to the relative writeout speeds.
116 *
117 * We do this by keeping a floating proportion between BDIs, based on page
118 * writeback completions [end_page_writeback()]. Those devices that write out
119 * pages fastest will get the larger share, while the slower will get a smaller
120 * share.
121 *
122 * We use page writeout completions because we are interested in getting rid of
123 * dirty pages. Having them written out is the primary goal.
124 *
125 * We introduce a concept of time, a period over which we measure these events,
126 * because demand can/will vary over time. The length of this period itself is
127 * measured in page writeback completions.
128 *
129 */
130static struct prop_descriptor vm_completions;
131
04fbfdc1
PZ
132/*
133 * couple the period to the dirty_ratio:
134 *
135 * period/2 ~ roundup_pow_of_two(dirty limit)
136 */
137static int calc_period_shift(void)
138{
139 unsigned long dirty_total;
140
2da02997
DR
141 if (vm_dirty_bytes)
142 dirty_total = vm_dirty_bytes / PAGE_SIZE;
143 else
144 dirty_total = (vm_dirty_ratio * determine_dirtyable_memory()) /
145 100;
04fbfdc1
PZ
146 return 2 + ilog2(dirty_total - 1);
147}
148
149/*
2da02997 150 * update the period when the dirty threshold changes.
04fbfdc1 151 */
2da02997
DR
152static void update_completion_period(void)
153{
154 int shift = calc_period_shift();
155 prop_change_shift(&vm_completions, shift);
9d823e8f
WF
156
157 writeback_set_ratelimit();
2da02997
DR
158}
159
160int dirty_background_ratio_handler(struct ctl_table *table, int write,
8d65af78 161 void __user *buffer, size_t *lenp,
2da02997
DR
162 loff_t *ppos)
163{
164 int ret;
165
8d65af78 166 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
2da02997
DR
167 if (ret == 0 && write)
168 dirty_background_bytes = 0;
169 return ret;
170}
171
172int dirty_background_bytes_handler(struct ctl_table *table, int write,
8d65af78 173 void __user *buffer, size_t *lenp,
2da02997
DR
174 loff_t *ppos)
175{
176 int ret;
177
8d65af78 178 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
2da02997
DR
179 if (ret == 0 && write)
180 dirty_background_ratio = 0;
181 return ret;
182}
183
04fbfdc1 184int dirty_ratio_handler(struct ctl_table *table, int write,
8d65af78 185 void __user *buffer, size_t *lenp,
04fbfdc1
PZ
186 loff_t *ppos)
187{
188 int old_ratio = vm_dirty_ratio;
2da02997
DR
189 int ret;
190
8d65af78 191 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
04fbfdc1 192 if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
2da02997
DR
193 update_completion_period();
194 vm_dirty_bytes = 0;
195 }
196 return ret;
197}
198
199
200int dirty_bytes_handler(struct ctl_table *table, int write,
8d65af78 201 void __user *buffer, size_t *lenp,
2da02997
DR
202 loff_t *ppos)
203{
fc3501d4 204 unsigned long old_bytes = vm_dirty_bytes;
2da02997
DR
205 int ret;
206
8d65af78 207 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
2da02997
DR
208 if (ret == 0 && write && vm_dirty_bytes != old_bytes) {
209 update_completion_period();
210 vm_dirty_ratio = 0;
04fbfdc1
PZ
211 }
212 return ret;
213}
214
215/*
216 * Increment the BDI's writeout completion count and the global writeout
217 * completion count. Called from test_clear_page_writeback().
218 */
219static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
220{
f7d2b1ec 221 __inc_bdi_stat(bdi, BDI_WRITTEN);
a42dde04
PZ
222 __prop_inc_percpu_max(&vm_completions, &bdi->completions,
223 bdi->max_prop_frac);
04fbfdc1
PZ
224}
225
dd5656e5
MS
226void bdi_writeout_inc(struct backing_dev_info *bdi)
227{
228 unsigned long flags;
229
230 local_irq_save(flags);
231 __bdi_writeout_inc(bdi);
232 local_irq_restore(flags);
233}
234EXPORT_SYMBOL_GPL(bdi_writeout_inc);
235
04fbfdc1
PZ
236/*
237 * Obtain an accurate fraction of the BDI's portion.
238 */
239static void bdi_writeout_fraction(struct backing_dev_info *bdi,
240 long *numerator, long *denominator)
241{
3efaf0fa 242 prop_fraction_percpu(&vm_completions, &bdi->completions,
04fbfdc1 243 numerator, denominator);
04fbfdc1
PZ
244}
245
189d3c4a 246/*
d08c429b
JW
247 * bdi_min_ratio keeps the sum of the minimum dirty shares of all
248 * registered backing devices, which, for obvious reasons, can not
249 * exceed 100%.
189d3c4a 250 */
189d3c4a
PZ
251static unsigned int bdi_min_ratio;
252
253int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio)
254{
255 int ret = 0;
189d3c4a 256
cfc4ba53 257 spin_lock_bh(&bdi_lock);
a42dde04 258 if (min_ratio > bdi->max_ratio) {
189d3c4a 259 ret = -EINVAL;
a42dde04
PZ
260 } else {
261 min_ratio -= bdi->min_ratio;
262 if (bdi_min_ratio + min_ratio < 100) {
263 bdi_min_ratio += min_ratio;
264 bdi->min_ratio += min_ratio;
265 } else {
266 ret = -EINVAL;
267 }
268 }
cfc4ba53 269 spin_unlock_bh(&bdi_lock);
a42dde04
PZ
270
271 return ret;
272}
273
274int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio)
275{
a42dde04
PZ
276 int ret = 0;
277
278 if (max_ratio > 100)
279 return -EINVAL;
280
cfc4ba53 281 spin_lock_bh(&bdi_lock);
a42dde04
PZ
282 if (bdi->min_ratio > max_ratio) {
283 ret = -EINVAL;
284 } else {
285 bdi->max_ratio = max_ratio;
286 bdi->max_prop_frac = (PROP_FRAC_BASE * max_ratio) / 100;
287 }
cfc4ba53 288 spin_unlock_bh(&bdi_lock);
189d3c4a
PZ
289
290 return ret;
291}
a42dde04 292EXPORT_SYMBOL(bdi_set_max_ratio);
189d3c4a 293
1da177e4
LT
294/*
295 * Work out the current dirty-memory clamping and background writeout
296 * thresholds.
297 *
298 * The main aim here is to lower them aggressively if there is a lot of mapped
299 * memory around. To avoid stressing page reclaim with lots of unreclaimable
300 * pages. It is better to clamp down on writers than to start swapping, and
301 * performing lots of scanning.
302 *
303 * We only allow 1/2 of the currently-unmapped memory to be dirtied.
304 *
305 * We don't permit the clamping level to fall below 5% - that is getting rather
306 * excessive.
307 *
308 * We make sure that the background writeout level is below the adjusted
309 * clamping level.
310 */
1b424464
CL
311
312static unsigned long highmem_dirtyable_memory(unsigned long total)
313{
314#ifdef CONFIG_HIGHMEM
315 int node;
316 unsigned long x = 0;
317
37b07e41 318 for_each_node_state(node, N_HIGH_MEMORY) {
1b424464
CL
319 struct zone *z =
320 &NODE_DATA(node)->node_zones[ZONE_HIGHMEM];
321
adea02a1
WF
322 x += zone_page_state(z, NR_FREE_PAGES) +
323 zone_reclaimable_pages(z);
1b424464
CL
324 }
325 /*
326 * Make sure that the number of highmem pages is never larger
327 * than the number of the total dirtyable memory. This can only
328 * occur in very strange VM situations but we want to make sure
329 * that this does not occur.
330 */
331 return min(x, total);
332#else
333 return 0;
334#endif
335}
336
3eefae99
SR
337/**
338 * determine_dirtyable_memory - amount of memory that may be used
339 *
340 * Returns the numebr of pages that can currently be freed and used
341 * by the kernel for direct mappings.
342 */
343unsigned long determine_dirtyable_memory(void)
1b424464
CL
344{
345 unsigned long x;
346
adea02a1 347 x = global_page_state(NR_FREE_PAGES) + global_reclaimable_pages();
195cf453
BG
348
349 if (!vm_highmem_is_dirtyable)
350 x -= highmem_dirtyable_memory(x);
351
1b424464
CL
352 return x + 1; /* Ensure that we never return 0 */
353}
354
6c14ae1e
WF
355static unsigned long dirty_freerun_ceiling(unsigned long thresh,
356 unsigned long bg_thresh)
357{
358 return (thresh + bg_thresh) / 2;
359}
360
ffd1f609
WF
361static unsigned long hard_dirty_limit(unsigned long thresh)
362{
363 return max(thresh, global_dirty_limit);
364}
365
03ab450f 366/*
1babe183
WF
367 * global_dirty_limits - background-writeback and dirty-throttling thresholds
368 *
369 * Calculate the dirty thresholds based on sysctl parameters
370 * - vm.dirty_background_ratio or vm.dirty_background_bytes
371 * - vm.dirty_ratio or vm.dirty_bytes
372 * The dirty limits will be lifted by 1/4 for PF_LESS_THROTTLE (ie. nfsd) and
ebd1373d 373 * real-time tasks.
1babe183 374 */
16c4042f 375void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty)
1da177e4 376{
364aeb28
DR
377 unsigned long background;
378 unsigned long dirty;
240c879f 379 unsigned long uninitialized_var(available_memory);
1da177e4
LT
380 struct task_struct *tsk;
381
240c879f
MK
382 if (!vm_dirty_bytes || !dirty_background_bytes)
383 available_memory = determine_dirtyable_memory();
384
2da02997
DR
385 if (vm_dirty_bytes)
386 dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE);
4cbec4c8
WF
387 else
388 dirty = (vm_dirty_ratio * available_memory) / 100;
1da177e4 389
2da02997
DR
390 if (dirty_background_bytes)
391 background = DIV_ROUND_UP(dirty_background_bytes, PAGE_SIZE);
392 else
393 background = (dirty_background_ratio * available_memory) / 100;
1da177e4 394
2da02997
DR
395 if (background >= dirty)
396 background = dirty / 2;
1da177e4
LT
397 tsk = current;
398 if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
399 background += background / 4;
400 dirty += dirty / 4;
401 }
402 *pbackground = background;
403 *pdirty = dirty;
e1cbe236 404 trace_global_dirty_state(background, dirty);
16c4042f 405}
04fbfdc1 406
6f718656 407/**
1babe183 408 * bdi_dirty_limit - @bdi's share of dirty throttling threshold
6f718656
WF
409 * @bdi: the backing_dev_info to query
410 * @dirty: global dirty limit in pages
1babe183 411 *
6f718656
WF
412 * Returns @bdi's dirty limit in pages. The term "dirty" in the context of
413 * dirty balancing includes all PG_dirty, PG_writeback and NFS unstable pages.
aed21ad2
WF
414 *
415 * Note that balance_dirty_pages() will only seriously take it as a hard limit
416 * when sleeping max_pause per page is not enough to keep the dirty pages under
417 * control. For example, when the device is completely stalled due to some error
418 * conditions, or when there are 1000 dd tasks writing to a slow 10MB/s USB key.
419 * In the other normal situations, it acts more gently by throttling the tasks
420 * more (rather than completely block them) when the bdi dirty pages go high.
1babe183 421 *
6f718656 422 * It allocates high/low dirty limits to fast/slow devices, in order to prevent
1babe183
WF
423 * - starving fast devices
424 * - piling up dirty pages (that will take long time to sync) on slow devices
425 *
426 * The bdi's share of dirty limit will be adapting to its throughput and
427 * bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set.
428 */
429unsigned long bdi_dirty_limit(struct backing_dev_info *bdi, unsigned long dirty)
16c4042f
WF
430{
431 u64 bdi_dirty;
432 long numerator, denominator;
04fbfdc1 433
16c4042f
WF
434 /*
435 * Calculate this BDI's share of the dirty ratio.
436 */
437 bdi_writeout_fraction(bdi, &numerator, &denominator);
04fbfdc1 438
16c4042f
WF
439 bdi_dirty = (dirty * (100 - bdi_min_ratio)) / 100;
440 bdi_dirty *= numerator;
441 do_div(bdi_dirty, denominator);
04fbfdc1 442
16c4042f
WF
443 bdi_dirty += (dirty * bdi->min_ratio) / 100;
444 if (bdi_dirty > (dirty * bdi->max_ratio) / 100)
445 bdi_dirty = dirty * bdi->max_ratio / 100;
446
447 return bdi_dirty;
1da177e4
LT
448}
449
6c14ae1e
WF
450/*
451 * Dirty position control.
452 *
453 * (o) global/bdi setpoints
454 *
455 * We want the dirty pages be balanced around the global/bdi setpoints.
456 * When the number of dirty pages is higher/lower than the setpoint, the
457 * dirty position control ratio (and hence task dirty ratelimit) will be
458 * decreased/increased to bring the dirty pages back to the setpoint.
459 *
460 * pos_ratio = 1 << RATELIMIT_CALC_SHIFT
461 *
462 * if (dirty < setpoint) scale up pos_ratio
463 * if (dirty > setpoint) scale down pos_ratio
464 *
465 * if (bdi_dirty < bdi_setpoint) scale up pos_ratio
466 * if (bdi_dirty > bdi_setpoint) scale down pos_ratio
467 *
468 * task_ratelimit = dirty_ratelimit * pos_ratio >> RATELIMIT_CALC_SHIFT
469 *
470 * (o) global control line
471 *
472 * ^ pos_ratio
473 * |
474 * | |<===== global dirty control scope ======>|
475 * 2.0 .............*
476 * | .*
477 * | . *
478 * | . *
479 * | . *
480 * | . *
481 * | . *
482 * 1.0 ................................*
483 * | . . *
484 * | . . *
485 * | . . *
486 * | . . *
487 * | . . *
488 * 0 +------------.------------------.----------------------*------------->
489 * freerun^ setpoint^ limit^ dirty pages
490 *
491 * (o) bdi control line
492 *
493 * ^ pos_ratio
494 * |
495 * | *
496 * | *
497 * | *
498 * | *
499 * | * |<=========== span ============>|
500 * 1.0 .......................*
501 * | . *
502 * | . *
503 * | . *
504 * | . *
505 * | . *
506 * | . *
507 * | . *
508 * | . *
509 * | . *
510 * | . *
511 * | . *
512 * 1/4 ...............................................* * * * * * * * * * * *
513 * | . .
514 * | . .
515 * | . .
516 * 0 +----------------------.-------------------------------.------------->
517 * bdi_setpoint^ x_intercept^
518 *
519 * The bdi control line won't drop below pos_ratio=1/4, so that bdi_dirty can
520 * be smoothly throttled down to normal if it starts high in situations like
521 * - start writing to a slow SD card and a fast disk at the same time. The SD
522 * card's bdi_dirty may rush to many times higher than bdi_setpoint.
523 * - the bdi dirty thresh drops quickly due to change of JBOD workload
524 */
525static unsigned long bdi_position_ratio(struct backing_dev_info *bdi,
526 unsigned long thresh,
527 unsigned long bg_thresh,
528 unsigned long dirty,
529 unsigned long bdi_thresh,
530 unsigned long bdi_dirty)
531{
532 unsigned long write_bw = bdi->avg_write_bandwidth;
533 unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh);
534 unsigned long limit = hard_dirty_limit(thresh);
535 unsigned long x_intercept;
536 unsigned long setpoint; /* dirty pages' target balance point */
537 unsigned long bdi_setpoint;
538 unsigned long span;
539 long long pos_ratio; /* for scaling up/down the rate limit */
540 long x;
541
542 if (unlikely(dirty >= limit))
543 return 0;
544
545 /*
546 * global setpoint
547 *
548 * setpoint - dirty 3
549 * f(dirty) := 1.0 + (----------------)
550 * limit - setpoint
551 *
552 * it's a 3rd order polynomial that subjects to
553 *
554 * (1) f(freerun) = 2.0 => rampup dirty_ratelimit reasonably fast
555 * (2) f(setpoint) = 1.0 => the balance point
556 * (3) f(limit) = 0 => the hard limit
557 * (4) df/dx <= 0 => negative feedback control
558 * (5) the closer to setpoint, the smaller |df/dx| (and the reverse)
559 * => fast response on large errors; small oscillation near setpoint
560 */
561 setpoint = (freerun + limit) / 2;
562 x = div_s64((setpoint - dirty) << RATELIMIT_CALC_SHIFT,
563 limit - setpoint + 1);
564 pos_ratio = x;
565 pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
566 pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
567 pos_ratio += 1 << RATELIMIT_CALC_SHIFT;
568
569 /*
570 * We have computed basic pos_ratio above based on global situation. If
571 * the bdi is over/under its share of dirty pages, we want to scale
572 * pos_ratio further down/up. That is done by the following mechanism.
573 */
574
575 /*
576 * bdi setpoint
577 *
578 * f(bdi_dirty) := 1.0 + k * (bdi_dirty - bdi_setpoint)
579 *
580 * x_intercept - bdi_dirty
581 * := --------------------------
582 * x_intercept - bdi_setpoint
583 *
584 * The main bdi control line is a linear function that subjects to
585 *
586 * (1) f(bdi_setpoint) = 1.0
587 * (2) k = - 1 / (8 * write_bw) (in single bdi case)
588 * or equally: x_intercept = bdi_setpoint + 8 * write_bw
589 *
590 * For single bdi case, the dirty pages are observed to fluctuate
591 * regularly within range
592 * [bdi_setpoint - write_bw/2, bdi_setpoint + write_bw/2]
593 * for various filesystems, where (2) can yield in a reasonable 12.5%
594 * fluctuation range for pos_ratio.
595 *
596 * For JBOD case, bdi_thresh (not bdi_dirty!) could fluctuate up to its
597 * own size, so move the slope over accordingly and choose a slope that
598 * yields 100% pos_ratio fluctuation on suddenly doubled bdi_thresh.
599 */
600 if (unlikely(bdi_thresh > thresh))
601 bdi_thresh = thresh;
aed21ad2
WF
602 /*
603 * It's very possible that bdi_thresh is close to 0 not because the
604 * device is slow, but that it has remained inactive for long time.
605 * Honour such devices a reasonable good (hopefully IO efficient)
606 * threshold, so that the occasional writes won't be blocked and active
607 * writes can rampup the threshold quickly.
608 */
8927f66c 609 bdi_thresh = max(bdi_thresh, (limit - dirty) / 8);
6c14ae1e
WF
610 /*
611 * scale global setpoint to bdi's:
612 * bdi_setpoint = setpoint * bdi_thresh / thresh
613 */
614 x = div_u64((u64)bdi_thresh << 16, thresh + 1);
615 bdi_setpoint = setpoint * (u64)x >> 16;
616 /*
617 * Use span=(8*write_bw) in single bdi case as indicated by
618 * (thresh - bdi_thresh ~= 0) and transit to bdi_thresh in JBOD case.
619 *
620 * bdi_thresh thresh - bdi_thresh
621 * span = ---------- * (8 * write_bw) + ------------------- * bdi_thresh
622 * thresh thresh
623 */
624 span = (thresh - bdi_thresh + 8 * write_bw) * (u64)x >> 16;
625 x_intercept = bdi_setpoint + span;
626
627 if (bdi_dirty < x_intercept - span / 4) {
50657fc4
WF
628 pos_ratio = div_u64(pos_ratio * (x_intercept - bdi_dirty),
629 x_intercept - bdi_setpoint + 1);
6c14ae1e
WF
630 } else
631 pos_ratio /= 4;
632
8927f66c
WF
633 /*
634 * bdi reserve area, safeguard against dirty pool underrun and disk idle
635 * It may push the desired control point of global dirty pages higher
636 * than setpoint.
637 */
638 x_intercept = bdi_thresh / 2;
639 if (bdi_dirty < x_intercept) {
50657fc4
WF
640 if (bdi_dirty > x_intercept / 8)
641 pos_ratio = div_u64(pos_ratio * x_intercept, bdi_dirty);
642 else
8927f66c
WF
643 pos_ratio *= 8;
644 }
645
6c14ae1e
WF
646 return pos_ratio;
647}
648
e98be2d5
WF
649static void bdi_update_write_bandwidth(struct backing_dev_info *bdi,
650 unsigned long elapsed,
651 unsigned long written)
652{
653 const unsigned long period = roundup_pow_of_two(3 * HZ);
654 unsigned long avg = bdi->avg_write_bandwidth;
655 unsigned long old = bdi->write_bandwidth;
656 u64 bw;
657
658 /*
659 * bw = written * HZ / elapsed
660 *
661 * bw * elapsed + write_bandwidth * (period - elapsed)
662 * write_bandwidth = ---------------------------------------------------
663 * period
664 */
665 bw = written - bdi->written_stamp;
666 bw *= HZ;
667 if (unlikely(elapsed > period)) {
668 do_div(bw, elapsed);
669 avg = bw;
670 goto out;
671 }
672 bw += (u64)bdi->write_bandwidth * (period - elapsed);
673 bw >>= ilog2(period);
674
675 /*
676 * one more level of smoothing, for filtering out sudden spikes
677 */
678 if (avg > old && old >= (unsigned long)bw)
679 avg -= (avg - old) >> 3;
680
681 if (avg < old && old <= (unsigned long)bw)
682 avg += (old - avg) >> 3;
683
684out:
685 bdi->write_bandwidth = bw;
686 bdi->avg_write_bandwidth = avg;
687}
688
c42843f2
WF
689/*
690 * The global dirtyable memory and dirty threshold could be suddenly knocked
691 * down by a large amount (eg. on the startup of KVM in a swapless system).
692 * This may throw the system into deep dirty exceeded state and throttle
693 * heavy/light dirtiers alike. To retain good responsiveness, maintain
694 * global_dirty_limit for tracking slowly down to the knocked down dirty
695 * threshold.
696 */
697static void update_dirty_limit(unsigned long thresh, unsigned long dirty)
698{
699 unsigned long limit = global_dirty_limit;
700
701 /*
702 * Follow up in one step.
703 */
704 if (limit < thresh) {
705 limit = thresh;
706 goto update;
707 }
708
709 /*
710 * Follow down slowly. Use the higher one as the target, because thresh
711 * may drop below dirty. This is exactly the reason to introduce
712 * global_dirty_limit which is guaranteed to lie above the dirty pages.
713 */
714 thresh = max(thresh, dirty);
715 if (limit > thresh) {
716 limit -= (limit - thresh) >> 5;
717 goto update;
718 }
719 return;
720update:
721 global_dirty_limit = limit;
722}
723
724static void global_update_bandwidth(unsigned long thresh,
725 unsigned long dirty,
726 unsigned long now)
727{
728 static DEFINE_SPINLOCK(dirty_lock);
729 static unsigned long update_time;
730
731 /*
732 * check locklessly first to optimize away locking for the most time
733 */
734 if (time_before(now, update_time + BANDWIDTH_INTERVAL))
735 return;
736
737 spin_lock(&dirty_lock);
738 if (time_after_eq(now, update_time + BANDWIDTH_INTERVAL)) {
739 update_dirty_limit(thresh, dirty);
740 update_time = now;
741 }
742 spin_unlock(&dirty_lock);
743}
744
be3ffa27
WF
745/*
746 * Maintain bdi->dirty_ratelimit, the base dirty throttle rate.
747 *
748 * Normal bdi tasks will be curbed at or below it in long term.
749 * Obviously it should be around (write_bw / N) when there are N dd tasks.
750 */
751static void bdi_update_dirty_ratelimit(struct backing_dev_info *bdi,
752 unsigned long thresh,
753 unsigned long bg_thresh,
754 unsigned long dirty,
755 unsigned long bdi_thresh,
756 unsigned long bdi_dirty,
757 unsigned long dirtied,
758 unsigned long elapsed)
759{
7381131c
WF
760 unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh);
761 unsigned long limit = hard_dirty_limit(thresh);
762 unsigned long setpoint = (freerun + limit) / 2;
be3ffa27
WF
763 unsigned long write_bw = bdi->avg_write_bandwidth;
764 unsigned long dirty_ratelimit = bdi->dirty_ratelimit;
765 unsigned long dirty_rate;
766 unsigned long task_ratelimit;
767 unsigned long balanced_dirty_ratelimit;
768 unsigned long pos_ratio;
7381131c
WF
769 unsigned long step;
770 unsigned long x;
be3ffa27
WF
771
772 /*
773 * The dirty rate will match the writeout rate in long term, except
774 * when dirty pages are truncated by userspace or re-dirtied by FS.
775 */
776 dirty_rate = (dirtied - bdi->dirtied_stamp) * HZ / elapsed;
777
778 pos_ratio = bdi_position_ratio(bdi, thresh, bg_thresh, dirty,
779 bdi_thresh, bdi_dirty);
780 /*
781 * task_ratelimit reflects each dd's dirty rate for the past 200ms.
782 */
783 task_ratelimit = (u64)dirty_ratelimit *
784 pos_ratio >> RATELIMIT_CALC_SHIFT;
785 task_ratelimit++; /* it helps rampup dirty_ratelimit from tiny values */
786
787 /*
788 * A linear estimation of the "balanced" throttle rate. The theory is,
789 * if there are N dd tasks, each throttled at task_ratelimit, the bdi's
790 * dirty_rate will be measured to be (N * task_ratelimit). So the below
791 * formula will yield the balanced rate limit (write_bw / N).
792 *
793 * Note that the expanded form is not a pure rate feedback:
794 * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) (1)
795 * but also takes pos_ratio into account:
796 * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) * pos_ratio (2)
797 *
798 * (1) is not realistic because pos_ratio also takes part in balancing
799 * the dirty rate. Consider the state
800 * pos_ratio = 0.5 (3)
801 * rate = 2 * (write_bw / N) (4)
802 * If (1) is used, it will stuck in that state! Because each dd will
803 * be throttled at
804 * task_ratelimit = pos_ratio * rate = (write_bw / N) (5)
805 * yielding
806 * dirty_rate = N * task_ratelimit = write_bw (6)
807 * put (6) into (1) we get
808 * rate_(i+1) = rate_(i) (7)
809 *
810 * So we end up using (2) to always keep
811 * rate_(i+1) ~= (write_bw / N) (8)
812 * regardless of the value of pos_ratio. As long as (8) is satisfied,
813 * pos_ratio is able to drive itself to 1.0, which is not only where
814 * the dirty count meet the setpoint, but also where the slope of
815 * pos_ratio is most flat and hence task_ratelimit is least fluctuated.
816 */
817 balanced_dirty_ratelimit = div_u64((u64)task_ratelimit * write_bw,
818 dirty_rate | 1);
819
7381131c
WF
820 /*
821 * We could safely do this and return immediately:
822 *
823 * bdi->dirty_ratelimit = balanced_dirty_ratelimit;
824 *
825 * However to get a more stable dirty_ratelimit, the below elaborated
826 * code makes use of task_ratelimit to filter out sigular points and
827 * limit the step size.
828 *
829 * The below code essentially only uses the relative value of
830 *
831 * task_ratelimit - dirty_ratelimit
832 * = (pos_ratio - 1) * dirty_ratelimit
833 *
834 * which reflects the direction and size of dirty position error.
835 */
836
837 /*
838 * dirty_ratelimit will follow balanced_dirty_ratelimit iff
839 * task_ratelimit is on the same side of dirty_ratelimit, too.
840 * For example, when
841 * - dirty_ratelimit > balanced_dirty_ratelimit
842 * - dirty_ratelimit > task_ratelimit (dirty pages are above setpoint)
843 * lowering dirty_ratelimit will help meet both the position and rate
844 * control targets. Otherwise, don't update dirty_ratelimit if it will
845 * only help meet the rate target. After all, what the users ultimately
846 * feel and care are stable dirty rate and small position error.
847 *
848 * |task_ratelimit - dirty_ratelimit| is used to limit the step size
849 * and filter out the sigular points of balanced_dirty_ratelimit. Which
850 * keeps jumping around randomly and can even leap far away at times
851 * due to the small 200ms estimation period of dirty_rate (we want to
852 * keep that period small to reduce time lags).
853 */
854 step = 0;
855 if (dirty < setpoint) {
856 x = min(bdi->balanced_dirty_ratelimit,
857 min(balanced_dirty_ratelimit, task_ratelimit));
858 if (dirty_ratelimit < x)
859 step = x - dirty_ratelimit;
860 } else {
861 x = max(bdi->balanced_dirty_ratelimit,
862 max(balanced_dirty_ratelimit, task_ratelimit));
863 if (dirty_ratelimit > x)
864 step = dirty_ratelimit - x;
865 }
866
867 /*
868 * Don't pursue 100% rate matching. It's impossible since the balanced
869 * rate itself is constantly fluctuating. So decrease the track speed
870 * when it gets close to the target. Helps eliminate pointless tremors.
871 */
872 step >>= dirty_ratelimit / (2 * step + 1);
873 /*
874 * Limit the tracking speed to avoid overshooting.
875 */
876 step = (step + 7) / 8;
877
878 if (dirty_ratelimit < balanced_dirty_ratelimit)
879 dirty_ratelimit += step;
880 else
881 dirty_ratelimit -= step;
882
883 bdi->dirty_ratelimit = max(dirty_ratelimit, 1UL);
884 bdi->balanced_dirty_ratelimit = balanced_dirty_ratelimit;
b48c104d
WF
885
886 trace_bdi_dirty_ratelimit(bdi, dirty_rate, task_ratelimit);
be3ffa27
WF
887}
888
e98be2d5 889void __bdi_update_bandwidth(struct backing_dev_info *bdi,
c42843f2 890 unsigned long thresh,
af6a3113 891 unsigned long bg_thresh,
c42843f2
WF
892 unsigned long dirty,
893 unsigned long bdi_thresh,
894 unsigned long bdi_dirty,
e98be2d5
WF
895 unsigned long start_time)
896{
897 unsigned long now = jiffies;
898 unsigned long elapsed = now - bdi->bw_time_stamp;
be3ffa27 899 unsigned long dirtied;
e98be2d5
WF
900 unsigned long written;
901
902 /*
903 * rate-limit, only update once every 200ms.
904 */
905 if (elapsed < BANDWIDTH_INTERVAL)
906 return;
907
be3ffa27 908 dirtied = percpu_counter_read(&bdi->bdi_stat[BDI_DIRTIED]);
e98be2d5
WF
909 written = percpu_counter_read(&bdi->bdi_stat[BDI_WRITTEN]);
910
911 /*
912 * Skip quiet periods when disk bandwidth is under-utilized.
913 * (at least 1s idle time between two flusher runs)
914 */
915 if (elapsed > HZ && time_before(bdi->bw_time_stamp, start_time))
916 goto snapshot;
917
be3ffa27 918 if (thresh) {
c42843f2 919 global_update_bandwidth(thresh, dirty, now);
be3ffa27
WF
920 bdi_update_dirty_ratelimit(bdi, thresh, bg_thresh, dirty,
921 bdi_thresh, bdi_dirty,
922 dirtied, elapsed);
923 }
e98be2d5
WF
924 bdi_update_write_bandwidth(bdi, elapsed, written);
925
926snapshot:
be3ffa27 927 bdi->dirtied_stamp = dirtied;
e98be2d5
WF
928 bdi->written_stamp = written;
929 bdi->bw_time_stamp = now;
930}
931
932static void bdi_update_bandwidth(struct backing_dev_info *bdi,
c42843f2 933 unsigned long thresh,
af6a3113 934 unsigned long bg_thresh,
c42843f2
WF
935 unsigned long dirty,
936 unsigned long bdi_thresh,
937 unsigned long bdi_dirty,
e98be2d5
WF
938 unsigned long start_time)
939{
940 if (time_is_after_eq_jiffies(bdi->bw_time_stamp + BANDWIDTH_INTERVAL))
941 return;
942 spin_lock(&bdi->wb.list_lock);
af6a3113
WF
943 __bdi_update_bandwidth(bdi, thresh, bg_thresh, dirty,
944 bdi_thresh, bdi_dirty, start_time);
e98be2d5
WF
945 spin_unlock(&bdi->wb.list_lock);
946}
947
9d823e8f
WF
948/*
949 * After a task dirtied this many pages, balance_dirty_pages_ratelimited_nr()
950 * will look to see if it needs to start dirty throttling.
951 *
952 * If dirty_poll_interval is too low, big NUMA machines will call the expensive
953 * global_page_state() too often. So scale it near-sqrt to the safety margin
954 * (the number of pages we may dirty without exceeding the dirty limits).
955 */
956static unsigned long dirty_poll_interval(unsigned long dirty,
957 unsigned long thresh)
958{
959 if (thresh > dirty)
960 return 1UL << (ilog2(thresh - dirty) >> 1);
961
962 return 1;
963}
964
7ccb9ad5
WF
965static long bdi_max_pause(struct backing_dev_info *bdi,
966 unsigned long bdi_dirty)
c8462cc9 967{
7ccb9ad5
WF
968 long bw = bdi->avg_write_bandwidth;
969 long t;
c8462cc9 970
7ccb9ad5
WF
971 /*
972 * Limit pause time for small memory systems. If sleeping for too long
973 * time, a small pool of dirty/writeback pages may go empty and disk go
974 * idle.
975 *
976 * 8 serves as the safety ratio.
977 */
978 t = bdi_dirty / (1 + bw / roundup_pow_of_two(1 + HZ / 8));
979 t++;
980
981 return min_t(long, t, MAX_PAUSE);
982}
983
984static long bdi_min_pause(struct backing_dev_info *bdi,
985 long max_pause,
986 unsigned long task_ratelimit,
987 unsigned long dirty_ratelimit,
988 int *nr_dirtied_pause)
989{
990 long hi = ilog2(bdi->avg_write_bandwidth);
991 long lo = ilog2(bdi->dirty_ratelimit);
992 long t; /* target pause */
993 long pause; /* estimated next pause */
994 int pages; /* target nr_dirtied_pause */
995
996 /* target for 10ms pause on 1-dd case */
997 t = max(1, HZ / 100);
c8462cc9
WF
998
999 /*
1000 * Scale up pause time for concurrent dirtiers in order to reduce CPU
1001 * overheads.
1002 *
7ccb9ad5 1003 * (N * 10ms) on 2^N concurrent tasks.
c8462cc9
WF
1004 */
1005 if (hi > lo)
7ccb9ad5 1006 t += (hi - lo) * (10 * HZ) / 1024;
c8462cc9
WF
1007
1008 /*
7ccb9ad5
WF
1009 * This is a bit convoluted. We try to base the next nr_dirtied_pause
1010 * on the much more stable dirty_ratelimit. However the next pause time
1011 * will be computed based on task_ratelimit and the two rate limits may
1012 * depart considerably at some time. Especially if task_ratelimit goes
1013 * below dirty_ratelimit/2 and the target pause is max_pause, the next
1014 * pause time will be max_pause*2 _trimmed down_ to max_pause. As a
1015 * result task_ratelimit won't be executed faithfully, which could
1016 * eventually bring down dirty_ratelimit.
c8462cc9 1017 *
7ccb9ad5
WF
1018 * We apply two rules to fix it up:
1019 * 1) try to estimate the next pause time and if necessary, use a lower
1020 * nr_dirtied_pause so as not to exceed max_pause. When this happens,
1021 * nr_dirtied_pause will be "dancing" with task_ratelimit.
1022 * 2) limit the target pause time to max_pause/2, so that the normal
1023 * small fluctuations of task_ratelimit won't trigger rule (1) and
1024 * nr_dirtied_pause will remain as stable as dirty_ratelimit.
c8462cc9 1025 */
7ccb9ad5
WF
1026 t = min(t, 1 + max_pause / 2);
1027 pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
1028
1029 pause = HZ * pages / (task_ratelimit + 1);
1030 if (pause > max_pause) {
1031 t = max_pause;
1032 pages = task_ratelimit * t / roundup_pow_of_two(HZ);
1033 }
c8462cc9 1034
7ccb9ad5 1035 *nr_dirtied_pause = pages;
c8462cc9 1036 /*
7ccb9ad5 1037 * The minimal pause time will normally be half the target pause time.
c8462cc9 1038 */
7ccb9ad5 1039 return 1 + t / 2;
c8462cc9
WF
1040}
1041
1da177e4
LT
1042/*
1043 * balance_dirty_pages() must be called by processes which are generating dirty
1044 * data. It looks at the number of dirty pages in the machine and will force
143dfe86 1045 * the caller to wait once crossing the (background_thresh + dirty_thresh) / 2.
5b0830cb
JA
1046 * If we're over `background_thresh' then the writeback threads are woken to
1047 * perform some writeout.
1da177e4 1048 */
3a2e9a5a 1049static void balance_dirty_pages(struct address_space *mapping,
143dfe86 1050 unsigned long pages_dirtied)
1da177e4 1051{
143dfe86
WF
1052 unsigned long nr_reclaimable; /* = file_dirty + unstable_nfs */
1053 unsigned long bdi_reclaimable;
7762741e
WF
1054 unsigned long nr_dirty; /* = file_dirty + writeback + unstable_nfs */
1055 unsigned long bdi_dirty;
6c14ae1e 1056 unsigned long freerun;
364aeb28
DR
1057 unsigned long background_thresh;
1058 unsigned long dirty_thresh;
1059 unsigned long bdi_thresh;
83712358 1060 long period;
7ccb9ad5
WF
1061 long pause;
1062 long max_pause;
1063 long min_pause;
1064 int nr_dirtied_pause;
e50e3720 1065 bool dirty_exceeded = false;
143dfe86 1066 unsigned long task_ratelimit;
7ccb9ad5 1067 unsigned long dirty_ratelimit;
143dfe86 1068 unsigned long pos_ratio;
1da177e4 1069 struct backing_dev_info *bdi = mapping->backing_dev_info;
e98be2d5 1070 unsigned long start_time = jiffies;
1da177e4
LT
1071
1072 for (;;) {
83712358
WF
1073 unsigned long now = jiffies;
1074
143dfe86
WF
1075 /*
1076 * Unstable writes are a feature of certain networked
1077 * filesystems (i.e. NFS) in which data may have been
1078 * written to the server's write cache, but has not yet
1079 * been flushed to permanent storage.
1080 */
5fce25a9
PZ
1081 nr_reclaimable = global_page_state(NR_FILE_DIRTY) +
1082 global_page_state(NR_UNSTABLE_NFS);
7762741e 1083 nr_dirty = nr_reclaimable + global_page_state(NR_WRITEBACK);
5fce25a9 1084
16c4042f
WF
1085 global_dirty_limits(&background_thresh, &dirty_thresh);
1086
1087 /*
1088 * Throttle it only when the background writeback cannot
1089 * catch-up. This avoids (excessively) small writeouts
1090 * when the bdi limits are ramping up.
1091 */
6c14ae1e
WF
1092 freerun = dirty_freerun_ceiling(dirty_thresh,
1093 background_thresh);
83712358
WF
1094 if (nr_dirty <= freerun) {
1095 current->dirty_paused_when = now;
1096 current->nr_dirtied = 0;
7ccb9ad5
WF
1097 current->nr_dirtied_pause =
1098 dirty_poll_interval(nr_dirty, dirty_thresh);
16c4042f 1099 break;
83712358 1100 }
16c4042f 1101
143dfe86
WF
1102 if (unlikely(!writeback_in_progress(bdi)))
1103 bdi_start_background_writeback(bdi);
1104
1105 /*
1106 * bdi_thresh is not treated as some limiting factor as
1107 * dirty_thresh, due to reasons
1108 * - in JBOD setup, bdi_thresh can fluctuate a lot
1109 * - in a system with HDD and USB key, the USB key may somehow
1110 * go into state (bdi_dirty >> bdi_thresh) either because
1111 * bdi_dirty starts high, or because bdi_thresh drops low.
1112 * In this case we don't want to hard throttle the USB key
1113 * dirtiers for 100 seconds until bdi_dirty drops under
1114 * bdi_thresh. Instead the auxiliary bdi control line in
1115 * bdi_position_ratio() will let the dirtier task progress
1116 * at some rate <= (write_bw / 2) for bringing down bdi_dirty.
1117 */
16c4042f 1118 bdi_thresh = bdi_dirty_limit(bdi, dirty_thresh);
16c4042f 1119
e50e3720
WF
1120 /*
1121 * In order to avoid the stacked BDI deadlock we need
1122 * to ensure we accurately count the 'dirty' pages when
1123 * the threshold is low.
1124 *
1125 * Otherwise it would be possible to get thresh+n pages
1126 * reported dirty, even though there are thresh-m pages
1127 * actually dirty; with m+n sitting in the percpu
1128 * deltas.
1129 */
143dfe86
WF
1130 if (bdi_thresh < 2 * bdi_stat_error(bdi)) {
1131 bdi_reclaimable = bdi_stat_sum(bdi, BDI_RECLAIMABLE);
1132 bdi_dirty = bdi_reclaimable +
7762741e 1133 bdi_stat_sum(bdi, BDI_WRITEBACK);
e50e3720 1134 } else {
143dfe86
WF
1135 bdi_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
1136 bdi_dirty = bdi_reclaimable +
7762741e 1137 bdi_stat(bdi, BDI_WRITEBACK);
e50e3720 1138 }
5fce25a9 1139
143dfe86 1140 dirty_exceeded = (bdi_dirty > bdi_thresh) ||
7762741e 1141 (nr_dirty > dirty_thresh);
143dfe86 1142 if (dirty_exceeded && !bdi->dirty_exceeded)
04fbfdc1 1143 bdi->dirty_exceeded = 1;
1da177e4 1144
af6a3113
WF
1145 bdi_update_bandwidth(bdi, dirty_thresh, background_thresh,
1146 nr_dirty, bdi_thresh, bdi_dirty,
1147 start_time);
e98be2d5 1148
143dfe86
WF
1149 dirty_ratelimit = bdi->dirty_ratelimit;
1150 pos_ratio = bdi_position_ratio(bdi, dirty_thresh,
1151 background_thresh, nr_dirty,
1152 bdi_thresh, bdi_dirty);
3a73dbbc
WF
1153 task_ratelimit = ((u64)dirty_ratelimit * pos_ratio) >>
1154 RATELIMIT_CALC_SHIFT;
7ccb9ad5
WF
1155 max_pause = bdi_max_pause(bdi, bdi_dirty);
1156 min_pause = bdi_min_pause(bdi, max_pause,
1157 task_ratelimit, dirty_ratelimit,
1158 &nr_dirtied_pause);
1159
3a73dbbc 1160 if (unlikely(task_ratelimit == 0)) {
83712358 1161 period = max_pause;
c8462cc9 1162 pause = max_pause;
143dfe86 1163 goto pause;
04fbfdc1 1164 }
83712358
WF
1165 period = HZ * pages_dirtied / task_ratelimit;
1166 pause = period;
1167 if (current->dirty_paused_when)
1168 pause -= now - current->dirty_paused_when;
1169 /*
1170 * For less than 1s think time (ext3/4 may block the dirtier
1171 * for up to 800ms from time to time on 1-HDD; so does xfs,
1172 * however at much less frequency), try to compensate it in
1173 * future periods by updating the virtual time; otherwise just
1174 * do a reset, as it may be a light dirtier.
1175 */
7ccb9ad5 1176 if (pause < min_pause) {
ece13ac3
WF
1177 trace_balance_dirty_pages(bdi,
1178 dirty_thresh,
1179 background_thresh,
1180 nr_dirty,
1181 bdi_thresh,
1182 bdi_dirty,
1183 dirty_ratelimit,
1184 task_ratelimit,
1185 pages_dirtied,
83712358 1186 period,
7ccb9ad5 1187 min(pause, 0L),
ece13ac3 1188 start_time);
83712358
WF
1189 if (pause < -HZ) {
1190 current->dirty_paused_when = now;
1191 current->nr_dirtied = 0;
1192 } else if (period) {
1193 current->dirty_paused_when += period;
1194 current->nr_dirtied = 0;
7ccb9ad5
WF
1195 } else if (current->nr_dirtied_pause <= pages_dirtied)
1196 current->nr_dirtied_pause += pages_dirtied;
57fc978c 1197 break;
04fbfdc1 1198 }
7ccb9ad5
WF
1199 if (unlikely(pause > max_pause)) {
1200 /* for occasional dropped task_ratelimit */
1201 now += min(pause - max_pause, max_pause);
1202 pause = max_pause;
1203 }
143dfe86
WF
1204
1205pause:
ece13ac3
WF
1206 trace_balance_dirty_pages(bdi,
1207 dirty_thresh,
1208 background_thresh,
1209 nr_dirty,
1210 bdi_thresh,
1211 bdi_dirty,
1212 dirty_ratelimit,
1213 task_ratelimit,
1214 pages_dirtied,
83712358 1215 period,
ece13ac3
WF
1216 pause,
1217 start_time);
499d05ec 1218 __set_current_state(TASK_KILLABLE);
d25105e8 1219 io_schedule_timeout(pause);
87c6a9b2 1220
83712358
WF
1221 current->dirty_paused_when = now + pause;
1222 current->nr_dirtied = 0;
7ccb9ad5 1223 current->nr_dirtied_pause = nr_dirtied_pause;
83712358 1224
ffd1f609 1225 /*
1df64719
WF
1226 * This is typically equal to (nr_dirty < dirty_thresh) and can
1227 * also keep "1000+ dd on a slow USB stick" under control.
ffd1f609 1228 */
1df64719 1229 if (task_ratelimit)
ffd1f609 1230 break;
499d05ec 1231
c5c6343c
WF
1232 /*
1233 * In the case of an unresponding NFS server and the NFS dirty
1234 * pages exceeds dirty_thresh, give the other good bdi's a pipe
1235 * to go through, so that tasks on them still remain responsive.
1236 *
1237 * In theory 1 page is enough to keep the comsumer-producer
1238 * pipe going: the flusher cleans 1 page => the task dirties 1
1239 * more page. However bdi_dirty has accounting errors. So use
1240 * the larger and more IO friendly bdi_stat_error.
1241 */
1242 if (bdi_dirty <= bdi_stat_error(bdi))
1243 break;
1244
499d05ec
JK
1245 if (fatal_signal_pending(current))
1246 break;
1da177e4
LT
1247 }
1248
143dfe86 1249 if (!dirty_exceeded && bdi->dirty_exceeded)
04fbfdc1 1250 bdi->dirty_exceeded = 0;
1da177e4
LT
1251
1252 if (writeback_in_progress(bdi))
5b0830cb 1253 return;
1da177e4
LT
1254
1255 /*
1256 * In laptop mode, we wait until hitting the higher threshold before
1257 * starting background writeout, and then write out all the way down
1258 * to the lower threshold. So slow writers cause minimal disk activity.
1259 *
1260 * In normal mode, we start background writeout at the lower
1261 * background_thresh, to keep the amount of dirty memory low.
1262 */
143dfe86
WF
1263 if (laptop_mode)
1264 return;
1265
1266 if (nr_reclaimable > background_thresh)
c5444198 1267 bdi_start_background_writeback(bdi);
1da177e4
LT
1268}
1269
a200ee18 1270void set_page_dirty_balance(struct page *page, int page_mkwrite)
edc79b2a 1271{
a200ee18 1272 if (set_page_dirty(page) || page_mkwrite) {
edc79b2a
PZ
1273 struct address_space *mapping = page_mapping(page);
1274
1275 if (mapping)
1276 balance_dirty_pages_ratelimited(mapping);
1277 }
1278}
1279
9d823e8f 1280static DEFINE_PER_CPU(int, bdp_ratelimits);
245b2e70 1281
54848d73
WF
1282/*
1283 * Normal tasks are throttled by
1284 * loop {
1285 * dirty tsk->nr_dirtied_pause pages;
1286 * take a snap in balance_dirty_pages();
1287 * }
1288 * However there is a worst case. If every task exit immediately when dirtied
1289 * (tsk->nr_dirtied_pause - 1) pages, balance_dirty_pages() will never be
1290 * called to throttle the page dirties. The solution is to save the not yet
1291 * throttled page dirties in dirty_throttle_leaks on task exit and charge them
1292 * randomly into the running tasks. This works well for the above worst case,
1293 * as the new task will pick up and accumulate the old task's leaked dirty
1294 * count and eventually get throttled.
1295 */
1296DEFINE_PER_CPU(int, dirty_throttle_leaks) = 0;
1297
1da177e4 1298/**
fa5a734e 1299 * balance_dirty_pages_ratelimited_nr - balance dirty memory state
67be2dd1 1300 * @mapping: address_space which was dirtied
a580290c 1301 * @nr_pages_dirtied: number of pages which the caller has just dirtied
1da177e4
LT
1302 *
1303 * Processes which are dirtying memory should call in here once for each page
1304 * which was newly dirtied. The function will periodically check the system's
1305 * dirty state and will initiate writeback if needed.
1306 *
1307 * On really big machines, get_writeback_state is expensive, so try to avoid
1308 * calling it too often (ratelimiting). But once we're over the dirty memory
1309 * limit we decrease the ratelimiting by a lot, to prevent individual processes
1310 * from overshooting the limit by (ratelimit_pages) each.
1311 */
fa5a734e
AM
1312void balance_dirty_pages_ratelimited_nr(struct address_space *mapping,
1313 unsigned long nr_pages_dirtied)
1da177e4 1314{
36715cef 1315 struct backing_dev_info *bdi = mapping->backing_dev_info;
9d823e8f
WF
1316 int ratelimit;
1317 int *p;
1da177e4 1318
36715cef
WF
1319 if (!bdi_cap_account_dirty(bdi))
1320 return;
1321
9d823e8f
WF
1322 ratelimit = current->nr_dirtied_pause;
1323 if (bdi->dirty_exceeded)
1324 ratelimit = min(ratelimit, 32 >> (PAGE_SHIFT - 10));
1325
9d823e8f 1326 preempt_disable();
1da177e4 1327 /*
9d823e8f
WF
1328 * This prevents one CPU to accumulate too many dirtied pages without
1329 * calling into balance_dirty_pages(), which can happen when there are
1330 * 1000+ tasks, all of them start dirtying pages at exactly the same
1331 * time, hence all honoured too large initial task->nr_dirtied_pause.
1da177e4 1332 */
245b2e70 1333 p = &__get_cpu_var(bdp_ratelimits);
9d823e8f 1334 if (unlikely(current->nr_dirtied >= ratelimit))
fa5a734e 1335 *p = 0;
d3bc1fef
WF
1336 else if (unlikely(*p >= ratelimit_pages)) {
1337 *p = 0;
1338 ratelimit = 0;
1da177e4 1339 }
54848d73
WF
1340 /*
1341 * Pick up the dirtied pages by the exited tasks. This avoids lots of
1342 * short-lived tasks (eg. gcc invocations in a kernel build) escaping
1343 * the dirty throttling and livelock other long-run dirtiers.
1344 */
1345 p = &__get_cpu_var(dirty_throttle_leaks);
1346 if (*p > 0 && current->nr_dirtied < ratelimit) {
1347 nr_pages_dirtied = min(*p, ratelimit - current->nr_dirtied);
1348 *p -= nr_pages_dirtied;
1349 current->nr_dirtied += nr_pages_dirtied;
1350 }
fa5a734e 1351 preempt_enable();
9d823e8f
WF
1352
1353 if (unlikely(current->nr_dirtied >= ratelimit))
1354 balance_dirty_pages(mapping, current->nr_dirtied);
1da177e4 1355}
fa5a734e 1356EXPORT_SYMBOL(balance_dirty_pages_ratelimited_nr);
1da177e4 1357
232ea4d6 1358void throttle_vm_writeout(gfp_t gfp_mask)
1da177e4 1359{
364aeb28
DR
1360 unsigned long background_thresh;
1361 unsigned long dirty_thresh;
1da177e4
LT
1362
1363 for ( ; ; ) {
16c4042f 1364 global_dirty_limits(&background_thresh, &dirty_thresh);
1da177e4
LT
1365
1366 /*
1367 * Boost the allowable dirty threshold a bit for page
1368 * allocators so they don't get DoS'ed by heavy writers
1369 */
1370 dirty_thresh += dirty_thresh / 10; /* wheeee... */
1371
c24f21bd
CL
1372 if (global_page_state(NR_UNSTABLE_NFS) +
1373 global_page_state(NR_WRITEBACK) <= dirty_thresh)
1374 break;
8aa7e847 1375 congestion_wait(BLK_RW_ASYNC, HZ/10);
369f2389
FW
1376
1377 /*
1378 * The caller might hold locks which can prevent IO completion
1379 * or progress in the filesystem. So we cannot just sit here
1380 * waiting for IO to complete.
1381 */
1382 if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO))
1383 break;
1da177e4
LT
1384 }
1385}
1386
1da177e4
LT
1387/*
1388 * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
1389 */
1390int dirty_writeback_centisecs_handler(ctl_table *table, int write,
8d65af78 1391 void __user *buffer, size_t *length, loff_t *ppos)
1da177e4 1392{
8d65af78 1393 proc_dointvec(table, write, buffer, length, ppos);
6423104b 1394 bdi_arm_supers_timer();
1da177e4
LT
1395 return 0;
1396}
1397
c2c4986e 1398#ifdef CONFIG_BLOCK
31373d09 1399void laptop_mode_timer_fn(unsigned long data)
1da177e4 1400{
31373d09
MG
1401 struct request_queue *q = (struct request_queue *)data;
1402 int nr_pages = global_page_state(NR_FILE_DIRTY) +
1403 global_page_state(NR_UNSTABLE_NFS);
1da177e4 1404
31373d09
MG
1405 /*
1406 * We want to write everything out, not just down to the dirty
1407 * threshold
1408 */
31373d09 1409 if (bdi_has_dirty_io(&q->backing_dev_info))
0e175a18
CW
1410 bdi_start_writeback(&q->backing_dev_info, nr_pages,
1411 WB_REASON_LAPTOP_TIMER);
1da177e4
LT
1412}
1413
1414/*
1415 * We've spun up the disk and we're in laptop mode: schedule writeback
1416 * of all dirty data a few seconds from now. If the flush is already scheduled
1417 * then push it back - the user is still using the disk.
1418 */
31373d09 1419void laptop_io_completion(struct backing_dev_info *info)
1da177e4 1420{
31373d09 1421 mod_timer(&info->laptop_mode_wb_timer, jiffies + laptop_mode);
1da177e4
LT
1422}
1423
1424/*
1425 * We're in laptop mode and we've just synced. The sync's writes will have
1426 * caused another writeback to be scheduled by laptop_io_completion.
1427 * Nothing needs to be written back anymore, so we unschedule the writeback.
1428 */
1429void laptop_sync_completion(void)
1430{
31373d09
MG
1431 struct backing_dev_info *bdi;
1432
1433 rcu_read_lock();
1434
1435 list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
1436 del_timer(&bdi->laptop_mode_wb_timer);
1437
1438 rcu_read_unlock();
1da177e4 1439}
c2c4986e 1440#endif
1da177e4
LT
1441
1442/*
1443 * If ratelimit_pages is too high then we can get into dirty-data overload
1444 * if a large number of processes all perform writes at the same time.
1445 * If it is too low then SMP machines will call the (expensive)
1446 * get_writeback_state too often.
1447 *
1448 * Here we set ratelimit_pages to a level which ensures that when all CPUs are
1449 * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
9d823e8f 1450 * thresholds.
1da177e4
LT
1451 */
1452
2d1d43f6 1453void writeback_set_ratelimit(void)
1da177e4 1454{
9d823e8f
WF
1455 unsigned long background_thresh;
1456 unsigned long dirty_thresh;
1457 global_dirty_limits(&background_thresh, &dirty_thresh);
1458 ratelimit_pages = dirty_thresh / (num_online_cpus() * 32);
1da177e4
LT
1459 if (ratelimit_pages < 16)
1460 ratelimit_pages = 16;
1da177e4
LT
1461}
1462
26c2143b 1463static int __cpuinit
1da177e4
LT
1464ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
1465{
2d1d43f6 1466 writeback_set_ratelimit();
aa0f0303 1467 return NOTIFY_DONE;
1da177e4
LT
1468}
1469
74b85f37 1470static struct notifier_block __cpuinitdata ratelimit_nb = {
1da177e4
LT
1471 .notifier_call = ratelimit_handler,
1472 .next = NULL,
1473};
1474
1475/*
dc6e29da
LT
1476 * Called early on to tune the page writeback dirty limits.
1477 *
1478 * We used to scale dirty pages according to how total memory
1479 * related to pages that could be allocated for buffers (by
1480 * comparing nr_free_buffer_pages() to vm_total_pages.
1481 *
1482 * However, that was when we used "dirty_ratio" to scale with
1483 * all memory, and we don't do that any more. "dirty_ratio"
1484 * is now applied to total non-HIGHPAGE memory (by subtracting
1485 * totalhigh_pages from vm_total_pages), and as such we can't
1486 * get into the old insane situation any more where we had
1487 * large amounts of dirty pages compared to a small amount of
1488 * non-HIGHMEM memory.
1489 *
1490 * But we might still want to scale the dirty_ratio by how
1491 * much memory the box has..
1da177e4
LT
1492 */
1493void __init page_writeback_init(void)
1494{
04fbfdc1
PZ
1495 int shift;
1496
2d1d43f6 1497 writeback_set_ratelimit();
1da177e4 1498 register_cpu_notifier(&ratelimit_nb);
04fbfdc1
PZ
1499
1500 shift = calc_period_shift();
1501 prop_descriptor_init(&vm_completions, shift);
1da177e4
LT
1502}
1503
f446daae
JK
1504/**
1505 * tag_pages_for_writeback - tag pages to be written by write_cache_pages
1506 * @mapping: address space structure to write
1507 * @start: starting page index
1508 * @end: ending page index (inclusive)
1509 *
1510 * This function scans the page range from @start to @end (inclusive) and tags
1511 * all pages that have DIRTY tag set with a special TOWRITE tag. The idea is
1512 * that write_cache_pages (or whoever calls this function) will then use
1513 * TOWRITE tag to identify pages eligible for writeback. This mechanism is
1514 * used to avoid livelocking of writeback by a process steadily creating new
1515 * dirty pages in the file (thus it is important for this function to be quick
1516 * so that it can tag pages faster than a dirtying process can create them).
1517 */
1518/*
1519 * We tag pages in batches of WRITEBACK_TAG_BATCH to reduce tree_lock latency.
1520 */
f446daae
JK
1521void tag_pages_for_writeback(struct address_space *mapping,
1522 pgoff_t start, pgoff_t end)
1523{
3c111a07 1524#define WRITEBACK_TAG_BATCH 4096
f446daae
JK
1525 unsigned long tagged;
1526
1527 do {
1528 spin_lock_irq(&mapping->tree_lock);
1529 tagged = radix_tree_range_tag_if_tagged(&mapping->page_tree,
1530 &start, end, WRITEBACK_TAG_BATCH,
1531 PAGECACHE_TAG_DIRTY, PAGECACHE_TAG_TOWRITE);
1532 spin_unlock_irq(&mapping->tree_lock);
1533 WARN_ON_ONCE(tagged > WRITEBACK_TAG_BATCH);
1534 cond_resched();
d5ed3a4a
JK
1535 /* We check 'start' to handle wrapping when end == ~0UL */
1536 } while (tagged >= WRITEBACK_TAG_BATCH && start);
f446daae
JK
1537}
1538EXPORT_SYMBOL(tag_pages_for_writeback);
1539
811d736f 1540/**
0ea97180 1541 * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
811d736f
DH
1542 * @mapping: address space structure to write
1543 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
0ea97180
MS
1544 * @writepage: function called for each page
1545 * @data: data passed to writepage function
811d736f 1546 *
0ea97180 1547 * If a page is already under I/O, write_cache_pages() skips it, even
811d736f
DH
1548 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
1549 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
1550 * and msync() need to guarantee that all the data which was dirty at the time
1551 * the call was made get new I/O started against them. If wbc->sync_mode is
1552 * WB_SYNC_ALL then we were called for data integrity and we must wait for
1553 * existing IO to complete.
f446daae
JK
1554 *
1555 * To avoid livelocks (when other process dirties new pages), we first tag
1556 * pages which should be written back with TOWRITE tag and only then start
1557 * writing them. For data-integrity sync we have to be careful so that we do
1558 * not miss some pages (e.g., because some other process has cleared TOWRITE
1559 * tag we set). The rule we follow is that TOWRITE tag can be cleared only
1560 * by the process clearing the DIRTY tag (and submitting the page for IO).
811d736f 1561 */
0ea97180
MS
1562int write_cache_pages(struct address_space *mapping,
1563 struct writeback_control *wbc, writepage_t writepage,
1564 void *data)
811d736f 1565{
811d736f
DH
1566 int ret = 0;
1567 int done = 0;
811d736f
DH
1568 struct pagevec pvec;
1569 int nr_pages;
31a12666 1570 pgoff_t uninitialized_var(writeback_index);
811d736f
DH
1571 pgoff_t index;
1572 pgoff_t end; /* Inclusive */
bd19e012 1573 pgoff_t done_index;
31a12666 1574 int cycled;
811d736f 1575 int range_whole = 0;
f446daae 1576 int tag;
811d736f 1577
811d736f
DH
1578 pagevec_init(&pvec, 0);
1579 if (wbc->range_cyclic) {
31a12666
NP
1580 writeback_index = mapping->writeback_index; /* prev offset */
1581 index = writeback_index;
1582 if (index == 0)
1583 cycled = 1;
1584 else
1585 cycled = 0;
811d736f
DH
1586 end = -1;
1587 } else {
1588 index = wbc->range_start >> PAGE_CACHE_SHIFT;
1589 end = wbc->range_end >> PAGE_CACHE_SHIFT;
1590 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
1591 range_whole = 1;
31a12666 1592 cycled = 1; /* ignore range_cyclic tests */
811d736f 1593 }
6e6938b6 1594 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
f446daae
JK
1595 tag = PAGECACHE_TAG_TOWRITE;
1596 else
1597 tag = PAGECACHE_TAG_DIRTY;
811d736f 1598retry:
6e6938b6 1599 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
f446daae 1600 tag_pages_for_writeback(mapping, index, end);
bd19e012 1601 done_index = index;
5a3d5c98
NP
1602 while (!done && (index <= end)) {
1603 int i;
1604
f446daae 1605 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
5a3d5c98
NP
1606 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
1607 if (nr_pages == 0)
1608 break;
811d736f 1609
811d736f
DH
1610 for (i = 0; i < nr_pages; i++) {
1611 struct page *page = pvec.pages[i];
1612
1613 /*
d5482cdf
NP
1614 * At this point, the page may be truncated or
1615 * invalidated (changing page->mapping to NULL), or
1616 * even swizzled back from swapper_space to tmpfs file
1617 * mapping. However, page->index will not change
1618 * because we have a reference on the page.
811d736f 1619 */
d5482cdf
NP
1620 if (page->index > end) {
1621 /*
1622 * can't be range_cyclic (1st pass) because
1623 * end == -1 in that case.
1624 */
1625 done = 1;
1626 break;
1627 }
1628
cf15b07c 1629 done_index = page->index;
d5482cdf 1630
811d736f
DH
1631 lock_page(page);
1632
5a3d5c98
NP
1633 /*
1634 * Page truncated or invalidated. We can freely skip it
1635 * then, even for data integrity operations: the page
1636 * has disappeared concurrently, so there could be no
1637 * real expectation of this data interity operation
1638 * even if there is now a new, dirty page at the same
1639 * pagecache address.
1640 */
811d736f 1641 if (unlikely(page->mapping != mapping)) {
5a3d5c98 1642continue_unlock:
811d736f
DH
1643 unlock_page(page);
1644 continue;
1645 }
1646
515f4a03
NP
1647 if (!PageDirty(page)) {
1648 /* someone wrote it for us */
1649 goto continue_unlock;
1650 }
1651
1652 if (PageWriteback(page)) {
1653 if (wbc->sync_mode != WB_SYNC_NONE)
1654 wait_on_page_writeback(page);
1655 else
1656 goto continue_unlock;
1657 }
811d736f 1658
515f4a03
NP
1659 BUG_ON(PageWriteback(page));
1660 if (!clear_page_dirty_for_io(page))
5a3d5c98 1661 goto continue_unlock;
811d736f 1662
9e094383 1663 trace_wbc_writepage(wbc, mapping->backing_dev_info);
0ea97180 1664 ret = (*writepage)(page, wbc, data);
00266770
NP
1665 if (unlikely(ret)) {
1666 if (ret == AOP_WRITEPAGE_ACTIVATE) {
1667 unlock_page(page);
1668 ret = 0;
1669 } else {
1670 /*
1671 * done_index is set past this page,
1672 * so media errors will not choke
1673 * background writeout for the entire
1674 * file. This has consequences for
1675 * range_cyclic semantics (ie. it may
1676 * not be suitable for data integrity
1677 * writeout).
1678 */
cf15b07c 1679 done_index = page->index + 1;
00266770
NP
1680 done = 1;
1681 break;
1682 }
0b564927 1683 }
00266770 1684
546a1924
DC
1685 /*
1686 * We stop writing back only if we are not doing
1687 * integrity sync. In case of integrity sync we have to
1688 * keep going until we have written all the pages
1689 * we tagged for writeback prior to entering this loop.
1690 */
1691 if (--wbc->nr_to_write <= 0 &&
1692 wbc->sync_mode == WB_SYNC_NONE) {
1693 done = 1;
1694 break;
05fe478d 1695 }
811d736f
DH
1696 }
1697 pagevec_release(&pvec);
1698 cond_resched();
1699 }
3a4c6800 1700 if (!cycled && !done) {
811d736f 1701 /*
31a12666 1702 * range_cyclic:
811d736f
DH
1703 * We hit the last page and there is more work to be done: wrap
1704 * back to the start of the file
1705 */
31a12666 1706 cycled = 1;
811d736f 1707 index = 0;
31a12666 1708 end = writeback_index - 1;
811d736f
DH
1709 goto retry;
1710 }
0b564927
DC
1711 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
1712 mapping->writeback_index = done_index;
06d6cf69 1713
811d736f
DH
1714 return ret;
1715}
0ea97180
MS
1716EXPORT_SYMBOL(write_cache_pages);
1717
1718/*
1719 * Function used by generic_writepages to call the real writepage
1720 * function and set the mapping flags on error
1721 */
1722static int __writepage(struct page *page, struct writeback_control *wbc,
1723 void *data)
1724{
1725 struct address_space *mapping = data;
1726 int ret = mapping->a_ops->writepage(page, wbc);
1727 mapping_set_error(mapping, ret);
1728 return ret;
1729}
1730
1731/**
1732 * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
1733 * @mapping: address space structure to write
1734 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
1735 *
1736 * This is a library function, which implements the writepages()
1737 * address_space_operation.
1738 */
1739int generic_writepages(struct address_space *mapping,
1740 struct writeback_control *wbc)
1741{
9b6096a6
SL
1742 struct blk_plug plug;
1743 int ret;
1744
0ea97180
MS
1745 /* deal with chardevs and other special file */
1746 if (!mapping->a_ops->writepage)
1747 return 0;
1748
9b6096a6
SL
1749 blk_start_plug(&plug);
1750 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
1751 blk_finish_plug(&plug);
1752 return ret;
0ea97180 1753}
811d736f
DH
1754
1755EXPORT_SYMBOL(generic_writepages);
1756
1da177e4
LT
1757int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
1758{
22905f77
AM
1759 int ret;
1760
1da177e4
LT
1761 if (wbc->nr_to_write <= 0)
1762 return 0;
1763 if (mapping->a_ops->writepages)
d08b3851 1764 ret = mapping->a_ops->writepages(mapping, wbc);
22905f77
AM
1765 else
1766 ret = generic_writepages(mapping, wbc);
22905f77 1767 return ret;
1da177e4
LT
1768}
1769
1770/**
1771 * write_one_page - write out a single page and optionally wait on I/O
67be2dd1
MW
1772 * @page: the page to write
1773 * @wait: if true, wait on writeout
1da177e4
LT
1774 *
1775 * The page must be locked by the caller and will be unlocked upon return.
1776 *
1777 * write_one_page() returns a negative error code if I/O failed.
1778 */
1779int write_one_page(struct page *page, int wait)
1780{
1781 struct address_space *mapping = page->mapping;
1782 int ret = 0;
1783 struct writeback_control wbc = {
1784 .sync_mode = WB_SYNC_ALL,
1785 .nr_to_write = 1,
1786 };
1787
1788 BUG_ON(!PageLocked(page));
1789
1790 if (wait)
1791 wait_on_page_writeback(page);
1792
1793 if (clear_page_dirty_for_io(page)) {
1794 page_cache_get(page);
1795 ret = mapping->a_ops->writepage(page, &wbc);
1796 if (ret == 0 && wait) {
1797 wait_on_page_writeback(page);
1798 if (PageError(page))
1799 ret = -EIO;
1800 }
1801 page_cache_release(page);
1802 } else {
1803 unlock_page(page);
1804 }
1805 return ret;
1806}
1807EXPORT_SYMBOL(write_one_page);
1808
76719325
KC
1809/*
1810 * For address_spaces which do not use buffers nor write back.
1811 */
1812int __set_page_dirty_no_writeback(struct page *page)
1813{
1814 if (!PageDirty(page))
c3f0da63 1815 return !TestSetPageDirty(page);
76719325
KC
1816 return 0;
1817}
1818
e3a7cca1
ES
1819/*
1820 * Helper function for set_page_dirty family.
1821 * NOTE: This relies on being atomic wrt interrupts.
1822 */
1823void account_page_dirtied(struct page *page, struct address_space *mapping)
1824{
1825 if (mapping_cap_account_dirty(mapping)) {
1826 __inc_zone_page_state(page, NR_FILE_DIRTY);
ea941f0e 1827 __inc_zone_page_state(page, NR_DIRTIED);
e3a7cca1 1828 __inc_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
c8e28ce0 1829 __inc_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
e3a7cca1 1830 task_io_account_write(PAGE_CACHE_SIZE);
d3bc1fef
WF
1831 current->nr_dirtied++;
1832 this_cpu_inc(bdp_ratelimits);
e3a7cca1
ES
1833 }
1834}
679ceace 1835EXPORT_SYMBOL(account_page_dirtied);
e3a7cca1 1836
f629d1c9
MR
1837/*
1838 * Helper function for set_page_writeback family.
1839 * NOTE: Unlike account_page_dirtied this does not rely on being atomic
1840 * wrt interrupts.
1841 */
1842void account_page_writeback(struct page *page)
1843{
1844 inc_zone_page_state(page, NR_WRITEBACK);
1845}
1846EXPORT_SYMBOL(account_page_writeback);
1847
1da177e4
LT
1848/*
1849 * For address_spaces which do not use buffers. Just tag the page as dirty in
1850 * its radix tree.
1851 *
1852 * This is also used when a single buffer is being dirtied: we want to set the
1853 * page dirty in that case, but not all the buffers. This is a "bottom-up"
1854 * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
1855 *
1856 * Most callers have locked the page, which pins the address_space in memory.
1857 * But zap_pte_range() does not lock the page, however in that case the
1858 * mapping is pinned by the vma's ->vm_file reference.
1859 *
1860 * We take care to handle the case where the page was truncated from the
183ff22b 1861 * mapping by re-checking page_mapping() inside tree_lock.
1da177e4
LT
1862 */
1863int __set_page_dirty_nobuffers(struct page *page)
1864{
1da177e4
LT
1865 if (!TestSetPageDirty(page)) {
1866 struct address_space *mapping = page_mapping(page);
1867 struct address_space *mapping2;
1868
8c08540f
AM
1869 if (!mapping)
1870 return 1;
1871
19fd6231 1872 spin_lock_irq(&mapping->tree_lock);
8c08540f
AM
1873 mapping2 = page_mapping(page);
1874 if (mapping2) { /* Race with truncate? */
1875 BUG_ON(mapping2 != mapping);
787d2214 1876 WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
e3a7cca1 1877 account_page_dirtied(page, mapping);
8c08540f
AM
1878 radix_tree_tag_set(&mapping->page_tree,
1879 page_index(page), PAGECACHE_TAG_DIRTY);
1880 }
19fd6231 1881 spin_unlock_irq(&mapping->tree_lock);
8c08540f
AM
1882 if (mapping->host) {
1883 /* !PageAnon && !swapper_space */
1884 __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
1da177e4 1885 }
4741c9fd 1886 return 1;
1da177e4 1887 }
4741c9fd 1888 return 0;
1da177e4
LT
1889}
1890EXPORT_SYMBOL(__set_page_dirty_nobuffers);
1891
2f800fbd
WF
1892/*
1893 * Call this whenever redirtying a page, to de-account the dirty counters
1894 * (NR_DIRTIED, BDI_DIRTIED, tsk->nr_dirtied), so that they match the written
1895 * counters (NR_WRITTEN, BDI_WRITTEN) in long term. The mismatches will lead to
1896 * systematic errors in balanced_dirty_ratelimit and the dirty pages position
1897 * control.
1898 */
1899void account_page_redirty(struct page *page)
1900{
1901 struct address_space *mapping = page->mapping;
1902 if (mapping && mapping_cap_account_dirty(mapping)) {
1903 current->nr_dirtied--;
1904 dec_zone_page_state(page, NR_DIRTIED);
1905 dec_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
1906 }
1907}
1908EXPORT_SYMBOL(account_page_redirty);
1909
1da177e4
LT
1910/*
1911 * When a writepage implementation decides that it doesn't want to write this
1912 * page for some reason, it should redirty the locked page via
1913 * redirty_page_for_writepage() and it should then unlock the page and return 0
1914 */
1915int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
1916{
1917 wbc->pages_skipped++;
2f800fbd 1918 account_page_redirty(page);
1da177e4
LT
1919 return __set_page_dirty_nobuffers(page);
1920}
1921EXPORT_SYMBOL(redirty_page_for_writepage);
1922
1923/*
6746aff7
WF
1924 * Dirty a page.
1925 *
1926 * For pages with a mapping this should be done under the page lock
1927 * for the benefit of asynchronous memory errors who prefer a consistent
1928 * dirty state. This rule can be broken in some special cases,
1929 * but should be better not to.
1930 *
1da177e4
LT
1931 * If the mapping doesn't provide a set_page_dirty a_op, then
1932 * just fall through and assume that it wants buffer_heads.
1933 */
1cf6e7d8 1934int set_page_dirty(struct page *page)
1da177e4
LT
1935{
1936 struct address_space *mapping = page_mapping(page);
1937
1938 if (likely(mapping)) {
1939 int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
278df9f4
MK
1940 /*
1941 * readahead/lru_deactivate_page could remain
1942 * PG_readahead/PG_reclaim due to race with end_page_writeback
1943 * About readahead, if the page is written, the flags would be
1944 * reset. So no problem.
1945 * About lru_deactivate_page, if the page is redirty, the flag
1946 * will be reset. So no problem. but if the page is used by readahead
1947 * it will confuse readahead and make it restart the size rampup
1948 * process. But it's a trivial problem.
1949 */
1950 ClearPageReclaim(page);
9361401e
DH
1951#ifdef CONFIG_BLOCK
1952 if (!spd)
1953 spd = __set_page_dirty_buffers;
1954#endif
1955 return (*spd)(page);
1da177e4 1956 }
4741c9fd
AM
1957 if (!PageDirty(page)) {
1958 if (!TestSetPageDirty(page))
1959 return 1;
1960 }
1da177e4
LT
1961 return 0;
1962}
1963EXPORT_SYMBOL(set_page_dirty);
1964
1965/*
1966 * set_page_dirty() is racy if the caller has no reference against
1967 * page->mapping->host, and if the page is unlocked. This is because another
1968 * CPU could truncate the page off the mapping and then free the mapping.
1969 *
1970 * Usually, the page _is_ locked, or the caller is a user-space process which
1971 * holds a reference on the inode by having an open file.
1972 *
1973 * In other cases, the page should be locked before running set_page_dirty().
1974 */
1975int set_page_dirty_lock(struct page *page)
1976{
1977 int ret;
1978
7eaceacc 1979 lock_page(page);
1da177e4
LT
1980 ret = set_page_dirty(page);
1981 unlock_page(page);
1982 return ret;
1983}
1984EXPORT_SYMBOL(set_page_dirty_lock);
1985
1da177e4
LT
1986/*
1987 * Clear a page's dirty flag, while caring for dirty memory accounting.
1988 * Returns true if the page was previously dirty.
1989 *
1990 * This is for preparing to put the page under writeout. We leave the page
1991 * tagged as dirty in the radix tree so that a concurrent write-for-sync
1992 * can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
1993 * implementation will run either set_page_writeback() or set_page_dirty(),
1994 * at which stage we bring the page's dirty flag and radix-tree dirty tag
1995 * back into sync.
1996 *
1997 * This incoherency between the page's dirty flag and radix-tree tag is
1998 * unfortunate, but it only exists while the page is locked.
1999 */
2000int clear_page_dirty_for_io(struct page *page)
2001{
2002 struct address_space *mapping = page_mapping(page);
2003
79352894
NP
2004 BUG_ON(!PageLocked(page));
2005
7658cc28
LT
2006 if (mapping && mapping_cap_account_dirty(mapping)) {
2007 /*
2008 * Yes, Virginia, this is indeed insane.
2009 *
2010 * We use this sequence to make sure that
2011 * (a) we account for dirty stats properly
2012 * (b) we tell the low-level filesystem to
2013 * mark the whole page dirty if it was
2014 * dirty in a pagetable. Only to then
2015 * (c) clean the page again and return 1 to
2016 * cause the writeback.
2017 *
2018 * This way we avoid all nasty races with the
2019 * dirty bit in multiple places and clearing
2020 * them concurrently from different threads.
2021 *
2022 * Note! Normally the "set_page_dirty(page)"
2023 * has no effect on the actual dirty bit - since
2024 * that will already usually be set. But we
2025 * need the side effects, and it can help us
2026 * avoid races.
2027 *
2028 * We basically use the page "master dirty bit"
2029 * as a serialization point for all the different
2030 * threads doing their things.
7658cc28
LT
2031 */
2032 if (page_mkclean(page))
2033 set_page_dirty(page);
79352894
NP
2034 /*
2035 * We carefully synchronise fault handlers against
2036 * installing a dirty pte and marking the page dirty
2037 * at this point. We do this by having them hold the
2038 * page lock at some point after installing their
2039 * pte, but before marking the page dirty.
2040 * Pages are always locked coming in here, so we get
2041 * the desired exclusion. See mm/memory.c:do_wp_page()
2042 * for more comments.
2043 */
7658cc28 2044 if (TestClearPageDirty(page)) {
8c08540f 2045 dec_zone_page_state(page, NR_FILE_DIRTY);
c9e51e41
PZ
2046 dec_bdi_stat(mapping->backing_dev_info,
2047 BDI_RECLAIMABLE);
7658cc28 2048 return 1;
1da177e4 2049 }
7658cc28 2050 return 0;
1da177e4 2051 }
7658cc28 2052 return TestClearPageDirty(page);
1da177e4 2053}
58bb01a9 2054EXPORT_SYMBOL(clear_page_dirty_for_io);
1da177e4
LT
2055
2056int test_clear_page_writeback(struct page *page)
2057{
2058 struct address_space *mapping = page_mapping(page);
2059 int ret;
2060
2061 if (mapping) {
69cb51d1 2062 struct backing_dev_info *bdi = mapping->backing_dev_info;
1da177e4
LT
2063 unsigned long flags;
2064
19fd6231 2065 spin_lock_irqsave(&mapping->tree_lock, flags);
1da177e4 2066 ret = TestClearPageWriteback(page);
69cb51d1 2067 if (ret) {
1da177e4
LT
2068 radix_tree_tag_clear(&mapping->page_tree,
2069 page_index(page),
2070 PAGECACHE_TAG_WRITEBACK);
e4ad08fe 2071 if (bdi_cap_account_writeback(bdi)) {
69cb51d1 2072 __dec_bdi_stat(bdi, BDI_WRITEBACK);
04fbfdc1
PZ
2073 __bdi_writeout_inc(bdi);
2074 }
69cb51d1 2075 }
19fd6231 2076 spin_unlock_irqrestore(&mapping->tree_lock, flags);
1da177e4
LT
2077 } else {
2078 ret = TestClearPageWriteback(page);
2079 }
99b12e3d 2080 if (ret) {
d688abf5 2081 dec_zone_page_state(page, NR_WRITEBACK);
99b12e3d
WF
2082 inc_zone_page_state(page, NR_WRITTEN);
2083 }
1da177e4
LT
2084 return ret;
2085}
2086
2087int test_set_page_writeback(struct page *page)
2088{
2089 struct address_space *mapping = page_mapping(page);
2090 int ret;
2091
2092 if (mapping) {
69cb51d1 2093 struct backing_dev_info *bdi = mapping->backing_dev_info;
1da177e4
LT
2094 unsigned long flags;
2095
19fd6231 2096 spin_lock_irqsave(&mapping->tree_lock, flags);
1da177e4 2097 ret = TestSetPageWriteback(page);
69cb51d1 2098 if (!ret) {
1da177e4
LT
2099 radix_tree_tag_set(&mapping->page_tree,
2100 page_index(page),
2101 PAGECACHE_TAG_WRITEBACK);
e4ad08fe 2102 if (bdi_cap_account_writeback(bdi))
69cb51d1
PZ
2103 __inc_bdi_stat(bdi, BDI_WRITEBACK);
2104 }
1da177e4
LT
2105 if (!PageDirty(page))
2106 radix_tree_tag_clear(&mapping->page_tree,
2107 page_index(page),
2108 PAGECACHE_TAG_DIRTY);
f446daae
JK
2109 radix_tree_tag_clear(&mapping->page_tree,
2110 page_index(page),
2111 PAGECACHE_TAG_TOWRITE);
19fd6231 2112 spin_unlock_irqrestore(&mapping->tree_lock, flags);
1da177e4
LT
2113 } else {
2114 ret = TestSetPageWriteback(page);
2115 }
d688abf5 2116 if (!ret)
f629d1c9 2117 account_page_writeback(page);
1da177e4
LT
2118 return ret;
2119
2120}
2121EXPORT_SYMBOL(test_set_page_writeback);
2122
2123/*
00128188 2124 * Return true if any of the pages in the mapping are marked with the
1da177e4
LT
2125 * passed tag.
2126 */
2127int mapping_tagged(struct address_space *mapping, int tag)
2128{
72c47832 2129 return radix_tree_tagged(&mapping->page_tree, tag);
1da177e4
LT
2130}
2131EXPORT_SYMBOL(mapping_tagged);