blob: 0ae2008eb54043970a1632a4d4d9f244a7a3ee7b [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>
David Howellscf9a2ae2006-08-29 19:05:54 +010035#include <linux/buffer_head.h>
David Howells811d7362006-08-29 19:06:09 +010036#include <linux/pagevec.h>
Dave Chinner028c2dd2010-07-07 13:24:07 +100037#include <trace/events/writeback.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070038
39/*
Wu Fengguangffd1f602011-06-19 22:18:42 -060040 * Sleep at most 200ms at a time in balance_dirty_pages().
41 */
42#define MAX_PAUSE max(HZ/5, 1)
43
44/*
Wu Fengguang5b9b3572011-12-06 13:17:17 -060045 * Try to keep balance_dirty_pages() call intervals higher than this many pages
46 * by raising pause time to max_pause when falls below it.
47 */
48#define DIRTY_POLL_THRESH (128 >> (PAGE_SHIFT - 10))
49
50/*
Wu Fengguange98be2d2010-08-29 11:22:30 -060051 * Estimate write bandwidth at 200ms intervals.
52 */
53#define BANDWIDTH_INTERVAL max(HZ/5, 1)
54
Wu Fengguang6c14ae12011-03-02 16:04:18 -060055#define RATELIMIT_CALC_SHIFT 10
56
Wu Fengguange98be2d2010-08-29 11:22:30 -060057/*
Linus Torvalds1da177e2005-04-16 15:20:36 -070058 * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
59 * will look to see if it needs to force writeback or throttling.
60 */
61static long ratelimit_pages = 32;
62
Linus Torvalds1da177e2005-04-16 15:20:36 -070063/* The following parameters are exported via /proc/sys/vm */
64
65/*
Jens Axboe5b0830c2009-09-23 19:37:09 +020066 * Start background writeback (via writeback threads) at this percentage
Linus Torvalds1da177e2005-04-16 15:20:36 -070067 */
Wu Fengguang1b5e62b2009-03-23 08:57:38 +080068int dirty_background_ratio = 10;
Linus Torvalds1da177e2005-04-16 15:20:36 -070069
70/*
David Rientjes2da02992009-01-06 14:39:31 -080071 * dirty_background_bytes starts at 0 (disabled) so that it is a function of
72 * dirty_background_ratio * the amount of dirtyable memory
73 */
74unsigned long dirty_background_bytes;
75
76/*
Bron Gondwana195cf4532008-02-04 22:29:20 -080077 * free highmem will not be subtracted from the total free memory
78 * for calculating free ratios if vm_highmem_is_dirtyable is true
79 */
80int vm_highmem_is_dirtyable;
81
82/*
Linus Torvalds1da177e2005-04-16 15:20:36 -070083 * The generator of dirty data starts writeback at this percentage
84 */
Wu Fengguang1b5e62b2009-03-23 08:57:38 +080085int vm_dirty_ratio = 20;
Linus Torvalds1da177e2005-04-16 15:20:36 -070086
87/*
David Rientjes2da02992009-01-06 14:39:31 -080088 * vm_dirty_bytes starts at 0 (disabled) so that it is a function of
89 * vm_dirty_ratio * the amount of dirtyable memory
90 */
91unsigned long vm_dirty_bytes;
92
93/*
Alexey Dobriyan704503d2009-03-31 15:23:18 -070094 * The interval between `kupdate'-style writebacks
Linus Torvalds1da177e2005-04-16 15:20:36 -070095 */
Toshiyuki Okajima22ef37e2009-05-16 22:56:28 -070096unsigned int dirty_writeback_interval = 5 * 100; /* centiseconds */
Linus Torvalds1da177e2005-04-16 15:20:36 -070097
98/*
Alexey Dobriyan704503d2009-03-31 15:23:18 -070099 * The longest time for which data is allowed to remain dirty
Linus Torvalds1da177e2005-04-16 15:20:36 -0700100 */
Toshiyuki Okajima22ef37e2009-05-16 22:56:28 -0700101unsigned int dirty_expire_interval = 30 * 100; /* centiseconds */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700102
103/*
104 * Flag that makes the machine dump writes/reads and block dirtyings.
105 */
106int block_dump;
107
108/*
Bart Samweled5b43f2006-03-24 03:15:49 -0800109 * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
110 * a full sync is triggered after this time elapses without any disk activity.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700111 */
112int laptop_mode;
113
114EXPORT_SYMBOL(laptop_mode);
115
116/* End of sysctl-exported parameters */
117
Wu Fengguangc42843f2011-03-02 15:54:09 -0600118unsigned long global_dirty_limit;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700119
Linus Torvalds1da177e2005-04-16 15:20:36 -0700120/*
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700121 * Scale the writeback cache size proportional to the relative writeout speeds.
122 *
123 * We do this by keeping a floating proportion between BDIs, based on page
124 * writeback completions [end_page_writeback()]. Those devices that write out
125 * pages fastest will get the larger share, while the slower will get a smaller
126 * share.
127 *
128 * We use page writeout completions because we are interested in getting rid of
129 * dirty pages. Having them written out is the primary goal.
130 *
131 * We introduce a concept of time, a period over which we measure these events,
132 * because demand can/will vary over time. The length of this period itself is
133 * measured in page writeback completions.
134 *
135 */
136static struct prop_descriptor vm_completions;
137
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700138/*
139 * couple the period to the dirty_ratio:
140 *
141 * period/2 ~ roundup_pow_of_two(dirty limit)
142 */
143static int calc_period_shift(void)
144{
145 unsigned long dirty_total;
146
David Rientjes2da02992009-01-06 14:39:31 -0800147 if (vm_dirty_bytes)
148 dirty_total = vm_dirty_bytes / PAGE_SIZE;
149 else
150 dirty_total = (vm_dirty_ratio * determine_dirtyable_memory()) /
151 100;
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700152 return 2 + ilog2(dirty_total - 1);
153}
154
155/*
David Rientjes2da02992009-01-06 14:39:31 -0800156 * update the period when the dirty threshold changes.
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700157 */
David Rientjes2da02992009-01-06 14:39:31 -0800158static void update_completion_period(void)
159{
160 int shift = calc_period_shift();
161 prop_change_shift(&vm_completions, shift);
Wu Fengguang9d823e82011-06-11 18:10:12 -0600162
163 writeback_set_ratelimit();
David Rientjes2da02992009-01-06 14:39:31 -0800164}
165
166int dirty_background_ratio_handler(struct ctl_table *table, int write,
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700167 void __user *buffer, size_t *lenp,
David Rientjes2da02992009-01-06 14:39:31 -0800168 loff_t *ppos)
169{
170 int ret;
171
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700172 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
David Rientjes2da02992009-01-06 14:39:31 -0800173 if (ret == 0 && write)
174 dirty_background_bytes = 0;
175 return ret;
176}
177
178int dirty_background_bytes_handler(struct ctl_table *table, int write,
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700179 void __user *buffer, size_t *lenp,
David Rientjes2da02992009-01-06 14:39:31 -0800180 loff_t *ppos)
181{
182 int ret;
183
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700184 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
David Rientjes2da02992009-01-06 14:39:31 -0800185 if (ret == 0 && write)
186 dirty_background_ratio = 0;
187 return ret;
188}
189
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700190int dirty_ratio_handler(struct ctl_table *table, int write,
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700191 void __user *buffer, size_t *lenp,
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700192 loff_t *ppos)
193{
194 int old_ratio = vm_dirty_ratio;
David Rientjes2da02992009-01-06 14:39:31 -0800195 int ret;
196
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700197 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700198 if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
David Rientjes2da02992009-01-06 14:39:31 -0800199 update_completion_period();
200 vm_dirty_bytes = 0;
201 }
202 return ret;
203}
204
205
206int dirty_bytes_handler(struct ctl_table *table, int write,
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700207 void __user *buffer, size_t *lenp,
David Rientjes2da02992009-01-06 14:39:31 -0800208 loff_t *ppos)
209{
Sven Wegenerfc3501d2009-02-11 13:04:23 -0800210 unsigned long old_bytes = vm_dirty_bytes;
David Rientjes2da02992009-01-06 14:39:31 -0800211 int ret;
212
Alexey Dobriyan8d65af72009-09-23 15:57:19 -0700213 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
David Rientjes2da02992009-01-06 14:39:31 -0800214 if (ret == 0 && write && vm_dirty_bytes != old_bytes) {
215 update_completion_period();
216 vm_dirty_ratio = 0;
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700217 }
218 return ret;
219}
220
221/*
222 * Increment the BDI's writeout completion count and the global writeout
223 * completion count. Called from test_clear_page_writeback().
224 */
225static inline void __bdi_writeout_inc(struct backing_dev_info *bdi)
226{
Jan Karaf7d2b1e2010-12-08 22:44:24 -0600227 __inc_bdi_stat(bdi, BDI_WRITTEN);
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700228 __prop_inc_percpu_max(&vm_completions, &bdi->completions,
229 bdi->max_prop_frac);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700230}
231
Miklos Szeredidd5656e2008-04-30 00:54:37 -0700232void bdi_writeout_inc(struct backing_dev_info *bdi)
233{
234 unsigned long flags;
235
236 local_irq_save(flags);
237 __bdi_writeout_inc(bdi);
238 local_irq_restore(flags);
239}
240EXPORT_SYMBOL_GPL(bdi_writeout_inc);
241
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700242/*
243 * Obtain an accurate fraction of the BDI's portion.
244 */
245static void bdi_writeout_fraction(struct backing_dev_info *bdi,
246 long *numerator, long *denominator)
247{
Wu Fengguang3efaf0f2010-12-16 22:22:00 -0600248 prop_fraction_percpu(&vm_completions, &bdi->completions,
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700249 numerator, denominator);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700250}
251
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700252/*
Johannes Weinerd08c4292011-10-31 17:07:05 -0700253 * bdi_min_ratio keeps the sum of the minimum dirty shares of all
254 * registered backing devices, which, for obvious reasons, can not
255 * exceed 100%.
Peter Zijlstra189d3c42008-04-30 00:54:35 -0700256 */
Peter Zijlstra189d3c42008-04-30 00:54:35 -0700257static unsigned int bdi_min_ratio;
258
259int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio)
260{
261 int ret = 0;
Peter Zijlstra189d3c42008-04-30 00:54:35 -0700262
Jens Axboecfc4ba52009-09-14 13:12:40 +0200263 spin_lock_bh(&bdi_lock);
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700264 if (min_ratio > bdi->max_ratio) {
Peter Zijlstra189d3c42008-04-30 00:54:35 -0700265 ret = -EINVAL;
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700266 } else {
267 min_ratio -= bdi->min_ratio;
268 if (bdi_min_ratio + min_ratio < 100) {
269 bdi_min_ratio += min_ratio;
270 bdi->min_ratio += min_ratio;
271 } else {
272 ret = -EINVAL;
273 }
274 }
Jens Axboecfc4ba52009-09-14 13:12:40 +0200275 spin_unlock_bh(&bdi_lock);
Peter Zijlstra189d3c42008-04-30 00:54:35 -0700276
277 return ret;
278}
279
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700280int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio)
281{
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700282 int ret = 0;
283
284 if (max_ratio > 100)
285 return -EINVAL;
286
Jens Axboecfc4ba52009-09-14 13:12:40 +0200287 spin_lock_bh(&bdi_lock);
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700288 if (bdi->min_ratio > max_ratio) {
289 ret = -EINVAL;
290 } else {
291 bdi->max_ratio = max_ratio;
292 bdi->max_prop_frac = (PROP_FRAC_BASE * max_ratio) / 100;
293 }
Jens Axboecfc4ba52009-09-14 13:12:40 +0200294 spin_unlock_bh(&bdi_lock);
Peter Zijlstraa42dde02008-04-30 00:54:36 -0700295
296 return ret;
297}
298EXPORT_SYMBOL(bdi_set_max_ratio);
299
Peter Zijlstra189d3c42008-04-30 00:54:35 -0700300/*
Linus Torvalds1da177e2005-04-16 15:20:36 -0700301 * Work out the current dirty-memory clamping and background writeout
302 * thresholds.
303 *
304 * The main aim here is to lower them aggressively if there is a lot of mapped
305 * memory around. To avoid stressing page reclaim with lots of unreclaimable
306 * pages. It is better to clamp down on writers than to start swapping, and
307 * performing lots of scanning.
308 *
309 * We only allow 1/2 of the currently-unmapped memory to be dirtied.
310 *
311 * We don't permit the clamping level to fall below 5% - that is getting rather
312 * excessive.
313 *
314 * We make sure that the background writeout level is below the adjusted
315 * clamping level.
316 */
Christoph Lameter1b424462007-05-06 14:48:59 -0700317
318static unsigned long highmem_dirtyable_memory(unsigned long total)
319{
320#ifdef CONFIG_HIGHMEM
321 int node;
322 unsigned long x = 0;
323
Lee Schermerhorn37b07e42007-10-16 01:25:39 -0700324 for_each_node_state(node, N_HIGH_MEMORY) {
Christoph Lameter1b424462007-05-06 14:48:59 -0700325 struct zone *z =
326 &NODE_DATA(node)->node_zones[ZONE_HIGHMEM];
327
Wu Fengguangadea02a2009-09-21 17:01:42 -0700328 x += zone_page_state(z, NR_FREE_PAGES) +
329 zone_reclaimable_pages(z);
Christoph Lameter1b424462007-05-06 14:48:59 -0700330 }
331 /*
332 * Make sure that the number of highmem pages is never larger
333 * than the number of the total dirtyable memory. This can only
334 * occur in very strange VM situations but we want to make sure
335 * that this does not occur.
336 */
337 return min(x, total);
338#else
339 return 0;
340#endif
341}
342
Steven Rostedt3eefae92008-05-12 21:21:04 +0200343/**
344 * determine_dirtyable_memory - amount of memory that may be used
345 *
346 * Returns the numebr of pages that can currently be freed and used
347 * by the kernel for direct mappings.
348 */
349unsigned long determine_dirtyable_memory(void)
Christoph Lameter1b424462007-05-06 14:48:59 -0700350{
351 unsigned long x;
352
Wu Fengguangadea02a2009-09-21 17:01:42 -0700353 x = global_page_state(NR_FREE_PAGES) + global_reclaimable_pages();
Bron Gondwana195cf4532008-02-04 22:29:20 -0800354
355 if (!vm_highmem_is_dirtyable)
356 x -= highmem_dirtyable_memory(x);
357
Christoph Lameter1b424462007-05-06 14:48:59 -0700358 return x + 1; /* Ensure that we never return 0 */
359}
360
Wu Fengguang6c14ae12011-03-02 16:04:18 -0600361static unsigned long dirty_freerun_ceiling(unsigned long thresh,
362 unsigned long bg_thresh)
363{
364 return (thresh + bg_thresh) / 2;
365}
366
Wu Fengguangffd1f602011-06-19 22:18:42 -0600367static unsigned long hard_dirty_limit(unsigned long thresh)
368{
369 return max(thresh, global_dirty_limit);
370}
371
Randy Dunlap03ab4502010-08-14 13:05:17 -0700372/*
Wu Fengguang1babe182010-08-11 14:17:40 -0700373 * global_dirty_limits - background-writeback and dirty-throttling thresholds
374 *
375 * Calculate the dirty thresholds based on sysctl parameters
376 * - vm.dirty_background_ratio or vm.dirty_background_bytes
377 * - vm.dirty_ratio or vm.dirty_bytes
378 * The dirty limits will be lifted by 1/4 for PF_LESS_THROTTLE (ie. nfsd) and
Minchan Kimebd13732011-01-04 01:36:48 +0900379 * real-time tasks.
Wu Fengguang1babe182010-08-11 14:17:40 -0700380 */
Wu Fengguang16c40422010-08-11 14:17:39 -0700381void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700382{
David Rientjes364aeb22009-01-06 14:39:29 -0800383 unsigned long background;
384 unsigned long dirty;
Minchan Kim240c8792011-01-13 15:46:27 -0800385 unsigned long uninitialized_var(available_memory);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700386 struct task_struct *tsk;
387
Minchan Kim240c8792011-01-13 15:46:27 -0800388 if (!vm_dirty_bytes || !dirty_background_bytes)
389 available_memory = determine_dirtyable_memory();
390
David Rientjes2da02992009-01-06 14:39:31 -0800391 if (vm_dirty_bytes)
392 dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE);
Wu Fengguang4cbec4c2010-10-26 14:21:45 -0700393 else
394 dirty = (vm_dirty_ratio * available_memory) / 100;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700395
David Rientjes2da02992009-01-06 14:39:31 -0800396 if (dirty_background_bytes)
397 background = DIV_ROUND_UP(dirty_background_bytes, PAGE_SIZE);
398 else
399 background = (dirty_background_ratio * available_memory) / 100;
400
401 if (background >= dirty)
402 background = dirty / 2;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700403 tsk = current;
404 if (tsk->flags & PF_LESS_THROTTLE || rt_task(tsk)) {
405 background += background / 4;
406 dirty += dirty / 4;
407 }
408 *pbackground = background;
409 *pdirty = dirty;
Wu Fengguange1cbe232010-12-06 22:34:29 -0600410 trace_global_dirty_state(background, dirty);
Wu Fengguang16c40422010-08-11 14:17:39 -0700411}
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700412
Wu Fengguang6f718652011-03-02 17:14:34 -0600413/**
Wu Fengguang1babe182010-08-11 14:17:40 -0700414 * bdi_dirty_limit - @bdi's share of dirty throttling threshold
Wu Fengguang6f718652011-03-02 17:14:34 -0600415 * @bdi: the backing_dev_info to query
416 * @dirty: global dirty limit in pages
Wu Fengguang1babe182010-08-11 14:17:40 -0700417 *
Wu Fengguang6f718652011-03-02 17:14:34 -0600418 * Returns @bdi's dirty limit in pages. The term "dirty" in the context of
419 * dirty balancing includes all PG_dirty, PG_writeback and NFS unstable pages.
Wu Fengguangaed21ad2011-11-23 11:44:41 -0600420 *
421 * Note that balance_dirty_pages() will only seriously take it as a hard limit
422 * when sleeping max_pause per page is not enough to keep the dirty pages under
423 * control. For example, when the device is completely stalled due to some error
424 * conditions, or when there are 1000 dd tasks writing to a slow 10MB/s USB key.
425 * In the other normal situations, it acts more gently by throttling the tasks
426 * more (rather than completely block them) when the bdi dirty pages go high.
Wu Fengguang6f718652011-03-02 17:14:34 -0600427 *
428 * It allocates high/low dirty limits to fast/slow devices, in order to prevent
Wu Fengguang1babe182010-08-11 14:17:40 -0700429 * - starving fast devices
430 * - piling up dirty pages (that will take long time to sync) on slow devices
431 *
432 * The bdi's share of dirty limit will be adapting to its throughput and
433 * bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set.
434 */
435unsigned long bdi_dirty_limit(struct backing_dev_info *bdi, unsigned long dirty)
Wu Fengguang16c40422010-08-11 14:17:39 -0700436{
437 u64 bdi_dirty;
438 long numerator, denominator;
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700439
Wu Fengguang16c40422010-08-11 14:17:39 -0700440 /*
441 * Calculate this BDI's share of the dirty ratio.
442 */
443 bdi_writeout_fraction(bdi, &numerator, &denominator);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700444
Wu Fengguang16c40422010-08-11 14:17:39 -0700445 bdi_dirty = (dirty * (100 - bdi_min_ratio)) / 100;
446 bdi_dirty *= numerator;
447 do_div(bdi_dirty, denominator);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -0700448
Wu Fengguang16c40422010-08-11 14:17:39 -0700449 bdi_dirty += (dirty * bdi->min_ratio) / 100;
450 if (bdi_dirty > (dirty * bdi->max_ratio) / 100)
451 bdi_dirty = dirty * bdi->max_ratio / 100;
452
453 return bdi_dirty;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700454}
455
Wu Fengguang6c14ae12011-03-02 16:04:18 -0600456/*
457 * Dirty position control.
458 *
459 * (o) global/bdi setpoints
460 *
461 * We want the dirty pages be balanced around the global/bdi setpoints.
462 * When the number of dirty pages is higher/lower than the setpoint, the
463 * dirty position control ratio (and hence task dirty ratelimit) will be
464 * decreased/increased to bring the dirty pages back to the setpoint.
465 *
466 * pos_ratio = 1 << RATELIMIT_CALC_SHIFT
467 *
468 * if (dirty < setpoint) scale up pos_ratio
469 * if (dirty > setpoint) scale down pos_ratio
470 *
471 * if (bdi_dirty < bdi_setpoint) scale up pos_ratio
472 * if (bdi_dirty > bdi_setpoint) scale down pos_ratio
473 *
474 * task_ratelimit = dirty_ratelimit * pos_ratio >> RATELIMIT_CALC_SHIFT
475 *
476 * (o) global control line
477 *
478 * ^ pos_ratio
479 * |
480 * | |<===== global dirty control scope ======>|
481 * 2.0 .............*
482 * | .*
483 * | . *
484 * | . *
485 * | . *
486 * | . *
487 * | . *
488 * 1.0 ................................*
489 * | . . *
490 * | . . *
491 * | . . *
492 * | . . *
493 * | . . *
494 * 0 +------------.------------------.----------------------*------------->
495 * freerun^ setpoint^ limit^ dirty pages
496 *
497 * (o) bdi control line
498 *
499 * ^ pos_ratio
500 * |
501 * | *
502 * | *
503 * | *
504 * | *
505 * | * |<=========== span ============>|
506 * 1.0 .......................*
507 * | . *
508 * | . *
509 * | . *
510 * | . *
511 * | . *
512 * | . *
513 * | . *
514 * | . *
515 * | . *
516 * | . *
517 * | . *
518 * 1/4 ...............................................* * * * * * * * * * * *
519 * | . .
520 * | . .
521 * | . .
522 * 0 +----------------------.-------------------------------.------------->
523 * bdi_setpoint^ x_intercept^
524 *
525 * The bdi control line won't drop below pos_ratio=1/4, so that bdi_dirty can
526 * be smoothly throttled down to normal if it starts high in situations like
527 * - start writing to a slow SD card and a fast disk at the same time. The SD
528 * card's bdi_dirty may rush to many times higher than bdi_setpoint.
529 * - the bdi dirty thresh drops quickly due to change of JBOD workload
530 */
531static unsigned long bdi_position_ratio(struct backing_dev_info *bdi,
532 unsigned long thresh,
533 unsigned long bg_thresh,
534 unsigned long dirty,
535 unsigned long bdi_thresh,
536 unsigned long bdi_dirty)
537{
538 unsigned long write_bw = bdi->avg_write_bandwidth;
539 unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh);
540 unsigned long limit = hard_dirty_limit(thresh);
541 unsigned long x_intercept;
542 unsigned long setpoint; /* dirty pages' target balance point */
543 unsigned long bdi_setpoint;
544 unsigned long span;
545 long long pos_ratio; /* for scaling up/down the rate limit */
546 long x;
547
548 if (unlikely(dirty >= limit))
549 return 0;
550
551 /*
552 * global setpoint
553 *
554 * setpoint - dirty 3
555 * f(dirty) := 1.0 + (----------------)
556 * limit - setpoint
557 *
558 * it's a 3rd order polynomial that subjects to
559 *
560 * (1) f(freerun) = 2.0 => rampup dirty_ratelimit reasonably fast
561 * (2) f(setpoint) = 1.0 => the balance point
562 * (3) f(limit) = 0 => the hard limit
563 * (4) df/dx <= 0 => negative feedback control
564 * (5) the closer to setpoint, the smaller |df/dx| (and the reverse)
565 * => fast response on large errors; small oscillation near setpoint
566 */
567 setpoint = (freerun + limit) / 2;
568 x = div_s64((setpoint - dirty) << RATELIMIT_CALC_SHIFT,
569 limit - setpoint + 1);
570 pos_ratio = x;
571 pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
572 pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
573 pos_ratio += 1 << RATELIMIT_CALC_SHIFT;
574
575 /*
576 * We have computed basic pos_ratio above based on global situation. If
577 * the bdi is over/under its share of dirty pages, we want to scale
578 * pos_ratio further down/up. That is done by the following mechanism.
579 */
580
581 /*
582 * bdi setpoint
583 *
584 * f(bdi_dirty) := 1.0 + k * (bdi_dirty - bdi_setpoint)
585 *
586 * x_intercept - bdi_dirty
587 * := --------------------------
588 * x_intercept - bdi_setpoint
589 *
590 * The main bdi control line is a linear function that subjects to
591 *
592 * (1) f(bdi_setpoint) = 1.0
593 * (2) k = - 1 / (8 * write_bw) (in single bdi case)
594 * or equally: x_intercept = bdi_setpoint + 8 * write_bw
595 *
596 * For single bdi case, the dirty pages are observed to fluctuate
597 * regularly within range
598 * [bdi_setpoint - write_bw/2, bdi_setpoint + write_bw/2]
599 * for various filesystems, where (2) can yield in a reasonable 12.5%
600 * fluctuation range for pos_ratio.
601 *
602 * For JBOD case, bdi_thresh (not bdi_dirty!) could fluctuate up to its
603 * own size, so move the slope over accordingly and choose a slope that
604 * yields 100% pos_ratio fluctuation on suddenly doubled bdi_thresh.
605 */
606 if (unlikely(bdi_thresh > thresh))
607 bdi_thresh = thresh;
Wu Fengguangaed21ad2011-11-23 11:44:41 -0600608 /*
609 * It's very possible that bdi_thresh is close to 0 not because the
610 * device is slow, but that it has remained inactive for long time.
611 * Honour such devices a reasonable good (hopefully IO efficient)
612 * threshold, so that the occasional writes won't be blocked and active
613 * writes can rampup the threshold quickly.
614 */
Wu Fengguang8927f662011-08-04 22:16:46 -0600615 bdi_thresh = max(bdi_thresh, (limit - dirty) / 8);
Wu Fengguang6c14ae12011-03-02 16:04:18 -0600616 /*
617 * scale global setpoint to bdi's:
618 * bdi_setpoint = setpoint * bdi_thresh / thresh
619 */
620 x = div_u64((u64)bdi_thresh << 16, thresh + 1);
621 bdi_setpoint = setpoint * (u64)x >> 16;
622 /*
623 * Use span=(8*write_bw) in single bdi case as indicated by
624 * (thresh - bdi_thresh ~= 0) and transit to bdi_thresh in JBOD case.
625 *
626 * bdi_thresh thresh - bdi_thresh
627 * span = ---------- * (8 * write_bw) + ------------------- * bdi_thresh
628 * thresh thresh
629 */
630 span = (thresh - bdi_thresh + 8 * write_bw) * (u64)x >> 16;
631 x_intercept = bdi_setpoint + span;
632
633 if (bdi_dirty < x_intercept - span / 4) {
Wu Fengguang50657fc2011-10-11 17:06:33 -0600634 pos_ratio = div_u64(pos_ratio * (x_intercept - bdi_dirty),
635 x_intercept - bdi_setpoint + 1);
Wu Fengguang6c14ae12011-03-02 16:04:18 -0600636 } else
637 pos_ratio /= 4;
638
Wu Fengguang8927f662011-08-04 22:16:46 -0600639 /*
640 * bdi reserve area, safeguard against dirty pool underrun and disk idle
641 * It may push the desired control point of global dirty pages higher
642 * than setpoint.
643 */
644 x_intercept = bdi_thresh / 2;
645 if (bdi_dirty < x_intercept) {
Wu Fengguang50657fc2011-10-11 17:06:33 -0600646 if (bdi_dirty > x_intercept / 8)
647 pos_ratio = div_u64(pos_ratio * x_intercept, bdi_dirty);
648 else
Wu Fengguang8927f662011-08-04 22:16:46 -0600649 pos_ratio *= 8;
650 }
651
Wu Fengguang6c14ae12011-03-02 16:04:18 -0600652 return pos_ratio;
653}
654
Wu Fengguange98be2d2010-08-29 11:22:30 -0600655static void bdi_update_write_bandwidth(struct backing_dev_info *bdi,
656 unsigned long elapsed,
657 unsigned long written)
658{
659 const unsigned long period = roundup_pow_of_two(3 * HZ);
660 unsigned long avg = bdi->avg_write_bandwidth;
661 unsigned long old = bdi->write_bandwidth;
662 u64 bw;
663
664 /*
665 * bw = written * HZ / elapsed
666 *
667 * bw * elapsed + write_bandwidth * (period - elapsed)
668 * write_bandwidth = ---------------------------------------------------
669 * period
670 */
671 bw = written - bdi->written_stamp;
672 bw *= HZ;
673 if (unlikely(elapsed > period)) {
674 do_div(bw, elapsed);
675 avg = bw;
676 goto out;
677 }
678 bw += (u64)bdi->write_bandwidth * (period - elapsed);
679 bw >>= ilog2(period);
680
681 /*
682 * one more level of smoothing, for filtering out sudden spikes
683 */
684 if (avg > old && old >= (unsigned long)bw)
685 avg -= (avg - old) >> 3;
686
687 if (avg < old && old <= (unsigned long)bw)
688 avg += (old - avg) >> 3;
689
690out:
691 bdi->write_bandwidth = bw;
692 bdi->avg_write_bandwidth = avg;
693}
694
Wu Fengguangc42843f2011-03-02 15:54:09 -0600695/*
696 * The global dirtyable memory and dirty threshold could be suddenly knocked
697 * down by a large amount (eg. on the startup of KVM in a swapless system).
698 * This may throw the system into deep dirty exceeded state and throttle
699 * heavy/light dirtiers alike. To retain good responsiveness, maintain
700 * global_dirty_limit for tracking slowly down to the knocked down dirty
701 * threshold.
702 */
703static void update_dirty_limit(unsigned long thresh, unsigned long dirty)
704{
705 unsigned long limit = global_dirty_limit;
706
707 /*
708 * Follow up in one step.
709 */
710 if (limit < thresh) {
711 limit = thresh;
712 goto update;
713 }
714
715 /*
716 * Follow down slowly. Use the higher one as the target, because thresh
717 * may drop below dirty. This is exactly the reason to introduce
718 * global_dirty_limit which is guaranteed to lie above the dirty pages.
719 */
720 thresh = max(thresh, dirty);
721 if (limit > thresh) {
722 limit -= (limit - thresh) >> 5;
723 goto update;
724 }
725 return;
726update:
727 global_dirty_limit = limit;
728}
729
730static void global_update_bandwidth(unsigned long thresh,
731 unsigned long dirty,
732 unsigned long now)
733{
734 static DEFINE_SPINLOCK(dirty_lock);
735 static unsigned long update_time;
736
737 /*
738 * check locklessly first to optimize away locking for the most time
739 */
740 if (time_before(now, update_time + BANDWIDTH_INTERVAL))
741 return;
742
743 spin_lock(&dirty_lock);
744 if (time_after_eq(now, update_time + BANDWIDTH_INTERVAL)) {
745 update_dirty_limit(thresh, dirty);
746 update_time = now;
747 }
748 spin_unlock(&dirty_lock);
749}
750
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600751/*
752 * Maintain bdi->dirty_ratelimit, the base dirty throttle rate.
753 *
754 * Normal bdi tasks will be curbed at or below it in long term.
755 * Obviously it should be around (write_bw / N) when there are N dd tasks.
756 */
757static void bdi_update_dirty_ratelimit(struct backing_dev_info *bdi,
758 unsigned long thresh,
759 unsigned long bg_thresh,
760 unsigned long dirty,
761 unsigned long bdi_thresh,
762 unsigned long bdi_dirty,
763 unsigned long dirtied,
764 unsigned long elapsed)
765{
Wu Fengguang73811312011-08-26 15:53:24 -0600766 unsigned long freerun = dirty_freerun_ceiling(thresh, bg_thresh);
767 unsigned long limit = hard_dirty_limit(thresh);
768 unsigned long setpoint = (freerun + limit) / 2;
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600769 unsigned long write_bw = bdi->avg_write_bandwidth;
770 unsigned long dirty_ratelimit = bdi->dirty_ratelimit;
771 unsigned long dirty_rate;
772 unsigned long task_ratelimit;
773 unsigned long balanced_dirty_ratelimit;
774 unsigned long pos_ratio;
Wu Fengguang73811312011-08-26 15:53:24 -0600775 unsigned long step;
776 unsigned long x;
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600777
778 /*
779 * The dirty rate will match the writeout rate in long term, except
780 * when dirty pages are truncated by userspace or re-dirtied by FS.
781 */
782 dirty_rate = (dirtied - bdi->dirtied_stamp) * HZ / elapsed;
783
784 pos_ratio = bdi_position_ratio(bdi, thresh, bg_thresh, dirty,
785 bdi_thresh, bdi_dirty);
786 /*
787 * task_ratelimit reflects each dd's dirty rate for the past 200ms.
788 */
789 task_ratelimit = (u64)dirty_ratelimit *
790 pos_ratio >> RATELIMIT_CALC_SHIFT;
791 task_ratelimit++; /* it helps rampup dirty_ratelimit from tiny values */
792
793 /*
794 * A linear estimation of the "balanced" throttle rate. The theory is,
795 * if there are N dd tasks, each throttled at task_ratelimit, the bdi's
796 * dirty_rate will be measured to be (N * task_ratelimit). So the below
797 * formula will yield the balanced rate limit (write_bw / N).
798 *
799 * Note that the expanded form is not a pure rate feedback:
800 * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) (1)
801 * but also takes pos_ratio into account:
802 * rate_(i+1) = rate_(i) * (write_bw / dirty_rate) * pos_ratio (2)
803 *
804 * (1) is not realistic because pos_ratio also takes part in balancing
805 * the dirty rate. Consider the state
806 * pos_ratio = 0.5 (3)
807 * rate = 2 * (write_bw / N) (4)
808 * If (1) is used, it will stuck in that state! Because each dd will
809 * be throttled at
810 * task_ratelimit = pos_ratio * rate = (write_bw / N) (5)
811 * yielding
812 * dirty_rate = N * task_ratelimit = write_bw (6)
813 * put (6) into (1) we get
814 * rate_(i+1) = rate_(i) (7)
815 *
816 * So we end up using (2) to always keep
817 * rate_(i+1) ~= (write_bw / N) (8)
818 * regardless of the value of pos_ratio. As long as (8) is satisfied,
819 * pos_ratio is able to drive itself to 1.0, which is not only where
820 * the dirty count meet the setpoint, but also where the slope of
821 * pos_ratio is most flat and hence task_ratelimit is least fluctuated.
822 */
823 balanced_dirty_ratelimit = div_u64((u64)task_ratelimit * write_bw,
824 dirty_rate | 1);
Wu Fengguangbdaac492011-08-03 14:30:36 -0600825 /*
826 * balanced_dirty_ratelimit ~= (write_bw / N) <= write_bw
827 */
828 if (unlikely(balanced_dirty_ratelimit > write_bw))
829 balanced_dirty_ratelimit = write_bw;
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600830
Wu Fengguang73811312011-08-26 15:53:24 -0600831 /*
832 * We could safely do this and return immediately:
833 *
834 * bdi->dirty_ratelimit = balanced_dirty_ratelimit;
835 *
836 * However to get a more stable dirty_ratelimit, the below elaborated
837 * code makes use of task_ratelimit to filter out sigular points and
838 * limit the step size.
839 *
840 * The below code essentially only uses the relative value of
841 *
842 * task_ratelimit - dirty_ratelimit
843 * = (pos_ratio - 1) * dirty_ratelimit
844 *
845 * which reflects the direction and size of dirty position error.
846 */
847
848 /*
849 * dirty_ratelimit will follow balanced_dirty_ratelimit iff
850 * task_ratelimit is on the same side of dirty_ratelimit, too.
851 * For example, when
852 * - dirty_ratelimit > balanced_dirty_ratelimit
853 * - dirty_ratelimit > task_ratelimit (dirty pages are above setpoint)
854 * lowering dirty_ratelimit will help meet both the position and rate
855 * control targets. Otherwise, don't update dirty_ratelimit if it will
856 * only help meet the rate target. After all, what the users ultimately
857 * feel and care are stable dirty rate and small position error.
858 *
859 * |task_ratelimit - dirty_ratelimit| is used to limit the step size
860 * and filter out the sigular points of balanced_dirty_ratelimit. Which
861 * keeps jumping around randomly and can even leap far away at times
862 * due to the small 200ms estimation period of dirty_rate (we want to
863 * keep that period small to reduce time lags).
864 */
865 step = 0;
866 if (dirty < setpoint) {
867 x = min(bdi->balanced_dirty_ratelimit,
868 min(balanced_dirty_ratelimit, task_ratelimit));
869 if (dirty_ratelimit < x)
870 step = x - dirty_ratelimit;
871 } else {
872 x = max(bdi->balanced_dirty_ratelimit,
873 max(balanced_dirty_ratelimit, task_ratelimit));
874 if (dirty_ratelimit > x)
875 step = dirty_ratelimit - x;
876 }
877
878 /*
879 * Don't pursue 100% rate matching. It's impossible since the balanced
880 * rate itself is constantly fluctuating. So decrease the track speed
881 * when it gets close to the target. Helps eliminate pointless tremors.
882 */
883 step >>= dirty_ratelimit / (2 * step + 1);
884 /*
885 * Limit the tracking speed to avoid overshooting.
886 */
887 step = (step + 7) / 8;
888
889 if (dirty_ratelimit < balanced_dirty_ratelimit)
890 dirty_ratelimit += step;
891 else
892 dirty_ratelimit -= step;
893
894 bdi->dirty_ratelimit = max(dirty_ratelimit, 1UL);
895 bdi->balanced_dirty_ratelimit = balanced_dirty_ratelimit;
Wu Fengguangb48c1042011-03-02 17:22:49 -0600896
897 trace_bdi_dirty_ratelimit(bdi, dirty_rate, task_ratelimit);
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600898}
899
Wu Fengguange98be2d2010-08-29 11:22:30 -0600900void __bdi_update_bandwidth(struct backing_dev_info *bdi,
Wu Fengguangc42843f2011-03-02 15:54:09 -0600901 unsigned long thresh,
Wu Fengguangaf6a3112011-10-03 20:46:17 -0600902 unsigned long bg_thresh,
Wu Fengguangc42843f2011-03-02 15:54:09 -0600903 unsigned long dirty,
904 unsigned long bdi_thresh,
905 unsigned long bdi_dirty,
Wu Fengguange98be2d2010-08-29 11:22:30 -0600906 unsigned long start_time)
907{
908 unsigned long now = jiffies;
909 unsigned long elapsed = now - bdi->bw_time_stamp;
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600910 unsigned long dirtied;
Wu Fengguange98be2d2010-08-29 11:22:30 -0600911 unsigned long written;
912
913 /*
914 * rate-limit, only update once every 200ms.
915 */
916 if (elapsed < BANDWIDTH_INTERVAL)
917 return;
918
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600919 dirtied = percpu_counter_read(&bdi->bdi_stat[BDI_DIRTIED]);
Wu Fengguange98be2d2010-08-29 11:22:30 -0600920 written = percpu_counter_read(&bdi->bdi_stat[BDI_WRITTEN]);
921
922 /*
923 * Skip quiet periods when disk bandwidth is under-utilized.
924 * (at least 1s idle time between two flusher runs)
925 */
926 if (elapsed > HZ && time_before(bdi->bw_time_stamp, start_time))
927 goto snapshot;
928
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600929 if (thresh) {
Wu Fengguangc42843f2011-03-02 15:54:09 -0600930 global_update_bandwidth(thresh, dirty, now);
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600931 bdi_update_dirty_ratelimit(bdi, thresh, bg_thresh, dirty,
932 bdi_thresh, bdi_dirty,
933 dirtied, elapsed);
934 }
Wu Fengguange98be2d2010-08-29 11:22:30 -0600935 bdi_update_write_bandwidth(bdi, elapsed, written);
936
937snapshot:
Wu Fengguangbe3ffa22011-06-12 10:51:31 -0600938 bdi->dirtied_stamp = dirtied;
Wu Fengguange98be2d2010-08-29 11:22:30 -0600939 bdi->written_stamp = written;
940 bdi->bw_time_stamp = now;
941}
942
943static void bdi_update_bandwidth(struct backing_dev_info *bdi,
Wu Fengguangc42843f2011-03-02 15:54:09 -0600944 unsigned long thresh,
Wu Fengguangaf6a3112011-10-03 20:46:17 -0600945 unsigned long bg_thresh,
Wu Fengguangc42843f2011-03-02 15:54:09 -0600946 unsigned long dirty,
947 unsigned long bdi_thresh,
948 unsigned long bdi_dirty,
Wu Fengguange98be2d2010-08-29 11:22:30 -0600949 unsigned long start_time)
950{
951 if (time_is_after_eq_jiffies(bdi->bw_time_stamp + BANDWIDTH_INTERVAL))
952 return;
953 spin_lock(&bdi->wb.list_lock);
Wu Fengguangaf6a3112011-10-03 20:46:17 -0600954 __bdi_update_bandwidth(bdi, thresh, bg_thresh, dirty,
955 bdi_thresh, bdi_dirty, start_time);
Wu Fengguange98be2d2010-08-29 11:22:30 -0600956 spin_unlock(&bdi->wb.list_lock);
957}
958
Linus Torvalds1da177e2005-04-16 15:20:36 -0700959/*
Wu Fengguang9d823e82011-06-11 18:10:12 -0600960 * After a task dirtied this many pages, balance_dirty_pages_ratelimited_nr()
961 * will look to see if it needs to start dirty throttling.
962 *
963 * If dirty_poll_interval is too low, big NUMA machines will call the expensive
964 * global_page_state() too often. So scale it near-sqrt to the safety margin
965 * (the number of pages we may dirty without exceeding the dirty limits).
966 */
967static unsigned long dirty_poll_interval(unsigned long dirty,
968 unsigned long thresh)
969{
970 if (thresh > dirty)
971 return 1UL << (ilog2(thresh - dirty) >> 1);
972
973 return 1;
974}
975
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -0600976static long bdi_max_pause(struct backing_dev_info *bdi,
977 unsigned long bdi_dirty)
Wu Fengguangc8462cc2011-06-11 19:21:43 -0600978{
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -0600979 long bw = bdi->avg_write_bandwidth;
980 long t;
Wu Fengguangc8462cc2011-06-11 19:21:43 -0600981
982 /*
983 * Limit pause time for small memory systems. If sleeping for too long
984 * time, a small pool of dirty/writeback pages may go empty and disk go
985 * idle.
986 *
987 * 8 serves as the safety ratio.
988 */
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -0600989 t = bdi_dirty / (1 + bw / roundup_pow_of_two(1 + HZ / 8));
990 t++;
991
992 return min_t(long, t, MAX_PAUSE);
993}
994
995static long bdi_min_pause(struct backing_dev_info *bdi,
996 long max_pause,
997 unsigned long task_ratelimit,
998 unsigned long dirty_ratelimit,
999 int *nr_dirtied_pause)
1000{
1001 long hi = ilog2(bdi->avg_write_bandwidth);
1002 long lo = ilog2(bdi->dirty_ratelimit);
1003 long t; /* target pause */
1004 long pause; /* estimated next pause */
1005 int pages; /* target nr_dirtied_pause */
1006
1007 /* target for 10ms pause on 1-dd case */
1008 t = max(1, HZ / 100);
Wu Fengguangc8462cc2011-06-11 19:21:43 -06001009
1010 /*
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001011 * Scale up pause time for concurrent dirtiers in order to reduce CPU
1012 * overheads.
1013 *
1014 * (N * 10ms) on 2^N concurrent tasks.
Wu Fengguangc8462cc2011-06-11 19:21:43 -06001015 */
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001016 if (hi > lo)
1017 t += (hi - lo) * (10 * HZ) / 1024;
1018
1019 /*
1020 * This is a bit convoluted. We try to base the next nr_dirtied_pause
1021 * on the much more stable dirty_ratelimit. However the next pause time
1022 * will be computed based on task_ratelimit and the two rate limits may
1023 * depart considerably at some time. Especially if task_ratelimit goes
1024 * below dirty_ratelimit/2 and the target pause is max_pause, the next
1025 * pause time will be max_pause*2 _trimmed down_ to max_pause. As a
1026 * result task_ratelimit won't be executed faithfully, which could
1027 * eventually bring down dirty_ratelimit.
1028 *
1029 * We apply two rules to fix it up:
1030 * 1) try to estimate the next pause time and if necessary, use a lower
1031 * nr_dirtied_pause so as not to exceed max_pause. When this happens,
1032 * nr_dirtied_pause will be "dancing" with task_ratelimit.
1033 * 2) limit the target pause time to max_pause/2, so that the normal
1034 * small fluctuations of task_ratelimit won't trigger rule (1) and
1035 * nr_dirtied_pause will remain as stable as dirty_ratelimit.
1036 */
1037 t = min(t, 1 + max_pause / 2);
1038 pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
1039
Wu Fengguang5b9b3572011-12-06 13:17:17 -06001040 /*
1041 * Tiny nr_dirtied_pause is found to hurt I/O performance in the test
1042 * case fio-mmap-randwrite-64k, which does 16*{sync read, async write}.
1043 * When the 16 consecutive reads are often interrupted by some dirty
1044 * throttling pause during the async writes, cfq will go into idles
1045 * (deadline is fine). So push nr_dirtied_pause as high as possible
1046 * until reaches DIRTY_POLL_THRESH=32 pages.
1047 */
1048 if (pages < DIRTY_POLL_THRESH) {
1049 t = max_pause;
1050 pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
1051 if (pages > DIRTY_POLL_THRESH) {
1052 pages = DIRTY_POLL_THRESH;
1053 t = HZ * DIRTY_POLL_THRESH / dirty_ratelimit;
1054 }
1055 }
1056
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001057 pause = HZ * pages / (task_ratelimit + 1);
1058 if (pause > max_pause) {
1059 t = max_pause;
1060 pages = task_ratelimit * t / roundup_pow_of_two(HZ);
1061 }
1062
1063 *nr_dirtied_pause = pages;
1064 /*
1065 * The minimal pause time will normally be half the target pause time.
1066 */
Wu Fengguang5b9b3572011-12-06 13:17:17 -06001067 return pages >= DIRTY_POLL_THRESH ? 1 + t / 2 : t;
Wu Fengguangc8462cc2011-06-11 19:21:43 -06001068}
1069
Wu Fengguang9d823e82011-06-11 18:10:12 -06001070/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001071 * balance_dirty_pages() must be called by processes which are generating dirty
1072 * data. It looks at the number of dirty pages in the machine and will force
Wu Fengguang143dfe82010-08-27 18:45:12 -06001073 * the caller to wait once crossing the (background_thresh + dirty_thresh) / 2.
Jens Axboe5b0830c2009-09-23 19:37:09 +02001074 * If we're over `background_thresh' then the writeback threads are woken to
1075 * perform some writeout.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001076 */
Wu Fengguang3a2e9a52009-09-23 21:56:00 +08001077static void balance_dirty_pages(struct address_space *mapping,
Wu Fengguang143dfe82010-08-27 18:45:12 -06001078 unsigned long pages_dirtied)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001079{
Wu Fengguang143dfe82010-08-27 18:45:12 -06001080 unsigned long nr_reclaimable; /* = file_dirty + unstable_nfs */
1081 unsigned long bdi_reclaimable;
Wu Fengguang77627412010-09-12 13:34:05 -06001082 unsigned long nr_dirty; /* = file_dirty + writeback + unstable_nfs */
1083 unsigned long bdi_dirty;
Wu Fengguang6c14ae12011-03-02 16:04:18 -06001084 unsigned long freerun;
David Rientjes364aeb22009-01-06 14:39:29 -08001085 unsigned long background_thresh;
1086 unsigned long dirty_thresh;
1087 unsigned long bdi_thresh;
Wu Fengguang83712352011-06-11 19:25:42 -06001088 long period;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001089 long pause;
1090 long max_pause;
1091 long min_pause;
1092 int nr_dirtied_pause;
Wu Fengguange50e3722010-08-11 14:17:37 -07001093 bool dirty_exceeded = false;
Wu Fengguang143dfe82010-08-27 18:45:12 -06001094 unsigned long task_ratelimit;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001095 unsigned long dirty_ratelimit;
Wu Fengguang143dfe82010-08-27 18:45:12 -06001096 unsigned long pos_ratio;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001097 struct backing_dev_info *bdi = mapping->backing_dev_info;
Wu Fengguange98be2d2010-08-29 11:22:30 -06001098 unsigned long start_time = jiffies;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001099
1100 for (;;) {
Wu Fengguang83712352011-06-11 19:25:42 -06001101 unsigned long now = jiffies;
1102
Wu Fengguang143dfe82010-08-27 18:45:12 -06001103 /*
1104 * Unstable writes are a feature of certain networked
1105 * filesystems (i.e. NFS) in which data may have been
1106 * written to the server's write cache, but has not yet
1107 * been flushed to permanent storage.
1108 */
Peter Zijlstra5fce25a2007-11-14 16:59:15 -08001109 nr_reclaimable = global_page_state(NR_FILE_DIRTY) +
1110 global_page_state(NR_UNSTABLE_NFS);
Wu Fengguang77627412010-09-12 13:34:05 -06001111 nr_dirty = nr_reclaimable + global_page_state(NR_WRITEBACK);
Peter Zijlstra5fce25a2007-11-14 16:59:15 -08001112
Wu Fengguang16c40422010-08-11 14:17:39 -07001113 global_dirty_limits(&background_thresh, &dirty_thresh);
1114
1115 /*
1116 * Throttle it only when the background writeback cannot
1117 * catch-up. This avoids (excessively) small writeouts
1118 * when the bdi limits are ramping up.
1119 */
Wu Fengguang6c14ae12011-03-02 16:04:18 -06001120 freerun = dirty_freerun_ceiling(dirty_thresh,
1121 background_thresh);
Wu Fengguang83712352011-06-11 19:25:42 -06001122 if (nr_dirty <= freerun) {
1123 current->dirty_paused_when = now;
1124 current->nr_dirtied = 0;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001125 current->nr_dirtied_pause =
1126 dirty_poll_interval(nr_dirty, dirty_thresh);
Wu Fengguang16c40422010-08-11 14:17:39 -07001127 break;
Wu Fengguang83712352011-06-11 19:25:42 -06001128 }
Wu Fengguang16c40422010-08-11 14:17:39 -07001129
Wu Fengguang143dfe82010-08-27 18:45:12 -06001130 if (unlikely(!writeback_in_progress(bdi)))
1131 bdi_start_background_writeback(bdi);
1132
1133 /*
1134 * bdi_thresh is not treated as some limiting factor as
1135 * dirty_thresh, due to reasons
1136 * - in JBOD setup, bdi_thresh can fluctuate a lot
1137 * - in a system with HDD and USB key, the USB key may somehow
1138 * go into state (bdi_dirty >> bdi_thresh) either because
1139 * bdi_dirty starts high, or because bdi_thresh drops low.
1140 * In this case we don't want to hard throttle the USB key
1141 * dirtiers for 100 seconds until bdi_dirty drops under
1142 * bdi_thresh. Instead the auxiliary bdi control line in
1143 * bdi_position_ratio() will let the dirtier task progress
1144 * at some rate <= (write_bw / 2) for bringing down bdi_dirty.
1145 */
Wu Fengguang16c40422010-08-11 14:17:39 -07001146 bdi_thresh = bdi_dirty_limit(bdi, dirty_thresh);
Wu Fengguang16c40422010-08-11 14:17:39 -07001147
Wu Fengguange50e3722010-08-11 14:17:37 -07001148 /*
1149 * In order to avoid the stacked BDI deadlock we need
1150 * to ensure we accurately count the 'dirty' pages when
1151 * the threshold is low.
1152 *
1153 * Otherwise it would be possible to get thresh+n pages
1154 * reported dirty, even though there are thresh-m pages
1155 * actually dirty; with m+n sitting in the percpu
1156 * deltas.
1157 */
Wu Fengguang143dfe82010-08-27 18:45:12 -06001158 if (bdi_thresh < 2 * bdi_stat_error(bdi)) {
1159 bdi_reclaimable = bdi_stat_sum(bdi, BDI_RECLAIMABLE);
1160 bdi_dirty = bdi_reclaimable +
Wu Fengguang77627412010-09-12 13:34:05 -06001161 bdi_stat_sum(bdi, BDI_WRITEBACK);
Wu Fengguange50e3722010-08-11 14:17:37 -07001162 } else {
Wu Fengguang143dfe82010-08-27 18:45:12 -06001163 bdi_reclaimable = bdi_stat(bdi, BDI_RECLAIMABLE);
1164 bdi_dirty = bdi_reclaimable +
Wu Fengguang77627412010-09-12 13:34:05 -06001165 bdi_stat(bdi, BDI_WRITEBACK);
Wu Fengguange50e3722010-08-11 14:17:37 -07001166 }
Peter Zijlstra5fce25a2007-11-14 16:59:15 -08001167
Wu Fengguang82791942011-12-03 21:26:01 -06001168 dirty_exceeded = (bdi_dirty > bdi_thresh) &&
Wu Fengguang77627412010-09-12 13:34:05 -06001169 (nr_dirty > dirty_thresh);
Wu Fengguang143dfe82010-08-27 18:45:12 -06001170 if (dirty_exceeded && !bdi->dirty_exceeded)
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -07001171 bdi->dirty_exceeded = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001172
Wu Fengguangaf6a3112011-10-03 20:46:17 -06001173 bdi_update_bandwidth(bdi, dirty_thresh, background_thresh,
1174 nr_dirty, bdi_thresh, bdi_dirty,
1175 start_time);
Wu Fengguange98be2d2010-08-29 11:22:30 -06001176
Wu Fengguang143dfe82010-08-27 18:45:12 -06001177 dirty_ratelimit = bdi->dirty_ratelimit;
1178 pos_ratio = bdi_position_ratio(bdi, dirty_thresh,
1179 background_thresh, nr_dirty,
1180 bdi_thresh, bdi_dirty);
Wu Fengguang3a73dbb2011-11-07 19:19:28 +08001181 task_ratelimit = ((u64)dirty_ratelimit * pos_ratio) >>
1182 RATELIMIT_CALC_SHIFT;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001183 max_pause = bdi_max_pause(bdi, bdi_dirty);
1184 min_pause = bdi_min_pause(bdi, max_pause,
1185 task_ratelimit, dirty_ratelimit,
1186 &nr_dirtied_pause);
1187
Wu Fengguang3a73dbb2011-11-07 19:19:28 +08001188 if (unlikely(task_ratelimit == 0)) {
Wu Fengguang83712352011-06-11 19:25:42 -06001189 period = max_pause;
Wu Fengguangc8462cc2011-06-11 19:21:43 -06001190 pause = max_pause;
Wu Fengguang143dfe82010-08-27 18:45:12 -06001191 goto pause;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001192 }
Wu Fengguang83712352011-06-11 19:25:42 -06001193 period = HZ * pages_dirtied / task_ratelimit;
1194 pause = period;
1195 if (current->dirty_paused_when)
1196 pause -= now - current->dirty_paused_when;
1197 /*
1198 * For less than 1s think time (ext3/4 may block the dirtier
1199 * for up to 800ms from time to time on 1-HDD; so does xfs,
1200 * however at much less frequency), try to compensate it in
1201 * future periods by updating the virtual time; otherwise just
1202 * do a reset, as it may be a light dirtier.
1203 */
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001204 if (pause < min_pause) {
Wu Fengguangece13ac32010-08-29 23:33:20 -06001205 trace_balance_dirty_pages(bdi,
1206 dirty_thresh,
1207 background_thresh,
1208 nr_dirty,
1209 bdi_thresh,
1210 bdi_dirty,
1211 dirty_ratelimit,
1212 task_ratelimit,
1213 pages_dirtied,
Wu Fengguang83712352011-06-11 19:25:42 -06001214 period,
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001215 min(pause, 0L),
Wu Fengguangece13ac32010-08-29 23:33:20 -06001216 start_time);
Wu Fengguang83712352011-06-11 19:25:42 -06001217 if (pause < -HZ) {
1218 current->dirty_paused_when = now;
1219 current->nr_dirtied = 0;
1220 } else if (period) {
1221 current->dirty_paused_when += period;
1222 current->nr_dirtied = 0;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001223 } else if (current->nr_dirtied_pause <= pages_dirtied)
1224 current->nr_dirtied_pause += pages_dirtied;
Wu Fengguang57fc9782011-06-11 19:32:32 -06001225 break;
1226 }
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001227 if (unlikely(pause > max_pause)) {
1228 /* for occasional dropped task_ratelimit */
1229 now += min(pause - max_pause, max_pause);
1230 pause = max_pause;
1231 }
Wu Fengguang143dfe82010-08-27 18:45:12 -06001232
1233pause:
Wu Fengguangece13ac32010-08-29 23:33:20 -06001234 trace_balance_dirty_pages(bdi,
1235 dirty_thresh,
1236 background_thresh,
1237 nr_dirty,
1238 bdi_thresh,
1239 bdi_dirty,
1240 dirty_ratelimit,
1241 task_ratelimit,
1242 pages_dirtied,
Wu Fengguang83712352011-06-11 19:25:42 -06001243 period,
Wu Fengguangece13ac32010-08-29 23:33:20 -06001244 pause,
1245 start_time);
Jan Kara499d05e2011-11-16 19:34:48 +08001246 __set_current_state(TASK_KILLABLE);
Wu Fengguangd25105e2009-10-09 12:40:42 +02001247 io_schedule_timeout(pause);
Jens Axboe87c6a9b2009-09-17 19:59:14 +02001248
Wu Fengguang83712352011-06-11 19:25:42 -06001249 current->dirty_paused_when = now + pause;
1250 current->nr_dirtied = 0;
Wu Fengguang7ccb9ad2011-11-30 11:08:55 -06001251 current->nr_dirtied_pause = nr_dirtied_pause;
Wu Fengguang83712352011-06-11 19:25:42 -06001252
Wu Fengguangffd1f602011-06-19 22:18:42 -06001253 /*
Wu Fengguang1df64712011-11-13 19:47:32 -06001254 * This is typically equal to (nr_dirty < dirty_thresh) and can
1255 * also keep "1000+ dd on a slow USB stick" under control.
Wu Fengguangffd1f602011-06-19 22:18:42 -06001256 */
Wu Fengguang1df64712011-11-13 19:47:32 -06001257 if (task_ratelimit)
Wu Fengguangffd1f602011-06-19 22:18:42 -06001258 break;
Jan Kara499d05e2011-11-16 19:34:48 +08001259
Wu Fengguangc5c63432011-12-02 10:21:33 -06001260 /*
1261 * In the case of an unresponding NFS server and the NFS dirty
1262 * pages exceeds dirty_thresh, give the other good bdi's a pipe
1263 * to go through, so that tasks on them still remain responsive.
1264 *
1265 * In theory 1 page is enough to keep the comsumer-producer
1266 * pipe going: the flusher cleans 1 page => the task dirties 1
1267 * more page. However bdi_dirty has accounting errors. So use
1268 * the larger and more IO friendly bdi_stat_error.
1269 */
1270 if (bdi_dirty <= bdi_stat_error(bdi))
1271 break;
1272
Jan Kara499d05e2011-11-16 19:34:48 +08001273 if (fatal_signal_pending(current))
1274 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001275 }
1276
Wu Fengguang143dfe82010-08-27 18:45:12 -06001277 if (!dirty_exceeded && bdi->dirty_exceeded)
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -07001278 bdi->dirty_exceeded = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001279
1280 if (writeback_in_progress(bdi))
Jens Axboe5b0830c2009-09-23 19:37:09 +02001281 return;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001282
1283 /*
1284 * In laptop mode, we wait until hitting the higher threshold before
1285 * starting background writeout, and then write out all the way down
1286 * to the lower threshold. So slow writers cause minimal disk activity.
1287 *
1288 * In normal mode, we start background writeout at the lower
1289 * background_thresh, to keep the amount of dirty memory low.
1290 */
Wu Fengguang143dfe82010-08-27 18:45:12 -06001291 if (laptop_mode)
1292 return;
1293
1294 if (nr_reclaimable > background_thresh)
Christoph Hellwigc5444192010-06-08 18:15:15 +02001295 bdi_start_background_writeback(bdi);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001296}
1297
Peter Zijlstraa200ee12007-10-08 18:54:37 +02001298void set_page_dirty_balance(struct page *page, int page_mkwrite)
Peter Zijlstraedc79b22006-09-25 23:30:58 -07001299{
Peter Zijlstraa200ee12007-10-08 18:54:37 +02001300 if (set_page_dirty(page) || page_mkwrite) {
Peter Zijlstraedc79b22006-09-25 23:30:58 -07001301 struct address_space *mapping = page_mapping(page);
1302
1303 if (mapping)
1304 balance_dirty_pages_ratelimited(mapping);
1305 }
1306}
1307
Wu Fengguang9d823e82011-06-11 18:10:12 -06001308static DEFINE_PER_CPU(int, bdp_ratelimits);
Tejun Heo245b2e72009-06-24 15:13:48 +09001309
Wu Fengguang54848d72011-04-05 13:21:19 -06001310/*
1311 * Normal tasks are throttled by
1312 * loop {
1313 * dirty tsk->nr_dirtied_pause pages;
1314 * take a snap in balance_dirty_pages();
1315 * }
1316 * However there is a worst case. If every task exit immediately when dirtied
1317 * (tsk->nr_dirtied_pause - 1) pages, balance_dirty_pages() will never be
1318 * called to throttle the page dirties. The solution is to save the not yet
1319 * throttled page dirties in dirty_throttle_leaks on task exit and charge them
1320 * randomly into the running tasks. This works well for the above worst case,
1321 * as the new task will pick up and accumulate the old task's leaked dirty
1322 * count and eventually get throttled.
1323 */
1324DEFINE_PER_CPU(int, dirty_throttle_leaks) = 0;
1325
Linus Torvalds1da177e2005-04-16 15:20:36 -07001326/**
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001327 * balance_dirty_pages_ratelimited_nr - balance dirty memory state
Martin Waitz67be2dd2005-05-01 08:59:26 -07001328 * @mapping: address_space which was dirtied
Martin Waitza5802902006-04-02 13:59:55 +02001329 * @nr_pages_dirtied: number of pages which the caller has just dirtied
Linus Torvalds1da177e2005-04-16 15:20:36 -07001330 *
1331 * Processes which are dirtying memory should call in here once for each page
1332 * which was newly dirtied. The function will periodically check the system's
1333 * dirty state and will initiate writeback if needed.
1334 *
1335 * On really big machines, get_writeback_state is expensive, so try to avoid
1336 * calling it too often (ratelimiting). But once we're over the dirty memory
1337 * limit we decrease the ratelimiting by a lot, to prevent individual processes
1338 * from overshooting the limit by (ratelimit_pages) each.
1339 */
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001340void balance_dirty_pages_ratelimited_nr(struct address_space *mapping,
1341 unsigned long nr_pages_dirtied)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001342{
Wu Fengguang36715ce2011-06-11 17:53:57 -06001343 struct backing_dev_info *bdi = mapping->backing_dev_info;
Wu Fengguang9d823e82011-06-11 18:10:12 -06001344 int ratelimit;
1345 int *p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001346
Wu Fengguang36715ce2011-06-11 17:53:57 -06001347 if (!bdi_cap_account_dirty(bdi))
1348 return;
1349
Wu Fengguang9d823e82011-06-11 18:10:12 -06001350 ratelimit = current->nr_dirtied_pause;
1351 if (bdi->dirty_exceeded)
1352 ratelimit = min(ratelimit, 32 >> (PAGE_SHIFT - 10));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001353
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001354 preempt_disable();
Wu Fengguang9d823e82011-06-11 18:10:12 -06001355 /*
1356 * This prevents one CPU to accumulate too many dirtied pages without
1357 * calling into balance_dirty_pages(), which can happen when there are
1358 * 1000+ tasks, all of them start dirtying pages at exactly the same
1359 * time, hence all honoured too large initial task->nr_dirtied_pause.
1360 */
Tejun Heo245b2e72009-06-24 15:13:48 +09001361 p = &__get_cpu_var(bdp_ratelimits);
Wu Fengguang9d823e82011-06-11 18:10:12 -06001362 if (unlikely(current->nr_dirtied >= ratelimit))
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001363 *p = 0;
Wu Fengguangd3bc1fe2011-04-14 07:52:37 -06001364 else if (unlikely(*p >= ratelimit_pages)) {
1365 *p = 0;
1366 ratelimit = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001367 }
Wu Fengguang54848d72011-04-05 13:21:19 -06001368 /*
1369 * Pick up the dirtied pages by the exited tasks. This avoids lots of
1370 * short-lived tasks (eg. gcc invocations in a kernel build) escaping
1371 * the dirty throttling and livelock other long-run dirtiers.
1372 */
1373 p = &__get_cpu_var(dirty_throttle_leaks);
1374 if (*p > 0 && current->nr_dirtied < ratelimit) {
1375 nr_pages_dirtied = min(*p, ratelimit - current->nr_dirtied);
1376 *p -= nr_pages_dirtied;
1377 current->nr_dirtied += nr_pages_dirtied;
1378 }
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001379 preempt_enable();
Wu Fengguang9d823e82011-06-11 18:10:12 -06001380
1381 if (unlikely(current->nr_dirtied >= ratelimit))
1382 balance_dirty_pages(mapping, current->nr_dirtied);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001383}
Andrew Mortonfa5a7342006-03-24 03:18:10 -08001384EXPORT_SYMBOL(balance_dirty_pages_ratelimited_nr);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001385
Andrew Morton232ea4d2007-02-28 20:13:21 -08001386void throttle_vm_writeout(gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001387{
David Rientjes364aeb22009-01-06 14:39:29 -08001388 unsigned long background_thresh;
1389 unsigned long dirty_thresh;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001390
1391 for ( ; ; ) {
Wu Fengguang16c40422010-08-11 14:17:39 -07001392 global_dirty_limits(&background_thresh, &dirty_thresh);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001393
1394 /*
1395 * Boost the allowable dirty threshold a bit for page
1396 * allocators so they don't get DoS'ed by heavy writers
1397 */
1398 dirty_thresh += dirty_thresh / 10; /* wheeee... */
1399
Christoph Lameterc24f21b2006-06-30 01:55:42 -07001400 if (global_page_state(NR_UNSTABLE_NFS) +
1401 global_page_state(NR_WRITEBACK) <= dirty_thresh)
1402 break;
Jens Axboe8aa7e842009-07-09 14:52:32 +02001403 congestion_wait(BLK_RW_ASYNC, HZ/10);
Fengguang Wu369f2382007-10-16 23:30:45 -07001404
1405 /*
1406 * The caller might hold locks which can prevent IO completion
1407 * or progress in the filesystem. So we cannot just sit here
1408 * waiting for IO to complete.
1409 */
1410 if ((gfp_mask & (__GFP_FS|__GFP_IO)) != (__GFP_FS|__GFP_IO))
1411 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001412 }
1413}
1414
Linus Torvalds1da177e2005-04-16 15:20:36 -07001415/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001416 * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
1417 */
1418int dirty_writeback_centisecs_handler(ctl_table *table, int write,
Alexey Dobriyan8d65af72009-09-23 15:57:19 -07001419 void __user *buffer, size_t *length, loff_t *ppos)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001420{
Alexey Dobriyan8d65af72009-09-23 15:57:19 -07001421 proc_dointvec(table, write, buffer, length, ppos);
Jens Axboe64231042010-05-21 20:00:35 +02001422 bdi_arm_supers_timer();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001423 return 0;
1424}
1425
Jens Axboec2c49862010-05-20 09:18:47 +02001426#ifdef CONFIG_BLOCK
Matthew Garrett31373d02010-04-06 14:25:14 +02001427void laptop_mode_timer_fn(unsigned long data)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001428{
Matthew Garrett31373d02010-04-06 14:25:14 +02001429 struct request_queue *q = (struct request_queue *)data;
1430 int nr_pages = global_page_state(NR_FILE_DIRTY) +
1431 global_page_state(NR_UNSTABLE_NFS);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001432
Matthew Garrett31373d02010-04-06 14:25:14 +02001433 /*
1434 * We want to write everything out, not just down to the dirty
1435 * threshold
1436 */
Matthew Garrett31373d02010-04-06 14:25:14 +02001437 if (bdi_has_dirty_io(&q->backing_dev_info))
Curt Wohlgemuth0e175a12011-10-07 21:54:10 -06001438 bdi_start_writeback(&q->backing_dev_info, nr_pages,
1439 WB_REASON_LAPTOP_TIMER);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001440}
1441
1442/*
1443 * We've spun up the disk and we're in laptop mode: schedule writeback
1444 * of all dirty data a few seconds from now. If the flush is already scheduled
1445 * then push it back - the user is still using the disk.
1446 */
Matthew Garrett31373d02010-04-06 14:25:14 +02001447void laptop_io_completion(struct backing_dev_info *info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001448{
Matthew Garrett31373d02010-04-06 14:25:14 +02001449 mod_timer(&info->laptop_mode_wb_timer, jiffies + laptop_mode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001450}
1451
1452/*
1453 * We're in laptop mode and we've just synced. The sync's writes will have
1454 * caused another writeback to be scheduled by laptop_io_completion.
1455 * Nothing needs to be written back anymore, so we unschedule the writeback.
1456 */
1457void laptop_sync_completion(void)
1458{
Matthew Garrett31373d02010-04-06 14:25:14 +02001459 struct backing_dev_info *bdi;
1460
1461 rcu_read_lock();
1462
1463 list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
1464 del_timer(&bdi->laptop_mode_wb_timer);
1465
1466 rcu_read_unlock();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001467}
Jens Axboec2c49862010-05-20 09:18:47 +02001468#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -07001469
1470/*
1471 * If ratelimit_pages is too high then we can get into dirty-data overload
1472 * if a large number of processes all perform writes at the same time.
1473 * If it is too low then SMP machines will call the (expensive)
1474 * get_writeback_state too often.
1475 *
1476 * Here we set ratelimit_pages to a level which ensures that when all CPUs are
1477 * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
Wu Fengguang9d823e82011-06-11 18:10:12 -06001478 * thresholds.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001479 */
1480
Chandra Seetharaman2d1d43f2006-09-29 02:01:25 -07001481void writeback_set_ratelimit(void)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001482{
Wu Fengguang9d823e82011-06-11 18:10:12 -06001483 unsigned long background_thresh;
1484 unsigned long dirty_thresh;
1485 global_dirty_limits(&background_thresh, &dirty_thresh);
1486 ratelimit_pages = dirty_thresh / (num_online_cpus() * 32);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001487 if (ratelimit_pages < 16)
1488 ratelimit_pages = 16;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001489}
1490
Chandra Seetharaman26c21432006-06-27 02:54:10 -07001491static int __cpuinit
Linus Torvalds1da177e2005-04-16 15:20:36 -07001492ratelimit_handler(struct notifier_block *self, unsigned long u, void *v)
1493{
Chandra Seetharaman2d1d43f2006-09-29 02:01:25 -07001494 writeback_set_ratelimit();
Paul E. McKenneyaa0f0302007-02-10 01:46:37 -08001495 return NOTIFY_DONE;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001496}
1497
Chandra Seetharaman74b85f32006-06-27 02:54:09 -07001498static struct notifier_block __cpuinitdata ratelimit_nb = {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001499 .notifier_call = ratelimit_handler,
1500 .next = NULL,
1501};
1502
1503/*
Linus Torvaldsdc6e29d2007-01-29 16:37:38 -08001504 * Called early on to tune the page writeback dirty limits.
1505 *
1506 * We used to scale dirty pages according to how total memory
1507 * related to pages that could be allocated for buffers (by
1508 * comparing nr_free_buffer_pages() to vm_total_pages.
1509 *
1510 * However, that was when we used "dirty_ratio" to scale with
1511 * all memory, and we don't do that any more. "dirty_ratio"
1512 * is now applied to total non-HIGHPAGE memory (by subtracting
1513 * totalhigh_pages from vm_total_pages), and as such we can't
1514 * get into the old insane situation any more where we had
1515 * large amounts of dirty pages compared to a small amount of
1516 * non-HIGHMEM memory.
1517 *
1518 * But we might still want to scale the dirty_ratio by how
1519 * much memory the box has..
Linus Torvalds1da177e2005-04-16 15:20:36 -07001520 */
1521void __init page_writeback_init(void)
1522{
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -07001523 int shift;
1524
Chandra Seetharaman2d1d43f2006-09-29 02:01:25 -07001525 writeback_set_ratelimit();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001526 register_cpu_notifier(&ratelimit_nb);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -07001527
1528 shift = calc_period_shift();
1529 prop_descriptor_init(&vm_completions, shift);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001530}
1531
David Howells811d7362006-08-29 19:06:09 +01001532/**
Jan Karaf446daae2010-08-09 17:19:12 -07001533 * tag_pages_for_writeback - tag pages to be written by write_cache_pages
1534 * @mapping: address space structure to write
1535 * @start: starting page index
1536 * @end: ending page index (inclusive)
1537 *
1538 * This function scans the page range from @start to @end (inclusive) and tags
1539 * all pages that have DIRTY tag set with a special TOWRITE tag. The idea is
1540 * that write_cache_pages (or whoever calls this function) will then use
1541 * TOWRITE tag to identify pages eligible for writeback. This mechanism is
1542 * used to avoid livelocking of writeback by a process steadily creating new
1543 * dirty pages in the file (thus it is important for this function to be quick
1544 * so that it can tag pages faster than a dirtying process can create them).
1545 */
1546/*
1547 * We tag pages in batches of WRITEBACK_TAG_BATCH to reduce tree_lock latency.
1548 */
Jan Karaf446daae2010-08-09 17:19:12 -07001549void tag_pages_for_writeback(struct address_space *mapping,
1550 pgoff_t start, pgoff_t end)
1551{
Randy Dunlap3c111a02010-08-11 14:17:30 -07001552#define WRITEBACK_TAG_BATCH 4096
Jan Karaf446daae2010-08-09 17:19:12 -07001553 unsigned long tagged;
1554
1555 do {
1556 spin_lock_irq(&mapping->tree_lock);
1557 tagged = radix_tree_range_tag_if_tagged(&mapping->page_tree,
1558 &start, end, WRITEBACK_TAG_BATCH,
1559 PAGECACHE_TAG_DIRTY, PAGECACHE_TAG_TOWRITE);
1560 spin_unlock_irq(&mapping->tree_lock);
1561 WARN_ON_ONCE(tagged > WRITEBACK_TAG_BATCH);
1562 cond_resched();
Jan Karad5ed3a42010-08-19 14:13:33 -07001563 /* We check 'start' to handle wrapping when end == ~0UL */
1564 } while (tagged >= WRITEBACK_TAG_BATCH && start);
Jan Karaf446daae2010-08-09 17:19:12 -07001565}
1566EXPORT_SYMBOL(tag_pages_for_writeback);
1567
1568/**
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001569 * 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 +01001570 * @mapping: address space structure to write
1571 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001572 * @writepage: function called for each page
1573 * @data: data passed to writepage function
David Howells811d7362006-08-29 19:06:09 +01001574 *
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001575 * If a page is already under I/O, write_cache_pages() skips it, even
David Howells811d7362006-08-29 19:06:09 +01001576 * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
1577 * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
1578 * and msync() need to guarantee that all the data which was dirty at the time
1579 * the call was made get new I/O started against them. If wbc->sync_mode is
1580 * WB_SYNC_ALL then we were called for data integrity and we must wait for
1581 * existing IO to complete.
Jan Karaf446daae2010-08-09 17:19:12 -07001582 *
1583 * To avoid livelocks (when other process dirties new pages), we first tag
1584 * pages which should be written back with TOWRITE tag and only then start
1585 * writing them. For data-integrity sync we have to be careful so that we do
1586 * not miss some pages (e.g., because some other process has cleared TOWRITE
1587 * tag we set). The rule we follow is that TOWRITE tag can be cleared only
1588 * by the process clearing the DIRTY tag (and submitting the page for IO).
David Howells811d7362006-08-29 19:06:09 +01001589 */
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001590int write_cache_pages(struct address_space *mapping,
1591 struct writeback_control *wbc, writepage_t writepage,
1592 void *data)
David Howells811d7362006-08-29 19:06:09 +01001593{
David Howells811d7362006-08-29 19:06:09 +01001594 int ret = 0;
1595 int done = 0;
David Howells811d7362006-08-29 19:06:09 +01001596 struct pagevec pvec;
1597 int nr_pages;
Nick Piggin31a12662009-01-06 14:39:04 -08001598 pgoff_t uninitialized_var(writeback_index);
David Howells811d7362006-08-29 19:06:09 +01001599 pgoff_t index;
1600 pgoff_t end; /* Inclusive */
Nick Pigginbd19e012009-01-06 14:39:06 -08001601 pgoff_t done_index;
Nick Piggin31a12662009-01-06 14:39:04 -08001602 int cycled;
David Howells811d7362006-08-29 19:06:09 +01001603 int range_whole = 0;
Jan Karaf446daae2010-08-09 17:19:12 -07001604 int tag;
David Howells811d7362006-08-29 19:06:09 +01001605
David Howells811d7362006-08-29 19:06:09 +01001606 pagevec_init(&pvec, 0);
1607 if (wbc->range_cyclic) {
Nick Piggin31a12662009-01-06 14:39:04 -08001608 writeback_index = mapping->writeback_index; /* prev offset */
1609 index = writeback_index;
1610 if (index == 0)
1611 cycled = 1;
1612 else
1613 cycled = 0;
David Howells811d7362006-08-29 19:06:09 +01001614 end = -1;
1615 } else {
1616 index = wbc->range_start >> PAGE_CACHE_SHIFT;
1617 end = wbc->range_end >> PAGE_CACHE_SHIFT;
1618 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
1619 range_whole = 1;
Nick Piggin31a12662009-01-06 14:39:04 -08001620 cycled = 1; /* ignore range_cyclic tests */
David Howells811d7362006-08-29 19:06:09 +01001621 }
Wu Fengguang6e6938b2010-06-06 10:38:15 -06001622 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
Jan Karaf446daae2010-08-09 17:19:12 -07001623 tag = PAGECACHE_TAG_TOWRITE;
1624 else
1625 tag = PAGECACHE_TAG_DIRTY;
David Howells811d7362006-08-29 19:06:09 +01001626retry:
Wu Fengguang6e6938b2010-06-06 10:38:15 -06001627 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
Jan Karaf446daae2010-08-09 17:19:12 -07001628 tag_pages_for_writeback(mapping, index, end);
Nick Pigginbd19e012009-01-06 14:39:06 -08001629 done_index = index;
Nick Piggin5a3d5c92009-01-06 14:39:09 -08001630 while (!done && (index <= end)) {
1631 int i;
1632
Jan Karaf446daae2010-08-09 17:19:12 -07001633 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
Nick Piggin5a3d5c92009-01-06 14:39:09 -08001634 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
1635 if (nr_pages == 0)
1636 break;
David Howells811d7362006-08-29 19:06:09 +01001637
David Howells811d7362006-08-29 19:06:09 +01001638 for (i = 0; i < nr_pages; i++) {
1639 struct page *page = pvec.pages[i];
1640
Nick Piggind5482cd2009-01-06 14:39:11 -08001641 /*
1642 * At this point, the page may be truncated or
1643 * invalidated (changing page->mapping to NULL), or
1644 * even swizzled back from swapper_space to tmpfs file
1645 * mapping. However, page->index will not change
1646 * because we have a reference on the page.
1647 */
1648 if (page->index > end) {
1649 /*
1650 * can't be range_cyclic (1st pass) because
1651 * end == -1 in that case.
1652 */
1653 done = 1;
1654 break;
1655 }
1656
Jun'ichi Nomuracf15b072011-03-22 16:33:40 -07001657 done_index = page->index;
Nick Pigginbd19e012009-01-06 14:39:06 -08001658
David Howells811d7362006-08-29 19:06:09 +01001659 lock_page(page);
1660
Nick Piggin5a3d5c92009-01-06 14:39:09 -08001661 /*
1662 * Page truncated or invalidated. We can freely skip it
1663 * then, even for data integrity operations: the page
1664 * has disappeared concurrently, so there could be no
1665 * real expectation of this data interity operation
1666 * even if there is now a new, dirty page at the same
1667 * pagecache address.
1668 */
David Howells811d7362006-08-29 19:06:09 +01001669 if (unlikely(page->mapping != mapping)) {
Nick Piggin5a3d5c92009-01-06 14:39:09 -08001670continue_unlock:
David Howells811d7362006-08-29 19:06:09 +01001671 unlock_page(page);
1672 continue;
1673 }
1674
Nick Piggin515f4a02009-01-06 14:39:10 -08001675 if (!PageDirty(page)) {
1676 /* someone wrote it for us */
1677 goto continue_unlock;
1678 }
David Howells811d7362006-08-29 19:06:09 +01001679
Nick Piggin515f4a02009-01-06 14:39:10 -08001680 if (PageWriteback(page)) {
1681 if (wbc->sync_mode != WB_SYNC_NONE)
1682 wait_on_page_writeback(page);
1683 else
1684 goto continue_unlock;
1685 }
1686
1687 BUG_ON(PageWriteback(page));
1688 if (!clear_page_dirty_for_io(page))
Nick Piggin5a3d5c92009-01-06 14:39:09 -08001689 goto continue_unlock;
David Howells811d7362006-08-29 19:06:09 +01001690
Dave Chinner9e094382010-07-07 13:24:08 +10001691 trace_wbc_writepage(wbc, mapping->backing_dev_info);
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001692 ret = (*writepage)(page, wbc, data);
Nick Piggin00266772009-01-06 14:39:06 -08001693 if (unlikely(ret)) {
1694 if (ret == AOP_WRITEPAGE_ACTIVATE) {
1695 unlock_page(page);
1696 ret = 0;
1697 } else {
1698 /*
1699 * done_index is set past this page,
1700 * so media errors will not choke
1701 * background writeout for the entire
1702 * file. This has consequences for
1703 * range_cyclic semantics (ie. it may
1704 * not be suitable for data integrity
1705 * writeout).
1706 */
Jun'ichi Nomuracf15b072011-03-22 16:33:40 -07001707 done_index = page->index + 1;
Nick Piggin00266772009-01-06 14:39:06 -08001708 done = 1;
1709 break;
1710 }
Dave Chinner0b564922010-06-09 10:37:18 +10001711 }
David Howells811d7362006-08-29 19:06:09 +01001712
Dave Chinner546a1922010-08-24 11:44:34 +10001713 /*
1714 * We stop writing back only if we are not doing
1715 * integrity sync. In case of integrity sync we have to
1716 * keep going until we have written all the pages
1717 * we tagged for writeback prior to entering this loop.
1718 */
1719 if (--wbc->nr_to_write <= 0 &&
1720 wbc->sync_mode == WB_SYNC_NONE) {
1721 done = 1;
1722 break;
Nick Piggin05fe4782009-01-06 14:39:08 -08001723 }
David Howells811d7362006-08-29 19:06:09 +01001724 }
1725 pagevec_release(&pvec);
1726 cond_resched();
1727 }
Nick Piggin3a4c6802009-02-12 04:34:23 +01001728 if (!cycled && !done) {
David Howells811d7362006-08-29 19:06:09 +01001729 /*
Nick Piggin31a12662009-01-06 14:39:04 -08001730 * range_cyclic:
David Howells811d7362006-08-29 19:06:09 +01001731 * We hit the last page and there is more work to be done: wrap
1732 * back to the start of the file
1733 */
Nick Piggin31a12662009-01-06 14:39:04 -08001734 cycled = 1;
David Howells811d7362006-08-29 19:06:09 +01001735 index = 0;
Nick Piggin31a12662009-01-06 14:39:04 -08001736 end = writeback_index - 1;
David Howells811d7362006-08-29 19:06:09 +01001737 goto retry;
1738 }
Dave Chinner0b564922010-06-09 10:37:18 +10001739 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
1740 mapping->writeback_index = done_index;
Aneesh Kumar K.V06d6cf62008-07-11 19:27:31 -04001741
David Howells811d7362006-08-29 19:06:09 +01001742 return ret;
1743}
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001744EXPORT_SYMBOL(write_cache_pages);
1745
1746/*
1747 * Function used by generic_writepages to call the real writepage
1748 * function and set the mapping flags on error
1749 */
1750static int __writepage(struct page *page, struct writeback_control *wbc,
1751 void *data)
1752{
1753 struct address_space *mapping = data;
1754 int ret = mapping->a_ops->writepage(page, wbc);
1755 mapping_set_error(mapping, ret);
1756 return ret;
1757}
1758
1759/**
1760 * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
1761 * @mapping: address space structure to write
1762 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
1763 *
1764 * This is a library function, which implements the writepages()
1765 * address_space_operation.
1766 */
1767int generic_writepages(struct address_space *mapping,
1768 struct writeback_control *wbc)
1769{
Shaohua Li9b6096a2011-03-17 10:47:06 +01001770 struct blk_plug plug;
1771 int ret;
1772
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001773 /* deal with chardevs and other special file */
1774 if (!mapping->a_ops->writepage)
1775 return 0;
1776
Shaohua Li9b6096a2011-03-17 10:47:06 +01001777 blk_start_plug(&plug);
1778 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
1779 blk_finish_plug(&plug);
1780 return ret;
Miklos Szeredi0ea97182007-05-10 22:22:51 -07001781}
David Howells811d7362006-08-29 19:06:09 +01001782
1783EXPORT_SYMBOL(generic_writepages);
1784
Linus Torvalds1da177e2005-04-16 15:20:36 -07001785int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
1786{
Andrew Morton22905f72005-11-16 15:07:01 -08001787 int ret;
1788
Linus Torvalds1da177e2005-04-16 15:20:36 -07001789 if (wbc->nr_to_write <= 0)
1790 return 0;
1791 if (mapping->a_ops->writepages)
Peter Zijlstrad08b3852006-09-25 23:30:57 -07001792 ret = mapping->a_ops->writepages(mapping, wbc);
Andrew Morton22905f72005-11-16 15:07:01 -08001793 else
1794 ret = generic_writepages(mapping, wbc);
Andrew Morton22905f72005-11-16 15:07:01 -08001795 return ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001796}
1797
1798/**
1799 * write_one_page - write out a single page and optionally wait on I/O
Martin Waitz67be2dd2005-05-01 08:59:26 -07001800 * @page: the page to write
1801 * @wait: if true, wait on writeout
Linus Torvalds1da177e2005-04-16 15:20:36 -07001802 *
1803 * The page must be locked by the caller and will be unlocked upon return.
1804 *
1805 * write_one_page() returns a negative error code if I/O failed.
1806 */
1807int write_one_page(struct page *page, int wait)
1808{
1809 struct address_space *mapping = page->mapping;
1810 int ret = 0;
1811 struct writeback_control wbc = {
1812 .sync_mode = WB_SYNC_ALL,
1813 .nr_to_write = 1,
1814 };
1815
1816 BUG_ON(!PageLocked(page));
1817
1818 if (wait)
1819 wait_on_page_writeback(page);
1820
1821 if (clear_page_dirty_for_io(page)) {
1822 page_cache_get(page);
1823 ret = mapping->a_ops->writepage(page, &wbc);
1824 if (ret == 0 && wait) {
1825 wait_on_page_writeback(page);
1826 if (PageError(page))
1827 ret = -EIO;
1828 }
1829 page_cache_release(page);
1830 } else {
1831 unlock_page(page);
1832 }
1833 return ret;
1834}
1835EXPORT_SYMBOL(write_one_page);
1836
1837/*
Ken Chen76719322007-02-10 01:43:15 -08001838 * For address_spaces which do not use buffers nor write back.
1839 */
1840int __set_page_dirty_no_writeback(struct page *page)
1841{
1842 if (!PageDirty(page))
Bob Liuc3f0da62011-01-13 15:45:49 -08001843 return !TestSetPageDirty(page);
Ken Chen76719322007-02-10 01:43:15 -08001844 return 0;
1845}
1846
1847/*
Edward Shishkine3a7cca2009-03-31 15:19:39 -07001848 * Helper function for set_page_dirty family.
1849 * NOTE: This relies on being atomic wrt interrupts.
1850 */
1851void account_page_dirtied(struct page *page, struct address_space *mapping)
1852{
1853 if (mapping_cap_account_dirty(mapping)) {
1854 __inc_zone_page_state(page, NR_FILE_DIRTY);
Michael Rubinea941f02010-10-26 14:21:35 -07001855 __inc_zone_page_state(page, NR_DIRTIED);
Edward Shishkine3a7cca2009-03-31 15:19:39 -07001856 __inc_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
Wu Fengguangc8e28ce2011-01-23 10:07:47 -06001857 __inc_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
Edward Shishkine3a7cca2009-03-31 15:19:39 -07001858 task_io_account_write(PAGE_CACHE_SIZE);
Wu Fengguangd3bc1fe2011-04-14 07:52:37 -06001859 current->nr_dirtied++;
1860 this_cpu_inc(bdp_ratelimits);
Edward Shishkine3a7cca2009-03-31 15:19:39 -07001861 }
1862}
Michael Rubin679ceac2010-08-20 02:31:26 -07001863EXPORT_SYMBOL(account_page_dirtied);
Edward Shishkine3a7cca2009-03-31 15:19:39 -07001864
1865/*
Michael Rubinf629d1c2010-10-26 14:21:33 -07001866 * Helper function for set_page_writeback family.
1867 * NOTE: Unlike account_page_dirtied this does not rely on being atomic
1868 * wrt interrupts.
1869 */
1870void account_page_writeback(struct page *page)
1871{
1872 inc_zone_page_state(page, NR_WRITEBACK);
1873}
1874EXPORT_SYMBOL(account_page_writeback);
1875
1876/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001877 * For address_spaces which do not use buffers. Just tag the page as dirty in
1878 * its radix tree.
1879 *
1880 * This is also used when a single buffer is being dirtied: we want to set the
1881 * page dirty in that case, but not all the buffers. This is a "bottom-up"
1882 * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
1883 *
1884 * Most callers have locked the page, which pins the address_space in memory.
1885 * But zap_pte_range() does not lock the page, however in that case the
1886 * mapping is pinned by the vma's ->vm_file reference.
1887 *
1888 * We take care to handle the case where the page was truncated from the
Simon Arlott183ff222007-10-20 01:27:18 +02001889 * mapping by re-checking page_mapping() inside tree_lock.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001890 */
1891int __set_page_dirty_nobuffers(struct page *page)
1892{
Linus Torvalds1da177e2005-04-16 15:20:36 -07001893 if (!TestSetPageDirty(page)) {
1894 struct address_space *mapping = page_mapping(page);
1895 struct address_space *mapping2;
1896
Andrew Morton8c085402006-12-10 02:19:24 -08001897 if (!mapping)
1898 return 1;
1899
Nick Piggin19fd6232008-07-25 19:45:32 -07001900 spin_lock_irq(&mapping->tree_lock);
Andrew Morton8c085402006-12-10 02:19:24 -08001901 mapping2 = page_mapping(page);
1902 if (mapping2) { /* Race with truncate? */
1903 BUG_ON(mapping2 != mapping);
Nick Piggin787d2212007-07-17 04:03:34 -07001904 WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
Edward Shishkine3a7cca2009-03-31 15:19:39 -07001905 account_page_dirtied(page, mapping);
Andrew Morton8c085402006-12-10 02:19:24 -08001906 radix_tree_tag_set(&mapping->page_tree,
1907 page_index(page), PAGECACHE_TAG_DIRTY);
1908 }
Nick Piggin19fd6232008-07-25 19:45:32 -07001909 spin_unlock_irq(&mapping->tree_lock);
Andrew Morton8c085402006-12-10 02:19:24 -08001910 if (mapping->host) {
1911 /* !PageAnon && !swapper_space */
1912 __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001913 }
Andrew Morton4741c9f2006-03-24 03:18:11 -08001914 return 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001915 }
Andrew Morton4741c9f2006-03-24 03:18:11 -08001916 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001917}
1918EXPORT_SYMBOL(__set_page_dirty_nobuffers);
1919
1920/*
Wu Fengguang2f800fb2011-08-08 15:22:00 -06001921 * Call this whenever redirtying a page, to de-account the dirty counters
1922 * (NR_DIRTIED, BDI_DIRTIED, tsk->nr_dirtied), so that they match the written
1923 * counters (NR_WRITTEN, BDI_WRITTEN) in long term. The mismatches will lead to
1924 * systematic errors in balanced_dirty_ratelimit and the dirty pages position
1925 * control.
1926 */
1927void account_page_redirty(struct page *page)
1928{
1929 struct address_space *mapping = page->mapping;
1930 if (mapping && mapping_cap_account_dirty(mapping)) {
1931 current->nr_dirtied--;
1932 dec_zone_page_state(page, NR_DIRTIED);
1933 dec_bdi_stat(mapping->backing_dev_info, BDI_DIRTIED);
1934 }
1935}
1936EXPORT_SYMBOL(account_page_redirty);
1937
1938/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001939 * When a writepage implementation decides that it doesn't want to write this
1940 * page for some reason, it should redirty the locked page via
1941 * redirty_page_for_writepage() and it should then unlock the page and return 0
1942 */
1943int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
1944{
1945 wbc->pages_skipped++;
Wu Fengguang2f800fb2011-08-08 15:22:00 -06001946 account_page_redirty(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001947 return __set_page_dirty_nobuffers(page);
1948}
1949EXPORT_SYMBOL(redirty_page_for_writepage);
1950
1951/*
Wu Fengguang6746aff2009-09-16 11:50:14 +02001952 * Dirty a page.
1953 *
1954 * For pages with a mapping this should be done under the page lock
1955 * for the benefit of asynchronous memory errors who prefer a consistent
1956 * dirty state. This rule can be broken in some special cases,
1957 * but should be better not to.
1958 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07001959 * If the mapping doesn't provide a set_page_dirty a_op, then
1960 * just fall through and assume that it wants buffer_heads.
1961 */
Nick Piggin1cf6e7d2009-02-18 14:48:18 -08001962int set_page_dirty(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001963{
1964 struct address_space *mapping = page_mapping(page);
1965
1966 if (likely(mapping)) {
1967 int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
Minchan Kim278df9f2011-03-22 16:32:54 -07001968 /*
1969 * readahead/lru_deactivate_page could remain
1970 * PG_readahead/PG_reclaim due to race with end_page_writeback
1971 * About readahead, if the page is written, the flags would be
1972 * reset. So no problem.
1973 * About lru_deactivate_page, if the page is redirty, the flag
1974 * will be reset. So no problem. but if the page is used by readahead
1975 * it will confuse readahead and make it restart the size rampup
1976 * process. But it's a trivial problem.
1977 */
1978 ClearPageReclaim(page);
David Howells93614012006-09-30 20:45:40 +02001979#ifdef CONFIG_BLOCK
1980 if (!spd)
1981 spd = __set_page_dirty_buffers;
1982#endif
1983 return (*spd)(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001984 }
Andrew Morton4741c9f2006-03-24 03:18:11 -08001985 if (!PageDirty(page)) {
1986 if (!TestSetPageDirty(page))
1987 return 1;
1988 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001989 return 0;
1990}
1991EXPORT_SYMBOL(set_page_dirty);
1992
1993/*
1994 * set_page_dirty() is racy if the caller has no reference against
1995 * page->mapping->host, and if the page is unlocked. This is because another
1996 * CPU could truncate the page off the mapping and then free the mapping.
1997 *
1998 * Usually, the page _is_ locked, or the caller is a user-space process which
1999 * holds a reference on the inode by having an open file.
2000 *
2001 * In other cases, the page should be locked before running set_page_dirty().
2002 */
2003int set_page_dirty_lock(struct page *page)
2004{
2005 int ret;
2006
Jens Axboe7eaceac2011-03-10 08:52:07 +01002007 lock_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002008 ret = set_page_dirty(page);
2009 unlock_page(page);
2010 return ret;
2011}
2012EXPORT_SYMBOL(set_page_dirty_lock);
2013
2014/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07002015 * Clear a page's dirty flag, while caring for dirty memory accounting.
2016 * Returns true if the page was previously dirty.
2017 *
2018 * This is for preparing to put the page under writeout. We leave the page
2019 * tagged as dirty in the radix tree so that a concurrent write-for-sync
2020 * can discover it via a PAGECACHE_TAG_DIRTY walk. The ->writepage
2021 * implementation will run either set_page_writeback() or set_page_dirty(),
2022 * at which stage we bring the page's dirty flag and radix-tree dirty tag
2023 * back into sync.
2024 *
2025 * This incoherency between the page's dirty flag and radix-tree tag is
2026 * unfortunate, but it only exists while the page is locked.
2027 */
2028int clear_page_dirty_for_io(struct page *page)
2029{
2030 struct address_space *mapping = page_mapping(page);
2031
Nick Piggin79352892007-07-19 01:47:22 -07002032 BUG_ON(!PageLocked(page));
2033
Linus Torvalds7658cc22006-12-29 10:00:58 -08002034 if (mapping && mapping_cap_account_dirty(mapping)) {
2035 /*
2036 * Yes, Virginia, this is indeed insane.
2037 *
2038 * We use this sequence to make sure that
2039 * (a) we account for dirty stats properly
2040 * (b) we tell the low-level filesystem to
2041 * mark the whole page dirty if it was
2042 * dirty in a pagetable. Only to then
2043 * (c) clean the page again and return 1 to
2044 * cause the writeback.
2045 *
2046 * This way we avoid all nasty races with the
2047 * dirty bit in multiple places and clearing
2048 * them concurrently from different threads.
2049 *
2050 * Note! Normally the "set_page_dirty(page)"
2051 * has no effect on the actual dirty bit - since
2052 * that will already usually be set. But we
2053 * need the side effects, and it can help us
2054 * avoid races.
2055 *
2056 * We basically use the page "master dirty bit"
2057 * as a serialization point for all the different
2058 * threads doing their things.
Linus Torvalds7658cc22006-12-29 10:00:58 -08002059 */
2060 if (page_mkclean(page))
2061 set_page_dirty(page);
Nick Piggin79352892007-07-19 01:47:22 -07002062 /*
2063 * We carefully synchronise fault handlers against
2064 * installing a dirty pte and marking the page dirty
2065 * at this point. We do this by having them hold the
2066 * page lock at some point after installing their
2067 * pte, but before marking the page dirty.
2068 * Pages are always locked coming in here, so we get
2069 * the desired exclusion. See mm/memory.c:do_wp_page()
2070 * for more comments.
2071 */
Linus Torvalds7658cc22006-12-29 10:00:58 -08002072 if (TestClearPageDirty(page)) {
Andrew Morton8c085402006-12-10 02:19:24 -08002073 dec_zone_page_state(page, NR_FILE_DIRTY);
Peter Zijlstrac9e51e42007-10-16 23:25:47 -07002074 dec_bdi_stat(mapping->backing_dev_info,
2075 BDI_RECLAIMABLE);
Linus Torvalds7658cc22006-12-29 10:00:58 -08002076 return 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002077 }
Linus Torvalds7658cc22006-12-29 10:00:58 -08002078 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002079 }
Linus Torvalds7658cc22006-12-29 10:00:58 -08002080 return TestClearPageDirty(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002081}
Hans Reiser58bb01a2005-11-18 01:10:53 -08002082EXPORT_SYMBOL(clear_page_dirty_for_io);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002083
2084int test_clear_page_writeback(struct page *page)
2085{
2086 struct address_space *mapping = page_mapping(page);
2087 int ret;
2088
2089 if (mapping) {
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002090 struct backing_dev_info *bdi = mapping->backing_dev_info;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002091 unsigned long flags;
2092
Nick Piggin19fd6232008-07-25 19:45:32 -07002093 spin_lock_irqsave(&mapping->tree_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002094 ret = TestClearPageWriteback(page);
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002095 if (ret) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002096 radix_tree_tag_clear(&mapping->page_tree,
2097 page_index(page),
2098 PAGECACHE_TAG_WRITEBACK);
Miklos Szeredie4ad08f2008-04-30 00:54:37 -07002099 if (bdi_cap_account_writeback(bdi)) {
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002100 __dec_bdi_stat(bdi, BDI_WRITEBACK);
Peter Zijlstra04fbfdc2007-10-16 23:25:50 -07002101 __bdi_writeout_inc(bdi);
2102 }
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002103 }
Nick Piggin19fd6232008-07-25 19:45:32 -07002104 spin_unlock_irqrestore(&mapping->tree_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002105 } else {
2106 ret = TestClearPageWriteback(page);
2107 }
Wu Fengguang99b12e32011-07-25 17:12:37 -07002108 if (ret) {
Andrew Mortond688abf2007-07-19 01:49:17 -07002109 dec_zone_page_state(page, NR_WRITEBACK);
Wu Fengguang99b12e32011-07-25 17:12:37 -07002110 inc_zone_page_state(page, NR_WRITTEN);
2111 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002112 return ret;
2113}
2114
2115int test_set_page_writeback(struct page *page)
2116{
2117 struct address_space *mapping = page_mapping(page);
2118 int ret;
2119
2120 if (mapping) {
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002121 struct backing_dev_info *bdi = mapping->backing_dev_info;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002122 unsigned long flags;
2123
Nick Piggin19fd6232008-07-25 19:45:32 -07002124 spin_lock_irqsave(&mapping->tree_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002125 ret = TestSetPageWriteback(page);
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002126 if (!ret) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002127 radix_tree_tag_set(&mapping->page_tree,
2128 page_index(page),
2129 PAGECACHE_TAG_WRITEBACK);
Miklos Szeredie4ad08f2008-04-30 00:54:37 -07002130 if (bdi_cap_account_writeback(bdi))
Peter Zijlstra69cb51d2007-10-16 23:25:48 -07002131 __inc_bdi_stat(bdi, BDI_WRITEBACK);
2132 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002133 if (!PageDirty(page))
2134 radix_tree_tag_clear(&mapping->page_tree,
2135 page_index(page),
2136 PAGECACHE_TAG_DIRTY);
Jan Karaf446daae2010-08-09 17:19:12 -07002137 radix_tree_tag_clear(&mapping->page_tree,
2138 page_index(page),
2139 PAGECACHE_TAG_TOWRITE);
Nick Piggin19fd6232008-07-25 19:45:32 -07002140 spin_unlock_irqrestore(&mapping->tree_lock, flags);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002141 } else {
2142 ret = TestSetPageWriteback(page);
2143 }
Andrew Mortond688abf2007-07-19 01:49:17 -07002144 if (!ret)
Michael Rubinf629d1c2010-10-26 14:21:33 -07002145 account_page_writeback(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002146 return ret;
2147
2148}
2149EXPORT_SYMBOL(test_set_page_writeback);
2150
2151/*
Nick Piggin00128182007-10-16 01:24:40 -07002152 * Return true if any of the pages in the mapping are marked with the
Linus Torvalds1da177e2005-04-16 15:20:36 -07002153 * passed tag.
2154 */
2155int mapping_tagged(struct address_space *mapping, int tag)
2156{
Konstantin Khlebnikov72c47832011-07-25 17:12:31 -07002157 return radix_tree_tagged(&mapping->page_tree, tag);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002158}
2159EXPORT_SYMBOL(mapping_tagged);