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