blob: 3c05bcef04efb36f12f87d2b3bbec9b3e2e076d6 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/*
Uwe Zeisbergerf30c2262006-10-03 23:01:26 +02002 * mm/page-writeback.c
Linus Torvalds1da177e2005-04-16 15:20:36 -07003 *
4 * Copyright (C) 2002, Linus Torvalds.
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -07005 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
Linus Torvalds1da177e2005-04-16 15:20:36 -07006 *
7 * Contains functions related to writing back dirty pages at the
8 * address_space level.
9 *
Francois Camie1f8e872008-10-15 22:01:59 -070010 * 10Apr2002 Andrew Morton
Linus Torvalds1da177e2005-04-16 15:20:36 -070011 * Initial version
12 */
13
14#include <linux/kernel.h>
Paul Gortmakerb95f1b312011-10-16 02:01:52 -040015#include <linux/export.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070016#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>
Andrew Morton55e829a2006-12-10 02:19:27 -080025#include <linux/task_io_accounting_ops.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070026#include <linux/blkdev.h>
27#include <linux/mpage.h>
Peter Zijlstrad08b3852006-09-25 23:30:57 -070028#include <linux/rmap.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070029#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>
Al Viroff01bb42011-09-16 02:31:11 -040035#include <linux/buffer_head.h> /* __set_page_dirty_buffers */
David Howells811d7362006-08-29 19:06:09 +010036#include <linux/pagevec.h>
Lisa Du36abcfd2013-09-11 14:22:36 -070037#include <linux/mm_inline.h>
Dave Chinner028c2dd2010-07-07 13:24:07 +100038#include <trace/events/writeback.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070039
Lisa Du36abcfd2013-09-11 14:22:36 -070040#include "internal.h"
41
Linus Torvalds1da177e2005-04-16 15:20:36 -070042/*
Wu Fengguangffd1f602011-06-19 22:18:42 -060043 * Sleep at most 200ms at a time in balance_dirty_pages().
44 */
45#define MAX_PAUSE max(HZ/5, 1)
46
47/*
Wu Fengguang5b9b3572011-12-06 13:17:17 -060048 * Try to keep balance_dirty_pages() call intervals higher than this many pages
49 * by raising pause time to max_pause when falls below it.
50 */
51#define DIRTY_POLL_THRESH (128 >> (PAGE_SHIFT - 10))
52
53/*
Wu Fengguange98be2d2010-08-29 11:22:30 -060054 * Estimate write bandwidth at 200ms intervals.
55 */
56#define BANDWIDTH_INTERVAL max(HZ/5, 1)
57
Wu Fengguang6c14ae12011-03-02 16:04:18 -060058#define RATELIMIT_CALC_SHIFT 10
59
Wu Fengguange98be2d2010-08-29 11:22:30 -060060/*
Linus Torvalds1da177e2005-04-16 15:20:36 -070061 * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
62 * will look to see if it needs to force writeback or throttling.
63 */
64static long ratelimit_pages = 32;
65
Linus Torvalds1da177e2005-04-16 15:20:36 -070066/* The following parameters are exported via /proc/sys/vm */
67
68/*
Jens Axboe5b0830c2009-09-23 19:37:09 +020069 * Start background writeback (via writeback threads) at this percentage
Linus Torvalds1da177e2005-04-16 15:20:36 -070070 */
Wu Fengguang1b5e62b2009-03-23 08:57:38 +080071int dirty_background_ratio = 10;
Linus Torvalds1da177e2005-04-16 15:20:36 -070072
73/*
David Rientjes2da02992009-01-06 14:39:31 -080074 * dirty_background_bytes starts at 0 (disabled) so that it is a function of
75 * dirty_background_ratio * the amount of dirtyable memory
76 */
77unsigned long dirty_background_bytes;
78
79/*
Bron Gondwana195cf452008-02-04 22:29:20 -080080 * free highmem will not be subtracted from the total free memory
81 * for calculating free ratios if vm_highmem_is_dirtyable is true
82 */
83int vm_highmem_is_dirtyable;
84
85/*
Linus Torvalds1da177e2005-04-16 15:20:36 -070086 * The generator of dirty data starts writeback at this percentage
87 */
Wu Fengguang1b5e62b2009-03-23 08:57:38 +080088int vm_dirty_ratio = 20;
Linus Torvalds1da177e2005-04-16 15:20:36 -070089
90/*
David Rientjes2da02992009-01-06 14:39:31 -080091 * vm_dirty_bytes starts at 0 (disabled) so that it is a function of
92 * vm_dirty_ratio * the amount of dirtyable memory
93 */
94unsigned long vm_dirty_bytes;
95
96/*
Alexey Dobriyan704503d2009-03-31 15:23:18 -070097 * The interval between `kupdate'-style writebacks
Linus Torvalds1da177e2005-04-16 15:20:36 -070098 */
Toshiyuki Okajima22ef37e2009-05-16 22:56:28 -070099unsigned int dirty_writeback_interval = 5 * 100; /* centiseconds */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700100
Artem Bityutskiy91913a22012-03-21 22:33:00 -0400101EXPORT_SYMBOL_GPL(dirty_writeback_interval);
102
Linus Torvalds1da177e2005-04-16 15:20:36 -0700103/*
Alexey Dobriyan704503d2009-03-31 15:23:18 -0700104 * The longest time for which data is allowed to remain dirty
Linus Torvalds1da177e2005-04-16 15:20:36 -0700105 */
Toshiyuki Okajima22ef37e2009-05-16 22:56:28 -0700106unsigned int dirty_expire_interval = 30 * 100; /* centiseconds */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700107
108/*
109 * Flag that makes the machine dump writes/reads and block dirtyings.
110 */
111int block_dump;
112
113/*
Bart Samweled5b43f2006-03-24 03:15:49 -0800114 * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
115 * a full sync is triggered after this time elapses without any disk activity.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700116 */
117int laptop_mode;
118
119EXPORT_SYMBOL(laptop_mode);
120
121/* End of sysctl-exported parameters */
122
Wu Fengguangc42843f2011-03-02 15:54:09 -0600123unsigned long global_dirty_limit;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700124
Linus Torvalds1da177e2005-04-16 15:20:36 -0700125/*
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700126 * Scale the writeback cache size proportional to the relative writeout speeds.
127 *
128 * We do this by keeping a floating proportion between BDIs, based on page
129 * writeback completions [end_page_writeback()]. Those devices that write out
130 * pages fastest will get the larger share, while the slower will get a smaller
131 * share.
132 *
133 * We use page writeout completions because we are interested in getting rid of
134 * dirty pages. Having them written out is the primary goal.
135 *
136 * We introduce a concept of time, a period over which we measure these events,
137 * because demand can/will vary over time. The length of this period itself is
138 * measured in page writeback completions.
139 *
140 */
141static struct prop_descriptor vm_completions;
142
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700143/*
Johannes Weiner1edf2232012-01-10 15:06:57 -0800144 * Work out the current dirty-memory clamping and background writeout
145 * thresholds.
146 *
147 * The main aim here is to lower them aggressively if there is a lot of mapped
148 * memory around. To avoid stressing page reclaim with lots of unreclaimable
149 * pages. It is better to clamp down on writers than to start swapping, and
150 * performing lots of scanning.
151 *
152 * We only allow 1/2 of the currently-unmapped memory to be dirtied.
153 *
154 * We don't permit the clamping level to fall below 5% - that is getting rather
155 * excessive.
156 *
157 * We make sure that the background writeout level is below the adjusted
158 * clamping level.
159 */
Johannes Weinerccafa282012-01-10 15:07:44 -0800160
Johannes Weinera756cf52012-01-10 15:07:49 -0800161/*
162 * In a memory zone, there is a certain amount of pages we consider
163 * available for the page cache, which is essentially the number of
164 * free and reclaimable pages, minus some zone reserves to protect
165 * lowmem and the ability to uphold the zone's watermarks without
166 * requiring writeback.
167 *
168 * This number of dirtyable pages is the base value of which the
169 * user-configurable dirty ratio is the effictive number of pages that
170 * are allowed to be actually dirtied. Per individual zone, or
171 * globally by using the sum of dirtyable pages over all zones.
172 *
173 * Because the user is allowed to specify the dirty limit globally as
174 * absolute number of bytes, calculating the per-zone dirty limit can
175 * require translating the configured limit into a percentage of
176 * global dirtyable memory first.
177 */
178
Johannes Weiner74febf02014-01-29 14:05:39 -0800179/**
180 * zone_dirtyable_memory - number of dirtyable pages in a zone
181 * @zone: the zone
182 *
183 * Returns the zone's number of pages potentially available for dirty
184 * page cache. This is the base value for the per-zone dirty limits.
185 */
186static unsigned long zone_dirtyable_memory(struct zone *zone)
187{
188 unsigned long nr_pages;
189
190 nr_pages = zone_page_state(zone, NR_FREE_PAGES);
191 nr_pages -= min(nr_pages, zone->dirty_balance_reserve);
192
193 nr_pages += zone_reclaimable_pages(zone);
194
195 return nr_pages;
196}
197
Johannes Weiner1edf2232012-01-10 15:06:57 -0800198static unsigned long highmem_dirtyable_memory(unsigned long total)
199{
200#ifdef CONFIG_HIGHMEM
201 int node;
202 unsigned long x = 0;
203
204 for_each_node_state(node, N_HIGH_MEMORY) {
Johannes Weiner74febf02014-01-29 14:05:39 -0800205 struct zone *z = &NODE_DATA(node)->node_zones[ZONE_HIGHMEM];
Johannes Weiner1edf2232012-01-10 15:06:57 -0800206
Johannes Weiner74febf02014-01-29 14:05:39 -0800207 x += zone_dirtyable_memory(z);
Johannes Weiner1edf2232012-01-10 15:06:57 -0800208 }
209 /*
Sonny Rao711cf002012-12-20 15:05:07 -0800210 * Unreclaimable memory (kernel memory or anonymous memory
211 * without swap) can bring down the dirtyable pages below
212 * the zone's dirty balance reserve and the above calculation
213 * will underflow. However we still want to add in nodes
214 * which are below threshold (negative values) to get a more
215 * accurate calculation but make sure that the total never
216 * underflows.
217 */
218 if ((long)x < 0)
219 x = 0;
220
221 /*
Johannes Weiner1edf2232012-01-10 15:06:57 -0800222 * Make sure that the number of highmem pages is never larger
223 * than the number of the total dirtyable memory. This can only
224 * occur in very strange VM situations but we want to make sure
225 * that this does not occur.
226 */
227 return min(x, total);
228#else
229 return 0;
230#endif
231}
232
233/**
Johannes Weinerccafa282012-01-10 15:07:44 -0800234 * global_dirtyable_memory - number of globally dirtyable pages
Johannes Weiner1edf2232012-01-10 15:06:57 -0800235 *
Johannes Weinerccafa282012-01-10 15:07:44 -0800236 * Returns the global number of pages potentially available for dirty
237 * page cache. This is the base value for the global dirty limits.
Johannes Weiner1edf2232012-01-10 15:06:57 -0800238 */
Johannes Weinerccafa282012-01-10 15:07:44 -0800239unsigned long global_dirtyable_memory(void)
Johannes Weiner1edf2232012-01-10 15:06:57 -0800240{
241 unsigned long x;
242
Johannes Weiner74febf02014-01-29 14:05:39 -0800243 x = global_page_state(NR_FREE_PAGES);
Sonny Rao711cf002012-12-20 15:05:07 -0800244 x -= min(x, dirty_balance_reserve);
Johannes Weiner1edf2232012-01-10 15:06:57 -0800245
Johannes Weiner74febf02014-01-29 14:05:39 -0800246 x += global_reclaimable_pages();
247
Johannes Weiner1edf2232012-01-10 15:06:57 -0800248 if (!vm_highmem_is_dirtyable)
249 x -= highmem_dirtyable_memory(x);
250
251 return x + 1; /* Ensure that we never return 0 */
252}
253
254/*
Johannes Weinerccafa282012-01-10 15:07:44 -0800255 * global_dirty_limits - background-writeback and dirty-throttling thresholds
256 *
257 * Calculate the dirty thresholds based on sysctl parameters
258 * - vm.dirty_background_ratio or vm.dirty_background_bytes
259 * - vm.dirty_ratio or vm.dirty_bytes
260 * The dirty limits will be lifted by 1/4 for PF_LESS_THROTTLE (ie. nfsd) and
261 * real-time tasks.
262 */
263void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty)
264{
265 unsigned long background;
266 unsigned long dirty;
267 unsigned long uninitialized_var(available_memory);
268 struct task_struct *tsk;
269
270 if (!vm_dirty_bytes || !dirty_background_bytes)
271 available_memory = global_dirtyable_memory();
272
273 if (vm_dirty_bytes)
274 dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE);
275 else
276 dirty = (vm_dirty_ratio * available_memory) / 100;
277
278 if (dirty_background_bytes)
279 background = DIV_ROUND_UP(dirty_background_bytes, PAGE_SIZE);
280 else
281 background = (dirty_background_ratio * available_memory) / 100;
282
283 if (background >= dirty)
284 background = dirty / 2;
285 tsk = current;
286 if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
287 background += background / 4;
288 dirty += dirty / 4;
289 }
290 *pbackground = background;
291 *pdirty = dirty;
292 trace_global_dirty_state(background, dirty);
293}
294
Johannes Weinera756cf52012-01-10 15:07:49 -0800295/**
Johannes Weinera756cf52012-01-10 15:07:49 -0800296 * zone_dirty_limit - maximum number of dirty pages allowed in a zone
297 * @zone: the zone
298 *
299 * Returns the maximum number of dirty pages allowed in a zone, based
300 * on the zone's dirtyable memory.
301 */
302static unsigned long zone_dirty_limit(struct zone *zone)
303{
304 unsigned long zone_memory = zone_dirtyable_memory(zone);
305 struct task_struct *tsk = current;
306 unsigned long dirty;
307
308 if (vm_dirty_bytes)
309 dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE) *
310 zone_memory / global_dirtyable_memory();
311 else
312 dirty = vm_dirty_ratio * zone_memory / 100;
313
314 if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk))
315 dirty += dirty / 4;
316
317 return dirty;
318}
319
320/**
321 * zone_dirty_ok - tells whether a zone is within its dirty limits
322 * @zone: the zone to check
323 *
324 * Returns %true when the dirty pages in @zone are within the zone's
325 * dirty limit, %false if the limit is exceeded.
326 */
327bool zone_dirty_ok(struct zone *zone)
328{
329 unsigned long limit = zone_dirty_limit(zone);
330
331 return zone_page_state(zone, NR_FILE_DIRTY) +
332 zone_page_state(zone, NR_UNSTABLE_NFS) +
333 zone_page_state(zone, NR_WRITEBACK) <= limit;
334}
335
Johannes Weinerccafa282012-01-10 15:07:44 -0800336/*
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700337 * couple the period to the dirty_ratio:
338 *
339 * period/2 ~ roundup_pow_of_two(dirty limit)
340 */
341static int calc_period_shift(void)
342{
343 unsigned long dirty_total;
344
David Rientjes2da02992009-01-06 14:39:31 -0800345 if (vm_dirty_bytes)
346 dirty_total = vm_dirty_bytes / PAGE_SIZE;
347 else
Johannes Weinerccafa282012-01-10 15:07:44 -0800348 dirty_total = (vm_dirty_ratio * global_dirtyable_memory()) /
David Rientjes2da02992009-01-06 14:39:31 -0800349 100;
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700350 return 2 + ilog2(dirty_total - 1);
351}
352
353/*
David Rientjes2da02992009-01-06 14:39:31 -0800354 * update the period when the dirty threshold changes.
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700355 */
David Rientjes2da02992009-01-06 14:39:31 -0800356static void update_completion_period(void)
357{
358 int shift = calc_period_shift();
359 prop_change_shift(&vm_completions, shift);
Wu Fengguang9d823e82011-06-11 18:10:12 -0600360
361 writeback_set_ratelimit();
David Rientjes2da02992009-01-06 14:39:31 -0800362}
363
364int dirty_background_ratio_handler(struct ctl_table *table, int write,
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700365 void __user *buffer, size_t *lenp,
David Rientjes2da02992009-01-06 14:39:31 -0800366 loff_t *ppos)
367{
368 int ret;
369
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700370 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
David Rientjes2da02992009-01-06 14:39:31 -0800371 if (ret == 0 && write)
372 dirty_background_bytes = 0;
373 return ret;
374}
375
376int dirty_background_bytes_handler(struct ctl_table *table, int write,
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700377 void __user *buffer, size_t *lenp,
David Rientjes2da02992009-01-06 14:39:31 -0800378 loff_t *ppos)
379{
380 int ret;
381
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700382 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
David Rientjes2da02992009-01-06 14:39:31 -0800383 if (ret == 0 && write)
384 dirty_background_ratio = 0;
385 return ret;
386}
387
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700388int dirty_ratio_handler(struct ctl_table *table, int write,
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700389 void __user *buffer, size_t *lenp,
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700390 loff_t *ppos)
391{
392 int old_ratio = vm_dirty_ratio;
David Rientjes2da02992009-01-06 14:39:31 -0800393 int ret;
394
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700395 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700396 if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
David Rientjes2da02992009-01-06 14:39:31 -0800397 update_completion_period();
398 vm_dirty_bytes = 0;
399 }
400 return ret;
401}
402
David Rientjes2da02992009-01-06 14:39:31 -0800403int dirty_bytes_handler(struct ctl_table *table, int write,
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700404 void __user *buffer, size_t *lenp,
David Rientjes2da02992009-01-06 14:39:31 -0800405 loff_t *ppos)
406{
Sven Wegenerfc3501d2009-02-11 13:04:23 -0800407 unsigned long old_bytes = vm_dirty_bytes;
David Rientjes2da02992009-01-06 14:39:31 -0800408 int ret;
409
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700410 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
David Rientjes2da02992009-01-06 14:39:31 -0800411 if (ret == 0 && write && vm_dirty_bytes != old_bytes) {
412 update_completion_period();
413 vm_dirty_ratio = 0;
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700414 }
415 return ret;
416}
417
418/*
419 * Increment the BDI's writeout completion count and the global writeout
420 * completion count. Called from test_clear_page_writeback().
421 */
422static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
423{
Jan Karaf7d2b1e2010-12-08 22:44:24 -0600424 __inc_bdi_stat(bdi, BDI_WRITTEN);
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700425 __prop_inc_percpu_max(&vm_completions, &bdi->completions,
426 bdi->max_prop_frac);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700427}
428
Miklos Szeredidd5656e2008-04-30 00:54:37 -0700429void bdi_writeout_inc(struct backing_dev_info *bdi)
430{
431 unsigned long flags;
432
433 local_irq_save(flags);
434 __bdi_writeout_inc(bdi);
435 local_irq_restore(flags);
436}
437EXPORT_SYMBOL_GPL(bdi_writeout_inc);
438
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700439/*
440 * Obtain an accurate fraction of the BDI's portion.
441 */
442static void bdi_writeout_fraction(struct backing_dev_info *bdi,
443 long *numerator, long *denominator)
444{
Wu Fengguang3efaf0f2010-12-16 22:22:00 -0600445 prop_fraction_percpu(&vm_completions, &bdi->completions,
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700446 numerator, denominator);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700447}
448
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700449/*
Johannes Weinerd08c4292011-10-31 17:07:05 -0700450 * bdi_min_ratio keeps the sum of the minimum dirty shares of all
451 * registered backing devices, which, for obvious reasons, can not
452 * exceed 100%.
Peter Zijlstra189d3c42008-04-30 00:54:35 -0700453 */
Peter Zijlstra189d3c42008-04-30 00:54:35 -0700454static unsigned int bdi_min_ratio;
455
456int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio)
457{
458 int ret = 0;
Peter Zijlstra189d3c42008-04-30 00:54:35 -0700459
Jens Axboecfc4ba52009-09-14 13:12:40 +0200460 spin_lock_bh(&bdi_lock);
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700461 if (min_ratio > bdi->max_ratio) {
Peter Zijlstra189d3c42008-04-30 00:54:35 -0700462 ret = -EINVAL;
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700463 } else {
464 min_ratio -= bdi->min_ratio;
465 if (bdi_min_ratio + min_ratio < 100) {
466 bdi_min_ratio += min_ratio;
467 bdi->min_ratio += min_ratio;
468 } else {
469 ret = -EINVAL;
470 }
471 }
Jens Axboecfc4ba52009-09-14 13:12:40 +0200472 spin_unlock_bh(&bdi_lock);
Peter Zijlstra189d3c42008-04-30 00:54:35 -0700473
474 return ret;
475}
476
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700477int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio)
478{
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700479 int ret = 0;
480
481 if (max_ratio > 100)
482 return -EINVAL;
483
Jens Axboecfc4ba52009-09-14 13:12:40 +0200484 spin_lock_bh(&bdi_lock);
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700485 if (bdi->min_ratio > max_ratio) {
486 ret = -EINVAL;
487 } else {
488 bdi->max_ratio = max_ratio;
489 bdi->max_prop_frac = (PROP_FRAC_BASE * max_ratio) / 100;
490 }
Jens Axboecfc4ba52009-09-14 13:12:40 +0200491 spin_unlock_bh(&bdi_lock);
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700492
493 return ret;
494}
495EXPORT_SYMBOL(bdi_set_max_ratio);
496
Wu Fengguang6c14ae12011-03-02 16:04:18 -0600497static unsigned long dirty_freerun_ceiling(unsigned long thresh,
498 unsigned long bg_thresh)
499{
500 return (thresh + bg_thresh) / 2;
501}
502
Wu Fengguangffd1f602011-06-19 22:18:42 -0600503static unsigned long hard_dirty_limit(unsigned long thresh)
504{
505 return max(thresh, global_dirty_limit);
506}
507
Wu Fengguang6f718652011-03-02 17:14:34 -0600508/**
Wu Fengguang1babe182010-08-11 14:17:40 -0700509 * bdi_dirty_limit - @bdi's share of dirty throttling threshold
Wu Fengguang6f718652011-03-02 17:14:34 -0600510 * @bdi: the backing_dev_info to query
511 * @dirty: global dirty limit in pages
Wu Fengguang1babe182010-08-11 14:17:40 -0700512 *
Wu Fengguang6f718652011-03-02 17:14:34 -0600513 * Returns @bdi's dirty limit in pages. The term "dirty" in the context of
514 * dirty balancing includes all PG_dirty, PG_writeback and NFS unstable pages.
Wu Fengguangaed21ad2011-11-23 11:44:41 -0600515 *
516 * Note that balance_dirty_pages() will only seriously take it as a hard limit
517 * when sleeping max_pause per page is not enough to keep the dirty pages under
518 * control. For example, when the device is completely stalled due to some error
519 * conditions, or when there are 1000 dd tasks writing to a slow 10MB/s USB key.
520 * In the other normal situations, it acts more gently by throttling the tasks
521 * more (rather than completely block them) when the bdi dirty pages go high.
Wu Fengguang6f718652011-03-02 17:14:34 -0600522 *
523 * It allocates high/low dirty limits to fast/slow devices, in order to prevent
Wu Fengguang1babe182010-08-11 14:17:40 -0700524 * - starving fast devices
525 * - piling up dirty pages (that will take long time to sync) on slow devices
526 *
527 * The bdi's share of dirty limit will be adapting to its throughput and
528 * bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set.
529 */
530unsigned long bdi_dirty_limit(struct backing_dev_info *bdi, unsigned long dirty)
Wu Fengguang16c40422010-08-11 14:17:39 -0700531{
532 u64 bdi_dirty;
533 long numerator, denominator;
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700534
Wu Fengguang16c40422010-08-11 14:17:39 -0700535 /*
536 * Calculate this BDI's share of the dirty ratio.
537 */
538 bdi_writeout_fraction(bdi, &numerator, &denominator);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700539
Wu Fengguang16c40422010-08-11 14:17:39 -0700540 bdi_dirty = (dirty * (100 - bdi_min_ratio)) / 100;
541 bdi_dirty *= numerator;
542 do_div(bdi_dirty, denominator);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700543
Wu Fengguang16c40422010-08-11 14:17:39 -0700544 bdi_dirty += (dirty * bdi->min_ratio) / 100;
545 if (bdi_dirty > (dirty * bdi->max_ratio) / 100)
546 bdi_dirty = dirty * bdi->max_ratio / 100;
547
548 return bdi_dirty;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700549}
550
Wu Fengguang6c14ae12011-03-02 16:04:18 -0600551/*
552 * Dirty position control.
553 *
554 * (o) global/bdi setpoints
555 *
556 * We want the dirty pages be balanced around the global/bdi setpoints.
557 * When the number of dirty pages is higher/lower than the setpoint, the
558 * dirty position control ratio (and hence task dirty ratelimit) will be
559 * decreased/increased to bring the dirty pages back to the setpoint.
560 *
561 * pos_ratio = 1 << RATELIMIT_CALC_SHIFT
562 *
563 * if (dirty < setpoint) scale up pos_ratio
564 * if (dirty > setpoint) scale down pos_ratio
565 *
566 * if (bdi_dirty < bdi_setpoint) scale up pos_ratio
567 * if (bdi_dirty > bdi_setpoint) scale down pos_ratio
568 *
569 * task_ratelimit = dirty_ratelimit * pos_ratio >> RATELIMIT_CALC_SHIFT
570 *
571 * (o) global control line
572 *
573 * ^ pos_ratio
574 * |
575 * | |<===== global dirty control scope ======>|
576 * 2.0 .............*
577 * | .*
578 * | . *
579 * | . *
580 * | . *
581 * | . *
582 * | . *
583 * 1.0 ................................*
584 * | . . *
585 * | . . *
586 * | . . *
587 * | . . *
588 * | . . *
589 * 0 +------------.------------------.----------------------*------------->
590 * freerun^ setpoint^ limit^ dirty pages
591 *
592 * (o) bdi control line
593 *
594 * ^ pos_ratio
595 * |
596 * | *
597 * | *
598 * | *
599 * | *
600 * | * |<=========== span ============>|
601 * 1.0 .......................*
602 * | . *
603 * | . *
604 * | . *
605 * | . *
606 * | . *
607 * | . *
608 * | . *
609 * | . *
610 * | . *
611 * | . *
612 * | . *
613 * 1/4 ...............................................* * * * * * * * * * * *
614 * | . .
615 * | . .
616 * | . .
617 * 0 +----------------------.-------------------------------.------------->
618 * bdi_setpoint^ x_intercept^
619 *
620 * The bdi control line won't drop below pos_ratio=1/4, so that bdi_dirty can
621 * be smoothly throttled down to normal if it starts high in situations like
622 * - start writing to a slow SD card and a fast disk at the same time. The SD
623 * card's bdi_dirty may rush to many times higher than bdi_setpoint.
624 * - the bdi dirty thresh drops quickly due to change of JBOD workload
625 */
626static unsigned long bdi_position_ratio(struct backing_dev_info *bdi,
627 unsigned long thresh,
628 unsigned long bg_thresh,
629 unsigned long dirty,
630 unsigned long bdi_thresh,
631 unsigned long bdi_dirty)
632{
633 unsigned long write_bw = bdi->avg_write_bandwidth;
634 unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh);
635 unsigned long limit = hard_dirty_limit(thresh);
636 unsigned long x_intercept;
637 unsigned long setpoint; /* dirty pages' target balance point */
638 unsigned long bdi_setpoint;
639 unsigned long span;
640 long long pos_ratio; /* for scaling up/down the rate limit */
641 long x;
642
643 if (unlikely(dirty >= limit))
644 return 0;
645
646 /*
647 * global setpoint
648 *
649 * setpoint - dirty 3
650 * f(dirty) := 1.0 + (----------------)
651 * limit - setpoint
652 *
653 * it's a 3rd order polynomial that subjects to
654 *
655 * (1) f(freerun) = 2.0 => rampup dirty_ratelimit reasonably fast
656 * (2) f(setpoint) = 1.0 => the balance point
657 * (3) f(limit) = 0 => the hard limit
658 * (4) df/dx <= 0 => negative feedback control
659 * (5) the closer to setpoint, the smaller |df/dx| (and the reverse)
660 * => fast response on large errors; small oscillation near setpoint
661 */
662 setpoint = (freerun + limit) / 2;
663 x = div_s64((setpoint - dirty) << RATELIMIT_CALC_SHIFT,
664 limit - setpoint + 1);
665 pos_ratio = x;
666 pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
667 pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
668 pos_ratio += 1 << RATELIMIT_CALC_SHIFT;
669
670 /*
671 * We have computed basic pos_ratio above based on global situation. If
672 * the bdi is over/under its share of dirty pages, we want to scale
673 * pos_ratio further down/up. That is done by the following mechanism.
674 */
675
676 /*
677 * bdi setpoint
678 *
679 * f(bdi_dirty) := 1.0 + k * (bdi_dirty - bdi_setpoint)
680 *
681 * x_intercept - bdi_dirty
682 * := --------------------------
683 * x_intercept - bdi_setpoint
684 *
685 * The main bdi control line is a linear function that subjects to
686 *
687 * (1) f(bdi_setpoint) = 1.0
688 * (2) k = - 1 / (8 * write_bw) (in single bdi case)
689 * or equally: x_intercept = bdi_setpoint + 8 * write_bw
690 *
691 * For single bdi case, the dirty pages are observed to fluctuate
692 * regularly within range
693 * [bdi_setpoint - write_bw/2, bdi_setpoint + write_bw/2]
694 * for various filesystems, where (2) can yield in a reasonable 12.5%
695 * fluctuation range for pos_ratio.
696 *
697 * For JBOD case, bdi_thresh (not bdi_dirty!) could fluctuate up to its
698 * own size, so move the slope over accordingly and choose a slope that
699 * yields 100% pos_ratio fluctuation on suddenly doubled bdi_thresh.
700 */
701 if (unlikely(bdi_thresh > thresh))
702 bdi_thresh = thresh;
Wu Fengguangaed21ad2011-11-23 11:44:41 -0600703 /*
704 * It's very possible that bdi_thresh is close to 0 not because the
705 * device is slow, but that it has remained inactive for long time.
706 * Honour such devices a reasonable good (hopefully IO efficient)
707 * threshold, so that the occasional writes won't be blocked and active
708 * writes can rampup the threshold quickly.
709 */
Wu Fengguang8927f662011-08-04 22:16:46 -0600710 bdi_thresh = max(bdi_thresh, (limit - dirty) / 8);
Wu Fengguang6c14ae12011-03-02 16:04:18 -0600711 /*
712 * scale global setpoint to bdi's:
713 * bdi_setpoint = setpoint * bdi_thresh / thresh
714 */
José Adolfo Galdámez900469d2015-06-20 23:45:36 -0600715 x = div_u64((u64)bdi_thresh << 16, thresh | 1);
Wu Fengguang6c14ae12011-03-02 16:04:18 -0600716 bdi_setpoint = setpoint * (u64)x >> 16;
717 /*
718 * Use span=(8*write_bw) in single bdi case as indicated by
719 * (thresh - bdi_thresh ~= 0) and transit to bdi_thresh in JBOD case.
720 *
721 * bdi_thresh thresh - bdi_thresh
722 * span = ---------- * (8 * write_bw) + ------------------- * bdi_thresh
723 * thresh thresh
724 */
725 span = (thresh - bdi_thresh + 8 * write_bw) * (u64)x >> 16;
726 x_intercept = bdi_setpoint + span;
727
728 if (bdi_dirty < x_intercept - span / 4) {
Wu Fengguang50657fc2011-10-11 17:06:33 -0600729 pos_ratio = div_u64(pos_ratio * (x_intercept - bdi_dirty),
730 x_intercept - bdi_setpoint + 1);
Wu Fengguang6c14ae12011-03-02 16:04:18 -0600731 } else
732 pos_ratio /= 4;
733
Wu Fengguang8927f662011-08-04 22:16:46 -0600734 /*
735 * bdi reserve area, safeguard against dirty pool underrun and disk idle
736 * It may push the desired control point of global dirty pages higher
737 * than setpoint.
738 */
739 x_intercept = bdi_thresh / 2;
740 if (bdi_dirty < x_intercept) {
Wu Fengguang50657fc2011-10-11 17:06:33 -0600741 if (bdi_dirty > x_intercept / 8)
742 pos_ratio = div_u64(pos_ratio * x_intercept, bdi_dirty);
743 else
Wu Fengguang8927f662011-08-04 22:16:46 -0600744 pos_ratio *= 8;
745 }
746
Wu Fengguang6c14ae12011-03-02 16:04:18 -0600747 return pos_ratio;
748}
749
Wu Fengguange98be2d2010-08-29 11:22:30 -0600750static void bdi_update_write_bandwidth(struct backing_dev_info *bdi,
751 unsigned long elapsed,
752 unsigned long written)
753{
754 const unsigned long period = roundup_pow_of_two(3 * HZ);
755 unsigned long avg = bdi->avg_write_bandwidth;
756 unsigned long old = bdi->write_bandwidth;
757 u64 bw;
758
759 /*
760 * bw = written * HZ / elapsed
761 *
762 * bw * elapsed + write_bandwidth * (period - elapsed)
763 * write_bandwidth = ---------------------------------------------------
764 * period
José Adolfo Galdámez900469d2015-06-20 23:45:36 -0600765 *
766 * @written may have decreased due to account_page_redirty().
767 * Avoid underflowing @bw calculation.
Wu Fengguange98be2d2010-08-29 11:22:30 -0600768 */
José Adolfo Galdámez900469d2015-06-20 23:45:36 -0600769 bw = written - min(written, bdi->written_stamp);
Wu Fengguange98be2d2010-08-29 11:22:30 -0600770 bw *= HZ;
771 if (unlikely(elapsed > period)) {
772 do_div(bw, elapsed);
773 avg = bw;
774 goto out;
775 }
776 bw += (u64)bdi->write_bandwidth * (period - elapsed);
777 bw >>= ilog2(period);
778
779 /*
780 * one more level of smoothing, for filtering out sudden spikes
781 */
782 if (avg > old && old >= (unsigned long)bw)
783 avg -= (avg - old) >> 3;
784
785 if (avg < old && old <= (unsigned long)bw)
786 avg += (old - avg) >> 3;
787
788out:
789 bdi->write_bandwidth = bw;
790 bdi->avg_write_bandwidth = avg;
791}
792
Wu Fengguangc42843f2011-03-02 15:54:09 -0600793/*
794 * The global dirtyable memory and dirty threshold could be suddenly knocked
795 * down by a large amount (eg. on the startup of KVM in a swapless system).
796 * This may throw the system into deep dirty exceeded state and throttle
797 * heavy/light dirtiers alike. To retain good responsiveness, maintain
798 * global_dirty_limit for tracking slowly down to the knocked down dirty
799 * threshold.
800 */
801static void update_dirty_limit(unsigned long thresh, unsigned long dirty)
802{
803 unsigned long limit = global_dirty_limit;
804
805 /*
806 * Follow up in one step.
807 */
808 if (limit < thresh) {
809 limit = thresh;
810 goto update;
811 }
812
813 /*
814 * Follow down slowly. Use the higher one as the target, because thresh
815 * may drop below dirty. This is exactly the reason to introduce
816 * global_dirty_limit which is guaranteed to lie above the dirty pages.
817 */
818 thresh = max(thresh, dirty);
819 if (limit > thresh) {
820 limit -= (limit - thresh) >> 5;
821 goto update;
822 }
823 return;
824update:
825 global_dirty_limit = limit;
826}
827
828static void global_update_bandwidth(unsigned long thresh,
829 unsigned long dirty,
830 unsigned long now)
831{
832 static DEFINE_SPINLOCK(dirty_lock);
José Adolfo Galdámez900469d2015-06-20 23:45:36 -0600833 static unsigned long update_time = INITIAL_JIFFIES;
Wu Fengguangc42843f2011-03-02 15:54:09 -0600834
835 /*
836 * check locklessly first to optimize away locking for the most time
837 */
838 if (time_before(now, update_time + BANDWIDTH_INTERVAL))
839 return;
840
841 spin_lock(&dirty_lock);
842 if (time_after_eq(now, update_time + BANDWIDTH_INTERVAL)) {
843 update_dirty_limit(thresh, dirty);
844 update_time = now;
845 }
846 spin_unlock(&dirty_lock);
847}
848
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600849/*
850 * Maintain bdi->dirty_ratelimit, the base dirty throttle rate.
851 *
852 * Normal bdi tasks will be curbed at or below it in long term.
853 * Obviously it should be around (write_bw / N) when there are N dd tasks.
854 */
855static void bdi_update_dirty_ratelimit(struct backing_dev_info *bdi,
856 unsigned long thresh,
857 unsigned long bg_thresh,
858 unsigned long dirty,
859 unsigned long bdi_thresh,
860 unsigned long bdi_dirty,
861 unsigned long dirtied,
862 unsigned long elapsed)
863{
Wu Fengguang73811312011-08-26 15:53:24 -0600864 unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh);
865 unsigned long limit = hard_dirty_limit(thresh);
866 unsigned long setpoint = (freerun + limit) / 2;
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600867 unsigned long write_bw = bdi->avg_write_bandwidth;
868 unsigned long dirty_ratelimit = bdi->dirty_ratelimit;
869 unsigned long dirty_rate;
870 unsigned long task_ratelimit;
871 unsigned long balanced_dirty_ratelimit;
872 unsigned long pos_ratio;
Wu Fengguang73811312011-08-26 15:53:24 -0600873 unsigned long step;
874 unsigned long x;
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600875
876 /*
877 * The dirty rate will match the writeout rate in long term, except
878 * when dirty pages are truncated by userspace or re-dirtied by FS.
879 */
880 dirty_rate = (dirtied - bdi->dirtied_stamp) * HZ / elapsed;
881
882 pos_ratio = bdi_position_ratio(bdi, thresh, bg_thresh, dirty,
883 bdi_thresh, bdi_dirty);
884 /*
885 * task_ratelimit reflects each dd's dirty rate for the past 200ms.
886 */
887 task_ratelimit = (u64)dirty_ratelimit *
888 pos_ratio >> RATELIMIT_CALC_SHIFT;
889 task_ratelimit++; /* it helps rampup dirty_ratelimit from tiny values */
890
891 /*
892 * A linear estimation of the "balanced" throttle rate. The theory is,
893 * if there are N dd tasks, each throttled at task_ratelimit, the bdi's
894 * dirty_rate will be measured to be (N * task_ratelimit). So the below
895 * formula will yield the balanced rate limit (write_bw / N).
896 *
897 * Note that the expanded form is not a pure rate feedback:
898 * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) (1)
899 * but also takes pos_ratio into account:
900 * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) * pos_ratio (2)
901 *
902 * (1) is not realistic because pos_ratio also takes part in balancing
903 * the dirty rate. Consider the state
904 * pos_ratio = 0.5 (3)
905 * rate = 2 * (write_bw / N) (4)
906 * If (1) is used, it will stuck in that state! Because each dd will
907 * be throttled at
908 * task_ratelimit = pos_ratio * rate = (write_bw / N) (5)
909 * yielding
910 * dirty_rate = N * task_ratelimit = write_bw (6)
911 * put (6) into (1) we get
912 * rate_(i+1) = rate_(i) (7)
913 *
914 * So we end up using (2) to always keep
915 * rate_(i+1) ~= (write_bw / N) (8)
916 * regardless of the value of pos_ratio. As long as (8) is satisfied,
917 * pos_ratio is able to drive itself to 1.0, which is not only where
918 * the dirty count meet the setpoint, but also where the slope of
919 * pos_ratio is most flat and hence task_ratelimit is least fluctuated.
920 */
921 balanced_dirty_ratelimit = div_u64((u64)task_ratelimit * write_bw,
922 dirty_rate | 1);
Wu Fengguangbdaac492011-08-03 14:30:36 -0600923 /*
924 * balanced_dirty_ratelimit ~= (write_bw / N) <= write_bw
925 */
926 if (unlikely(balanced_dirty_ratelimit > write_bw))
927 balanced_dirty_ratelimit = write_bw;
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600928
Wu Fengguang73811312011-08-26 15:53:24 -0600929 /*
930 * We could safely do this and return immediately:
931 *
932 * bdi->dirty_ratelimit = balanced_dirty_ratelimit;
933 *
934 * However to get a more stable dirty_ratelimit, the below elaborated
935 * code makes use of task_ratelimit to filter out sigular points and
936 * limit the step size.
937 *
938 * The below code essentially only uses the relative value of
939 *
940 * task_ratelimit - dirty_ratelimit
941 * = (pos_ratio - 1) * dirty_ratelimit
942 *
943 * which reflects the direction and size of dirty position error.
944 */
945
946 /*
947 * dirty_ratelimit will follow balanced_dirty_ratelimit iff
948 * task_ratelimit is on the same side of dirty_ratelimit, too.
949 * For example, when
950 * - dirty_ratelimit > balanced_dirty_ratelimit
951 * - dirty_ratelimit > task_ratelimit (dirty pages are above setpoint)
952 * lowering dirty_ratelimit will help meet both the position and rate
953 * control targets. Otherwise, don't update dirty_ratelimit if it will
954 * only help meet the rate target. After all, what the users ultimately
955 * feel and care are stable dirty rate and small position error.
956 *
957 * |task_ratelimit - dirty_ratelimit| is used to limit the step size
958 * and filter out the sigular points of balanced_dirty_ratelimit. Which
959 * keeps jumping around randomly and can even leap far away at times
960 * due to the small 200ms estimation period of dirty_rate (we want to
961 * keep that period small to reduce time lags).
962 */
963 step = 0;
964 if (dirty < setpoint) {
965 x = min(bdi->balanced_dirty_ratelimit,
966 min(balanced_dirty_ratelimit, task_ratelimit));
967 if (dirty_ratelimit < x)
968 step = x - dirty_ratelimit;
969 } else {
970 x = max(bdi->balanced_dirty_ratelimit,
971 max(balanced_dirty_ratelimit, task_ratelimit));
972 if (dirty_ratelimit > x)
973 step = dirty_ratelimit - x;
974 }
975
976 /*
977 * Don't pursue 100% rate matching. It's impossible since the balanced
978 * rate itself is constantly fluctuating. So decrease the track speed
979 * when it gets close to the target. Helps eliminate pointless tremors.
980 */
981 step >>= dirty_ratelimit / (2 * step + 1);
982 /*
983 * Limit the tracking speed to avoid overshooting.
984 */
985 step = (step + 7) / 8;
986
987 if (dirty_ratelimit < balanced_dirty_ratelimit)
988 dirty_ratelimit += step;
989 else
990 dirty_ratelimit -= step;
991
992 bdi->dirty_ratelimit = max(dirty_ratelimit, 1UL);
993 bdi->balanced_dirty_ratelimit = balanced_dirty_ratelimit;
Wu Fengguangb48c1042011-03-02 17:22:49 -0600994
995 trace_bdi_dirty_ratelimit(bdi, dirty_rate, task_ratelimit);
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600996}
997
Wu Fengguange98be2d2010-08-29 11:22:30 -0600998void __bdi_update_bandwidth(struct backing_dev_info *bdi,
Wu Fengguangc42843f2011-03-02 15:54:09 -0600999 unsigned long thresh,
Wu Fengguangaf6a3112011-10-03 20:46:17 -06001000 unsigned long bg_thresh,
Wu Fengguangc42843f2011-03-02 15:54:09 -06001001 unsigned long dirty,
1002 unsigned long bdi_thresh,
1003 unsigned long bdi_dirty,
Wu Fengguange98be2d2010-08-29 11:22:30 -06001004 unsigned long start_time)
1005{
1006 unsigned long now = jiffies;
1007 unsigned long elapsed = now - bdi->bw_time_stamp;
Wu Fengguangbe3ffa22011-06-12 10:51:31 -06001008 unsigned long dirtied;
Wu Fengguange98be2d2010-08-29 11:22:30 -06001009 unsigned long written;
1010
1011 /*
1012 * rate-limit, only update once every 200ms.
1013 */
1014 if (elapsed < BANDWIDTH_INTERVAL)
1015 return;
1016
Wu Fengguangbe3ffa22011-06-12 10:51:31 -06001017 dirtied = percpu_counter_read(&bdi->bdi_stat[BDI_DIRTIED]);
Wu Fengguange98be2d2010-08-29 11:22:30 -06001018 written = percpu_counter_read(&bdi->bdi_stat[BDI_WRITTEN]);
1019
1020 /*
1021 * Skip quiet periods when disk bandwidth is under-utilized.
1022 * (at least 1s idle time between two flusher runs)
1023 */
1024 if (elapsed > HZ && time_before(bdi->bw_time_stamp, start_time))
1025 goto snapshot;
1026
Wu Fengguangbe3ffa22011-06-12 10:51:31 -06001027 if (thresh) {
Wu Fengguangc42843f2011-03-02 15:54:09 -06001028 global_update_bandwidth(thresh, dirty, now);
Wu Fengguangbe3ffa22011-06-12 10:51:31 -06001029 bdi_update_dirty_ratelimit(bdi, thresh, bg_thresh, dirty,
1030 bdi_thresh, bdi_dirty,
1031 dirtied, elapsed);
1032 }
Wu Fengguange98be2d2010-08-29 11:22:30 -06001033 bdi_update_write_bandwidth(bdi, elapsed, written);
1034
1035snapshot:
Wu Fengguangbe3ffa22011-06-12 10:51:31 -06001036 bdi->dirtied_stamp = dirtied;
Wu Fengguange98be2d2010-08-29 11:22:30 -06001037 bdi->written_stamp = written;
1038 bdi->bw_time_stamp = now;
1039}
1040
1041static void bdi_update_bandwidth(struct backing_dev_info *bdi,
Wu Fengguangc42843f2011-03-02 15:54:09 -06001042 unsigned long thresh,
Wu Fengguangaf6a3112011-10-03 20:46:17 -06001043 unsigned long bg_thresh,
Wu Fengguangc42843f2011-03-02 15:54:09 -06001044 unsigned long dirty,
1045 unsigned long bdi_thresh,
1046 unsigned long bdi_dirty,
Wu Fengguange98be2d2010-08-29 11:22:30 -06001047 unsigned long start_time)
1048{
1049 if (time_is_after_eq_jiffies(bdi->bw_time_stamp + BANDWIDTH_INTERVAL))
1050 return;
1051 spin_lock(&bdi->wb.list_lock);
Wu Fengguangaf6a3112011-10-03 20:46:17 -06001052 __bdi_update_bandwidth(bdi, thresh, bg_thresh, dirty,
1053 bdi_thresh, bdi_dirty, start_time);
Wu Fengguange98be2d2010-08-29 11:22:30 -06001054 spin_unlock(&bdi->wb.list_lock);
1055}
1056
Linus Torvalds1da177e2005-04-16 15:20:36 -07001057/*
Wu Fengguang9d823e82011-06-11 18:10:12 -06001058 * After a task dirtied this many pages, balance_dirty_pages_ratelimited_nr()
1059 * will look to see if it needs to start dirty throttling.
1060 *
1061 * If dirty_poll_interval is too low, big NUMA machines will call the expensive
1062 * global_page_state() too often. So scale it near-sqrt to the safety margin
1063 * (the number of pages we may dirty without exceeding the dirty limits).
1064 */
1065static unsigned long dirty_poll_interval(unsigned long dirty,
1066 unsigned long thresh)
1067{
1068 if (thresh > dirty)
1069 return 1UL << (ilog2(thresh - dirty) >> 1);
1070
1071 return 1;
1072}
1073
Fengguang Wu60c6aa32013-10-16 13:47:03 -07001074static unsigned long bdi_max_pause(struct backing_dev_info *bdi,
1075 unsigned long bdi_dirty)
Wu Fengguangc8462cc2011-06-11 19:21:43 -06001076{
Fengguang Wu60c6aa32013-10-16 13:47:03 -07001077 unsigned long bw = bdi->avg_write_bandwidth;
1078 unsigned long t;
Wu Fengguangc8462cc2011-06-11 19:21:43 -06001079
1080 /*
1081 * Limit pause time for small memory systems. If sleeping for too long
1082 * time, a small pool of dirty/writeback pages may go empty and disk go
1083 * idle.
1084 *
1085 * 8 serves as the safety ratio.
1086 */
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001087 t = bdi_dirty / (1 + bw / roundup_pow_of_two(1 + HZ / 8));
1088 t++;
1089
Fengguang Wu60c6aa32013-10-16 13:47:03 -07001090 return min_t(unsigned long, t, MAX_PAUSE);
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001091}
1092
1093static long bdi_min_pause(struct backing_dev_info *bdi,
1094 long max_pause,
1095 unsigned long task_ratelimit,
1096 unsigned long dirty_ratelimit,
1097 int *nr_dirtied_pause)
1098{
1099 long hi = ilog2(bdi->avg_write_bandwidth);
1100 long lo = ilog2(bdi->dirty_ratelimit);
1101 long t; /* target pause */
1102 long pause; /* estimated next pause */
1103 int pages; /* target nr_dirtied_pause */
1104
1105 /* target for 10ms pause on 1-dd case */
1106 t = max(1, HZ / 100);
Wu Fengguangc8462cc2011-06-11 19:21:43 -06001107
1108 /*
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001109 * Scale up pause time for concurrent dirtiers in order to reduce CPU
1110 * overheads.
1111 *
1112 * (N * 10ms) on 2^N concurrent tasks.
Wu Fengguangc8462cc2011-06-11 19:21:43 -06001113 */
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001114 if (hi > lo)
1115 t += (hi - lo) * (10 * HZ) / 1024;
1116
1117 /*
1118 * This is a bit convoluted. We try to base the next nr_dirtied_pause
1119 * on the much more stable dirty_ratelimit. However the next pause time
1120 * will be computed based on task_ratelimit and the two rate limits may
1121 * depart considerably at some time. Especially if task_ratelimit goes
1122 * below dirty_ratelimit/2 and the target pause is max_pause, the next
1123 * pause time will be max_pause*2 _trimmed down_ to max_pause. As a
1124 * result task_ratelimit won't be executed faithfully, which could
1125 * eventually bring down dirty_ratelimit.
1126 *
1127 * We apply two rules to fix it up:
1128 * 1) try to estimate the next pause time and if necessary, use a lower
1129 * nr_dirtied_pause so as not to exceed max_pause. When this happens,
1130 * nr_dirtied_pause will be "dancing" with task_ratelimit.
1131 * 2) limit the target pause time to max_pause/2, so that the normal
1132 * small fluctuations of task_ratelimit won't trigger rule (1) and
1133 * nr_dirtied_pause will remain as stable as dirty_ratelimit.
1134 */
1135 t = min(t, 1 + max_pause / 2);
1136 pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
1137
Wu Fengguang5b9b3572011-12-06 13:17:17 -06001138 /*
1139 * Tiny nr_dirtied_pause is found to hurt I/O performance in the test
1140 * case fio-mmap-randwrite-64k, which does 16*{sync read, async write}.
1141 * When the 16 consecutive reads are often interrupted by some dirty
1142 * throttling pause during the async writes, cfq will go into idles
1143 * (deadline is fine). So push nr_dirtied_pause as high as possible
1144 * until reaches DIRTY_POLL_THRESH=32 pages.
1145 */
1146 if (pages < DIRTY_POLL_THRESH) {
1147 t = max_pause;
1148 pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
1149 if (pages > DIRTY_POLL_THRESH) {
1150 pages = DIRTY_POLL_THRESH;
1151 t = HZ * DIRTY_POLL_THRESH / dirty_ratelimit;
1152 }
1153 }
1154
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001155 pause = HZ * pages / (task_ratelimit + 1);
1156 if (pause > max_pause) {
1157 t = max_pause;
1158 pages = task_ratelimit * t / roundup_pow_of_two(HZ);
1159 }
1160
1161 *nr_dirtied_pause = pages;
1162 /*
1163 * The minimal pause time will normally be half the target pause time.
1164 */
Wu Fengguang5b9b3572011-12-06 13:17:17 -06001165 return pages >= DIRTY_POLL_THRESH ? 1 + t / 2 : t;
Wu Fengguangc8462cc2011-06-11 19:21:43 -06001166}
1167
Wu Fengguang9d823e82011-06-11 18:10:12 -06001168/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001169 * balance_dirty_pages() must be called by processes which are generating dirty
1170 * data. It looks at the number of dirty pages in the machine and will force
Wu Fengguang143dfe82010-08-27 18:45:12 -06001171 * the caller to wait once crossing the (background_thresh + dirty_thresh) / 2.
Jens Axboe5b0830c2009-09-23 19:37:09 +02001172 * If we're over `background_thresh' then the writeback threads are woken to
1173 * perform some writeout.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001174 */
Wu Fengguang3a2e9a52009-09-23 21:56:00 +08001175static void balance_dirty_pages(struct address_space *mapping,
Wu Fengguang143dfe82010-08-27 18:45:12 -06001176 unsigned long pages_dirtied)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001177{
Wu Fengguang143dfe82010-08-27 18:45:12 -06001178 unsigned long nr_reclaimable; /* = file_dirty + unstable_nfs */
1179 unsigned long bdi_reclaimable;
Wu Fengguang77627412010-09-12 13:34:05 -06001180 unsigned long nr_dirty; /* = file_dirty + writeback + unstable_nfs */
1181 unsigned long bdi_dirty;
Wu Fengguang6c14ae12011-03-02 16:04:18 -06001182 unsigned long freerun;
David Rientjes364aeb22009-01-06 14:39:29 -08001183 unsigned long background_thresh;
1184 unsigned long dirty_thresh;
1185 unsigned long bdi_thresh;
Wu Fengguang83712352011-06-11 19:25:42 -06001186 long period;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001187 long pause;
1188 long max_pause;
1189 long min_pause;
1190 int nr_dirtied_pause;
Wu Fengguange50e3722010-08-11 14:17:37 -07001191 bool dirty_exceeded = false;
Wu Fengguang143dfe82010-08-27 18:45:12 -06001192 unsigned long task_ratelimit;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001193 unsigned long dirty_ratelimit;
Wu Fengguang143dfe82010-08-27 18:45:12 -06001194 unsigned long pos_ratio;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001195 struct backing_dev_info *bdi = mapping->backing_dev_info;
Wu Fengguange98be2d2010-08-29 11:22:30 -06001196 unsigned long start_time = jiffies;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001197
1198 for (;;) {
Wu Fengguang83712352011-06-11 19:25:42 -06001199 unsigned long now = jiffies;
1200
Wu Fengguang143dfe82010-08-27 18:45:12 -06001201 /*
1202 * Unstable writes are a feature of certain networked
1203 * filesystems (i.e. NFS) in which data may have been
1204 * written to the server's write cache, but has not yet
1205 * been flushed to permanent storage.
1206 */
Peter Zijlstra5fce25a2007-11-14 16:59:15 -08001207 nr_reclaimable = global_page_state(NR_FILE_DIRTY) +
1208 global_page_state(NR_UNSTABLE_NFS);
Wu Fengguang77627412010-09-12 13:34:05 -06001209 nr_dirty = nr_reclaimable + global_page_state(NR_WRITEBACK);
Peter Zijlstra5fce25a2007-11-14 16:59:15 -08001210
Wu Fengguang16c40422010-08-11 14:17:39 -07001211 global_dirty_limits(&background_thresh, &dirty_thresh);
1212
1213 /*
1214 * Throttle it only when the background writeback cannot
1215 * catch-up. This avoids (excessively) small writeouts
1216 * when the bdi limits are ramping up.
1217 */
Wu Fengguang6c14ae12011-03-02 16:04:18 -06001218 freerun = dirty_freerun_ceiling(dirty_thresh,
1219 background_thresh);
Wu Fengguang83712352011-06-11 19:25:42 -06001220 if (nr_dirty <= freerun) {
1221 current->dirty_paused_when = now;
1222 current->nr_dirtied = 0;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001223 current->nr_dirtied_pause =
1224 dirty_poll_interval(nr_dirty, dirty_thresh);
Wu Fengguang16c40422010-08-11 14:17:39 -07001225 break;
Wu Fengguang83712352011-06-11 19:25:42 -06001226 }
Wu Fengguang16c40422010-08-11 14:17:39 -07001227
Wu Fengguang143dfe82010-08-27 18:45:12 -06001228 if (unlikely(!writeback_in_progress(bdi)))
1229 bdi_start_background_writeback(bdi);
1230
1231 /*
1232 * bdi_thresh is not treated as some limiting factor as
1233 * dirty_thresh, due to reasons
1234 * - in JBOD setup, bdi_thresh can fluctuate a lot
1235 * - in a system with HDD and USB key, the USB key may somehow
1236 * go into state (bdi_dirty >> bdi_thresh) either because
1237 * bdi_dirty starts high, or because bdi_thresh drops low.
1238 * In this case we don't want to hard throttle the USB key
1239 * dirtiers for 100 seconds until bdi_dirty drops under
1240 * bdi_thresh. Instead the auxiliary bdi control line in
1241 * bdi_position_ratio() will let the dirtier task progress
1242 * at some rate <= (write_bw / 2) for bringing down bdi_dirty.
1243 */
Wu Fengguang16c40422010-08-11 14:17:39 -07001244 bdi_thresh = bdi_dirty_limit(bdi, dirty_thresh);
Wu Fengguang16c40422010-08-11 14:17:39 -07001245
Wu Fengguange50e3722010-08-11 14:17:37 -07001246 /*
1247 * In order to avoid the stacked BDI deadlock we need
1248 * to ensure we accurately count the 'dirty' pages when
1249 * the threshold is low.
1250 *
1251 * Otherwise it would be possible to get thresh+n pages
1252 * reported dirty, even though there are thresh-m pages
1253 * actually dirty; with m+n sitting in the percpu
1254 * deltas.
1255 */
Wu Fengguang143dfe82010-08-27 18:45:12 -06001256 if (bdi_thresh < 2 * bdi_stat_error(bdi)) {
1257 bdi_reclaimable = bdi_stat_sum(bdi, BDI_RECLAIMABLE);
1258 bdi_dirty = bdi_reclaimable +
Wu Fengguang77627412010-09-12 13:34:05 -06001259 bdi_stat_sum(bdi, BDI_WRITEBACK);
Wu Fengguange50e3722010-08-11 14:17:37 -07001260 } else {
Wu Fengguang143dfe82010-08-27 18:45:12 -06001261 bdi_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
1262 bdi_dirty = bdi_reclaimable +
Wu Fengguang77627412010-09-12 13:34:05 -06001263 bdi_stat(bdi, BDI_WRITEBACK);
Wu Fengguange50e3722010-08-11 14:17:37 -07001264 }
Peter Zijlstra5fce25a2007-11-14 16:59:15 -08001265
Wu Fengguang82791942011-12-03 21:26:01 -06001266 dirty_exceeded = (bdi_dirty > bdi_thresh) &&
Wu Fengguang77627412010-09-12 13:34:05 -06001267 (nr_dirty > dirty_thresh);
Wu Fengguang143dfe82010-08-27 18:45:12 -06001268 if (dirty_exceeded && !bdi->dirty_exceeded)
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -07001269 bdi->dirty_exceeded = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001270
Wu Fengguangaf6a3112011-10-03 20:46:17 -06001271 bdi_update_bandwidth(bdi, dirty_thresh, background_thresh,
1272 nr_dirty, bdi_thresh, bdi_dirty,
1273 start_time);
Wu Fengguange98be2d2010-08-29 11:22:30 -06001274
Wu Fengguang143dfe82010-08-27 18:45:12 -06001275 dirty_ratelimit = bdi->dirty_ratelimit;
1276 pos_ratio = bdi_position_ratio(bdi, dirty_thresh,
1277 background_thresh, nr_dirty,
1278 bdi_thresh, bdi_dirty);
Wu Fengguang3a73dbb2011-11-07 19:19:28 +08001279 task_ratelimit = ((u64)dirty_ratelimit * pos_ratio) >>
1280 RATELIMIT_CALC_SHIFT;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001281 max_pause = bdi_max_pause(bdi, bdi_dirty);
1282 min_pause = bdi_min_pause(bdi, max_pause,
1283 task_ratelimit, dirty_ratelimit,
1284 &nr_dirtied_pause);
1285
Wu Fengguang3a73dbb2011-11-07 19:19:28 +08001286 if (unlikely(task_ratelimit == 0)) {
Wu Fengguang83712352011-06-11 19:25:42 -06001287 period = max_pause;
Wu Fengguangc8462cc2011-06-11 19:21:43 -06001288 pause = max_pause;
Wu Fengguang143dfe82010-08-27 18:45:12 -06001289 goto pause;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001290 }
Wu Fengguang83712352011-06-11 19:25:42 -06001291 period = HZ * pages_dirtied / task_ratelimit;
1292 pause = period;
1293 if (current->dirty_paused_when)
1294 pause -= now - current->dirty_paused_when;
1295 /*
1296 * For less than 1s think time (ext3/4 may block the dirtier
1297 * for up to 800ms from time to time on 1-HDD; so does xfs,
1298 * however at much less frequency), try to compensate it in
1299 * future periods by updating the virtual time; otherwise just
1300 * do a reset, as it may be a light dirtier.
1301 */
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001302 if (pause < min_pause) {
Wu Fengguangece13ac2010-08-29 23:33:20 -06001303 trace_balance_dirty_pages(bdi,
1304 dirty_thresh,
1305 background_thresh,
1306 nr_dirty,
1307 bdi_thresh,
1308 bdi_dirty,
1309 dirty_ratelimit,
1310 task_ratelimit,
1311 pages_dirtied,
Wu Fengguang83712352011-06-11 19:25:42 -06001312 period,
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001313 min(pause, 0L),
Wu Fengguangece13ac2010-08-29 23:33:20 -06001314 start_time);
Wu Fengguang83712352011-06-11 19:25:42 -06001315 if (pause < -HZ) {
1316 current->dirty_paused_when = now;
1317 current->nr_dirtied = 0;
1318 } else if (period) {
1319 current->dirty_paused_when += period;
1320 current->nr_dirtied = 0;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001321 } else if (current->nr_dirtied_pause <= pages_dirtied)
1322 current->nr_dirtied_pause += pages_dirtied;
Wu Fengguang57fc9782011-06-11 19:32:32 -06001323 break;
1324 }
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001325 if (unlikely(pause > max_pause)) {
1326 /* for occasional dropped task_ratelimit */
1327 now += min(pause - max_pause, max_pause);
1328 pause = max_pause;
1329 }
Wu Fengguang143dfe82010-08-27 18:45:12 -06001330
1331pause:
Wu Fengguangece13ac2010-08-29 23:33:20 -06001332 trace_balance_dirty_pages(bdi,
1333 dirty_thresh,
1334 background_thresh,
1335 nr_dirty,
1336 bdi_thresh,
1337 bdi_dirty,
1338 dirty_ratelimit,
1339 task_ratelimit,
1340 pages_dirtied,
Wu Fengguang83712352011-06-11 19:25:42 -06001341 period,
Wu Fengguangece13ac2010-08-29 23:33:20 -06001342 pause,
1343 start_time);
Jan Kara499d05e2011-11-16 19:34:48 +08001344 __set_current_state(TASK_KILLABLE);
Wu Fengguangd25105e2009-10-09 12:40:42 +02001345 io_schedule_timeout(pause);
Jens Axboe87c6a9b2009-09-17 19:59:14 +02001346
Wu Fengguang83712352011-06-11 19:25:42 -06001347 current->dirty_paused_when = now + pause;
1348 current->nr_dirtied = 0;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001349 current->nr_dirtied_pause = nr_dirtied_pause;
Wu Fengguang83712352011-06-11 19:25:42 -06001350
Wu Fengguangffd1f602011-06-19 22:18:42 -06001351 /*
Wu Fengguang1df64712011-11-13 19:47:32 -06001352 * This is typically equal to (nr_dirty < dirty_thresh) and can
1353 * also keep "1000+ dd on a slow USB stick" under control.
Wu Fengguangffd1f602011-06-19 22:18:42 -06001354 */
Wu Fengguang1df64712011-11-13 19:47:32 -06001355 if (task_ratelimit)
Wu Fengguangffd1f602011-06-19 22:18:42 -06001356 break;
Jan Kara499d05e2011-11-16 19:34:48 +08001357
Wu Fengguangc5c63432011-12-02 10:21:33 -06001358 /*
1359 * In the case of an unresponding NFS server and the NFS dirty
1360 * pages exceeds dirty_thresh, give the other good bdi's a pipe
1361 * to go through, so that tasks on them still remain responsive.
1362 *
1363 * In theory 1 page is enough to keep the comsumer-producer
1364 * pipe going: the flusher cleans 1 page => the task dirties 1
1365 * more page. However bdi_dirty has accounting errors. So use
1366 * the larger and more IO friendly bdi_stat_error.
1367 */
1368 if (bdi_dirty <= bdi_stat_error(bdi))
1369 break;
1370
Jan Kara499d05e2011-11-16 19:34:48 +08001371 if (fatal_signal_pending(current))
1372 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001373 }
1374
Wu Fengguang143dfe82010-08-27 18:45:12 -06001375 if (!dirty_exceeded && bdi->dirty_exceeded)
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -07001376 bdi->dirty_exceeded = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001377
1378 if (writeback_in_progress(bdi))
Jens Axboe5b0830c2009-09-23 19:37:09 +02001379 return;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001380
1381 /*
1382 * In laptop mode, we wait until hitting the higher threshold before
1383 * starting background writeout, and then write out all the way down
1384 * to the lower threshold. So slow writers cause minimal disk activity.
1385 *
1386 * In normal mode, we start background writeout at the lower
1387 * background_thresh, to keep the amount of dirty memory low.
1388 */
Wu Fengguang143dfe82010-08-27 18:45:12 -06001389 if (laptop_mode)
1390 return;
1391
1392 if (nr_reclaimable > background_thresh)
Christoph Hellwigc5444192010-06-08 18:15:15 +02001393 bdi_start_background_writeback(bdi);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001394}
1395
Wu Fengguang9d823e82011-06-11 18:10:12 -06001396static DEFINE_PER_CPU(int, bdp_ratelimits);
Tejun Heo245b2e72009-06-24 15:13:48 +09001397
Wu Fengguang54848d72011-04-05 13:21:19 -06001398/*
1399 * Normal tasks are throttled by
1400 * loop {
1401 * dirty tsk->nr_dirtied_pause pages;
1402 * take a snap in balance_dirty_pages();
1403 * }
1404 * However there is a worst case. If every task exit immediately when dirtied
1405 * (tsk->nr_dirtied_pause - 1) pages, balance_dirty_pages() will never be
1406 * called to throttle the page dirties. The solution is to save the not yet
1407 * throttled page dirties in dirty_throttle_leaks on task exit and charge them
1408 * randomly into the running tasks. This works well for the above worst case,
1409 * as the new task will pick up and accumulate the old task's leaked dirty
1410 * count and eventually get throttled.
1411 */
1412DEFINE_PER_CPU(int, dirty_throttle_leaks) = 0;
1413
Linus Torvalds1da177e2005-04-16 15:20:36 -07001414/**
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001415 * balance_dirty_pages_ratelimited_nr - balance dirty memory state
Martin Waitz67be2dd2005-05-01 08:59:26 -07001416 * @mapping: address_space which was dirtied
Martin Waitza5802902006-04-02 13:59:55 +02001417 * @nr_pages_dirtied: number of pages which the caller has just dirtied
Linus Torvalds1da177e2005-04-16 15:20:36 -07001418 *
1419 * Processes which are dirtying memory should call in here once for each page
1420 * which was newly dirtied. The function will periodically check the system's
1421 * dirty state and will initiate writeback if needed.
1422 *
1423 * On really big machines, get_writeback_state is expensive, so try to avoid
1424 * calling it too often (ratelimiting). But once we're over the dirty memory
1425 * limit we decrease the ratelimiting by a lot, to prevent individual processes
1426 * from overshooting the limit by (ratelimit_pages) each.
1427 */
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001428void balance_dirty_pages_ratelimited_nr(struct address_space *mapping,
1429 unsigned long nr_pages_dirtied)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001430{
Wu Fengguang36715ce2011-06-11 17:53:57 -06001431 struct backing_dev_info *bdi = mapping->backing_dev_info;
Wu Fengguang9d823e82011-06-11 18:10:12 -06001432 int ratelimit;
1433 int *p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001434
Wu Fengguang36715ce2011-06-11 17:53:57 -06001435 if (!bdi_cap_account_dirty(bdi))
1436 return;
1437
Wu Fengguang9d823e82011-06-11 18:10:12 -06001438 ratelimit = current->nr_dirtied_pause;
1439 if (bdi->dirty_exceeded)
1440 ratelimit = min(ratelimit, 32 >> (PAGE_SHIFT - 10));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001441
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001442 preempt_disable();
Wu Fengguang9d823e82011-06-11 18:10:12 -06001443 /*
1444 * This prevents one CPU to accumulate too many dirtied pages without
1445 * calling into balance_dirty_pages(), which can happen when there are
1446 * 1000+ tasks, all of them start dirtying pages at exactly the same
1447 * time, hence all honoured too large initial task->nr_dirtied_pause.
1448 */
Tejun Heo245b2e72009-06-24 15:13:48 +09001449 p = &__get_cpu_var(bdp_ratelimits);
Wu Fengguang9d823e82011-06-11 18:10:12 -06001450 if (unlikely(current->nr_dirtied >= ratelimit))
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001451 *p = 0;
Wu Fengguangd3bc1fe2011-04-14 07:52:37 -06001452 else if (unlikely(*p >= ratelimit_pages)) {
1453 *p = 0;
1454 ratelimit = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001455 }
Wu Fengguang54848d72011-04-05 13:21:19 -06001456 /*
1457 * Pick up the dirtied pages by the exited tasks. This avoids lots of
1458 * short-lived tasks (eg. gcc invocations in a kernel build) escaping
1459 * the dirty throttling and livelock other long-run dirtiers.
1460 */
1461 p = &__get_cpu_var(dirty_throttle_leaks);
1462 if (*p > 0 && current->nr_dirtied < ratelimit) {
1463 nr_pages_dirtied = min(*p, ratelimit - current->nr_dirtied);
1464 *p -= nr_pages_dirtied;
1465 current->nr_dirtied += nr_pages_dirtied;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001466 }
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001467 preempt_enable();
Wu Fengguang9d823e82011-06-11 18:10:12 -06001468
1469 if (unlikely(current->nr_dirtied >= ratelimit))
1470 balance_dirty_pages(mapping, current->nr_dirtied);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001471}
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001472EXPORT_SYMBOL(balance_dirty_pages_ratelimited_nr);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001473
Andrew Morton232ea4d2007-02-28 20:13:21 -08001474void throttle_vm_writeout(gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001475{
David Rientjes364aeb22009-01-06 14:39:29 -08001476 unsigned long background_thresh;
1477 unsigned long dirty_thresh;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001478
1479 for ( ; ; ) {
Wu Fengguang16c40422010-08-11 14:17:39 -07001480 global_dirty_limits(&background_thresh, &dirty_thresh);
Fengguang Wu47a13332012-03-21 16:34:09 -07001481 dirty_thresh = hard_dirty_limit(dirty_thresh);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001482
1483 /*
1484 * Boost the allowable dirty threshold a bit for page
1485 * allocators so they don't get DoS'ed by heavy writers
1486 */
1487 dirty_thresh += dirty_thresh / 10; /* wheeee... */
1488
Christoph Lameterc24f21b2006-06-30 01:55:42 -07001489 if (global_page_state(NR_UNSTABLE_NFS) +
1490 global_page_state(NR_WRITEBACK) <= dirty_thresh)
1491 break;
Jens Axboe8aa7e842009-07-09 14:52:32 +02001492 congestion_wait(BLK_RW_ASYNC, HZ/10);
Fengguang Wu369f2382007-10-16 23:30:45 -07001493
1494 /*
1495 * The caller might hold locks which can prevent IO completion
1496 * or progress in the filesystem. So we cannot just sit here
1497 * waiting for IO to complete.
1498 */
1499 if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO))
1500 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001501 }
1502}
1503
Linus Torvalds1da177e2005-04-16 15:20:36 -07001504/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001505 * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
1506 */
1507int dirty_writeback_centisecs_handler(ctl_table *table, int write,
Alexey Dobriyan8d65af72009-09-23 15:57:19 -07001508 void __user *buffer, size_t *length, loff_t *ppos)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001509{
Alexey Dobriyan8d65af72009-09-23 15:57:19 -07001510 proc_dointvec(table, write, buffer, length, ppos);
Jens Axboe64231042010-05-21 20:00:35 +02001511 bdi_arm_supers_timer();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001512 return 0;
1513}
1514
Jens Axboec2c49862010-05-20 09:18:47 +02001515#ifdef CONFIG_BLOCK
Matthew Garrett31373d02010-04-06 14:25:14 +02001516void laptop_mode_timer_fn(unsigned long data)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001517{
Matthew Garrett31373d02010-04-06 14:25:14 +02001518 struct request_queue *q = (struct request_queue *)data;
1519 int nr_pages = global_page_state(NR_FILE_DIRTY) +
1520 global_page_state(NR_UNSTABLE_NFS);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001521
Matthew Garrett31373d02010-04-06 14:25:14 +02001522 /*
1523 * We want to write everything out, not just down to the dirty
1524 * threshold
1525 */
Matthew Garrett31373d02010-04-06 14:25:14 +02001526 if (bdi_has_dirty_io(&q->backing_dev_info))
Curt Wohlgemuth0e175a12011-10-07 21:54:10 -06001527 bdi_start_writeback(&q->backing_dev_info, nr_pages,
1528 WB_REASON_LAPTOP_TIMER);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001529}
1530
1531/*
1532 * We've spun up the disk and we're in laptop mode: schedule writeback
1533 * of all dirty data a few seconds from now. If the flush is already scheduled
1534 * then push it back - the user is still using the disk.
1535 */
Matthew Garrett31373d02010-04-06 14:25:14 +02001536void laptop_io_completion(struct backing_dev_info *info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001537{
Matthew Garrett31373d02010-04-06 14:25:14 +02001538 mod_timer(&info->laptop_mode_wb_timer, jiffies + laptop_mode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001539}
1540
1541/*
1542 * We're in laptop mode and we've just synced. The sync's writes will have
1543 * caused another writeback to be scheduled by laptop_io_completion.
1544 * Nothing needs to be written back anymore, so we unschedule the writeback.
1545 */
1546void laptop_sync_completion(void)
1547{
Matthew Garrett31373d02010-04-06 14:25:14 +02001548 struct backing_dev_info *bdi;
1549
1550 rcu_read_lock();
1551
1552 list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
1553 del_timer(&bdi->laptop_mode_wb_timer);
1554
1555 rcu_read_unlock();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001556}
Jens Axboec2c49862010-05-20 09:18:47 +02001557#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -07001558
1559/*
1560 * If ratelimit_pages is too high then we can get into dirty-data overload
1561 * if a large number of processes all perform writes at the same time.
1562 * If it is too low then SMP machines will call the (expensive)
1563 * get_writeback_state too often.
1564 *
1565 * Here we set ratelimit_pages to a level which ensures that when all CPUs are
1566 * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
Wu Fengguang9d823e82011-06-11 18:10:12 -06001567 * thresholds.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001568 */
1569
Chandra Seetharaman2d1d43f2006-09-29 02:01:25 -07001570void writeback_set_ratelimit(void)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001571{
Wu Fengguang9d823e82011-06-11 18:10:12 -06001572 unsigned long background_thresh;
1573 unsigned long dirty_thresh;
1574 global_dirty_limits(&background_thresh, &dirty_thresh);
1575 ratelimit_pages = dirty_thresh / (num_online_cpus() * 32);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001576 if (ratelimit_pages < 16)
1577 ratelimit_pages = 16;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001578}
1579
Chandra Seetharaman26c21432006-06-27 02:54:10 -07001580static int __cpuinit
Srivatsa S. Bhate15e16b2012-09-28 20:27:49 +08001581ratelimit_handler(struct notifier_block *self, unsigned long action,
1582 void *hcpu)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001583{
Srivatsa S. Bhate15e16b2012-09-28 20:27:49 +08001584
1585 switch (action & ~CPU_TASKS_FROZEN) {
1586 case CPU_ONLINE:
1587 case CPU_DEAD:
1588 writeback_set_ratelimit();
1589 return NOTIFY_OK;
1590 default:
1591 return NOTIFY_DONE;
1592 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001593}
1594
Chandra Seetharaman74b85f32006-06-27 02:54:09 -07001595static struct notifier_block __cpuinitdata ratelimit_nb = {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001596 .notifier_call = ratelimit_handler,
1597 .next = NULL,
1598};
1599
1600/*
Linus Torvaldsdc6e29d2007-01-29 16:37:38 -08001601 * Called early on to tune the page writeback dirty limits.
1602 *
1603 * We used to scale dirty pages according to how total memory
1604 * related to pages that could be allocated for buffers (by
1605 * comparing nr_free_buffer_pages() to vm_total_pages.
1606 *
1607 * However, that was when we used "dirty_ratio" to scale with
1608 * all memory, and we don't do that any more. "dirty_ratio"
1609 * is now applied to total non-HIGHPAGE memory (by subtracting
1610 * totalhigh_pages from vm_total_pages), and as such we can't
1611 * get into the old insane situation any more where we had
1612 * large amounts of dirty pages compared to a small amount of
1613 * non-HIGHMEM memory.
1614 *
1615 * But we might still want to scale the dirty_ratio by how
1616 * much memory the box has..
Linus Torvalds1da177e2005-04-16 15:20:36 -07001617 */
1618void __init page_writeback_init(void)
1619{
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -07001620 int shift;
1621
Chandra Seetharaman2d1d43f2006-09-29 02:01:25 -07001622 writeback_set_ratelimit();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001623 register_cpu_notifier(&ratelimit_nb);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -07001624
1625 shift = calc_period_shift();
1626 prop_descriptor_init(&vm_completions, shift);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001627}
1628
David Howells811d7362006-08-29 19:06:09 +01001629/**
Jan Karaf446daa2010-08-09 17:19:12 -07001630 * tag_pages_for_writeback - tag pages to be written by write_cache_pages
1631 * @mapping: address space structure to write
1632 * @start: starting page index
1633 * @end: ending page index (inclusive)
1634 *
1635 * This function scans the page range from @start to @end (inclusive) and tags
1636 * all pages that have DIRTY tag set with a special TOWRITE tag. The idea is
1637 * that write_cache_pages (or whoever calls this function) will then use
1638 * TOWRITE tag to identify pages eligible for writeback. This mechanism is
1639 * used to avoid livelocking of writeback by a process steadily creating new
1640 * dirty pages in the file (thus it is important for this function to be quick
1641 * so that it can tag pages faster than a dirtying process can create them).
1642 */
1643/*
1644 * We tag pages in batches of WRITEBACK_TAG_BATCH to reduce tree_lock latency.
1645 */
Jan Karaf446daa2010-08-09 17:19:12 -07001646void tag_pages_for_writeback(struct address_space *mapping,
1647 pgoff_t start, pgoff_t end)
1648{
Randy Dunlap3c111a02010-08-11 14:17:30 -07001649#define WRITEBACK_TAG_BATCH 4096
Jan Karaf446daa2010-08-09 17:19:12 -07001650 unsigned long tagged;
1651
1652 do {
1653 spin_lock_irq(&mapping->tree_lock);
1654 tagged = radix_tree_range_tag_if_tagged(&mapping->page_tree,
1655 &start, end, WRITEBACK_TAG_BATCH,
1656 PAGECACHE_TAG_DIRTY, PAGECACHE_TAG_TOWRITE);
1657 spin_unlock_irq(&mapping->tree_lock);
1658 WARN_ON_ONCE(tagged > WRITEBACK_TAG_BATCH);
1659 cond_resched();
Jan Karad5ed3a42010-08-19 14:13:33 -07001660 /* We check 'start' to handle wrapping when end == ~0UL */
1661 } while (tagged >= WRITEBACK_TAG_BATCH && start);
Jan Karaf446daa2010-08-09 17:19:12 -07001662}
1663EXPORT_SYMBOL(tag_pages_for_writeback);
1664
1665/**
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001666 * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
David Howells811d7362006-08-29 19:06:09 +01001667 * @mapping: address space structure to write
1668 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001669 * @writepage: function called for each page
1670 * @data: data passed to writepage function
David Howells811d7362006-08-29 19:06:09 +01001671 *
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001672 * If a page is already under I/O, write_cache_pages() skips it, even
David Howells811d7362006-08-29 19:06:09 +01001673 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
1674 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
1675 * and msync() need to guarantee that all the data which was dirty at the time
1676 * the call was made get new I/O started against them. If wbc->sync_mode is
1677 * WB_SYNC_ALL then we were called for data integrity and we must wait for
1678 * existing IO to complete.
Jan Karaf446daa2010-08-09 17:19:12 -07001679 *
1680 * To avoid livelocks (when other process dirties new pages), we first tag
1681 * pages which should be written back with TOWRITE tag and only then start
1682 * writing them. For data-integrity sync we have to be careful so that we do
1683 * not miss some pages (e.g., because some other process has cleared TOWRITE
1684 * tag we set). The rule we follow is that TOWRITE tag can be cleared only
1685 * by the process clearing the DIRTY tag (and submitting the page for IO).
David Howells811d7362006-08-29 19:06:09 +01001686 */
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001687int write_cache_pages(struct address_space *mapping,
1688 struct writeback_control *wbc, writepage_t writepage,
1689 void *data)
David Howells811d7362006-08-29 19:06:09 +01001690{
David Howells811d7362006-08-29 19:06:09 +01001691 int ret = 0;
1692 int done = 0;
David Howells811d7362006-08-29 19:06:09 +01001693 struct pagevec pvec;
1694 int nr_pages;
Nick Piggin31a12662009-01-06 14:39:04 -08001695 pgoff_t uninitialized_var(writeback_index);
David Howells811d7362006-08-29 19:06:09 +01001696 pgoff_t index;
1697 pgoff_t end; /* Inclusive */
Nick Pigginbd19e012009-01-06 14:39:06 -08001698 pgoff_t done_index;
Nick Piggin31a12662009-01-06 14:39:04 -08001699 int cycled;
David Howells811d7362006-08-29 19:06:09 +01001700 int range_whole = 0;
Jan Karaf446daa2010-08-09 17:19:12 -07001701 int tag;
David Howells811d7362006-08-29 19:06:09 +01001702
David Howells811d7362006-08-29 19:06:09 +01001703 pagevec_init(&pvec, 0);
1704 if (wbc->range_cyclic) {
Nick Piggin31a12662009-01-06 14:39:04 -08001705 writeback_index = mapping->writeback_index; /* prev offset */
1706 index = writeback_index;
1707 if (index == 0)
1708 cycled = 1;
1709 else
1710 cycled = 0;
David Howells811d7362006-08-29 19:06:09 +01001711 end = -1;
1712 } else {
1713 index = wbc->range_start >> PAGE_CACHE_SHIFT;
1714 end = wbc->range_end >> PAGE_CACHE_SHIFT;
1715 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
1716 range_whole = 1;
Nick Piggin31a12662009-01-06 14:39:04 -08001717 cycled = 1; /* ignore range_cyclic tests */
David Howells811d7362006-08-29 19:06:09 +01001718 }
Wu Fengguang6e6938b2010-06-06 10:38:15 -06001719 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
Jan Karaf446daa2010-08-09 17:19:12 -07001720 tag = PAGECACHE_TAG_TOWRITE;
1721 else
1722 tag = PAGECACHE_TAG_DIRTY;
David Howells811d7362006-08-29 19:06:09 +01001723retry:
Wu Fengguang6e6938b2010-06-06 10:38:15 -06001724 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
Jan Karaf446daa2010-08-09 17:19:12 -07001725 tag_pages_for_writeback(mapping, index, end);
Nick Pigginbd19e012009-01-06 14:39:06 -08001726 done_index = index;
Nick Piggin5a3d5c92009-01-06 14:39:09 -08001727 while (!done && (index <= end)) {
1728 int i;
1729
Jan Karaf446daa2010-08-09 17:19:12 -07001730 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
Nick Piggin5a3d5c92009-01-06 14:39:09 -08001731 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
1732 if (nr_pages == 0)
1733 break;
David Howells811d7362006-08-29 19:06:09 +01001734
David Howells811d7362006-08-29 19:06:09 +01001735 for (i = 0; i < nr_pages; i++) {
1736 struct page *page = pvec.pages[i];
1737
Nick Piggind5482cd2009-01-06 14:39:11 -08001738 /*
1739 * At this point, the page may be truncated or
1740 * invalidated (changing page->mapping to NULL), or
1741 * even swizzled back from swapper_space to tmpfs file
1742 * mapping. However, page->index will not change
1743 * because we have a reference on the page.
1744 */
1745 if (page->index > end) {
1746 /*
1747 * can't be range_cyclic (1st pass) because
1748 * end == -1 in that case.
1749 */
1750 done = 1;
1751 break;
1752 }
1753
Jun'ichi Nomuracf15b072011-03-22 16:33:40 -07001754 done_index = page->index;
Nick Pigginbd19e012009-01-06 14:39:06 -08001755
David Howells811d7362006-08-29 19:06:09 +01001756 lock_page(page);
1757
Nick Piggin5a3d5c92009-01-06 14:39:09 -08001758 /*
1759 * Page truncated or invalidated. We can freely skip it
1760 * then, even for data integrity operations: the page
1761 * has disappeared concurrently, so there could be no
1762 * real expectation of this data interity operation
1763 * even if there is now a new, dirty page at the same
1764 * pagecache address.
1765 */
David Howells811d7362006-08-29 19:06:09 +01001766 if (unlikely(page->mapping != mapping)) {
Nick Piggin5a3d5c92009-01-06 14:39:09 -08001767continue_unlock:
David Howells811d7362006-08-29 19:06:09 +01001768 unlock_page(page);
1769 continue;
1770 }
1771
Nick Piggin515f4a02009-01-06 14:39:10 -08001772 if (!PageDirty(page)) {
1773 /* someone wrote it for us */
1774 goto continue_unlock;
1775 }
David Howells811d7362006-08-29 19:06:09 +01001776
Nick Piggin515f4a02009-01-06 14:39:10 -08001777 if (PageWriteback(page)) {
1778 if (wbc->sync_mode != WB_SYNC_NONE)
1779 wait_on_page_writeback(page);
1780 else
1781 goto continue_unlock;
1782 }
1783
1784 BUG_ON(PageWriteback(page));
1785 if (!clear_page_dirty_for_io(page))
Nick Piggin5a3d5c92009-01-06 14:39:09 -08001786 goto continue_unlock;
David Howells811d7362006-08-29 19:06:09 +01001787
Dave Chinner9e094382010-07-07 13:24:08 +10001788 trace_wbc_writepage(wbc, mapping->backing_dev_info);
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001789 ret = (*writepage)(page, wbc, data);
Nick Piggin00266772009-01-06 14:39:06 -08001790 if (unlikely(ret)) {
1791 if (ret == AOP_WRITEPAGE_ACTIVATE) {
1792 unlock_page(page);
1793 ret = 0;
1794 } else {
1795 /*
1796 * done_index is set past this page,
1797 * so media errors will not choke
1798 * background writeout for the entire
1799 * file. This has consequences for
1800 * range_cyclic semantics (ie. it may
1801 * not be suitable for data integrity
1802 * writeout).
1803 */
Jun'ichi Nomuracf15b072011-03-22 16:33:40 -07001804 done_index = page->index + 1;
Nick Piggin00266772009-01-06 14:39:06 -08001805 done = 1;
1806 break;
1807 }
Dave Chinner0b564922010-06-09 10:37:18 +10001808 }
David Howells811d7362006-08-29 19:06:09 +01001809
Dave Chinner546a1922010-08-24 11:44:34 +10001810 /*
1811 * We stop writing back only if we are not doing
1812 * integrity sync. In case of integrity sync we have to
1813 * keep going until we have written all the pages
1814 * we tagged for writeback prior to entering this loop.
1815 */
1816 if (--wbc->nr_to_write <= 0 &&
1817 wbc->sync_mode == WB_SYNC_NONE) {
1818 done = 1;
1819 break;
Nick Piggin05fe4782009-01-06 14:39:08 -08001820 }
David Howells811d7362006-08-29 19:06:09 +01001821 }
1822 pagevec_release(&pvec);
1823 cond_resched();
1824 }
Nick Piggin3a4c6802009-02-12 04:34:23 +01001825 if (!cycled && !done) {
David Howells811d7362006-08-29 19:06:09 +01001826 /*
Nick Piggin31a12662009-01-06 14:39:04 -08001827 * range_cyclic:
David Howells811d7362006-08-29 19:06:09 +01001828 * We hit the last page and there is more work to be done: wrap
1829 * back to the start of the file
1830 */
Nick Piggin31a12662009-01-06 14:39:04 -08001831 cycled = 1;
David Howells811d7362006-08-29 19:06:09 +01001832 index = 0;
Nick Piggin31a12662009-01-06 14:39:04 -08001833 end = writeback_index - 1;
David Howells811d7362006-08-29 19:06:09 +01001834 goto retry;
1835 }
Dave Chinner0b564922010-06-09 10:37:18 +10001836 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
1837 mapping->writeback_index = done_index;
Aneesh Kumar K.V06d6cf62008-07-11 19:27:31 -04001838
David Howells811d7362006-08-29 19:06:09 +01001839 return ret;
1840}
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001841EXPORT_SYMBOL(write_cache_pages);
1842
1843/*
1844 * Function used by generic_writepages to call the real writepage
1845 * function and set the mapping flags on error
1846 */
1847static int __writepage(struct page *page, struct writeback_control *wbc,
1848 void *data)
1849{
1850 struct address_space *mapping = data;
1851 int ret = mapping->a_ops->writepage(page, wbc);
1852 mapping_set_error(mapping, ret);
1853 return ret;
1854}
1855
1856/**
1857 * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
1858 * @mapping: address space structure to write
1859 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
1860 *
1861 * This is a library function, which implements the writepages()
1862 * address_space_operation.
1863 */
1864int generic_writepages(struct address_space *mapping,
1865 struct writeback_control *wbc)
1866{
Shaohua Li9b6096a2011-03-17 10:47:06 +01001867 struct blk_plug plug;
1868 int ret;
1869
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001870 /* deal with chardevs and other special file */
1871 if (!mapping->a_ops->writepage)
1872 return 0;
1873
Shaohua Li9b6096a2011-03-17 10:47:06 +01001874 blk_start_plug(&plug);
1875 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
1876 blk_finish_plug(&plug);
1877 return ret;
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001878}
David Howells811d7362006-08-29 19:06:09 +01001879
1880EXPORT_SYMBOL(generic_writepages);
1881
Linus Torvalds1da177e2005-04-16 15:20:36 -07001882int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
1883{
Andrew Morton22905f72005-11-16 15:07:01 -08001884 int ret;
1885
Linus Torvalds1da177e2005-04-16 15:20:36 -07001886 if (wbc->nr_to_write <= 0)
1887 return 0;
1888 if (mapping->a_ops->writepages)
Peter Zijlstrad08b3852006-09-25 23:30:57 -07001889 ret = mapping->a_ops->writepages(mapping, wbc);
Andrew Morton22905f72005-11-16 15:07:01 -08001890 else
1891 ret = generic_writepages(mapping, wbc);
Andrew Morton22905f72005-11-16 15:07:01 -08001892 return ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001893}
1894
1895/**
1896 * write_one_page - write out a single page and optionally wait on I/O
Martin Waitz67be2dd2005-05-01 08:59:26 -07001897 * @page: the page to write
1898 * @wait: if true, wait on writeout
Linus Torvalds1da177e2005-04-16 15:20:36 -07001899 *
1900 * The page must be locked by the caller and will be unlocked upon return.
1901 *
1902 * write_one_page() returns a negative error code if I/O failed.
1903 */
1904int write_one_page(struct page *page, int wait)
1905{
1906 struct address_space *mapping = page->mapping;
1907 int ret = 0;
1908 struct writeback_control wbc = {
1909 .sync_mode = WB_SYNC_ALL,
1910 .nr_to_write = 1,
1911 };
1912
1913 BUG_ON(!PageLocked(page));
1914
1915 if (wait)
1916 wait_on_page_writeback(page);
1917
1918 if (clear_page_dirty_for_io(page)) {
1919 page_cache_get(page);
1920 ret = mapping->a_ops->writepage(page, &wbc);
1921 if (ret == 0 && wait) {
1922 wait_on_page_writeback(page);
1923 if (PageError(page))
1924 ret = -EIO;
1925 }
1926 page_cache_release(page);
1927 } else {
1928 unlock_page(page);
1929 }
1930 return ret;
1931}
1932EXPORT_SYMBOL(write_one_page);
1933
1934/*
Ken Chen76719322007-02-10 01:43:15 -08001935 * For address_spaces which do not use buffers nor write back.
1936 */
1937int __set_page_dirty_no_writeback(struct page *page)
1938{
1939 if (!PageDirty(page))
Bob Liuc3f0da62011-01-13 15:45:49 -08001940 return !TestSetPageDirty(page);
Ken Chen76719322007-02-10 01:43:15 -08001941 return 0;
1942}
1943
1944/*
Edward Shishkine3a7cca2009-03-31 15:19:39 -07001945 * Helper function for set_page_dirty family.
1946 * NOTE: This relies on being atomic wrt interrupts.
1947 */
1948void account_page_dirtied(struct page *page, struct address_space *mapping)
1949{
1950 if (mapping_cap_account_dirty(mapping)) {
1951 __inc_zone_page_state(page, NR_FILE_DIRTY);
Michael Rubinea941f02010-10-26 14:21:35 -07001952 __inc_zone_page_state(page, NR_DIRTIED);
Edward Shishkine3a7cca2009-03-31 15:19:39 -07001953 __inc_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
Wu Fengguangc8e28ce2011-01-23 10:07:47 -06001954 __inc_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
Edward Shishkine3a7cca2009-03-31 15:19:39 -07001955 task_io_account_write(PAGE_CACHE_SIZE);
Wu Fengguangd3bc1fe2011-04-14 07:52:37 -06001956 current->nr_dirtied++;
1957 this_cpu_inc(bdp_ratelimits);
Edward Shishkine3a7cca2009-03-31 15:19:39 -07001958 }
1959}
Michael Rubin679ceac2010-08-20 02:31:26 -07001960EXPORT_SYMBOL(account_page_dirtied);
Edward Shishkine3a7cca2009-03-31 15:19:39 -07001961
1962/*
Michael Rubinf629d1c2010-10-26 14:21:33 -07001963 * Helper function for set_page_writeback family.
1964 * NOTE: Unlike account_page_dirtied this does not rely on being atomic
1965 * wrt interrupts.
1966 */
1967void account_page_writeback(struct page *page)
1968{
1969 inc_zone_page_state(page, NR_WRITEBACK);
1970}
1971EXPORT_SYMBOL(account_page_writeback);
1972
1973/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001974 * For address_spaces which do not use buffers. Just tag the page as dirty in
1975 * its radix tree.
1976 *
1977 * This is also used when a single buffer is being dirtied: we want to set the
1978 * page dirty in that case, but not all the buffers. This is a "bottom-up"
1979 * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
1980 *
Johannes Weiner15870702015-01-08 14:32:18 -08001981 * The caller must ensure this doesn't race with truncation. Most will simply
1982 * hold the page lock, but e.g. zap_pte_range() calls with the page mapped and
1983 * the pte lock held, which also locks out truncat
Linus Torvalds1da177e2005-04-16 15:20:36 -07001984 */
1985int __set_page_dirty_nobuffers(struct page *page)
1986{
Linus Torvalds1da177e2005-04-16 15:20:36 -07001987 if (!TestSetPageDirty(page)) {
1988 struct address_space *mapping = page_mapping(page);
KOSAKI Motohiro4d4bed82014-02-06 12:04:24 -08001989 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001990
Andrew Morton8c085402006-12-10 02:19:24 -08001991 if (!mapping)
1992 return 1;
1993
KOSAKI Motohiro4d4bed82014-02-06 12:04:24 -08001994 spin_lock_irqsave(&mapping->tree_lock, flags);
Johannes Weiner15870702015-01-08 14:32:18 -08001995 BUG_ON(page_mapping(page) != mapping);
1996 WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
1997 account_page_dirtied(page, mapping);
1998 radix_tree_tag_set(&mapping->page_tree, page_index(page),
1999 PAGECACHE_TAG_DIRTY);
KOSAKI Motohiro4d4bed82014-02-06 12:04:24 -08002000 spin_unlock_irqrestore(&mapping->tree_lock, flags);
Andrew Morton8c085402006-12-10 02:19:24 -08002001 if (mapping->host) {
2002 /* !PageAnon && !swapper_space */
2003 __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002004 }
Andrew Morton4741c9f2006-03-24 03:18:11 -08002005 return 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002006 }
Andrew Morton4741c9f2006-03-24 03:18:11 -08002007 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002008}
2009EXPORT_SYMBOL(__set_page_dirty_nobuffers);
2010
2011/*
Wu Fengguang2f800fb2011-08-08 15:22:00 -06002012 * Call this whenever redirtying a page, to de-account the dirty counters
2013 * (NR_DIRTIED, BDI_DIRTIED, tsk->nr_dirtied), so that they match the written
2014 * counters (NR_WRITTEN, BDI_WRITTEN) in long term. The mismatches will lead to
2015 * systematic errors in balanced_dirty_ratelimit and the dirty pages position
2016 * control.
2017 */
2018void account_page_redirty(struct page *page)
2019{
2020 struct address_space *mapping = page->mapping;
2021 if (mapping && mapping_cap_account_dirty(mapping)) {
2022 current->nr_dirtied--;
2023 dec_zone_page_state(page, NR_DIRTIED);
2024 dec_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
2025 }
2026}
2027EXPORT_SYMBOL(account_page_redirty);
2028
2029/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07002030 * When a writepage implementation decides that it doesn't want to write this
2031 * page for some reason, it should redirty the locked page via
2032 * redirty_page_for_writepage() and it should then unlock the page and return 0
2033 */
2034int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
2035{
2036 wbc->pages_skipped++;
Wu Fengguang2f800fb2011-08-08 15:22:00 -06002037 account_page_redirty(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002038 return __set_page_dirty_nobuffers(page);
2039}
2040EXPORT_SYMBOL(redirty_page_for_writepage);
2041
2042/*
Wu Fengguang6746aff2009-09-16 11:50:14 +02002043 * Dirty a page.
2044 *
2045 * For pages with a mapping this should be done under the page lock
2046 * for the benefit of asynchronous memory errors who prefer a consistent
2047 * dirty state. This rule can be broken in some special cases,
2048 * but should be better not to.
2049 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07002050 * If the mapping doesn't provide a set_page_dirty a_op, then
2051 * just fall through and assume that it wants buffer_heads.
2052 */
Nick Piggin1cf6e7d2009-02-18 14:48:18 -08002053int set_page_dirty(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002054{
2055 struct address_space *mapping = page_mapping(page);
2056
2057 if (likely(mapping)) {
2058 int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
Minchan Kim278df9f2011-03-22 16:32:54 -07002059 /*
2060 * readahead/lru_deactivate_page could remain
2061 * PG_readahead/PG_reclaim due to race with end_page_writeback
2062 * About readahead, if the page is written, the flags would be
2063 * reset. So no problem.
2064 * About lru_deactivate_page, if the page is redirty, the flag
2065 * will be reset. So no problem. but if the page is used by readahead
2066 * it will confuse readahead and make it restart the size rampup
2067 * process. But it's a trivial problem.
2068 */
2069 ClearPageReclaim(page);
David Howells93614012006-09-30 20:45:40 +02002070#ifdef CONFIG_BLOCK
2071 if (!spd)
2072 spd = __set_page_dirty_buffers;
2073#endif
2074 return (*spd)(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002075 }
Andrew Morton4741c9f2006-03-24 03:18:11 -08002076 if (!PageDirty(page)) {
2077 if (!TestSetPageDirty(page))
2078 return 1;
2079 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002080 return 0;
2081}
2082EXPORT_SYMBOL(set_page_dirty);
2083
2084/*
2085 * set_page_dirty() is racy if the caller has no reference against
2086 * page->mapping->host, and if the page is unlocked. This is because another
2087 * CPU could truncate the page off the mapping and then free the mapping.
2088 *
2089 * Usually, the page _is_ locked, or the caller is a user-space process which
2090 * holds a reference on the inode by having an open file.
2091 *
2092 * In other cases, the page should be locked before running set_page_dirty().
2093 */
2094int set_page_dirty_lock(struct page *page)
2095{
2096 int ret;
2097
Jens Axboe7eaceac2011-03-10 08:52:07 +01002098 lock_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002099 ret = set_page_dirty(page);
2100 unlock_page(page);
2101 return ret;
2102}
2103EXPORT_SYMBOL(set_page_dirty_lock);
2104
2105/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07002106 * Clear a page's dirty flag, while caring for dirty memory accounting.
2107 * Returns true if the page was previously dirty.
2108 *
2109 * This is for preparing to put the page under writeout. We leave the page
2110 * tagged as dirty in the radix tree so that a concurrent write-for-sync
2111 * can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
2112 * implementation will run either set_page_writeback() or set_page_dirty(),
2113 * at which stage we bring the page's dirty flag and radix-tree dirty tag
2114 * back into sync.
2115 *
2116 * This incoherency between the page's dirty flag and radix-tree tag is
2117 * unfortunate, but it only exists while the page is locked.
2118 */
2119int clear_page_dirty_for_io(struct page *page)
2120{
2121 struct address_space *mapping = page_mapping(page);
2122
Nick Piggin79352892007-07-19 01:47:22 -07002123 BUG_ON(!PageLocked(page));
2124
Linus Torvalds7658cc22006-12-29 10:00:58 -08002125 if (mapping && mapping_cap_account_dirty(mapping)) {
2126 /*
2127 * Yes, Virginia, this is indeed insane.
2128 *
2129 * We use this sequence to make sure that
2130 * (a) we account for dirty stats properly
2131 * (b) we tell the low-level filesystem to
2132 * mark the whole page dirty if it was
2133 * dirty in a pagetable. Only to then
2134 * (c) clean the page again and return 1 to
2135 * cause the writeback.
2136 *
2137 * This way we avoid all nasty races with the
2138 * dirty bit in multiple places and clearing
2139 * them concurrently from different threads.
2140 *
2141 * Note! Normally the "set_page_dirty(page)"
2142 * has no effect on the actual dirty bit - since
2143 * that will already usually be set. But we
2144 * need the side effects, and it can help us
2145 * avoid races.
2146 *
2147 * We basically use the page "master dirty bit"
2148 * as a serialization point for all the different
2149 * threads doing their things.
Linus Torvalds7658cc22006-12-29 10:00:58 -08002150 */
2151 if (page_mkclean(page))
2152 set_page_dirty(page);
Nick Piggin79352892007-07-19 01:47:22 -07002153 /*
2154 * We carefully synchronise fault handlers against
2155 * installing a dirty pte and marking the page dirty
Johannes Weiner15870702015-01-08 14:32:18 -08002156 * at this point. We do this by having them hold the
2157 * page lock while dirtying the page, and pages are
2158 * always locked coming in here, so we get the desired
2159 * exclusion.
Nick Piggin79352892007-07-19 01:47:22 -07002160 */
Linus Torvalds7658cc22006-12-29 10:00:58 -08002161 if (TestClearPageDirty(page)) {
Andrew Morton8c085402006-12-10 02:19:24 -08002162 dec_zone_page_state(page, NR_FILE_DIRTY);
Peter Zijlstrac9e51e42007-10-16 23:25:47 -07002163 dec_bdi_stat(mapping->backing_dev_info,
2164 BDI_RECLAIMABLE);
Linus Torvalds7658cc22006-12-29 10:00:58 -08002165 return 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002166 }
Linus Torvalds7658cc22006-12-29 10:00:58 -08002167 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002168 }
Linus Torvalds7658cc22006-12-29 10:00:58 -08002169 return TestClearPageDirty(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002170}
Hans Reiser58bb01a2005-11-18 01:10:53 -08002171EXPORT_SYMBOL(clear_page_dirty_for_io);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002172
2173int test_clear_page_writeback(struct page *page)
2174{
2175 struct address_space *mapping = page_mapping(page);
2176 int ret;
2177
2178 if (mapping) {
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002179 struct backing_dev_info *bdi = mapping->backing_dev_info;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002180 unsigned long flags;
2181
Nick Piggin19fd6232008-07-25 19:45:32 -07002182 spin_lock_irqsave(&mapping->tree_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002183 ret = TestClearPageWriteback(page);
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002184 if (ret) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002185 radix_tree_tag_clear(&mapping->page_tree,
2186 page_index(page),
2187 PAGECACHE_TAG_WRITEBACK);
Miklos Szeredie4ad08f2008-04-30 00:54:37 -07002188 if (bdi_cap_account_writeback(bdi)) {
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002189 __dec_bdi_stat(bdi, BDI_WRITEBACK);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -07002190 __bdi_writeout_inc(bdi);
2191 }
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002192 }
Nick Piggin19fd6232008-07-25 19:45:32 -07002193 spin_unlock_irqrestore(&mapping->tree_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002194 } else {
2195 ret = TestClearPageWriteback(page);
2196 }
Wu Fengguang99b12e32011-07-25 17:12:37 -07002197 if (ret) {
Andrew Mortond688abf2007-07-19 01:49:17 -07002198 dec_zone_page_state(page, NR_WRITEBACK);
Wu Fengguang99b12e32011-07-25 17:12:37 -07002199 inc_zone_page_state(page, NR_WRITTEN);
2200 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002201 return ret;
2202}
2203
2204int test_set_page_writeback(struct page *page)
2205{
2206 struct address_space *mapping = page_mapping(page);
2207 int ret;
2208
2209 if (mapping) {
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002210 struct backing_dev_info *bdi = mapping->backing_dev_info;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002211 unsigned long flags;
2212
Nick Piggin19fd6232008-07-25 19:45:32 -07002213 spin_lock_irqsave(&mapping->tree_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002214 ret = TestSetPageWriteback(page);
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002215 if (!ret) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002216 radix_tree_tag_set(&mapping->page_tree,
2217 page_index(page),
2218 PAGECACHE_TAG_WRITEBACK);
Miklos Szeredie4ad08f2008-04-30 00:54:37 -07002219 if (bdi_cap_account_writeback(bdi))
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002220 __inc_bdi_stat(bdi, BDI_WRITEBACK);
2221 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002222 if (!PageDirty(page))
2223 radix_tree_tag_clear(&mapping->page_tree,
2224 page_index(page),
2225 PAGECACHE_TAG_DIRTY);
Jan Karaf446daa2010-08-09 17:19:12 -07002226 radix_tree_tag_clear(&mapping->page_tree,
2227 page_index(page),
2228 PAGECACHE_TAG_TOWRITE);
Nick Piggin19fd6232008-07-25 19:45:32 -07002229 spin_unlock_irqrestore(&mapping->tree_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002230 } else {
2231 ret = TestSetPageWriteback(page);
2232 }
Andrew Mortond688abf2007-07-19 01:49:17 -07002233 if (!ret)
Michael Rubinf629d1c2010-10-26 14:21:33 -07002234 account_page_writeback(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002235 return ret;
2236
2237}
2238EXPORT_SYMBOL(test_set_page_writeback);
2239
2240/*
Nick Piggin00128182007-10-16 01:24:40 -07002241 * Return true if any of the pages in the mapping are marked with the
Linus Torvalds1da177e2005-04-16 15:20:36 -07002242 * passed tag.
2243 */
2244int mapping_tagged(struct address_space *mapping, int tag)
2245{
Konstantin Khlebnikov72c47832011-07-25 17:12:31 -07002246 return radix_tree_tagged(&mapping->page_tree, tag);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002247}
2248EXPORT_SYMBOL(mapping_tagged);