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