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