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