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