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