• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * mm/page-writeback.c
4  *
5  * Copyright (C) 2002, Linus Torvalds.
6  * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
7  *
8  * Contains functions related to writing back dirty pages at the
9  * address_space level.
10  *
11  * 10Apr2002	Andrew Morton
12  *		Initial version
13  */
14 
15 #include <linux/kernel.h>
16 #include <linux/export.h>
17 #include <linux/spinlock.h>
18 #include <linux/fs.h>
19 #include <linux/mm.h>
20 #include <linux/swap.h>
21 #include <linux/slab.h>
22 #include <linux/pagemap.h>
23 #include <linux/writeback.h>
24 #include <linux/init.h>
25 #include <linux/backing-dev.h>
26 #include <linux/task_io_accounting_ops.h>
27 #include <linux/blkdev.h>
28 #include <linux/mpage.h>
29 #include <linux/rmap.h>
30 #include <linux/percpu.h>
31 #include <linux/smp.h>
32 #include <linux/sysctl.h>
33 #include <linux/cpu.h>
34 #include <linux/syscalls.h>
35 #include <linux/buffer_head.h> /* __set_page_dirty_buffers */
36 #include <linux/pagevec.h>
37 #include <linux/timer.h>
38 #include <linux/sched/rt.h>
39 #include <linux/sched/signal.h>
40 #include <linux/mm_inline.h>
41 #include <trace/events/writeback.h>
42 
43 #include "internal.h"
44 
45 /*
46  * Sleep at most 200ms at a time in balance_dirty_pages().
47  */
48 #define MAX_PAUSE		max(HZ/5, 1)
49 
50 /*
51  * Try to keep balance_dirty_pages() call intervals higher than this many pages
52  * by raising pause time to max_pause when falls below it.
53  */
54 #define DIRTY_POLL_THRESH	(128 >> (PAGE_SHIFT - 10))
55 
56 /*
57  * Estimate write bandwidth at 200ms intervals.
58  */
59 #define BANDWIDTH_INTERVAL	max(HZ/5, 1)
60 
61 #define RATELIMIT_CALC_SHIFT	10
62 
63 /*
64  * After a CPU has dirtied this many pages, balance_dirty_pages_ratelimited
65  * will look to see if it needs to force writeback or throttling.
66  */
67 static long ratelimit_pages = 32;
68 
69 /* The following parameters are exported via /proc/sys/vm */
70 
71 /*
72  * Start background writeback (via writeback threads) at this percentage
73  */
74 int dirty_background_ratio = 10;
75 
76 /*
77  * dirty_background_bytes starts at 0 (disabled) so that it is a function of
78  * dirty_background_ratio * the amount of dirtyable memory
79  */
80 unsigned long dirty_background_bytes;
81 
82 /*
83  * free highmem will not be subtracted from the total free memory
84  * for calculating free ratios if vm_highmem_is_dirtyable is true
85  */
86 int vm_highmem_is_dirtyable;
87 
88 /*
89  * The generator of dirty data starts writeback at this percentage
90  */
91 int vm_dirty_ratio = 20;
92 
93 /*
94  * vm_dirty_bytes starts at 0 (disabled) so that it is a function of
95  * vm_dirty_ratio * the amount of dirtyable memory
96  */
97 unsigned long vm_dirty_bytes;
98 
99 /*
100  * The interval between `kupdate'-style writebacks
101  */
102 unsigned int dirty_writeback_interval = 5 * 100; /* centiseconds */
103 
104 EXPORT_SYMBOL_GPL(dirty_writeback_interval);
105 
106 /*
107  * The longest time for which data is allowed to remain dirty
108  */
109 unsigned int dirty_expire_interval = 30 * 100; /* centiseconds */
110 
111 /*
112  * Flag that puts the machine in "laptop mode". Doubles as a timeout in jiffies:
113  * a full sync is triggered after this time elapses without any disk activity.
114  */
115 int laptop_mode;
116 
117 EXPORT_SYMBOL(laptop_mode);
118 
119 /* End of sysctl-exported parameters */
120 
121 struct wb_domain global_wb_domain;
122 
123 /* consolidated parameters for balance_dirty_pages() and its subroutines */
124 struct dirty_throttle_control {
125 #ifdef CONFIG_CGROUP_WRITEBACK
126 	struct wb_domain	*dom;
127 	struct dirty_throttle_control *gdtc;	/* only set in memcg dtc's */
128 #endif
129 	struct bdi_writeback	*wb;
130 	struct fprop_local_percpu *wb_completions;
131 
132 	unsigned long		avail;		/* dirtyable */
133 	unsigned long		dirty;		/* file_dirty + write + nfs */
134 	unsigned long		thresh;		/* dirty threshold */
135 	unsigned long		bg_thresh;	/* dirty background threshold */
136 
137 	unsigned long		wb_dirty;	/* per-wb counterparts */
138 	unsigned long		wb_thresh;
139 	unsigned long		wb_bg_thresh;
140 
141 	unsigned long		pos_ratio;
142 };
143 
144 /*
145  * Length of period for aging writeout fractions of bdis. This is an
146  * arbitrarily chosen number. The longer the period, the slower fractions will
147  * reflect changes in current writeout rate.
148  */
149 #define VM_COMPLETIONS_PERIOD_LEN (3*HZ)
150 
151 #ifdef CONFIG_CGROUP_WRITEBACK
152 
153 #define GDTC_INIT(__wb)		.wb = (__wb),				\
154 				.dom = &global_wb_domain,		\
155 				.wb_completions = &(__wb)->completions
156 
157 #define GDTC_INIT_NO_WB		.dom = &global_wb_domain
158 
159 #define MDTC_INIT(__wb, __gdtc)	.wb = (__wb),				\
160 				.dom = mem_cgroup_wb_domain(__wb),	\
161 				.wb_completions = &(__wb)->memcg_completions, \
162 				.gdtc = __gdtc
163 
mdtc_valid(struct dirty_throttle_control * dtc)164 static bool mdtc_valid(struct dirty_throttle_control *dtc)
165 {
166 	return dtc->dom;
167 }
168 
dtc_dom(struct dirty_throttle_control * dtc)169 static struct wb_domain *dtc_dom(struct dirty_throttle_control *dtc)
170 {
171 	return dtc->dom;
172 }
173 
mdtc_gdtc(struct dirty_throttle_control * mdtc)174 static struct dirty_throttle_control *mdtc_gdtc(struct dirty_throttle_control *mdtc)
175 {
176 	return mdtc->gdtc;
177 }
178 
wb_memcg_completions(struct bdi_writeback * wb)179 static struct fprop_local_percpu *wb_memcg_completions(struct bdi_writeback *wb)
180 {
181 	return &wb->memcg_completions;
182 }
183 
wb_min_max_ratio(struct bdi_writeback * wb,unsigned long * minp,unsigned long * maxp)184 static void wb_min_max_ratio(struct bdi_writeback *wb,
185 			     unsigned long *minp, unsigned long *maxp)
186 {
187 	unsigned long this_bw = wb->avg_write_bandwidth;
188 	unsigned long tot_bw = atomic_long_read(&wb->bdi->tot_write_bandwidth);
189 	unsigned long long min = wb->bdi->min_ratio;
190 	unsigned long long max = wb->bdi->max_ratio;
191 
192 	/*
193 	 * @wb may already be clean by the time control reaches here and
194 	 * the total may not include its bw.
195 	 */
196 	if (this_bw < tot_bw) {
197 		if (min) {
198 			min *= this_bw;
199 			min = div64_ul(min, tot_bw);
200 		}
201 		if (max < 100) {
202 			max *= this_bw;
203 			max = div64_ul(max, tot_bw);
204 		}
205 	}
206 
207 	*minp = min;
208 	*maxp = max;
209 }
210 
211 #else	/* CONFIG_CGROUP_WRITEBACK */
212 
213 #define GDTC_INIT(__wb)		.wb = (__wb),                           \
214 				.wb_completions = &(__wb)->completions
215 #define GDTC_INIT_NO_WB
216 #define MDTC_INIT(__wb, __gdtc)
217 
mdtc_valid(struct dirty_throttle_control * dtc)218 static bool mdtc_valid(struct dirty_throttle_control *dtc)
219 {
220 	return false;
221 }
222 
dtc_dom(struct dirty_throttle_control * dtc)223 static struct wb_domain *dtc_dom(struct dirty_throttle_control *dtc)
224 {
225 	return &global_wb_domain;
226 }
227 
mdtc_gdtc(struct dirty_throttle_control * mdtc)228 static struct dirty_throttle_control *mdtc_gdtc(struct dirty_throttle_control *mdtc)
229 {
230 	return NULL;
231 }
232 
wb_memcg_completions(struct bdi_writeback * wb)233 static struct fprop_local_percpu *wb_memcg_completions(struct bdi_writeback *wb)
234 {
235 	return NULL;
236 }
237 
wb_min_max_ratio(struct bdi_writeback * wb,unsigned long * minp,unsigned long * maxp)238 static void wb_min_max_ratio(struct bdi_writeback *wb,
239 			     unsigned long *minp, unsigned long *maxp)
240 {
241 	*minp = wb->bdi->min_ratio;
242 	*maxp = wb->bdi->max_ratio;
243 }
244 
245 #endif	/* CONFIG_CGROUP_WRITEBACK */
246 
247 /*
248  * In a memory zone, there is a certain amount of pages we consider
249  * available for the page cache, which is essentially the number of
250  * free and reclaimable pages, minus some zone reserves to protect
251  * lowmem and the ability to uphold the zone's watermarks without
252  * requiring writeback.
253  *
254  * This number of dirtyable pages is the base value of which the
255  * user-configurable dirty ratio is the effective number of pages that
256  * are allowed to be actually dirtied.  Per individual zone, or
257  * globally by using the sum of dirtyable pages over all zones.
258  *
259  * Because the user is allowed to specify the dirty limit globally as
260  * absolute number of bytes, calculating the per-zone dirty limit can
261  * require translating the configured limit into a percentage of
262  * global dirtyable memory first.
263  */
264 
265 /**
266  * node_dirtyable_memory - number of dirtyable pages in a node
267  * @pgdat: the node
268  *
269  * Return: the node's number of pages potentially available for dirty
270  * page cache.  This is the base value for the per-node dirty limits.
271  */
node_dirtyable_memory(struct pglist_data * pgdat)272 static unsigned long node_dirtyable_memory(struct pglist_data *pgdat)
273 {
274 	unsigned long nr_pages = 0;
275 	int z;
276 
277 	for (z = 0; z < MAX_NR_ZONES; z++) {
278 		struct zone *zone = pgdat->node_zones + z;
279 
280 		if (!populated_zone(zone))
281 			continue;
282 
283 		nr_pages += zone_page_state(zone, NR_FREE_PAGES);
284 	}
285 
286 	/*
287 	 * Pages reserved for the kernel should not be considered
288 	 * dirtyable, to prevent a situation where reclaim has to
289 	 * clean pages in order to balance the zones.
290 	 */
291 	nr_pages -= min(nr_pages, pgdat->totalreserve_pages);
292 
293 	nr_pages += node_page_state(pgdat, NR_INACTIVE_FILE);
294 	nr_pages += node_page_state(pgdat, NR_ACTIVE_FILE);
295 
296 	return nr_pages;
297 }
298 
highmem_dirtyable_memory(unsigned long total)299 static unsigned long highmem_dirtyable_memory(unsigned long total)
300 {
301 #ifdef CONFIG_HIGHMEM
302 	int node;
303 	unsigned long x = 0;
304 	int i;
305 
306 	for_each_node_state(node, N_HIGH_MEMORY) {
307 		for (i = ZONE_NORMAL + 1; i < MAX_NR_ZONES; i++) {
308 			struct zone *z;
309 			unsigned long nr_pages;
310 
311 			if (!is_highmem_idx(i))
312 				continue;
313 
314 			z = &NODE_DATA(node)->node_zones[i];
315 			if (!populated_zone(z))
316 				continue;
317 
318 			nr_pages = zone_page_state(z, NR_FREE_PAGES);
319 			/* watch for underflows */
320 			nr_pages -= min(nr_pages, high_wmark_pages(z));
321 			nr_pages += zone_page_state(z, NR_ZONE_INACTIVE_FILE);
322 			nr_pages += zone_page_state(z, NR_ZONE_ACTIVE_FILE);
323 			x += nr_pages;
324 		}
325 	}
326 
327 	/*
328 	 * Unreclaimable memory (kernel memory or anonymous memory
329 	 * without swap) can bring down the dirtyable pages below
330 	 * the zone's dirty balance reserve and the above calculation
331 	 * will underflow.  However we still want to add in nodes
332 	 * which are below threshold (negative values) to get a more
333 	 * accurate calculation but make sure that the total never
334 	 * underflows.
335 	 */
336 	if ((long)x < 0)
337 		x = 0;
338 
339 	/*
340 	 * Make sure that the number of highmem pages is never larger
341 	 * than the number of the total dirtyable memory. This can only
342 	 * occur in very strange VM situations but we want to make sure
343 	 * that this does not occur.
344 	 */
345 	return min(x, total);
346 #else
347 	return 0;
348 #endif
349 }
350 
351 /**
352  * global_dirtyable_memory - number of globally dirtyable pages
353  *
354  * Return: the global number of pages potentially available for dirty
355  * page cache.  This is the base value for the global dirty limits.
356  */
global_dirtyable_memory(void)357 static unsigned long global_dirtyable_memory(void)
358 {
359 	unsigned long x;
360 
361 	x = global_zone_page_state(NR_FREE_PAGES);
362 	/*
363 	 * Pages reserved for the kernel should not be considered
364 	 * dirtyable, to prevent a situation where reclaim has to
365 	 * clean pages in order to balance the zones.
366 	 */
367 	x -= min(x, totalreserve_pages);
368 
369 	x += global_node_page_state(NR_INACTIVE_FILE);
370 	x += global_node_page_state(NR_ACTIVE_FILE);
371 
372 	if (!vm_highmem_is_dirtyable)
373 		x -= highmem_dirtyable_memory(x);
374 
375 	return x + 1;	/* Ensure that we never return 0 */
376 }
377 
378 /**
379  * domain_dirty_limits - calculate thresh and bg_thresh for a wb_domain
380  * @dtc: dirty_throttle_control of interest
381  *
382  * Calculate @dtc->thresh and ->bg_thresh considering
383  * vm_dirty_{bytes|ratio} and dirty_background_{bytes|ratio}.  The caller
384  * must ensure that @dtc->avail is set before calling this function.  The
385  * dirty limits will be lifted by 1/4 for real-time tasks.
386  */
domain_dirty_limits(struct dirty_throttle_control * dtc)387 static void domain_dirty_limits(struct dirty_throttle_control *dtc)
388 {
389 	const unsigned long available_memory = dtc->avail;
390 	struct dirty_throttle_control *gdtc = mdtc_gdtc(dtc);
391 	unsigned long bytes = vm_dirty_bytes;
392 	unsigned long bg_bytes = dirty_background_bytes;
393 	/* convert ratios to per-PAGE_SIZE for higher precision */
394 	unsigned long ratio = (vm_dirty_ratio * PAGE_SIZE) / 100;
395 	unsigned long bg_ratio = (dirty_background_ratio * PAGE_SIZE) / 100;
396 	unsigned long thresh;
397 	unsigned long bg_thresh;
398 	struct task_struct *tsk;
399 
400 	/* gdtc is !NULL iff @dtc is for memcg domain */
401 	if (gdtc) {
402 		unsigned long global_avail = gdtc->avail;
403 
404 		/*
405 		 * The byte settings can't be applied directly to memcg
406 		 * domains.  Convert them to ratios by scaling against
407 		 * globally available memory.  As the ratios are in
408 		 * per-PAGE_SIZE, they can be obtained by dividing bytes by
409 		 * number of pages.
410 		 */
411 		if (bytes)
412 			ratio = min(DIV_ROUND_UP(bytes, global_avail),
413 				    PAGE_SIZE);
414 		if (bg_bytes)
415 			bg_ratio = min(DIV_ROUND_UP(bg_bytes, global_avail),
416 				       PAGE_SIZE);
417 		bytes = bg_bytes = 0;
418 	}
419 
420 	if (bytes)
421 		thresh = DIV_ROUND_UP(bytes, PAGE_SIZE);
422 	else
423 		thresh = (ratio * available_memory) / PAGE_SIZE;
424 
425 	if (bg_bytes)
426 		bg_thresh = DIV_ROUND_UP(bg_bytes, PAGE_SIZE);
427 	else
428 		bg_thresh = (bg_ratio * available_memory) / PAGE_SIZE;
429 
430 	if (bg_thresh >= thresh)
431 		bg_thresh = thresh / 2;
432 	tsk = current;
433 	if (rt_task(tsk)) {
434 		bg_thresh += bg_thresh / 4 + global_wb_domain.dirty_limit / 32;
435 		thresh += thresh / 4 + global_wb_domain.dirty_limit / 32;
436 	}
437 	dtc->thresh = thresh;
438 	dtc->bg_thresh = bg_thresh;
439 
440 	/* we should eventually report the domain in the TP */
441 	if (!gdtc)
442 		trace_global_dirty_state(bg_thresh, thresh);
443 }
444 
445 /**
446  * global_dirty_limits - background-writeback and dirty-throttling thresholds
447  * @pbackground: out parameter for bg_thresh
448  * @pdirty: out parameter for thresh
449  *
450  * Calculate bg_thresh and thresh for global_wb_domain.  See
451  * domain_dirty_limits() for details.
452  */
global_dirty_limits(unsigned long * pbackground,unsigned long * pdirty)453 void global_dirty_limits(unsigned long *pbackground, unsigned long *pdirty)
454 {
455 	struct dirty_throttle_control gdtc = { GDTC_INIT_NO_WB };
456 
457 	gdtc.avail = global_dirtyable_memory();
458 	domain_dirty_limits(&gdtc);
459 
460 	*pbackground = gdtc.bg_thresh;
461 	*pdirty = gdtc.thresh;
462 }
463 
464 /**
465  * node_dirty_limit - maximum number of dirty pages allowed in a node
466  * @pgdat: the node
467  *
468  * Return: the maximum number of dirty pages allowed in a node, based
469  * on the node's dirtyable memory.
470  */
node_dirty_limit(struct pglist_data * pgdat)471 static unsigned long node_dirty_limit(struct pglist_data *pgdat)
472 {
473 	unsigned long node_memory = node_dirtyable_memory(pgdat);
474 	struct task_struct *tsk = current;
475 	unsigned long dirty;
476 
477 	if (vm_dirty_bytes)
478 		dirty = DIV_ROUND_UP(vm_dirty_bytes, PAGE_SIZE) *
479 			node_memory / global_dirtyable_memory();
480 	else
481 		dirty = vm_dirty_ratio * node_memory / 100;
482 
483 	if (rt_task(tsk))
484 		dirty += dirty / 4;
485 
486 	return dirty;
487 }
488 
489 /**
490  * node_dirty_ok - tells whether a node is within its dirty limits
491  * @pgdat: the node to check
492  *
493  * Return: %true when the dirty pages in @pgdat are within the node's
494  * dirty limit, %false if the limit is exceeded.
495  */
node_dirty_ok(struct pglist_data * pgdat)496 bool node_dirty_ok(struct pglist_data *pgdat)
497 {
498 	unsigned long limit = node_dirty_limit(pgdat);
499 	unsigned long nr_pages = 0;
500 
501 	nr_pages += node_page_state(pgdat, NR_FILE_DIRTY);
502 	nr_pages += node_page_state(pgdat, NR_WRITEBACK);
503 
504 	return nr_pages <= limit;
505 }
506 
dirty_background_ratio_handler(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)507 int dirty_background_ratio_handler(struct ctl_table *table, int write,
508 		void *buffer, size_t *lenp, loff_t *ppos)
509 {
510 	int ret;
511 
512 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
513 	if (ret == 0 && write)
514 		dirty_background_bytes = 0;
515 	return ret;
516 }
517 
dirty_background_bytes_handler(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)518 int dirty_background_bytes_handler(struct ctl_table *table, int write,
519 		void *buffer, size_t *lenp, loff_t *ppos)
520 {
521 	int ret;
522 
523 	ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
524 	if (ret == 0 && write)
525 		dirty_background_ratio = 0;
526 	return ret;
527 }
528 
dirty_ratio_handler(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)529 int dirty_ratio_handler(struct ctl_table *table, int write, void *buffer,
530 		size_t *lenp, loff_t *ppos)
531 {
532 	int old_ratio = vm_dirty_ratio;
533 	int ret;
534 
535 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
536 	if (ret == 0 && write && vm_dirty_ratio != old_ratio) {
537 		writeback_set_ratelimit();
538 		vm_dirty_bytes = 0;
539 	}
540 	return ret;
541 }
542 
dirty_bytes_handler(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)543 int dirty_bytes_handler(struct ctl_table *table, int write,
544 		void *buffer, size_t *lenp, loff_t *ppos)
545 {
546 	unsigned long old_bytes = vm_dirty_bytes;
547 	int ret;
548 
549 	ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
550 	if (ret == 0 && write && vm_dirty_bytes != old_bytes) {
551 		writeback_set_ratelimit();
552 		vm_dirty_ratio = 0;
553 	}
554 	return ret;
555 }
556 
wp_next_time(unsigned long cur_time)557 static unsigned long wp_next_time(unsigned long cur_time)
558 {
559 	cur_time += VM_COMPLETIONS_PERIOD_LEN;
560 	/* 0 has a special meaning... */
561 	if (!cur_time)
562 		return 1;
563 	return cur_time;
564 }
565 
wb_domain_writeout_inc(struct wb_domain * dom,struct fprop_local_percpu * completions,unsigned int max_prop_frac)566 static void wb_domain_writeout_inc(struct wb_domain *dom,
567 				   struct fprop_local_percpu *completions,
568 				   unsigned int max_prop_frac)
569 {
570 	__fprop_inc_percpu_max(&dom->completions, completions,
571 			       max_prop_frac);
572 	/* First event after period switching was turned off? */
573 	if (unlikely(!dom->period_time)) {
574 		/*
575 		 * We can race with other __bdi_writeout_inc calls here but
576 		 * it does not cause any harm since the resulting time when
577 		 * timer will fire and what is in writeout_period_time will be
578 		 * roughly the same.
579 		 */
580 		dom->period_time = wp_next_time(jiffies);
581 		mod_timer(&dom->period_timer, dom->period_time);
582 	}
583 }
584 
585 /*
586  * Increment @wb's writeout completion count and the global writeout
587  * completion count. Called from test_clear_page_writeback().
588  */
__wb_writeout_inc(struct bdi_writeback * wb)589 static inline void __wb_writeout_inc(struct bdi_writeback *wb)
590 {
591 	struct wb_domain *cgdom;
592 
593 	inc_wb_stat(wb, WB_WRITTEN);
594 	wb_domain_writeout_inc(&global_wb_domain, &wb->completions,
595 			       wb->bdi->max_prop_frac);
596 
597 	cgdom = mem_cgroup_wb_domain(wb);
598 	if (cgdom)
599 		wb_domain_writeout_inc(cgdom, wb_memcg_completions(wb),
600 				       wb->bdi->max_prop_frac);
601 }
602 
wb_writeout_inc(struct bdi_writeback * wb)603 void wb_writeout_inc(struct bdi_writeback *wb)
604 {
605 	unsigned long flags;
606 
607 	local_irq_save(flags);
608 	__wb_writeout_inc(wb);
609 	local_irq_restore(flags);
610 }
611 EXPORT_SYMBOL_GPL(wb_writeout_inc);
612 
613 /*
614  * On idle system, we can be called long after we scheduled because we use
615  * deferred timers so count with missed periods.
616  */
writeout_period(struct timer_list * t)617 static void writeout_period(struct timer_list *t)
618 {
619 	struct wb_domain *dom = from_timer(dom, t, period_timer);
620 	int miss_periods = (jiffies - dom->period_time) /
621 						 VM_COMPLETIONS_PERIOD_LEN;
622 
623 	if (fprop_new_period(&dom->completions, miss_periods + 1)) {
624 		dom->period_time = wp_next_time(dom->period_time +
625 				miss_periods * VM_COMPLETIONS_PERIOD_LEN);
626 		mod_timer(&dom->period_timer, dom->period_time);
627 	} else {
628 		/*
629 		 * Aging has zeroed all fractions. Stop wasting CPU on period
630 		 * updates.
631 		 */
632 		dom->period_time = 0;
633 	}
634 }
635 
wb_domain_init(struct wb_domain * dom,gfp_t gfp)636 int wb_domain_init(struct wb_domain *dom, gfp_t gfp)
637 {
638 	memset(dom, 0, sizeof(*dom));
639 
640 	spin_lock_init(&dom->lock);
641 
642 	timer_setup(&dom->period_timer, writeout_period, TIMER_DEFERRABLE);
643 
644 	dom->dirty_limit_tstamp = jiffies;
645 
646 	return fprop_global_init(&dom->completions, gfp);
647 }
648 
649 #ifdef CONFIG_CGROUP_WRITEBACK
wb_domain_exit(struct wb_domain * dom)650 void wb_domain_exit(struct wb_domain *dom)
651 {
652 	del_timer_sync(&dom->period_timer);
653 	fprop_global_destroy(&dom->completions);
654 }
655 #endif
656 
657 /*
658  * bdi_min_ratio keeps the sum of the minimum dirty shares of all
659  * registered backing devices, which, for obvious reasons, can not
660  * exceed 100%.
661  */
662 static unsigned int bdi_min_ratio;
663 
bdi_set_min_ratio(struct backing_dev_info * bdi,unsigned int min_ratio)664 int bdi_set_min_ratio(struct backing_dev_info *bdi, unsigned int min_ratio)
665 {
666 	int ret = 0;
667 
668 	spin_lock_bh(&bdi_lock);
669 	if (min_ratio > bdi->max_ratio) {
670 		ret = -EINVAL;
671 	} else {
672 		min_ratio -= bdi->min_ratio;
673 		if (bdi_min_ratio + min_ratio < 100) {
674 			bdi_min_ratio += min_ratio;
675 			bdi->min_ratio += min_ratio;
676 		} else {
677 			ret = -EINVAL;
678 		}
679 	}
680 	spin_unlock_bh(&bdi_lock);
681 
682 	return ret;
683 }
684 
bdi_set_max_ratio(struct backing_dev_info * bdi,unsigned max_ratio)685 int bdi_set_max_ratio(struct backing_dev_info *bdi, unsigned max_ratio)
686 {
687 	int ret = 0;
688 
689 	if (max_ratio > 100)
690 		return -EINVAL;
691 
692 	spin_lock_bh(&bdi_lock);
693 	if (bdi->min_ratio > max_ratio) {
694 		ret = -EINVAL;
695 	} else {
696 		bdi->max_ratio = max_ratio;
697 		bdi->max_prop_frac = (FPROP_FRAC_BASE * max_ratio) / 100;
698 	}
699 	spin_unlock_bh(&bdi_lock);
700 
701 	return ret;
702 }
703 EXPORT_SYMBOL(bdi_set_max_ratio);
704 
dirty_freerun_ceiling(unsigned long thresh,unsigned long bg_thresh)705 static unsigned long dirty_freerun_ceiling(unsigned long thresh,
706 					   unsigned long bg_thresh)
707 {
708 	return (thresh + bg_thresh) / 2;
709 }
710 
hard_dirty_limit(struct wb_domain * dom,unsigned long thresh)711 static unsigned long hard_dirty_limit(struct wb_domain *dom,
712 				      unsigned long thresh)
713 {
714 	return max(thresh, dom->dirty_limit);
715 }
716 
717 /*
718  * Memory which can be further allocated to a memcg domain is capped by
719  * system-wide clean memory excluding the amount being used in the domain.
720  */
mdtc_calc_avail(struct dirty_throttle_control * mdtc,unsigned long filepages,unsigned long headroom)721 static void mdtc_calc_avail(struct dirty_throttle_control *mdtc,
722 			    unsigned long filepages, unsigned long headroom)
723 {
724 	struct dirty_throttle_control *gdtc = mdtc_gdtc(mdtc);
725 	unsigned long clean = filepages - min(filepages, mdtc->dirty);
726 	unsigned long global_clean = gdtc->avail - min(gdtc->avail, gdtc->dirty);
727 	unsigned long other_clean = global_clean - min(global_clean, clean);
728 
729 	mdtc->avail = filepages + min(headroom, other_clean);
730 }
731 
732 /**
733  * __wb_calc_thresh - @wb's share of dirty throttling threshold
734  * @dtc: dirty_throttle_context of interest
735  *
736  * Note that balance_dirty_pages() will only seriously take it as a hard limit
737  * when sleeping max_pause per page is not enough to keep the dirty pages under
738  * control. For example, when the device is completely stalled due to some error
739  * conditions, or when there are 1000 dd tasks writing to a slow 10MB/s USB key.
740  * In the other normal situations, it acts more gently by throttling the tasks
741  * more (rather than completely block them) when the wb dirty pages go high.
742  *
743  * It allocates high/low dirty limits to fast/slow devices, in order to prevent
744  * - starving fast devices
745  * - piling up dirty pages (that will take long time to sync) on slow devices
746  *
747  * The wb's share of dirty limit will be adapting to its throughput and
748  * bounded by the bdi->min_ratio and/or bdi->max_ratio parameters, if set.
749  *
750  * Return: @wb's dirty limit in pages. The term "dirty" in the context of
751  * dirty balancing includes all PG_dirty and PG_writeback pages.
752  */
__wb_calc_thresh(struct dirty_throttle_control * dtc)753 static unsigned long __wb_calc_thresh(struct dirty_throttle_control *dtc)
754 {
755 	struct wb_domain *dom = dtc_dom(dtc);
756 	unsigned long thresh = dtc->thresh;
757 	u64 wb_thresh;
758 	unsigned long numerator, denominator;
759 	unsigned long wb_min_ratio, wb_max_ratio;
760 
761 	/*
762 	 * Calculate this BDI's share of the thresh ratio.
763 	 */
764 	fprop_fraction_percpu(&dom->completions, dtc->wb_completions,
765 			      &numerator, &denominator);
766 
767 	wb_thresh = (thresh * (100 - bdi_min_ratio)) / 100;
768 	wb_thresh *= numerator;
769 	wb_thresh = div64_ul(wb_thresh, denominator);
770 
771 	wb_min_max_ratio(dtc->wb, &wb_min_ratio, &wb_max_ratio);
772 
773 	wb_thresh += (thresh * wb_min_ratio) / 100;
774 	if (wb_thresh > (thresh * wb_max_ratio) / 100)
775 		wb_thresh = thresh * wb_max_ratio / 100;
776 
777 	return wb_thresh;
778 }
779 
wb_calc_thresh(struct bdi_writeback * wb,unsigned long thresh)780 unsigned long wb_calc_thresh(struct bdi_writeback *wb, unsigned long thresh)
781 {
782 	struct dirty_throttle_control gdtc = { GDTC_INIT(wb),
783 					       .thresh = thresh };
784 	return __wb_calc_thresh(&gdtc);
785 }
786 
787 /*
788  *                           setpoint - dirty 3
789  *        f(dirty) := 1.0 + (----------------)
790  *                           limit - setpoint
791  *
792  * it's a 3rd order polynomial that subjects to
793  *
794  * (1) f(freerun)  = 2.0 => rampup dirty_ratelimit reasonably fast
795  * (2) f(setpoint) = 1.0 => the balance point
796  * (3) f(limit)    = 0   => the hard limit
797  * (4) df/dx      <= 0	 => negative feedback control
798  * (5) the closer to setpoint, the smaller |df/dx| (and the reverse)
799  *     => fast response on large errors; small oscillation near setpoint
800  */
pos_ratio_polynom(unsigned long setpoint,unsigned long dirty,unsigned long limit)801 static long long pos_ratio_polynom(unsigned long setpoint,
802 					  unsigned long dirty,
803 					  unsigned long limit)
804 {
805 	long long pos_ratio;
806 	long x;
807 
808 	x = div64_s64(((s64)setpoint - (s64)dirty) << RATELIMIT_CALC_SHIFT,
809 		      (limit - setpoint) | 1);
810 	pos_ratio = x;
811 	pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
812 	pos_ratio = pos_ratio * x >> RATELIMIT_CALC_SHIFT;
813 	pos_ratio += 1 << RATELIMIT_CALC_SHIFT;
814 
815 	return clamp(pos_ratio, 0LL, 2LL << RATELIMIT_CALC_SHIFT);
816 }
817 
818 /*
819  * Dirty position control.
820  *
821  * (o) global/bdi setpoints
822  *
823  * We want the dirty pages be balanced around the global/wb setpoints.
824  * When the number of dirty pages is higher/lower than the setpoint, the
825  * dirty position control ratio (and hence task dirty ratelimit) will be
826  * decreased/increased to bring the dirty pages back to the setpoint.
827  *
828  *     pos_ratio = 1 << RATELIMIT_CALC_SHIFT
829  *
830  *     if (dirty < setpoint) scale up   pos_ratio
831  *     if (dirty > setpoint) scale down pos_ratio
832  *
833  *     if (wb_dirty < wb_setpoint) scale up   pos_ratio
834  *     if (wb_dirty > wb_setpoint) scale down pos_ratio
835  *
836  *     task_ratelimit = dirty_ratelimit * pos_ratio >> RATELIMIT_CALC_SHIFT
837  *
838  * (o) global control line
839  *
840  *     ^ pos_ratio
841  *     |
842  *     |            |<===== global dirty control scope ======>|
843  * 2.0 .............*
844  *     |            .*
845  *     |            . *
846  *     |            .   *
847  *     |            .     *
848  *     |            .        *
849  *     |            .            *
850  * 1.0 ................................*
851  *     |            .                  .     *
852  *     |            .                  .          *
853  *     |            .                  .              *
854  *     |            .                  .                 *
855  *     |            .                  .                    *
856  *   0 +------------.------------------.----------------------*------------->
857  *           freerun^          setpoint^                 limit^   dirty pages
858  *
859  * (o) wb control line
860  *
861  *     ^ pos_ratio
862  *     |
863  *     |            *
864  *     |              *
865  *     |                *
866  *     |                  *
867  *     |                    * |<=========== span ============>|
868  * 1.0 .......................*
869  *     |                      . *
870  *     |                      .   *
871  *     |                      .     *
872  *     |                      .       *
873  *     |                      .         *
874  *     |                      .           *
875  *     |                      .             *
876  *     |                      .               *
877  *     |                      .                 *
878  *     |                      .                   *
879  *     |                      .                     *
880  * 1/4 ...............................................* * * * * * * * * * * *
881  *     |                      .                         .
882  *     |                      .                           .
883  *     |                      .                             .
884  *   0 +----------------------.-------------------------------.------------->
885  *                wb_setpoint^                    x_intercept^
886  *
887  * The wb control line won't drop below pos_ratio=1/4, so that wb_dirty can
888  * be smoothly throttled down to normal if it starts high in situations like
889  * - start writing to a slow SD card and a fast disk at the same time. The SD
890  *   card's wb_dirty may rush to many times higher than wb_setpoint.
891  * - the wb dirty thresh drops quickly due to change of JBOD workload
892  */
wb_position_ratio(struct dirty_throttle_control * dtc)893 static void wb_position_ratio(struct dirty_throttle_control *dtc)
894 {
895 	struct bdi_writeback *wb = dtc->wb;
896 	unsigned long write_bw = wb->avg_write_bandwidth;
897 	unsigned long freerun = dirty_freerun_ceiling(dtc->thresh, dtc->bg_thresh);
898 	unsigned long limit = hard_dirty_limit(dtc_dom(dtc), dtc->thresh);
899 	unsigned long wb_thresh = dtc->wb_thresh;
900 	unsigned long x_intercept;
901 	unsigned long setpoint;		/* dirty pages' target balance point */
902 	unsigned long wb_setpoint;
903 	unsigned long span;
904 	long long pos_ratio;		/* for scaling up/down the rate limit */
905 	long x;
906 
907 	dtc->pos_ratio = 0;
908 
909 	if (unlikely(dtc->dirty >= limit))
910 		return;
911 
912 	/*
913 	 * global setpoint
914 	 *
915 	 * See comment for pos_ratio_polynom().
916 	 */
917 	setpoint = (freerun + limit) / 2;
918 	pos_ratio = pos_ratio_polynom(setpoint, dtc->dirty, limit);
919 
920 	/*
921 	 * The strictlimit feature is a tool preventing mistrusted filesystems
922 	 * from growing a large number of dirty pages before throttling. For
923 	 * such filesystems balance_dirty_pages always checks wb counters
924 	 * against wb limits. Even if global "nr_dirty" is under "freerun".
925 	 * This is especially important for fuse which sets bdi->max_ratio to
926 	 * 1% by default. Without strictlimit feature, fuse writeback may
927 	 * consume arbitrary amount of RAM because it is accounted in
928 	 * NR_WRITEBACK_TEMP which is not involved in calculating "nr_dirty".
929 	 *
930 	 * Here, in wb_position_ratio(), we calculate pos_ratio based on
931 	 * two values: wb_dirty and wb_thresh. Let's consider an example:
932 	 * total amount of RAM is 16GB, bdi->max_ratio is equal to 1%, global
933 	 * limits are set by default to 10% and 20% (background and throttle).
934 	 * Then wb_thresh is 1% of 20% of 16GB. This amounts to ~8K pages.
935 	 * wb_calc_thresh(wb, bg_thresh) is about ~4K pages. wb_setpoint is
936 	 * about ~6K pages (as the average of background and throttle wb
937 	 * limits). The 3rd order polynomial will provide positive feedback if
938 	 * wb_dirty is under wb_setpoint and vice versa.
939 	 *
940 	 * Note, that we cannot use global counters in these calculations
941 	 * because we want to throttle process writing to a strictlimit wb
942 	 * much earlier than global "freerun" is reached (~23MB vs. ~2.3GB
943 	 * in the example above).
944 	 */
945 	if (unlikely(wb->bdi->capabilities & BDI_CAP_STRICTLIMIT)) {
946 		long long wb_pos_ratio;
947 
948 		if (dtc->wb_dirty < 8) {
949 			dtc->pos_ratio = min_t(long long, pos_ratio * 2,
950 					   2 << RATELIMIT_CALC_SHIFT);
951 			return;
952 		}
953 
954 		if (dtc->wb_dirty >= wb_thresh)
955 			return;
956 
957 		wb_setpoint = dirty_freerun_ceiling(wb_thresh,
958 						    dtc->wb_bg_thresh);
959 
960 		if (wb_setpoint == 0 || wb_setpoint == wb_thresh)
961 			return;
962 
963 		wb_pos_ratio = pos_ratio_polynom(wb_setpoint, dtc->wb_dirty,
964 						 wb_thresh);
965 
966 		/*
967 		 * Typically, for strictlimit case, wb_setpoint << setpoint
968 		 * and pos_ratio >> wb_pos_ratio. In the other words global
969 		 * state ("dirty") is not limiting factor and we have to
970 		 * make decision based on wb counters. But there is an
971 		 * important case when global pos_ratio should get precedence:
972 		 * global limits are exceeded (e.g. due to activities on other
973 		 * wb's) while given strictlimit wb is below limit.
974 		 *
975 		 * "pos_ratio * wb_pos_ratio" would work for the case above,
976 		 * but it would look too non-natural for the case of all
977 		 * activity in the system coming from a single strictlimit wb
978 		 * with bdi->max_ratio == 100%.
979 		 *
980 		 * Note that min() below somewhat changes the dynamics of the
981 		 * control system. Normally, pos_ratio value can be well over 3
982 		 * (when globally we are at freerun and wb is well below wb
983 		 * setpoint). Now the maximum pos_ratio in the same situation
984 		 * is 2. We might want to tweak this if we observe the control
985 		 * system is too slow to adapt.
986 		 */
987 		dtc->pos_ratio = min(pos_ratio, wb_pos_ratio);
988 		return;
989 	}
990 
991 	/*
992 	 * We have computed basic pos_ratio above based on global situation. If
993 	 * the wb is over/under its share of dirty pages, we want to scale
994 	 * pos_ratio further down/up. That is done by the following mechanism.
995 	 */
996 
997 	/*
998 	 * wb setpoint
999 	 *
1000 	 *        f(wb_dirty) := 1.0 + k * (wb_dirty - wb_setpoint)
1001 	 *
1002 	 *                        x_intercept - wb_dirty
1003 	 *                     := --------------------------
1004 	 *                        x_intercept - wb_setpoint
1005 	 *
1006 	 * The main wb control line is a linear function that subjects to
1007 	 *
1008 	 * (1) f(wb_setpoint) = 1.0
1009 	 * (2) k = - 1 / (8 * write_bw)  (in single wb case)
1010 	 *     or equally: x_intercept = wb_setpoint + 8 * write_bw
1011 	 *
1012 	 * For single wb case, the dirty pages are observed to fluctuate
1013 	 * regularly within range
1014 	 *        [wb_setpoint - write_bw/2, wb_setpoint + write_bw/2]
1015 	 * for various filesystems, where (2) can yield in a reasonable 12.5%
1016 	 * fluctuation range for pos_ratio.
1017 	 *
1018 	 * For JBOD case, wb_thresh (not wb_dirty!) could fluctuate up to its
1019 	 * own size, so move the slope over accordingly and choose a slope that
1020 	 * yields 100% pos_ratio fluctuation on suddenly doubled wb_thresh.
1021 	 */
1022 	if (unlikely(wb_thresh > dtc->thresh))
1023 		wb_thresh = dtc->thresh;
1024 	/*
1025 	 * It's very possible that wb_thresh is close to 0 not because the
1026 	 * device is slow, but that it has remained inactive for long time.
1027 	 * Honour such devices a reasonable good (hopefully IO efficient)
1028 	 * threshold, so that the occasional writes won't be blocked and active
1029 	 * writes can rampup the threshold quickly.
1030 	 */
1031 	wb_thresh = max(wb_thresh, (limit - dtc->dirty) / 8);
1032 	/*
1033 	 * scale global setpoint to wb's:
1034 	 *	wb_setpoint = setpoint * wb_thresh / thresh
1035 	 */
1036 	x = div_u64((u64)wb_thresh << 16, dtc->thresh | 1);
1037 	wb_setpoint = setpoint * (u64)x >> 16;
1038 	/*
1039 	 * Use span=(8*write_bw) in single wb case as indicated by
1040 	 * (thresh - wb_thresh ~= 0) and transit to wb_thresh in JBOD case.
1041 	 *
1042 	 *        wb_thresh                    thresh - wb_thresh
1043 	 * span = --------- * (8 * write_bw) + ------------------ * wb_thresh
1044 	 *         thresh                           thresh
1045 	 */
1046 	span = (dtc->thresh - wb_thresh + 8 * write_bw) * (u64)x >> 16;
1047 	x_intercept = wb_setpoint + span;
1048 
1049 	if (dtc->wb_dirty < x_intercept - span / 4) {
1050 		pos_ratio = div64_u64(pos_ratio * (x_intercept - dtc->wb_dirty),
1051 				      (x_intercept - wb_setpoint) | 1);
1052 	} else
1053 		pos_ratio /= 4;
1054 
1055 	/*
1056 	 * wb reserve area, safeguard against dirty pool underrun and disk idle
1057 	 * It may push the desired control point of global dirty pages higher
1058 	 * than setpoint.
1059 	 */
1060 	x_intercept = wb_thresh / 2;
1061 	if (dtc->wb_dirty < x_intercept) {
1062 		if (dtc->wb_dirty > x_intercept / 8)
1063 			pos_ratio = div_u64(pos_ratio * x_intercept,
1064 					    dtc->wb_dirty);
1065 		else
1066 			pos_ratio *= 8;
1067 	}
1068 
1069 	dtc->pos_ratio = pos_ratio;
1070 }
1071 
wb_update_write_bandwidth(struct bdi_writeback * wb,unsigned long elapsed,unsigned long written)1072 static void wb_update_write_bandwidth(struct bdi_writeback *wb,
1073 				      unsigned long elapsed,
1074 				      unsigned long written)
1075 {
1076 	const unsigned long period = roundup_pow_of_two(3 * HZ);
1077 	unsigned long avg = wb->avg_write_bandwidth;
1078 	unsigned long old = wb->write_bandwidth;
1079 	u64 bw;
1080 
1081 	/*
1082 	 * bw = written * HZ / elapsed
1083 	 *
1084 	 *                   bw * elapsed + write_bandwidth * (period - elapsed)
1085 	 * write_bandwidth = ---------------------------------------------------
1086 	 *                                          period
1087 	 *
1088 	 * @written may have decreased due to account_page_redirty().
1089 	 * Avoid underflowing @bw calculation.
1090 	 */
1091 	bw = written - min(written, wb->written_stamp);
1092 	bw *= HZ;
1093 	if (unlikely(elapsed > period)) {
1094 		bw = div64_ul(bw, elapsed);
1095 		avg = bw;
1096 		goto out;
1097 	}
1098 	bw += (u64)wb->write_bandwidth * (period - elapsed);
1099 	bw >>= ilog2(period);
1100 
1101 	/*
1102 	 * one more level of smoothing, for filtering out sudden spikes
1103 	 */
1104 	if (avg > old && old >= (unsigned long)bw)
1105 		avg -= (avg - old) >> 3;
1106 
1107 	if (avg < old && old <= (unsigned long)bw)
1108 		avg += (old - avg) >> 3;
1109 
1110 out:
1111 	/* keep avg > 0 to guarantee that tot > 0 if there are dirty wbs */
1112 	avg = max(avg, 1LU);
1113 	if (wb_has_dirty_io(wb)) {
1114 		long delta = avg - wb->avg_write_bandwidth;
1115 		WARN_ON_ONCE(atomic_long_add_return(delta,
1116 					&wb->bdi->tot_write_bandwidth) <= 0);
1117 	}
1118 	wb->write_bandwidth = bw;
1119 	wb->avg_write_bandwidth = avg;
1120 }
1121 
update_dirty_limit(struct dirty_throttle_control * dtc)1122 static void update_dirty_limit(struct dirty_throttle_control *dtc)
1123 {
1124 	struct wb_domain *dom = dtc_dom(dtc);
1125 	unsigned long thresh = dtc->thresh;
1126 	unsigned long limit = dom->dirty_limit;
1127 
1128 	/*
1129 	 * Follow up in one step.
1130 	 */
1131 	if (limit < thresh) {
1132 		limit = thresh;
1133 		goto update;
1134 	}
1135 
1136 	/*
1137 	 * Follow down slowly. Use the higher one as the target, because thresh
1138 	 * may drop below dirty. This is exactly the reason to introduce
1139 	 * dom->dirty_limit which is guaranteed to lie above the dirty pages.
1140 	 */
1141 	thresh = max(thresh, dtc->dirty);
1142 	if (limit > thresh) {
1143 		limit -= (limit - thresh) >> 5;
1144 		goto update;
1145 	}
1146 	return;
1147 update:
1148 	dom->dirty_limit = limit;
1149 }
1150 
domain_update_bandwidth(struct dirty_throttle_control * dtc,unsigned long now)1151 static void domain_update_bandwidth(struct dirty_throttle_control *dtc,
1152 				    unsigned long now)
1153 {
1154 	struct wb_domain *dom = dtc_dom(dtc);
1155 
1156 	/*
1157 	 * check locklessly first to optimize away locking for the most time
1158 	 */
1159 	if (time_before(now, dom->dirty_limit_tstamp + BANDWIDTH_INTERVAL))
1160 		return;
1161 
1162 	spin_lock(&dom->lock);
1163 	if (time_after_eq(now, dom->dirty_limit_tstamp + BANDWIDTH_INTERVAL)) {
1164 		update_dirty_limit(dtc);
1165 		dom->dirty_limit_tstamp = now;
1166 	}
1167 	spin_unlock(&dom->lock);
1168 }
1169 
1170 /*
1171  * Maintain wb->dirty_ratelimit, the base dirty throttle rate.
1172  *
1173  * Normal wb tasks will be curbed at or below it in long term.
1174  * Obviously it should be around (write_bw / N) when there are N dd tasks.
1175  */
wb_update_dirty_ratelimit(struct dirty_throttle_control * dtc,unsigned long dirtied,unsigned long elapsed)1176 static void wb_update_dirty_ratelimit(struct dirty_throttle_control *dtc,
1177 				      unsigned long dirtied,
1178 				      unsigned long elapsed)
1179 {
1180 	struct bdi_writeback *wb = dtc->wb;
1181 	unsigned long dirty = dtc->dirty;
1182 	unsigned long freerun = dirty_freerun_ceiling(dtc->thresh, dtc->bg_thresh);
1183 	unsigned long limit = hard_dirty_limit(dtc_dom(dtc), dtc->thresh);
1184 	unsigned long setpoint = (freerun + limit) / 2;
1185 	unsigned long write_bw = wb->avg_write_bandwidth;
1186 	unsigned long dirty_ratelimit = wb->dirty_ratelimit;
1187 	unsigned long dirty_rate;
1188 	unsigned long task_ratelimit;
1189 	unsigned long balanced_dirty_ratelimit;
1190 	unsigned long step;
1191 	unsigned long x;
1192 	unsigned long shift;
1193 
1194 	/*
1195 	 * The dirty rate will match the writeout rate in long term, except
1196 	 * when dirty pages are truncated by userspace or re-dirtied by FS.
1197 	 */
1198 	dirty_rate = (dirtied - wb->dirtied_stamp) * HZ / elapsed;
1199 
1200 	/*
1201 	 * task_ratelimit reflects each dd's dirty rate for the past 200ms.
1202 	 */
1203 	task_ratelimit = (u64)dirty_ratelimit *
1204 					dtc->pos_ratio >> RATELIMIT_CALC_SHIFT;
1205 	task_ratelimit++; /* it helps rampup dirty_ratelimit from tiny values */
1206 
1207 	/*
1208 	 * A linear estimation of the "balanced" throttle rate. The theory is,
1209 	 * if there are N dd tasks, each throttled at task_ratelimit, the wb's
1210 	 * dirty_rate will be measured to be (N * task_ratelimit). So the below
1211 	 * formula will yield the balanced rate limit (write_bw / N).
1212 	 *
1213 	 * Note that the expanded form is not a pure rate feedback:
1214 	 *	rate_(i+1) = rate_(i) * (write_bw / dirty_rate)		     (1)
1215 	 * but also takes pos_ratio into account:
1216 	 *	rate_(i+1) = rate_(i) * (write_bw / dirty_rate) * pos_ratio  (2)
1217 	 *
1218 	 * (1) is not realistic because pos_ratio also takes part in balancing
1219 	 * the dirty rate.  Consider the state
1220 	 *	pos_ratio = 0.5						     (3)
1221 	 *	rate = 2 * (write_bw / N)				     (4)
1222 	 * If (1) is used, it will stuck in that state! Because each dd will
1223 	 * be throttled at
1224 	 *	task_ratelimit = pos_ratio * rate = (write_bw / N)	     (5)
1225 	 * yielding
1226 	 *	dirty_rate = N * task_ratelimit = write_bw		     (6)
1227 	 * put (6) into (1) we get
1228 	 *	rate_(i+1) = rate_(i)					     (7)
1229 	 *
1230 	 * So we end up using (2) to always keep
1231 	 *	rate_(i+1) ~= (write_bw / N)				     (8)
1232 	 * regardless of the value of pos_ratio. As long as (8) is satisfied,
1233 	 * pos_ratio is able to drive itself to 1.0, which is not only where
1234 	 * the dirty count meet the setpoint, but also where the slope of
1235 	 * pos_ratio is most flat and hence task_ratelimit is least fluctuated.
1236 	 */
1237 	balanced_dirty_ratelimit = div_u64((u64)task_ratelimit * write_bw,
1238 					   dirty_rate | 1);
1239 	/*
1240 	 * balanced_dirty_ratelimit ~= (write_bw / N) <= write_bw
1241 	 */
1242 	if (unlikely(balanced_dirty_ratelimit > write_bw))
1243 		balanced_dirty_ratelimit = write_bw;
1244 
1245 	/*
1246 	 * We could safely do this and return immediately:
1247 	 *
1248 	 *	wb->dirty_ratelimit = balanced_dirty_ratelimit;
1249 	 *
1250 	 * However to get a more stable dirty_ratelimit, the below elaborated
1251 	 * code makes use of task_ratelimit to filter out singular points and
1252 	 * limit the step size.
1253 	 *
1254 	 * The below code essentially only uses the relative value of
1255 	 *
1256 	 *	task_ratelimit - dirty_ratelimit
1257 	 *	= (pos_ratio - 1) * dirty_ratelimit
1258 	 *
1259 	 * which reflects the direction and size of dirty position error.
1260 	 */
1261 
1262 	/*
1263 	 * dirty_ratelimit will follow balanced_dirty_ratelimit iff
1264 	 * task_ratelimit is on the same side of dirty_ratelimit, too.
1265 	 * For example, when
1266 	 * - dirty_ratelimit > balanced_dirty_ratelimit
1267 	 * - dirty_ratelimit > task_ratelimit (dirty pages are above setpoint)
1268 	 * lowering dirty_ratelimit will help meet both the position and rate
1269 	 * control targets. Otherwise, don't update dirty_ratelimit if it will
1270 	 * only help meet the rate target. After all, what the users ultimately
1271 	 * feel and care are stable dirty rate and small position error.
1272 	 *
1273 	 * |task_ratelimit - dirty_ratelimit| is used to limit the step size
1274 	 * and filter out the singular points of balanced_dirty_ratelimit. Which
1275 	 * keeps jumping around randomly and can even leap far away at times
1276 	 * due to the small 200ms estimation period of dirty_rate (we want to
1277 	 * keep that period small to reduce time lags).
1278 	 */
1279 	step = 0;
1280 
1281 	/*
1282 	 * For strictlimit case, calculations above were based on wb counters
1283 	 * and limits (starting from pos_ratio = wb_position_ratio() and up to
1284 	 * balanced_dirty_ratelimit = task_ratelimit * write_bw / dirty_rate).
1285 	 * Hence, to calculate "step" properly, we have to use wb_dirty as
1286 	 * "dirty" and wb_setpoint as "setpoint".
1287 	 *
1288 	 * We rampup dirty_ratelimit forcibly if wb_dirty is low because
1289 	 * it's possible that wb_thresh is close to zero due to inactivity
1290 	 * of backing device.
1291 	 */
1292 	if (unlikely(wb->bdi->capabilities & BDI_CAP_STRICTLIMIT)) {
1293 		dirty = dtc->wb_dirty;
1294 		if (dtc->wb_dirty < 8)
1295 			setpoint = dtc->wb_dirty + 1;
1296 		else
1297 			setpoint = (dtc->wb_thresh + dtc->wb_bg_thresh) / 2;
1298 	}
1299 
1300 	if (dirty < setpoint) {
1301 		x = min3(wb->balanced_dirty_ratelimit,
1302 			 balanced_dirty_ratelimit, task_ratelimit);
1303 		if (dirty_ratelimit < x)
1304 			step = x - dirty_ratelimit;
1305 	} else {
1306 		x = max3(wb->balanced_dirty_ratelimit,
1307 			 balanced_dirty_ratelimit, task_ratelimit);
1308 		if (dirty_ratelimit > x)
1309 			step = dirty_ratelimit - x;
1310 	}
1311 
1312 	/*
1313 	 * Don't pursue 100% rate matching. It's impossible since the balanced
1314 	 * rate itself is constantly fluctuating. So decrease the track speed
1315 	 * when it gets close to the target. Helps eliminate pointless tremors.
1316 	 */
1317 	shift = dirty_ratelimit / (2 * step + 1);
1318 	if (shift < BITS_PER_LONG)
1319 		step = DIV_ROUND_UP(step >> shift, 8);
1320 	else
1321 		step = 0;
1322 
1323 	if (dirty_ratelimit < balanced_dirty_ratelimit)
1324 		dirty_ratelimit += step;
1325 	else
1326 		dirty_ratelimit -= step;
1327 
1328 	wb->dirty_ratelimit = max(dirty_ratelimit, 1UL);
1329 	wb->balanced_dirty_ratelimit = balanced_dirty_ratelimit;
1330 
1331 	trace_bdi_dirty_ratelimit(wb, dirty_rate, task_ratelimit);
1332 }
1333 
__wb_update_bandwidth(struct dirty_throttle_control * gdtc,struct dirty_throttle_control * mdtc,unsigned long start_time,bool update_ratelimit)1334 static void __wb_update_bandwidth(struct dirty_throttle_control *gdtc,
1335 				  struct dirty_throttle_control *mdtc,
1336 				  unsigned long start_time,
1337 				  bool update_ratelimit)
1338 {
1339 	struct bdi_writeback *wb = gdtc->wb;
1340 	unsigned long now = jiffies;
1341 	unsigned long elapsed = now - wb->bw_time_stamp;
1342 	unsigned long dirtied;
1343 	unsigned long written;
1344 
1345 	lockdep_assert_held(&wb->list_lock);
1346 
1347 	/*
1348 	 * rate-limit, only update once every 200ms.
1349 	 */
1350 	if (elapsed < BANDWIDTH_INTERVAL)
1351 		return;
1352 
1353 	dirtied = percpu_counter_read(&wb->stat[WB_DIRTIED]);
1354 	written = percpu_counter_read(&wb->stat[WB_WRITTEN]);
1355 
1356 	/*
1357 	 * Skip quiet periods when disk bandwidth is under-utilized.
1358 	 * (at least 1s idle time between two flusher runs)
1359 	 */
1360 	if (elapsed > HZ && time_before(wb->bw_time_stamp, start_time))
1361 		goto snapshot;
1362 
1363 	if (update_ratelimit) {
1364 		domain_update_bandwidth(gdtc, now);
1365 		wb_update_dirty_ratelimit(gdtc, dirtied, elapsed);
1366 
1367 		/*
1368 		 * @mdtc is always NULL if !CGROUP_WRITEBACK but the
1369 		 * compiler has no way to figure that out.  Help it.
1370 		 */
1371 		if (IS_ENABLED(CONFIG_CGROUP_WRITEBACK) && mdtc) {
1372 			domain_update_bandwidth(mdtc, now);
1373 			wb_update_dirty_ratelimit(mdtc, dirtied, elapsed);
1374 		}
1375 	}
1376 	wb_update_write_bandwidth(wb, elapsed, written);
1377 
1378 snapshot:
1379 	wb->dirtied_stamp = dirtied;
1380 	wb->written_stamp = written;
1381 	wb->bw_time_stamp = now;
1382 }
1383 
wb_update_bandwidth(struct bdi_writeback * wb,unsigned long start_time)1384 void wb_update_bandwidth(struct bdi_writeback *wb, unsigned long start_time)
1385 {
1386 	struct dirty_throttle_control gdtc = { GDTC_INIT(wb) };
1387 
1388 	__wb_update_bandwidth(&gdtc, NULL, start_time, false);
1389 }
1390 
1391 /*
1392  * After a task dirtied this many pages, balance_dirty_pages_ratelimited()
1393  * will look to see if it needs to start dirty throttling.
1394  *
1395  * If dirty_poll_interval is too low, big NUMA machines will call the expensive
1396  * global_zone_page_state() too often. So scale it near-sqrt to the safety margin
1397  * (the number of pages we may dirty without exceeding the dirty limits).
1398  */
dirty_poll_interval(unsigned long dirty,unsigned long thresh)1399 static unsigned long dirty_poll_interval(unsigned long dirty,
1400 					 unsigned long thresh)
1401 {
1402 	if (thresh > dirty)
1403 		return 1UL << (ilog2(thresh - dirty) >> 1);
1404 
1405 	return 1;
1406 }
1407 
wb_max_pause(struct bdi_writeback * wb,unsigned long wb_dirty)1408 static unsigned long wb_max_pause(struct bdi_writeback *wb,
1409 				  unsigned long wb_dirty)
1410 {
1411 	unsigned long bw = wb->avg_write_bandwidth;
1412 	unsigned long t;
1413 
1414 	/*
1415 	 * Limit pause time for small memory systems. If sleeping for too long
1416 	 * time, a small pool of dirty/writeback pages may go empty and disk go
1417 	 * idle.
1418 	 *
1419 	 * 8 serves as the safety ratio.
1420 	 */
1421 	t = wb_dirty / (1 + bw / roundup_pow_of_two(1 + HZ / 8));
1422 	t++;
1423 
1424 	return min_t(unsigned long, t, MAX_PAUSE);
1425 }
1426 
wb_min_pause(struct bdi_writeback * wb,long max_pause,unsigned long task_ratelimit,unsigned long dirty_ratelimit,int * nr_dirtied_pause)1427 static long wb_min_pause(struct bdi_writeback *wb,
1428 			 long max_pause,
1429 			 unsigned long task_ratelimit,
1430 			 unsigned long dirty_ratelimit,
1431 			 int *nr_dirtied_pause)
1432 {
1433 	long hi = ilog2(wb->avg_write_bandwidth);
1434 	long lo = ilog2(wb->dirty_ratelimit);
1435 	long t;		/* target pause */
1436 	long pause;	/* estimated next pause */
1437 	int pages;	/* target nr_dirtied_pause */
1438 
1439 	/* target for 10ms pause on 1-dd case */
1440 	t = max(1, HZ / 100);
1441 
1442 	/*
1443 	 * Scale up pause time for concurrent dirtiers in order to reduce CPU
1444 	 * overheads.
1445 	 *
1446 	 * (N * 10ms) on 2^N concurrent tasks.
1447 	 */
1448 	if (hi > lo)
1449 		t += (hi - lo) * (10 * HZ) / 1024;
1450 
1451 	/*
1452 	 * This is a bit convoluted. We try to base the next nr_dirtied_pause
1453 	 * on the much more stable dirty_ratelimit. However the next pause time
1454 	 * will be computed based on task_ratelimit and the two rate limits may
1455 	 * depart considerably at some time. Especially if task_ratelimit goes
1456 	 * below dirty_ratelimit/2 and the target pause is max_pause, the next
1457 	 * pause time will be max_pause*2 _trimmed down_ to max_pause.  As a
1458 	 * result task_ratelimit won't be executed faithfully, which could
1459 	 * eventually bring down dirty_ratelimit.
1460 	 *
1461 	 * We apply two rules to fix it up:
1462 	 * 1) try to estimate the next pause time and if necessary, use a lower
1463 	 *    nr_dirtied_pause so as not to exceed max_pause. When this happens,
1464 	 *    nr_dirtied_pause will be "dancing" with task_ratelimit.
1465 	 * 2) limit the target pause time to max_pause/2, so that the normal
1466 	 *    small fluctuations of task_ratelimit won't trigger rule (1) and
1467 	 *    nr_dirtied_pause will remain as stable as dirty_ratelimit.
1468 	 */
1469 	t = min(t, 1 + max_pause / 2);
1470 	pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
1471 
1472 	/*
1473 	 * Tiny nr_dirtied_pause is found to hurt I/O performance in the test
1474 	 * case fio-mmap-randwrite-64k, which does 16*{sync read, async write}.
1475 	 * When the 16 consecutive reads are often interrupted by some dirty
1476 	 * throttling pause during the async writes, cfq will go into idles
1477 	 * (deadline is fine). So push nr_dirtied_pause as high as possible
1478 	 * until reaches DIRTY_POLL_THRESH=32 pages.
1479 	 */
1480 	if (pages < DIRTY_POLL_THRESH) {
1481 		t = max_pause;
1482 		pages = dirty_ratelimit * t / roundup_pow_of_two(HZ);
1483 		if (pages > DIRTY_POLL_THRESH) {
1484 			pages = DIRTY_POLL_THRESH;
1485 			t = HZ * DIRTY_POLL_THRESH / dirty_ratelimit;
1486 		}
1487 	}
1488 
1489 	pause = HZ * pages / (task_ratelimit + 1);
1490 	if (pause > max_pause) {
1491 		t = max_pause;
1492 		pages = task_ratelimit * t / roundup_pow_of_two(HZ);
1493 	}
1494 
1495 	*nr_dirtied_pause = pages;
1496 	/*
1497 	 * The minimal pause time will normally be half the target pause time.
1498 	 */
1499 	return pages >= DIRTY_POLL_THRESH ? 1 + t / 2 : t;
1500 }
1501 
wb_dirty_limits(struct dirty_throttle_control * dtc)1502 static inline void wb_dirty_limits(struct dirty_throttle_control *dtc)
1503 {
1504 	struct bdi_writeback *wb = dtc->wb;
1505 	unsigned long wb_reclaimable;
1506 
1507 	/*
1508 	 * wb_thresh is not treated as some limiting factor as
1509 	 * dirty_thresh, due to reasons
1510 	 * - in JBOD setup, wb_thresh can fluctuate a lot
1511 	 * - in a system with HDD and USB key, the USB key may somehow
1512 	 *   go into state (wb_dirty >> wb_thresh) either because
1513 	 *   wb_dirty starts high, or because wb_thresh drops low.
1514 	 *   In this case we don't want to hard throttle the USB key
1515 	 *   dirtiers for 100 seconds until wb_dirty drops under
1516 	 *   wb_thresh. Instead the auxiliary wb control line in
1517 	 *   wb_position_ratio() will let the dirtier task progress
1518 	 *   at some rate <= (write_bw / 2) for bringing down wb_dirty.
1519 	 */
1520 	dtc->wb_thresh = __wb_calc_thresh(dtc);
1521 	dtc->wb_bg_thresh = dtc->thresh ?
1522 		div_u64((u64)dtc->wb_thresh * dtc->bg_thresh, dtc->thresh) : 0;
1523 
1524 	/*
1525 	 * In order to avoid the stacked BDI deadlock we need
1526 	 * to ensure we accurately count the 'dirty' pages when
1527 	 * the threshold is low.
1528 	 *
1529 	 * Otherwise it would be possible to get thresh+n pages
1530 	 * reported dirty, even though there are thresh-m pages
1531 	 * actually dirty; with m+n sitting in the percpu
1532 	 * deltas.
1533 	 */
1534 	if (dtc->wb_thresh < 2 * wb_stat_error()) {
1535 		wb_reclaimable = wb_stat_sum(wb, WB_RECLAIMABLE);
1536 		dtc->wb_dirty = wb_reclaimable + wb_stat_sum(wb, WB_WRITEBACK);
1537 	} else {
1538 		wb_reclaimable = wb_stat(wb, WB_RECLAIMABLE);
1539 		dtc->wb_dirty = wb_reclaimable + wb_stat(wb, WB_WRITEBACK);
1540 	}
1541 }
1542 
1543 /*
1544  * balance_dirty_pages() must be called by processes which are generating dirty
1545  * data.  It looks at the number of dirty pages in the machine and will force
1546  * the caller to wait once crossing the (background_thresh + dirty_thresh) / 2.
1547  * If we're over `background_thresh' then the writeback threads are woken to
1548  * perform some writeout.
1549  */
balance_dirty_pages(struct bdi_writeback * wb,unsigned long pages_dirtied)1550 static void balance_dirty_pages(struct bdi_writeback *wb,
1551 				unsigned long pages_dirtied)
1552 {
1553 	struct dirty_throttle_control gdtc_stor = { GDTC_INIT(wb) };
1554 	struct dirty_throttle_control mdtc_stor = { MDTC_INIT(wb, &gdtc_stor) };
1555 	struct dirty_throttle_control * const gdtc = &gdtc_stor;
1556 	struct dirty_throttle_control * const mdtc = mdtc_valid(&mdtc_stor) ?
1557 						     &mdtc_stor : NULL;
1558 	struct dirty_throttle_control *sdtc;
1559 	unsigned long nr_reclaimable;	/* = file_dirty */
1560 	long period;
1561 	long pause;
1562 	long max_pause;
1563 	long min_pause;
1564 	int nr_dirtied_pause;
1565 	bool dirty_exceeded = false;
1566 	unsigned long task_ratelimit;
1567 	unsigned long dirty_ratelimit;
1568 	struct backing_dev_info *bdi = wb->bdi;
1569 	bool strictlimit = bdi->capabilities & BDI_CAP_STRICTLIMIT;
1570 	unsigned long start_time = jiffies;
1571 
1572 	for (;;) {
1573 		unsigned long now = jiffies;
1574 		unsigned long dirty, thresh, bg_thresh;
1575 		unsigned long m_dirty = 0;	/* stop bogus uninit warnings */
1576 		unsigned long m_thresh = 0;
1577 		unsigned long m_bg_thresh = 0;
1578 
1579 		nr_reclaimable = global_node_page_state(NR_FILE_DIRTY);
1580 		gdtc->avail = global_dirtyable_memory();
1581 		gdtc->dirty = nr_reclaimable + global_node_page_state(NR_WRITEBACK);
1582 
1583 		domain_dirty_limits(gdtc);
1584 
1585 		if (unlikely(strictlimit)) {
1586 			wb_dirty_limits(gdtc);
1587 
1588 			dirty = gdtc->wb_dirty;
1589 			thresh = gdtc->wb_thresh;
1590 			bg_thresh = gdtc->wb_bg_thresh;
1591 		} else {
1592 			dirty = gdtc->dirty;
1593 			thresh = gdtc->thresh;
1594 			bg_thresh = gdtc->bg_thresh;
1595 		}
1596 
1597 		if (mdtc) {
1598 			unsigned long filepages, headroom, writeback;
1599 
1600 			/*
1601 			 * If @wb belongs to !root memcg, repeat the same
1602 			 * basic calculations for the memcg domain.
1603 			 */
1604 			mem_cgroup_wb_stats(wb, &filepages, &headroom,
1605 					    &mdtc->dirty, &writeback);
1606 			mdtc->dirty += writeback;
1607 			mdtc_calc_avail(mdtc, filepages, headroom);
1608 
1609 			domain_dirty_limits(mdtc);
1610 
1611 			if (unlikely(strictlimit)) {
1612 				wb_dirty_limits(mdtc);
1613 				m_dirty = mdtc->wb_dirty;
1614 				m_thresh = mdtc->wb_thresh;
1615 				m_bg_thresh = mdtc->wb_bg_thresh;
1616 			} else {
1617 				m_dirty = mdtc->dirty;
1618 				m_thresh = mdtc->thresh;
1619 				m_bg_thresh = mdtc->bg_thresh;
1620 			}
1621 		}
1622 
1623 		/*
1624 		 * Throttle it only when the background writeback cannot
1625 		 * catch-up. This avoids (excessively) small writeouts
1626 		 * when the wb limits are ramping up in case of !strictlimit.
1627 		 *
1628 		 * In strictlimit case make decision based on the wb counters
1629 		 * and limits. Small writeouts when the wb limits are ramping
1630 		 * up are the price we consciously pay for strictlimit-ing.
1631 		 *
1632 		 * If memcg domain is in effect, @dirty should be under
1633 		 * both global and memcg freerun ceilings.
1634 		 */
1635 		if (dirty <= dirty_freerun_ceiling(thresh, bg_thresh) &&
1636 		    (!mdtc ||
1637 		     m_dirty <= dirty_freerun_ceiling(m_thresh, m_bg_thresh))) {
1638 			unsigned long intv;
1639 			unsigned long m_intv;
1640 
1641 free_running:
1642 			intv = dirty_poll_interval(dirty, thresh);
1643 			m_intv = ULONG_MAX;
1644 
1645 			current->dirty_paused_when = now;
1646 			current->nr_dirtied = 0;
1647 			if (mdtc)
1648 				m_intv = dirty_poll_interval(m_dirty, m_thresh);
1649 			current->nr_dirtied_pause = min(intv, m_intv);
1650 			break;
1651 		}
1652 
1653 		if (unlikely(!writeback_in_progress(wb)))
1654 			wb_start_background_writeback(wb);
1655 
1656 		mem_cgroup_flush_foreign(wb);
1657 
1658 		/*
1659 		 * Calculate global domain's pos_ratio and select the
1660 		 * global dtc by default.
1661 		 */
1662 		if (!strictlimit) {
1663 			wb_dirty_limits(gdtc);
1664 
1665 			if ((current->flags & PF_LOCAL_THROTTLE) &&
1666 			    gdtc->wb_dirty <
1667 			    dirty_freerun_ceiling(gdtc->wb_thresh,
1668 						  gdtc->wb_bg_thresh))
1669 				/*
1670 				 * LOCAL_THROTTLE tasks must not be throttled
1671 				 * when below the per-wb freerun ceiling.
1672 				 */
1673 				goto free_running;
1674 		}
1675 
1676 		dirty_exceeded = (gdtc->wb_dirty > gdtc->wb_thresh) &&
1677 			((gdtc->dirty > gdtc->thresh) || strictlimit);
1678 
1679 		wb_position_ratio(gdtc);
1680 		sdtc = gdtc;
1681 
1682 		if (mdtc) {
1683 			/*
1684 			 * If memcg domain is in effect, calculate its
1685 			 * pos_ratio.  @wb should satisfy constraints from
1686 			 * both global and memcg domains.  Choose the one
1687 			 * w/ lower pos_ratio.
1688 			 */
1689 			if (!strictlimit) {
1690 				wb_dirty_limits(mdtc);
1691 
1692 				if ((current->flags & PF_LOCAL_THROTTLE) &&
1693 				    mdtc->wb_dirty <
1694 				    dirty_freerun_ceiling(mdtc->wb_thresh,
1695 							  mdtc->wb_bg_thresh))
1696 					/*
1697 					 * LOCAL_THROTTLE tasks must not be
1698 					 * throttled when below the per-wb
1699 					 * freerun ceiling.
1700 					 */
1701 					goto free_running;
1702 			}
1703 			dirty_exceeded |= (mdtc->wb_dirty > mdtc->wb_thresh) &&
1704 				((mdtc->dirty > mdtc->thresh) || strictlimit);
1705 
1706 			wb_position_ratio(mdtc);
1707 			if (mdtc->pos_ratio < gdtc->pos_ratio)
1708 				sdtc = mdtc;
1709 		}
1710 
1711 		if (dirty_exceeded && !wb->dirty_exceeded)
1712 			wb->dirty_exceeded = 1;
1713 
1714 		if (time_is_before_jiffies(wb->bw_time_stamp +
1715 					   BANDWIDTH_INTERVAL)) {
1716 			spin_lock(&wb->list_lock);
1717 			__wb_update_bandwidth(gdtc, mdtc, start_time, true);
1718 			spin_unlock(&wb->list_lock);
1719 		}
1720 
1721 		/* throttle according to the chosen dtc */
1722 		dirty_ratelimit = wb->dirty_ratelimit;
1723 		task_ratelimit = ((u64)dirty_ratelimit * sdtc->pos_ratio) >>
1724 							RATELIMIT_CALC_SHIFT;
1725 		max_pause = wb_max_pause(wb, sdtc->wb_dirty);
1726 		min_pause = wb_min_pause(wb, max_pause,
1727 					 task_ratelimit, dirty_ratelimit,
1728 					 &nr_dirtied_pause);
1729 
1730 		if (unlikely(task_ratelimit == 0)) {
1731 			period = max_pause;
1732 			pause = max_pause;
1733 			goto pause;
1734 		}
1735 		period = HZ * pages_dirtied / task_ratelimit;
1736 		pause = period;
1737 		if (current->dirty_paused_when)
1738 			pause -= now - current->dirty_paused_when;
1739 		/*
1740 		 * For less than 1s think time (ext3/4 may block the dirtier
1741 		 * for up to 800ms from time to time on 1-HDD; so does xfs,
1742 		 * however at much less frequency), try to compensate it in
1743 		 * future periods by updating the virtual time; otherwise just
1744 		 * do a reset, as it may be a light dirtier.
1745 		 */
1746 		if (pause < min_pause) {
1747 			trace_balance_dirty_pages(wb,
1748 						  sdtc->thresh,
1749 						  sdtc->bg_thresh,
1750 						  sdtc->dirty,
1751 						  sdtc->wb_thresh,
1752 						  sdtc->wb_dirty,
1753 						  dirty_ratelimit,
1754 						  task_ratelimit,
1755 						  pages_dirtied,
1756 						  period,
1757 						  min(pause, 0L),
1758 						  start_time);
1759 			if (pause < -HZ) {
1760 				current->dirty_paused_when = now;
1761 				current->nr_dirtied = 0;
1762 			} else if (period) {
1763 				current->dirty_paused_when += period;
1764 				current->nr_dirtied = 0;
1765 			} else if (current->nr_dirtied_pause <= pages_dirtied)
1766 				current->nr_dirtied_pause += pages_dirtied;
1767 			break;
1768 		}
1769 		if (unlikely(pause > max_pause)) {
1770 			/* for occasional dropped task_ratelimit */
1771 			now += min(pause - max_pause, max_pause);
1772 			pause = max_pause;
1773 		}
1774 
1775 pause:
1776 		trace_balance_dirty_pages(wb,
1777 					  sdtc->thresh,
1778 					  sdtc->bg_thresh,
1779 					  sdtc->dirty,
1780 					  sdtc->wb_thresh,
1781 					  sdtc->wb_dirty,
1782 					  dirty_ratelimit,
1783 					  task_ratelimit,
1784 					  pages_dirtied,
1785 					  period,
1786 					  pause,
1787 					  start_time);
1788 		__set_current_state(TASK_KILLABLE);
1789 		wb->dirty_sleep = now;
1790 		io_schedule_timeout(pause);
1791 
1792 		current->dirty_paused_when = now + pause;
1793 		current->nr_dirtied = 0;
1794 		current->nr_dirtied_pause = nr_dirtied_pause;
1795 
1796 		/*
1797 		 * This is typically equal to (dirty < thresh) and can also
1798 		 * keep "1000+ dd on a slow USB stick" under control.
1799 		 */
1800 		if (task_ratelimit)
1801 			break;
1802 
1803 		/*
1804 		 * In the case of an unresponding NFS server and the NFS dirty
1805 		 * pages exceeds dirty_thresh, give the other good wb's a pipe
1806 		 * to go through, so that tasks on them still remain responsive.
1807 		 *
1808 		 * In theory 1 page is enough to keep the consumer-producer
1809 		 * pipe going: the flusher cleans 1 page => the task dirties 1
1810 		 * more page. However wb_dirty has accounting errors.  So use
1811 		 * the larger and more IO friendly wb_stat_error.
1812 		 */
1813 		if (sdtc->wb_dirty <= wb_stat_error())
1814 			break;
1815 
1816 		if (fatal_signal_pending(current))
1817 			break;
1818 	}
1819 
1820 	if (!dirty_exceeded && wb->dirty_exceeded)
1821 		wb->dirty_exceeded = 0;
1822 
1823 	if (writeback_in_progress(wb))
1824 		return;
1825 
1826 	/*
1827 	 * In laptop mode, we wait until hitting the higher threshold before
1828 	 * starting background writeout, and then write out all the way down
1829 	 * to the lower threshold.  So slow writers cause minimal disk activity.
1830 	 *
1831 	 * In normal mode, we start background writeout at the lower
1832 	 * background_thresh, to keep the amount of dirty memory low.
1833 	 */
1834 	if (laptop_mode)
1835 		return;
1836 
1837 	if (nr_reclaimable > gdtc->bg_thresh)
1838 		wb_start_background_writeback(wb);
1839 }
1840 
1841 static DEFINE_PER_CPU(int, bdp_ratelimits);
1842 
1843 /*
1844  * Normal tasks are throttled by
1845  *	loop {
1846  *		dirty tsk->nr_dirtied_pause pages;
1847  *		take a snap in balance_dirty_pages();
1848  *	}
1849  * However there is a worst case. If every task exit immediately when dirtied
1850  * (tsk->nr_dirtied_pause - 1) pages, balance_dirty_pages() will never be
1851  * called to throttle the page dirties. The solution is to save the not yet
1852  * throttled page dirties in dirty_throttle_leaks on task exit and charge them
1853  * randomly into the running tasks. This works well for the above worst case,
1854  * as the new task will pick up and accumulate the old task's leaked dirty
1855  * count and eventually get throttled.
1856  */
1857 DEFINE_PER_CPU(int, dirty_throttle_leaks) = 0;
1858 
1859 /**
1860  * balance_dirty_pages_ratelimited - balance dirty memory state
1861  * @mapping: address_space which was dirtied
1862  *
1863  * Processes which are dirtying memory should call in here once for each page
1864  * which was newly dirtied.  The function will periodically check the system's
1865  * dirty state and will initiate writeback if needed.
1866  *
1867  * On really big machines, get_writeback_state is expensive, so try to avoid
1868  * calling it too often (ratelimiting).  But once we're over the dirty memory
1869  * limit we decrease the ratelimiting by a lot, to prevent individual processes
1870  * from overshooting the limit by (ratelimit_pages) each.
1871  */
balance_dirty_pages_ratelimited(struct address_space * mapping)1872 void balance_dirty_pages_ratelimited(struct address_space *mapping)
1873 {
1874 	struct inode *inode = mapping->host;
1875 	struct backing_dev_info *bdi = inode_to_bdi(inode);
1876 	struct bdi_writeback *wb = NULL;
1877 	int ratelimit;
1878 	int *p;
1879 
1880 	if (!(bdi->capabilities & BDI_CAP_WRITEBACK))
1881 		return;
1882 
1883 	if (inode_cgwb_enabled(inode))
1884 		wb = wb_get_create_current(bdi, GFP_KERNEL);
1885 	if (!wb)
1886 		wb = &bdi->wb;
1887 
1888 	ratelimit = current->nr_dirtied_pause;
1889 	if (wb->dirty_exceeded)
1890 		ratelimit = min(ratelimit, 32 >> (PAGE_SHIFT - 10));
1891 
1892 	preempt_disable();
1893 	/*
1894 	 * This prevents one CPU to accumulate too many dirtied pages without
1895 	 * calling into balance_dirty_pages(), which can happen when there are
1896 	 * 1000+ tasks, all of them start dirtying pages at exactly the same
1897 	 * time, hence all honoured too large initial task->nr_dirtied_pause.
1898 	 */
1899 	p =  this_cpu_ptr(&bdp_ratelimits);
1900 	if (unlikely(current->nr_dirtied >= ratelimit))
1901 		*p = 0;
1902 	else if (unlikely(*p >= ratelimit_pages)) {
1903 		*p = 0;
1904 		ratelimit = 0;
1905 	}
1906 	/*
1907 	 * Pick up the dirtied pages by the exited tasks. This avoids lots of
1908 	 * short-lived tasks (eg. gcc invocations in a kernel build) escaping
1909 	 * the dirty throttling and livelock other long-run dirtiers.
1910 	 */
1911 	p = this_cpu_ptr(&dirty_throttle_leaks);
1912 	if (*p > 0 && current->nr_dirtied < ratelimit) {
1913 		unsigned long nr_pages_dirtied;
1914 		nr_pages_dirtied = min(*p, ratelimit - current->nr_dirtied);
1915 		*p -= nr_pages_dirtied;
1916 		current->nr_dirtied += nr_pages_dirtied;
1917 	}
1918 	preempt_enable();
1919 
1920 	if (unlikely(current->nr_dirtied >= ratelimit))
1921 		balance_dirty_pages(wb, current->nr_dirtied);
1922 
1923 	wb_put(wb);
1924 }
1925 EXPORT_SYMBOL(balance_dirty_pages_ratelimited);
1926 
1927 /**
1928  * wb_over_bg_thresh - does @wb need to be written back?
1929  * @wb: bdi_writeback of interest
1930  *
1931  * Determines whether background writeback should keep writing @wb or it's
1932  * clean enough.
1933  *
1934  * Return: %true if writeback should continue.
1935  */
wb_over_bg_thresh(struct bdi_writeback * wb)1936 bool wb_over_bg_thresh(struct bdi_writeback *wb)
1937 {
1938 	struct dirty_throttle_control gdtc_stor = { GDTC_INIT(wb) };
1939 	struct dirty_throttle_control mdtc_stor = { MDTC_INIT(wb, &gdtc_stor) };
1940 	struct dirty_throttle_control * const gdtc = &gdtc_stor;
1941 	struct dirty_throttle_control * const mdtc = mdtc_valid(&mdtc_stor) ?
1942 						     &mdtc_stor : NULL;
1943 
1944 	/*
1945 	 * Similar to balance_dirty_pages() but ignores pages being written
1946 	 * as we're trying to decide whether to put more under writeback.
1947 	 */
1948 	gdtc->avail = global_dirtyable_memory();
1949 	gdtc->dirty = global_node_page_state(NR_FILE_DIRTY);
1950 	domain_dirty_limits(gdtc);
1951 
1952 	if (gdtc->dirty > gdtc->bg_thresh)
1953 		return true;
1954 
1955 	if (wb_stat(wb, WB_RECLAIMABLE) >
1956 	    wb_calc_thresh(gdtc->wb, gdtc->bg_thresh))
1957 		return true;
1958 
1959 	if (mdtc) {
1960 		unsigned long filepages, headroom, writeback;
1961 
1962 		mem_cgroup_wb_stats(wb, &filepages, &headroom, &mdtc->dirty,
1963 				    &writeback);
1964 		mdtc_calc_avail(mdtc, filepages, headroom);
1965 		domain_dirty_limits(mdtc);	/* ditto, ignore writeback */
1966 
1967 		if (mdtc->dirty > mdtc->bg_thresh)
1968 			return true;
1969 
1970 		if (wb_stat(wb, WB_RECLAIMABLE) >
1971 		    wb_calc_thresh(mdtc->wb, mdtc->bg_thresh))
1972 			return true;
1973 	}
1974 
1975 	return false;
1976 }
1977 
1978 /*
1979  * sysctl handler for /proc/sys/vm/dirty_writeback_centisecs
1980  */
dirty_writeback_centisecs_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)1981 int dirty_writeback_centisecs_handler(struct ctl_table *table, int write,
1982 		void *buffer, size_t *length, loff_t *ppos)
1983 {
1984 	unsigned int old_interval = dirty_writeback_interval;
1985 	int ret;
1986 
1987 	ret = proc_dointvec(table, write, buffer, length, ppos);
1988 
1989 	/*
1990 	 * Writing 0 to dirty_writeback_interval will disable periodic writeback
1991 	 * and a different non-zero value will wakeup the writeback threads.
1992 	 * wb_wakeup_delayed() would be more appropriate, but it's a pain to
1993 	 * iterate over all bdis and wbs.
1994 	 * The reason we do this is to make the change take effect immediately.
1995 	 */
1996 	if (!ret && write && dirty_writeback_interval &&
1997 		dirty_writeback_interval != old_interval)
1998 		wakeup_flusher_threads(WB_REASON_PERIODIC);
1999 
2000 	return ret;
2001 }
2002 
2003 #ifdef CONFIG_BLOCK
laptop_mode_timer_fn(struct timer_list * t)2004 void laptop_mode_timer_fn(struct timer_list *t)
2005 {
2006 	struct backing_dev_info *backing_dev_info =
2007 		from_timer(backing_dev_info, t, laptop_mode_wb_timer);
2008 
2009 	wakeup_flusher_threads_bdi(backing_dev_info, WB_REASON_LAPTOP_TIMER);
2010 }
2011 
2012 /*
2013  * We've spun up the disk and we're in laptop mode: schedule writeback
2014  * of all dirty data a few seconds from now.  If the flush is already scheduled
2015  * then push it back - the user is still using the disk.
2016  */
laptop_io_completion(struct backing_dev_info * info)2017 void laptop_io_completion(struct backing_dev_info *info)
2018 {
2019 	mod_timer(&info->laptop_mode_wb_timer, jiffies + laptop_mode);
2020 }
2021 
2022 /*
2023  * We're in laptop mode and we've just synced. The sync's writes will have
2024  * caused another writeback to be scheduled by laptop_io_completion.
2025  * Nothing needs to be written back anymore, so we unschedule the writeback.
2026  */
laptop_sync_completion(void)2027 void laptop_sync_completion(void)
2028 {
2029 	struct backing_dev_info *bdi;
2030 
2031 	rcu_read_lock();
2032 
2033 	list_for_each_entry_rcu(bdi, &bdi_list, bdi_list)
2034 		del_timer(&bdi->laptop_mode_wb_timer);
2035 
2036 	rcu_read_unlock();
2037 }
2038 #endif
2039 
2040 /*
2041  * If ratelimit_pages is too high then we can get into dirty-data overload
2042  * if a large number of processes all perform writes at the same time.
2043  * If it is too low then SMP machines will call the (expensive)
2044  * get_writeback_state too often.
2045  *
2046  * Here we set ratelimit_pages to a level which ensures that when all CPUs are
2047  * dirtying in parallel, we cannot go more than 3% (1/32) over the dirty memory
2048  * thresholds.
2049  */
2050 
writeback_set_ratelimit(void)2051 void writeback_set_ratelimit(void)
2052 {
2053 	struct wb_domain *dom = &global_wb_domain;
2054 	unsigned long background_thresh;
2055 	unsigned long dirty_thresh;
2056 
2057 	global_dirty_limits(&background_thresh, &dirty_thresh);
2058 	dom->dirty_limit = dirty_thresh;
2059 	ratelimit_pages = dirty_thresh / (num_online_cpus() * 32);
2060 	if (ratelimit_pages < 16)
2061 		ratelimit_pages = 16;
2062 }
2063 
page_writeback_cpu_online(unsigned int cpu)2064 static int page_writeback_cpu_online(unsigned int cpu)
2065 {
2066 	writeback_set_ratelimit();
2067 	return 0;
2068 }
2069 
2070 /*
2071  * Called early on to tune the page writeback dirty limits.
2072  *
2073  * We used to scale dirty pages according to how total memory
2074  * related to pages that could be allocated for buffers.
2075  *
2076  * However, that was when we used "dirty_ratio" to scale with
2077  * all memory, and we don't do that any more. "dirty_ratio"
2078  * is now applied to total non-HIGHPAGE memory, and as such we can't
2079  * get into the old insane situation any more where we had
2080  * large amounts of dirty pages compared to a small amount of
2081  * non-HIGHMEM memory.
2082  *
2083  * But we might still want to scale the dirty_ratio by how
2084  * much memory the box has..
2085  */
page_writeback_init(void)2086 void __init page_writeback_init(void)
2087 {
2088 	BUG_ON(wb_domain_init(&global_wb_domain, GFP_KERNEL));
2089 
2090 	cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "mm/writeback:online",
2091 			  page_writeback_cpu_online, NULL);
2092 	cpuhp_setup_state(CPUHP_MM_WRITEBACK_DEAD, "mm/writeback:dead", NULL,
2093 			  page_writeback_cpu_online);
2094 }
2095 
2096 /**
2097  * tag_pages_for_writeback - tag pages to be written by write_cache_pages
2098  * @mapping: address space structure to write
2099  * @start: starting page index
2100  * @end: ending page index (inclusive)
2101  *
2102  * This function scans the page range from @start to @end (inclusive) and tags
2103  * all pages that have DIRTY tag set with a special TOWRITE tag. The idea is
2104  * that write_cache_pages (or whoever calls this function) will then use
2105  * TOWRITE tag to identify pages eligible for writeback.  This mechanism is
2106  * used to avoid livelocking of writeback by a process steadily creating new
2107  * dirty pages in the file (thus it is important for this function to be quick
2108  * so that it can tag pages faster than a dirtying process can create them).
2109  */
tag_pages_for_writeback(struct address_space * mapping,pgoff_t start,pgoff_t end)2110 void tag_pages_for_writeback(struct address_space *mapping,
2111 			     pgoff_t start, pgoff_t end)
2112 {
2113 	XA_STATE(xas, &mapping->i_pages, start);
2114 	unsigned int tagged = 0;
2115 	void *page;
2116 
2117 	xas_lock_irq(&xas);
2118 	xas_for_each_marked(&xas, page, end, PAGECACHE_TAG_DIRTY) {
2119 		xas_set_mark(&xas, PAGECACHE_TAG_TOWRITE);
2120 		if (++tagged % XA_CHECK_SCHED)
2121 			continue;
2122 
2123 		xas_pause(&xas);
2124 		xas_unlock_irq(&xas);
2125 		cond_resched();
2126 		xas_lock_irq(&xas);
2127 	}
2128 	xas_unlock_irq(&xas);
2129 }
2130 EXPORT_SYMBOL(tag_pages_for_writeback);
2131 
2132 /**
2133  * write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
2134  * @mapping: address space structure to write
2135  * @wbc: subtract the number of written pages from *@wbc->nr_to_write
2136  * @writepage: function called for each page
2137  * @data: data passed to writepage function
2138  *
2139  * If a page is already under I/O, write_cache_pages() skips it, even
2140  * if it's dirty.  This is desirable behaviour for memory-cleaning writeback,
2141  * but it is INCORRECT for data-integrity system calls such as fsync().  fsync()
2142  * and msync() need to guarantee that all the data which was dirty at the time
2143  * the call was made get new I/O started against them.  If wbc->sync_mode is
2144  * WB_SYNC_ALL then we were called for data integrity and we must wait for
2145  * existing IO to complete.
2146  *
2147  * To avoid livelocks (when other process dirties new pages), we first tag
2148  * pages which should be written back with TOWRITE tag and only then start
2149  * writing them. For data-integrity sync we have to be careful so that we do
2150  * not miss some pages (e.g., because some other process has cleared TOWRITE
2151  * tag we set). The rule we follow is that TOWRITE tag can be cleared only
2152  * by the process clearing the DIRTY tag (and submitting the page for IO).
2153  *
2154  * To avoid deadlocks between range_cyclic writeback and callers that hold
2155  * pages in PageWriteback to aggregate IO until write_cache_pages() returns,
2156  * we do not loop back to the start of the file. Doing so causes a page
2157  * lock/page writeback access order inversion - we should only ever lock
2158  * multiple pages in ascending page->index order, and looping back to the start
2159  * of the file violates that rule and causes deadlocks.
2160  *
2161  * Return: %0 on success, negative error code otherwise
2162  */
write_cache_pages(struct address_space * mapping,struct writeback_control * wbc,writepage_t writepage,void * data)2163 int write_cache_pages(struct address_space *mapping,
2164 		      struct writeback_control *wbc, writepage_t writepage,
2165 		      void *data)
2166 {
2167 	int ret = 0;
2168 	int done = 0;
2169 	int error;
2170 	struct pagevec pvec;
2171 	int nr_pages;
2172 	pgoff_t index;
2173 	pgoff_t end;		/* Inclusive */
2174 	pgoff_t done_index;
2175 	int range_whole = 0;
2176 	xa_mark_t tag;
2177 
2178 	pagevec_init(&pvec);
2179 	if (wbc->range_cyclic) {
2180 		index = mapping->writeback_index; /* prev offset */
2181 		end = -1;
2182 	} else {
2183 		index = wbc->range_start >> PAGE_SHIFT;
2184 		end = wbc->range_end >> PAGE_SHIFT;
2185 		if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2186 			range_whole = 1;
2187 	}
2188 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) {
2189 		tag_pages_for_writeback(mapping, index, end);
2190 		tag = PAGECACHE_TAG_TOWRITE;
2191 	} else {
2192 		tag = PAGECACHE_TAG_DIRTY;
2193 	}
2194 	done_index = index;
2195 	while (!done && (index <= end)) {
2196 		int i;
2197 
2198 		nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
2199 				tag);
2200 		if (nr_pages == 0)
2201 			break;
2202 
2203 		for (i = 0; i < nr_pages; i++) {
2204 			struct page *page = pvec.pages[i];
2205 
2206 			done_index = page->index;
2207 
2208 			lock_page(page);
2209 
2210 			/*
2211 			 * Page truncated or invalidated. We can freely skip it
2212 			 * then, even for data integrity operations: the page
2213 			 * has disappeared concurrently, so there could be no
2214 			 * real expectation of this data interity operation
2215 			 * even if there is now a new, dirty page at the same
2216 			 * pagecache address.
2217 			 */
2218 			if (unlikely(page->mapping != mapping)) {
2219 continue_unlock:
2220 				unlock_page(page);
2221 				continue;
2222 			}
2223 
2224 			if (!PageDirty(page)) {
2225 				/* someone wrote it for us */
2226 				goto continue_unlock;
2227 			}
2228 
2229 			if (PageWriteback(page)) {
2230 				if (wbc->sync_mode != WB_SYNC_NONE)
2231 					wait_on_page_writeback(page);
2232 				else
2233 					goto continue_unlock;
2234 			}
2235 
2236 			BUG_ON(PageWriteback(page));
2237 			if (!clear_page_dirty_for_io(page))
2238 				goto continue_unlock;
2239 
2240 			trace_wbc_writepage(wbc, inode_to_bdi(mapping->host));
2241 			error = (*writepage)(page, wbc, data);
2242 			if (unlikely(error)) {
2243 				/*
2244 				 * Handle errors according to the type of
2245 				 * writeback. There's no need to continue for
2246 				 * background writeback. Just push done_index
2247 				 * past this page so media errors won't choke
2248 				 * writeout for the entire file. For integrity
2249 				 * writeback, we must process the entire dirty
2250 				 * set regardless of errors because the fs may
2251 				 * still have state to clear for each page. In
2252 				 * that case we continue processing and return
2253 				 * the first error.
2254 				 */
2255 				if (error == AOP_WRITEPAGE_ACTIVATE) {
2256 					unlock_page(page);
2257 					error = 0;
2258 				} else if (wbc->sync_mode != WB_SYNC_ALL) {
2259 					ret = error;
2260 					done_index = page->index + 1;
2261 					done = 1;
2262 					break;
2263 				}
2264 				if (!ret)
2265 					ret = error;
2266 			}
2267 
2268 			/*
2269 			 * We stop writing back only if we are not doing
2270 			 * integrity sync. In case of integrity sync we have to
2271 			 * keep going until we have written all the pages
2272 			 * we tagged for writeback prior to entering this loop.
2273 			 */
2274 			if (--wbc->nr_to_write <= 0 &&
2275 			    wbc->sync_mode == WB_SYNC_NONE) {
2276 				done = 1;
2277 				break;
2278 			}
2279 		}
2280 		pagevec_release(&pvec);
2281 		cond_resched();
2282 	}
2283 
2284 	/*
2285 	 * If we hit the last page and there is more work to be done: wrap
2286 	 * back the index back to the start of the file for the next
2287 	 * time we are called.
2288 	 */
2289 	if (wbc->range_cyclic && !done)
2290 		done_index = 0;
2291 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2292 		mapping->writeback_index = done_index;
2293 
2294 	return ret;
2295 }
2296 EXPORT_SYMBOL(write_cache_pages);
2297 
2298 /*
2299  * Function used by generic_writepages to call the real writepage
2300  * function and set the mapping flags on error
2301  */
__writepage(struct page * page,struct writeback_control * wbc,void * data)2302 static int __writepage(struct page *page, struct writeback_control *wbc,
2303 		       void *data)
2304 {
2305 	struct address_space *mapping = data;
2306 	int ret = mapping->a_ops->writepage(page, wbc);
2307 	mapping_set_error(mapping, ret);
2308 	return ret;
2309 }
2310 
2311 /**
2312  * generic_writepages - walk the list of dirty pages of the given address space and writepage() all of them.
2313  * @mapping: address space structure to write
2314  * @wbc: subtract the number of written pages from *@wbc->nr_to_write
2315  *
2316  * This is a library function, which implements the writepages()
2317  * address_space_operation.
2318  *
2319  * Return: %0 on success, negative error code otherwise
2320  */
generic_writepages(struct address_space * mapping,struct writeback_control * wbc)2321 int generic_writepages(struct address_space *mapping,
2322 		       struct writeback_control *wbc)
2323 {
2324 	struct blk_plug plug;
2325 	int ret;
2326 
2327 	/* deal with chardevs and other special file */
2328 	if (!mapping->a_ops->writepage)
2329 		return 0;
2330 
2331 	blk_start_plug(&plug);
2332 	ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2333 	blk_finish_plug(&plug);
2334 	return ret;
2335 }
2336 
2337 EXPORT_SYMBOL(generic_writepages);
2338 
do_writepages(struct address_space * mapping,struct writeback_control * wbc)2339 int do_writepages(struct address_space *mapping, struct writeback_control *wbc)
2340 {
2341 	int ret;
2342 
2343 	if (wbc->nr_to_write <= 0)
2344 		return 0;
2345 	while (1) {
2346 		if (mapping->a_ops->writepages)
2347 			ret = mapping->a_ops->writepages(mapping, wbc);
2348 		else
2349 			ret = generic_writepages(mapping, wbc);
2350 		if ((ret != -ENOMEM) || (wbc->sync_mode != WB_SYNC_ALL))
2351 			break;
2352 		cond_resched();
2353 		congestion_wait(BLK_RW_ASYNC, HZ/50);
2354 	}
2355 	return ret;
2356 }
2357 
2358 /**
2359  * write_one_page - write out a single page and wait on I/O
2360  * @page: the page to write
2361  *
2362  * The page must be locked by the caller and will be unlocked upon return.
2363  *
2364  * Note that the mapping's AS_EIO/AS_ENOSPC flags will be cleared when this
2365  * function returns.
2366  *
2367  * Return: %0 on success, negative error code otherwise
2368  */
write_one_page(struct page * page)2369 int write_one_page(struct page *page)
2370 {
2371 	struct address_space *mapping = page->mapping;
2372 	int ret = 0;
2373 	struct writeback_control wbc = {
2374 		.sync_mode = WB_SYNC_ALL,
2375 		.nr_to_write = 1,
2376 	};
2377 
2378 	BUG_ON(!PageLocked(page));
2379 
2380 	wait_on_page_writeback(page);
2381 
2382 	if (clear_page_dirty_for_io(page)) {
2383 		get_page(page);
2384 		ret = mapping->a_ops->writepage(page, &wbc);
2385 		if (ret == 0)
2386 			wait_on_page_writeback(page);
2387 		put_page(page);
2388 	} else {
2389 		unlock_page(page);
2390 	}
2391 
2392 	if (!ret)
2393 		ret = filemap_check_errors(mapping);
2394 	return ret;
2395 }
2396 EXPORT_SYMBOL(write_one_page);
2397 
2398 /*
2399  * For address_spaces which do not use buffers nor write back.
2400  */
__set_page_dirty_no_writeback(struct page * page)2401 int __set_page_dirty_no_writeback(struct page *page)
2402 {
2403 	if (!PageDirty(page))
2404 		return !TestSetPageDirty(page);
2405 	return 0;
2406 }
2407 
2408 /*
2409  * Helper function for set_page_dirty family.
2410  *
2411  * Caller must hold lock_page_memcg().
2412  *
2413  * NOTE: This relies on being atomic wrt interrupts.
2414  */
account_page_dirtied(struct page * page,struct address_space * mapping)2415 void account_page_dirtied(struct page *page, struct address_space *mapping)
2416 {
2417 	struct inode *inode = mapping->host;
2418 
2419 	trace_writeback_dirty_page(page, mapping);
2420 
2421 	if (mapping_can_writeback(mapping)) {
2422 		struct bdi_writeback *wb;
2423 
2424 		inode_attach_wb(inode, page);
2425 		wb = inode_to_wb(inode);
2426 
2427 		__inc_lruvec_page_state(page, NR_FILE_DIRTY);
2428 		__inc_zone_page_state(page, NR_ZONE_WRITE_PENDING);
2429 		__inc_node_page_state(page, NR_DIRTIED);
2430 		inc_wb_stat(wb, WB_RECLAIMABLE);
2431 		inc_wb_stat(wb, WB_DIRTIED);
2432 		task_io_account_write(PAGE_SIZE);
2433 		current->nr_dirtied++;
2434 		this_cpu_inc(bdp_ratelimits);
2435 
2436 		mem_cgroup_track_foreign_dirty(page, wb);
2437 	}
2438 }
2439 
2440 /*
2441  * Helper function for deaccounting dirty page without writeback.
2442  *
2443  * Caller must hold lock_page_memcg().
2444  */
account_page_cleaned(struct page * page,struct address_space * mapping,struct bdi_writeback * wb)2445 void account_page_cleaned(struct page *page, struct address_space *mapping,
2446 			  struct bdi_writeback *wb)
2447 {
2448 	if (mapping_can_writeback(mapping)) {
2449 		dec_lruvec_page_state(page, NR_FILE_DIRTY);
2450 		dec_zone_page_state(page, NR_ZONE_WRITE_PENDING);
2451 		dec_wb_stat(wb, WB_RECLAIMABLE);
2452 		task_io_account_cancelled_write(PAGE_SIZE);
2453 	}
2454 }
2455 
2456 /*
2457  * For address_spaces which do not use buffers.  Just tag the page as dirty in
2458  * the xarray.
2459  *
2460  * This is also used when a single buffer is being dirtied: we want to set the
2461  * page dirty in that case, but not all the buffers.  This is a "bottom-up"
2462  * dirtying, whereas __set_page_dirty_buffers() is a "top-down" dirtying.
2463  *
2464  * The caller must ensure this doesn't race with truncation.  Most will simply
2465  * hold the page lock, but e.g. zap_pte_range() calls with the page mapped and
2466  * the pte lock held, which also locks out truncation.
2467  */
__set_page_dirty_nobuffers(struct page * page)2468 int __set_page_dirty_nobuffers(struct page *page)
2469 {
2470 	lock_page_memcg(page);
2471 	if (!TestSetPageDirty(page)) {
2472 		struct address_space *mapping = page_mapping(page);
2473 		unsigned long flags;
2474 
2475 		if (!mapping) {
2476 			unlock_page_memcg(page);
2477 			return 1;
2478 		}
2479 
2480 		xa_lock_irqsave(&mapping->i_pages, flags);
2481 		BUG_ON(page_mapping(page) != mapping);
2482 		WARN_ON_ONCE(!PagePrivate(page) && !PageUptodate(page));
2483 		account_page_dirtied(page, mapping);
2484 		__xa_set_mark(&mapping->i_pages, page_index(page),
2485 				   PAGECACHE_TAG_DIRTY);
2486 		xa_unlock_irqrestore(&mapping->i_pages, flags);
2487 		unlock_page_memcg(page);
2488 
2489 		if (mapping->host) {
2490 			/* !PageAnon && !swapper_space */
2491 			__mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
2492 		}
2493 		return 1;
2494 	}
2495 	unlock_page_memcg(page);
2496 	return 0;
2497 }
2498 EXPORT_SYMBOL(__set_page_dirty_nobuffers);
2499 
2500 /*
2501  * Call this whenever redirtying a page, to de-account the dirty counters
2502  * (NR_DIRTIED, WB_DIRTIED, tsk->nr_dirtied), so that they match the written
2503  * counters (NR_WRITTEN, WB_WRITTEN) in long term. The mismatches will lead to
2504  * systematic errors in balanced_dirty_ratelimit and the dirty pages position
2505  * control.
2506  */
account_page_redirty(struct page * page)2507 void account_page_redirty(struct page *page)
2508 {
2509 	struct address_space *mapping = page->mapping;
2510 
2511 	if (mapping && mapping_can_writeback(mapping)) {
2512 		struct inode *inode = mapping->host;
2513 		struct bdi_writeback *wb;
2514 		struct wb_lock_cookie cookie = {};
2515 
2516 		wb = unlocked_inode_to_wb_begin(inode, &cookie);
2517 		current->nr_dirtied--;
2518 		dec_node_page_state(page, NR_DIRTIED);
2519 		dec_wb_stat(wb, WB_DIRTIED);
2520 		unlocked_inode_to_wb_end(inode, &cookie);
2521 	}
2522 }
2523 EXPORT_SYMBOL(account_page_redirty);
2524 
2525 /*
2526  * When a writepage implementation decides that it doesn't want to write this
2527  * page for some reason, it should redirty the locked page via
2528  * redirty_page_for_writepage() and it should then unlock the page and return 0
2529  */
redirty_page_for_writepage(struct writeback_control * wbc,struct page * page)2530 int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page)
2531 {
2532 	int ret;
2533 
2534 	wbc->pages_skipped++;
2535 	ret = __set_page_dirty_nobuffers(page);
2536 	account_page_redirty(page);
2537 	return ret;
2538 }
2539 EXPORT_SYMBOL(redirty_page_for_writepage);
2540 
2541 /*
2542  * Dirty a page.
2543  *
2544  * For pages with a mapping this should be done under the page lock
2545  * for the benefit of asynchronous memory errors who prefer a consistent
2546  * dirty state. This rule can be broken in some special cases,
2547  * but should be better not to.
2548  *
2549  * If the mapping doesn't provide a set_page_dirty a_op, then
2550  * just fall through and assume that it wants buffer_heads.
2551  */
set_page_dirty(struct page * page)2552 int set_page_dirty(struct page *page)
2553 {
2554 	struct address_space *mapping = page_mapping(page);
2555 
2556 	page = compound_head(page);
2557 	if (likely(mapping)) {
2558 		int (*spd)(struct page *) = mapping->a_ops->set_page_dirty;
2559 		/*
2560 		 * readahead/lru_deactivate_page could remain
2561 		 * PG_readahead/PG_reclaim due to race with end_page_writeback
2562 		 * About readahead, if the page is written, the flags would be
2563 		 * reset. So no problem.
2564 		 * About lru_deactivate_page, if the page is redirty, the flag
2565 		 * will be reset. So no problem. but if the page is used by readahead
2566 		 * it will confuse readahead and make it restart the size rampup
2567 		 * process. But it's a trivial problem.
2568 		 */
2569 		if (PageReclaim(page))
2570 			ClearPageReclaim(page);
2571 #ifdef CONFIG_BLOCK
2572 		if (!spd)
2573 			spd = __set_page_dirty_buffers;
2574 #endif
2575 		return (*spd)(page);
2576 	}
2577 	if (!PageDirty(page)) {
2578 		if (!TestSetPageDirty(page))
2579 			return 1;
2580 	}
2581 	return 0;
2582 }
2583 EXPORT_SYMBOL(set_page_dirty);
2584 
2585 /*
2586  * set_page_dirty() is racy if the caller has no reference against
2587  * page->mapping->host, and if the page is unlocked.  This is because another
2588  * CPU could truncate the page off the mapping and then free the mapping.
2589  *
2590  * Usually, the page _is_ locked, or the caller is a user-space process which
2591  * holds a reference on the inode by having an open file.
2592  *
2593  * In other cases, the page should be locked before running set_page_dirty().
2594  */
set_page_dirty_lock(struct page * page)2595 int set_page_dirty_lock(struct page *page)
2596 {
2597 	int ret;
2598 
2599 	lock_page(page);
2600 	ret = set_page_dirty(page);
2601 	unlock_page(page);
2602 	return ret;
2603 }
2604 EXPORT_SYMBOL(set_page_dirty_lock);
2605 
2606 /*
2607  * This cancels just the dirty bit on the kernel page itself, it does NOT
2608  * actually remove dirty bits on any mmap's that may be around. It also
2609  * leaves the page tagged dirty, so any sync activity will still find it on
2610  * the dirty lists, and in particular, clear_page_dirty_for_io() will still
2611  * look at the dirty bits in the VM.
2612  *
2613  * Doing this should *normally* only ever be done when a page is truncated,
2614  * and is not actually mapped anywhere at all. However, fs/buffer.c does
2615  * this when it notices that somebody has cleaned out all the buffers on a
2616  * page without actually doing it through the VM. Can you say "ext3 is
2617  * horribly ugly"? Thought you could.
2618  */
__cancel_dirty_page(struct page * page)2619 void __cancel_dirty_page(struct page *page)
2620 {
2621 	struct address_space *mapping = page_mapping(page);
2622 
2623 	if (mapping_can_writeback(mapping)) {
2624 		struct inode *inode = mapping->host;
2625 		struct bdi_writeback *wb;
2626 		struct wb_lock_cookie cookie = {};
2627 
2628 		lock_page_memcg(page);
2629 		wb = unlocked_inode_to_wb_begin(inode, &cookie);
2630 
2631 		if (TestClearPageDirty(page))
2632 			account_page_cleaned(page, mapping, wb);
2633 
2634 		unlocked_inode_to_wb_end(inode, &cookie);
2635 		unlock_page_memcg(page);
2636 	} else {
2637 		ClearPageDirty(page);
2638 	}
2639 }
2640 EXPORT_SYMBOL(__cancel_dirty_page);
2641 
2642 /*
2643  * Clear a page's dirty flag, while caring for dirty memory accounting.
2644  * Returns true if the page was previously dirty.
2645  *
2646  * This is for preparing to put the page under writeout.  We leave the page
2647  * tagged as dirty in the xarray so that a concurrent write-for-sync
2648  * can discover it via a PAGECACHE_TAG_DIRTY walk.  The ->writepage
2649  * implementation will run either set_page_writeback() or set_page_dirty(),
2650  * at which stage we bring the page's dirty flag and xarray dirty tag
2651  * back into sync.
2652  *
2653  * This incoherency between the page's dirty flag and xarray tag is
2654  * unfortunate, but it only exists while the page is locked.
2655  */
clear_page_dirty_for_io(struct page * page)2656 int clear_page_dirty_for_io(struct page *page)
2657 {
2658 	struct address_space *mapping = page_mapping(page);
2659 	int ret = 0;
2660 
2661 	VM_BUG_ON_PAGE(!PageLocked(page), page);
2662 
2663 	if (mapping && mapping_can_writeback(mapping)) {
2664 		struct inode *inode = mapping->host;
2665 		struct bdi_writeback *wb;
2666 		struct wb_lock_cookie cookie = {};
2667 
2668 		/*
2669 		 * Yes, Virginia, this is indeed insane.
2670 		 *
2671 		 * We use this sequence to make sure that
2672 		 *  (a) we account for dirty stats properly
2673 		 *  (b) we tell the low-level filesystem to
2674 		 *      mark the whole page dirty if it was
2675 		 *      dirty in a pagetable. Only to then
2676 		 *  (c) clean the page again and return 1 to
2677 		 *      cause the writeback.
2678 		 *
2679 		 * This way we avoid all nasty races with the
2680 		 * dirty bit in multiple places and clearing
2681 		 * them concurrently from different threads.
2682 		 *
2683 		 * Note! Normally the "set_page_dirty(page)"
2684 		 * has no effect on the actual dirty bit - since
2685 		 * that will already usually be set. But we
2686 		 * need the side effects, and it can help us
2687 		 * avoid races.
2688 		 *
2689 		 * We basically use the page "master dirty bit"
2690 		 * as a serialization point for all the different
2691 		 * threads doing their things.
2692 		 */
2693 		if (page_mkclean(page))
2694 			set_page_dirty(page);
2695 		/*
2696 		 * We carefully synchronise fault handlers against
2697 		 * installing a dirty pte and marking the page dirty
2698 		 * at this point.  We do this by having them hold the
2699 		 * page lock while dirtying the page, and pages are
2700 		 * always locked coming in here, so we get the desired
2701 		 * exclusion.
2702 		 */
2703 		wb = unlocked_inode_to_wb_begin(inode, &cookie);
2704 		if (TestClearPageDirty(page)) {
2705 			dec_lruvec_page_state(page, NR_FILE_DIRTY);
2706 			dec_zone_page_state(page, NR_ZONE_WRITE_PENDING);
2707 			dec_wb_stat(wb, WB_RECLAIMABLE);
2708 			ret = 1;
2709 		}
2710 		unlocked_inode_to_wb_end(inode, &cookie);
2711 		return ret;
2712 	}
2713 	return TestClearPageDirty(page);
2714 }
2715 EXPORT_SYMBOL(clear_page_dirty_for_io);
2716 
test_clear_page_writeback(struct page * page)2717 int test_clear_page_writeback(struct page *page)
2718 {
2719 	struct address_space *mapping = page_mapping(page);
2720 	struct mem_cgroup *memcg;
2721 	struct lruvec *lruvec;
2722 	int ret;
2723 
2724 	memcg = lock_page_memcg(page);
2725 	lruvec = mem_cgroup_page_lruvec(page, page_pgdat(page));
2726 	if (mapping && mapping_use_writeback_tags(mapping)) {
2727 		struct inode *inode = mapping->host;
2728 		struct backing_dev_info *bdi = inode_to_bdi(inode);
2729 		unsigned long flags;
2730 
2731 		xa_lock_irqsave(&mapping->i_pages, flags);
2732 		ret = TestClearPageWriteback(page);
2733 		if (ret) {
2734 			__xa_clear_mark(&mapping->i_pages, page_index(page),
2735 						PAGECACHE_TAG_WRITEBACK);
2736 			if (bdi->capabilities & BDI_CAP_WRITEBACK_ACCT) {
2737 				struct bdi_writeback *wb = inode_to_wb(inode);
2738 
2739 				dec_wb_stat(wb, WB_WRITEBACK);
2740 				__wb_writeout_inc(wb);
2741 			}
2742 		}
2743 
2744 		if (mapping->host && !mapping_tagged(mapping,
2745 						     PAGECACHE_TAG_WRITEBACK))
2746 			sb_clear_inode_writeback(mapping->host);
2747 
2748 		xa_unlock_irqrestore(&mapping->i_pages, flags);
2749 	} else {
2750 		ret = TestClearPageWriteback(page);
2751 	}
2752 	if (ret) {
2753 		dec_lruvec_state(lruvec, NR_WRITEBACK);
2754 		dec_zone_page_state(page, NR_ZONE_WRITE_PENDING);
2755 		inc_node_page_state(page, NR_WRITTEN);
2756 	}
2757 	__unlock_page_memcg(memcg);
2758 	return ret;
2759 }
2760 
__test_set_page_writeback(struct page * page,bool keep_write)2761 int __test_set_page_writeback(struct page *page, bool keep_write)
2762 {
2763 	struct address_space *mapping = page_mapping(page);
2764 	int ret, access_ret;
2765 
2766 	lock_page_memcg(page);
2767 	if (mapping && mapping_use_writeback_tags(mapping)) {
2768 		XA_STATE(xas, &mapping->i_pages, page_index(page));
2769 		struct inode *inode = mapping->host;
2770 		struct backing_dev_info *bdi = inode_to_bdi(inode);
2771 		unsigned long flags;
2772 
2773 		xas_lock_irqsave(&xas, flags);
2774 		xas_load(&xas);
2775 		ret = TestSetPageWriteback(page);
2776 		if (!ret) {
2777 			bool on_wblist;
2778 
2779 			on_wblist = mapping_tagged(mapping,
2780 						   PAGECACHE_TAG_WRITEBACK);
2781 
2782 			xas_set_mark(&xas, PAGECACHE_TAG_WRITEBACK);
2783 			if (bdi->capabilities & BDI_CAP_WRITEBACK_ACCT)
2784 				inc_wb_stat(inode_to_wb(inode), WB_WRITEBACK);
2785 
2786 			/*
2787 			 * We can come through here when swapping anonymous
2788 			 * pages, so we don't necessarily have an inode to track
2789 			 * for sync.
2790 			 */
2791 			if (mapping->host && !on_wblist)
2792 				sb_mark_inode_writeback(mapping->host);
2793 		}
2794 		if (!PageDirty(page))
2795 			xas_clear_mark(&xas, PAGECACHE_TAG_DIRTY);
2796 		if (!keep_write)
2797 			xas_clear_mark(&xas, PAGECACHE_TAG_TOWRITE);
2798 		xas_unlock_irqrestore(&xas, flags);
2799 	} else {
2800 		ret = TestSetPageWriteback(page);
2801 	}
2802 	if (!ret) {
2803 		inc_lruvec_page_state(page, NR_WRITEBACK);
2804 		inc_zone_page_state(page, NR_ZONE_WRITE_PENDING);
2805 	}
2806 	unlock_page_memcg(page);
2807 	access_ret = arch_make_page_accessible(page);
2808 	/*
2809 	 * If writeback has been triggered on a page that cannot be made
2810 	 * accessible, it is too late to recover here.
2811 	 */
2812 	VM_BUG_ON_PAGE(access_ret != 0, page);
2813 
2814 	return ret;
2815 
2816 }
2817 EXPORT_SYMBOL(__test_set_page_writeback);
2818 
2819 /*
2820  * Wait for a page to complete writeback
2821  */
wait_on_page_writeback(struct page * page)2822 void wait_on_page_writeback(struct page *page)
2823 {
2824 	while (PageWriteback(page)) {
2825 		trace_wait_on_page_writeback(page, page_mapping(page));
2826 		wait_on_page_bit(page, PG_writeback);
2827 	}
2828 }
2829 EXPORT_SYMBOL_GPL(wait_on_page_writeback);
2830 
2831 /**
2832  * wait_for_stable_page() - wait for writeback to finish, if necessary.
2833  * @page:	The page to wait on.
2834  *
2835  * This function determines if the given page is related to a backing device
2836  * that requires page contents to be held stable during writeback.  If so, then
2837  * it will wait for any pending writeback to complete.
2838  */
wait_for_stable_page(struct page * page)2839 void wait_for_stable_page(struct page *page)
2840 {
2841 	page = thp_head(page);
2842 	if (page->mapping->host->i_sb->s_iflags & SB_I_STABLE_WRITES)
2843 		wait_on_page_writeback(page);
2844 }
2845 EXPORT_SYMBOL_GPL(wait_for_stable_page);
2846