xref: /linux/mm/vmstat.c (revision 7b667acd69e316c2ed1b47e5dcd9d093be4a843f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/mm/vmstat.c
4  *
5  *  Manages VM statistics
6  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
7  *
8  *  zoned VM statistics
9  *  Copyright (C) 2006 Silicon Graphics, Inc.,
10  *		Christoph Lameter <christoph@lameter.com>
11  *  Copyright (C) 2008-2014 Christoph Lameter
12  */
13 #include <linux/fs.h>
14 #include <linux/mm.h>
15 #include <linux/err.h>
16 #include <linux/module.h>
17 #include <linux/slab.h>
18 #include <linux/cpu.h>
19 #include <linux/cpumask.h>
20 #include <linux/vmstat.h>
21 #include <linux/proc_fs.h>
22 #include <linux/seq_file.h>
23 #include <linux/debugfs.h>
24 #include <linux/sched.h>
25 #include <linux/math64.h>
26 #include <linux/writeback.h>
27 #include <linux/compaction.h>
28 #include <linux/mm_inline.h>
29 #include <linux/page_owner.h>
30 #include <linux/sched/isolation.h>
31 
32 #include "internal.h"
33 
34 #ifdef CONFIG_PROC_FS
35 #ifdef CONFIG_NUMA
36 #define ENABLE_NUMA_STAT 1
37 static int sysctl_vm_numa_stat = ENABLE_NUMA_STAT;
38 
39 /* zero numa counters within a zone */
40 static void zero_zone_numa_counters(struct zone *zone)
41 {
42 	int item, cpu;
43 
44 	for (item = 0; item < NR_VM_NUMA_EVENT_ITEMS; item++) {
45 		atomic_long_set(&zone->vm_numa_event[item], 0);
46 		for_each_online_cpu(cpu) {
47 			per_cpu_ptr(zone->per_cpu_zonestats, cpu)->vm_numa_event[item]
48 						= 0;
49 		}
50 	}
51 }
52 
53 /* zero numa counters of all the populated zones */
54 static void zero_zones_numa_counters(void)
55 {
56 	struct zone *zone;
57 
58 	for_each_populated_zone(zone)
59 		zero_zone_numa_counters(zone);
60 }
61 
62 /* zero global numa counters */
63 static void zero_global_numa_counters(void)
64 {
65 	int item;
66 
67 	for (item = 0; item < NR_VM_NUMA_EVENT_ITEMS; item++)
68 		atomic_long_set(&vm_numa_event[item], 0);
69 }
70 
71 static void invalid_numa_statistics(void)
72 {
73 	zero_zones_numa_counters();
74 	zero_global_numa_counters();
75 }
76 
77 static DEFINE_MUTEX(vm_numa_stat_lock);
78 
79 static int sysctl_vm_numa_stat_handler(const struct ctl_table *table, int write,
80 		void *buffer, size_t *length, loff_t *ppos)
81 {
82 	int ret, oldval;
83 
84 	mutex_lock(&vm_numa_stat_lock);
85 	if (write)
86 		oldval = sysctl_vm_numa_stat;
87 	ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
88 	if (ret || !write)
89 		goto out;
90 
91 	if (oldval == sysctl_vm_numa_stat)
92 		goto out;
93 	else if (sysctl_vm_numa_stat == ENABLE_NUMA_STAT) {
94 		static_branch_enable(&vm_numa_stat_key);
95 		pr_info("enable numa statistics\n");
96 	} else {
97 		static_branch_disable(&vm_numa_stat_key);
98 		invalid_numa_statistics();
99 		pr_info("disable numa statistics, and clear numa counters\n");
100 	}
101 
102 out:
103 	mutex_unlock(&vm_numa_stat_lock);
104 	return ret;
105 }
106 #endif
107 #endif /* CONFIG_PROC_FS */
108 
109 #ifdef CONFIG_VM_EVENT_COUNTERS
110 DEFINE_PER_CPU(struct vm_event_state, vm_event_states) = {{0}};
111 EXPORT_PER_CPU_SYMBOL(vm_event_states);
112 
113 static void sum_vm_events(unsigned long *ret)
114 {
115 	int cpu;
116 	int i;
117 
118 	memset(ret, 0, NR_VM_EVENT_ITEMS * sizeof(unsigned long));
119 
120 	for_each_online_cpu(cpu) {
121 		struct vm_event_state *this = &per_cpu(vm_event_states, cpu);
122 
123 		for (i = 0; i < NR_VM_EVENT_ITEMS; i++)
124 			ret[i] += this->event[i];
125 	}
126 }
127 
128 /*
129  * Accumulate the vm event counters across all CPUs.
130  * The result is unavoidably approximate - it can change
131  * during and after execution of this function.
132 */
133 void all_vm_events(unsigned long *ret)
134 {
135 	cpus_read_lock();
136 	sum_vm_events(ret);
137 	cpus_read_unlock();
138 }
139 EXPORT_SYMBOL_GPL(all_vm_events);
140 
141 /*
142  * Fold the foreign cpu events into our own.
143  *
144  * This is adding to the events on one processor
145  * but keeps the global counts constant.
146  */
147 void vm_events_fold_cpu(int cpu)
148 {
149 	struct vm_event_state *fold_state = &per_cpu(vm_event_states, cpu);
150 	int i;
151 
152 	for (i = 0; i < NR_VM_EVENT_ITEMS; i++) {
153 		count_vm_events(i, fold_state->event[i]);
154 		fold_state->event[i] = 0;
155 	}
156 }
157 
158 #endif /* CONFIG_VM_EVENT_COUNTERS */
159 
160 /*
161  * Manage combined zone based / global counters
162  *
163  * vm_stat contains the global counters
164  */
165 atomic_long_t vm_zone_stat[NR_VM_ZONE_STAT_ITEMS] __cacheline_aligned_in_smp;
166 atomic_long_t vm_node_stat[NR_VM_NODE_STAT_ITEMS] __cacheline_aligned_in_smp;
167 atomic_long_t vm_numa_event[NR_VM_NUMA_EVENT_ITEMS] __cacheline_aligned_in_smp;
168 EXPORT_SYMBOL(vm_zone_stat);
169 EXPORT_SYMBOL(vm_node_stat);
170 
171 #ifdef CONFIG_NUMA
172 static void fold_vm_zone_numa_events(struct zone *zone)
173 {
174 	unsigned long zone_numa_events[NR_VM_NUMA_EVENT_ITEMS] = { 0, };
175 	int cpu;
176 	enum numa_stat_item item;
177 
178 	for_each_online_cpu(cpu) {
179 		struct per_cpu_zonestat *pzstats;
180 
181 		pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
182 		for (item = 0; item < NR_VM_NUMA_EVENT_ITEMS; item++)
183 			zone_numa_events[item] += xchg(&pzstats->vm_numa_event[item], 0);
184 	}
185 
186 	for (item = 0; item < NR_VM_NUMA_EVENT_ITEMS; item++)
187 		zone_numa_event_add(zone_numa_events[item], zone, item);
188 }
189 
190 void fold_vm_numa_events(void)
191 {
192 	struct zone *zone;
193 
194 	for_each_populated_zone(zone)
195 		fold_vm_zone_numa_events(zone);
196 }
197 #endif
198 
199 #ifdef CONFIG_SMP
200 
201 int calculate_pressure_threshold(struct zone *zone)
202 {
203 	int threshold;
204 	int watermark_distance;
205 
206 	/*
207 	 * As vmstats are not up to date, there is drift between the estimated
208 	 * and real values. For high thresholds and a high number of CPUs, it
209 	 * is possible for the min watermark to be breached while the estimated
210 	 * value looks fine. The pressure threshold is a reduced value such
211 	 * that even the maximum amount of drift will not accidentally breach
212 	 * the min watermark
213 	 */
214 	watermark_distance = low_wmark_pages(zone) - min_wmark_pages(zone);
215 	threshold = max(1, (int)(watermark_distance / num_online_cpus()));
216 
217 	/*
218 	 * Maximum threshold is 125
219 	 */
220 	threshold = min(125, threshold);
221 
222 	return threshold;
223 }
224 
225 int calculate_normal_threshold(struct zone *zone)
226 {
227 	int threshold;
228 	int mem;	/* memory in 128 MB units */
229 
230 	/*
231 	 * The threshold scales with the number of processors and the amount
232 	 * of memory per zone. More memory means that we can defer updates for
233 	 * longer, more processors could lead to more contention.
234  	 * fls() is used to have a cheap way of logarithmic scaling.
235 	 *
236 	 * Some sample thresholds:
237 	 *
238 	 * Threshold	Processors	(fls)	Zonesize	fls(mem)+1
239 	 * ------------------------------------------------------------------
240 	 * 8		1		1	0.9-1 GB	4
241 	 * 16		2		2	0.9-1 GB	4
242 	 * 20 		2		2	1-2 GB		5
243 	 * 24		2		2	2-4 GB		6
244 	 * 28		2		2	4-8 GB		7
245 	 * 32		2		2	8-16 GB		8
246 	 * 4		2		2	<128M		1
247 	 * 30		4		3	2-4 GB		5
248 	 * 48		4		3	8-16 GB		8
249 	 * 32		8		4	1-2 GB		4
250 	 * 32		8		4	0.9-1GB		4
251 	 * 10		16		5	<128M		1
252 	 * 40		16		5	900M		4
253 	 * 70		64		7	2-4 GB		5
254 	 * 84		64		7	4-8 GB		6
255 	 * 108		512		9	4-8 GB		6
256 	 * 125		1024		10	8-16 GB		8
257 	 * 125		1024		10	16-32 GB	9
258 	 */
259 
260 	mem = zone_managed_pages(zone) >> (27 - PAGE_SHIFT);
261 
262 	threshold = 2 * fls(num_online_cpus()) * (1 + fls(mem));
263 
264 	/*
265 	 * Maximum threshold is 125
266 	 */
267 	threshold = min(125, threshold);
268 
269 	return threshold;
270 }
271 
272 /*
273  * Refresh the thresholds for each zone.
274  */
275 void refresh_zone_stat_thresholds(void)
276 {
277 	struct pglist_data *pgdat;
278 	struct zone *zone;
279 	int cpu;
280 	int threshold;
281 
282 	/* Zero current pgdat thresholds */
283 	for_each_online_pgdat(pgdat) {
284 		for_each_online_cpu(cpu) {
285 			per_cpu_ptr(pgdat->per_cpu_nodestats, cpu)->stat_threshold = 0;
286 		}
287 	}
288 
289 	for_each_populated_zone(zone) {
290 		struct pglist_data *pgdat = zone->zone_pgdat;
291 		unsigned long max_drift, tolerate_drift;
292 
293 		threshold = calculate_normal_threshold(zone);
294 
295 		for_each_online_cpu(cpu) {
296 			int pgdat_threshold;
297 
298 			per_cpu_ptr(zone->per_cpu_zonestats, cpu)->stat_threshold
299 							= threshold;
300 
301 			/* Base nodestat threshold on the largest populated zone. */
302 			pgdat_threshold = per_cpu_ptr(pgdat->per_cpu_nodestats, cpu)->stat_threshold;
303 			per_cpu_ptr(pgdat->per_cpu_nodestats, cpu)->stat_threshold
304 				= max(threshold, pgdat_threshold);
305 		}
306 
307 		/*
308 		 * Only set percpu_drift_mark if there is a danger that
309 		 * NR_FREE_PAGES reports the low watermark is ok when in fact
310 		 * the min watermark could be breached by an allocation
311 		 */
312 		tolerate_drift = low_wmark_pages(zone) - min_wmark_pages(zone);
313 		max_drift = num_online_cpus() * threshold;
314 		if (max_drift > tolerate_drift)
315 			zone->percpu_drift_mark = high_wmark_pages(zone) +
316 					max_drift;
317 	}
318 }
319 
320 void set_pgdat_percpu_threshold(pg_data_t *pgdat,
321 				int (*calculate_pressure)(struct zone *))
322 {
323 	struct zone *zone;
324 	int cpu;
325 	int threshold;
326 	int i;
327 
328 	for (i = 0; i < pgdat->nr_zones; i++) {
329 		zone = &pgdat->node_zones[i];
330 		if (!zone->percpu_drift_mark)
331 			continue;
332 
333 		threshold = (*calculate_pressure)(zone);
334 		for_each_online_cpu(cpu)
335 			per_cpu_ptr(zone->per_cpu_zonestats, cpu)->stat_threshold
336 							= threshold;
337 	}
338 }
339 
340 /*
341  * For use when we know that interrupts are disabled,
342  * or when we know that preemption is disabled and that
343  * particular counter cannot be updated from interrupt context.
344  */
345 void __mod_zone_page_state(struct zone *zone, enum zone_stat_item item,
346 			   long delta)
347 {
348 	struct per_cpu_zonestat __percpu *pcp = zone->per_cpu_zonestats;
349 	s8 __percpu *p = pcp->vm_stat_diff + item;
350 	long x;
351 	long t;
352 
353 	/*
354 	 * Accurate vmstat updates require a RMW. On !PREEMPT_RT kernels,
355 	 * atomicity is provided by IRQs being disabled -- either explicitly
356 	 * or via local_lock_irq. On PREEMPT_RT, local_lock_irq only disables
357 	 * CPU migrations and preemption potentially corrupts a counter so
358 	 * disable preemption.
359 	 */
360 	preempt_disable_nested();
361 
362 	x = delta + __this_cpu_read(*p);
363 
364 	t = __this_cpu_read(pcp->stat_threshold);
365 
366 	if (unlikely(abs(x) > t)) {
367 		zone_page_state_add(x, zone, item);
368 		x = 0;
369 	}
370 	__this_cpu_write(*p, x);
371 
372 	preempt_enable_nested();
373 }
374 EXPORT_SYMBOL(__mod_zone_page_state);
375 
376 void __mod_node_page_state(struct pglist_data *pgdat, enum node_stat_item item,
377 				long delta)
378 {
379 	struct per_cpu_nodestat __percpu *pcp = pgdat->per_cpu_nodestats;
380 	s8 __percpu *p = pcp->vm_node_stat_diff + item;
381 	long x;
382 	long t;
383 
384 	if (vmstat_item_in_bytes(item)) {
385 		/*
386 		 * Only cgroups use subpage accounting right now; at
387 		 * the global level, these items still change in
388 		 * multiples of whole pages. Store them as pages
389 		 * internally to keep the per-cpu counters compact.
390 		 */
391 		VM_WARN_ON_ONCE(delta & (PAGE_SIZE - 1));
392 		delta >>= PAGE_SHIFT;
393 	}
394 
395 	/* See __mod_node_page_state */
396 	preempt_disable_nested();
397 
398 	x = delta + __this_cpu_read(*p);
399 
400 	t = __this_cpu_read(pcp->stat_threshold);
401 
402 	if (unlikely(abs(x) > t)) {
403 		node_page_state_add(x, pgdat, item);
404 		x = 0;
405 	}
406 	__this_cpu_write(*p, x);
407 
408 	preempt_enable_nested();
409 }
410 EXPORT_SYMBOL(__mod_node_page_state);
411 
412 /*
413  * Optimized increment and decrement functions.
414  *
415  * These are only for a single page and therefore can take a struct page *
416  * argument instead of struct zone *. This allows the inclusion of the code
417  * generated for page_zone(page) into the optimized functions.
418  *
419  * No overflow check is necessary and therefore the differential can be
420  * incremented or decremented in place which may allow the compilers to
421  * generate better code.
422  * The increment or decrement is known and therefore one boundary check can
423  * be omitted.
424  *
425  * NOTE: These functions are very performance sensitive. Change only
426  * with care.
427  *
428  * Some processors have inc/dec instructions that are atomic vs an interrupt.
429  * However, the code must first determine the differential location in a zone
430  * based on the processor number and then inc/dec the counter. There is no
431  * guarantee without disabling preemption that the processor will not change
432  * in between and therefore the atomicity vs. interrupt cannot be exploited
433  * in a useful way here.
434  */
435 void __inc_zone_state(struct zone *zone, enum zone_stat_item item)
436 {
437 	struct per_cpu_zonestat __percpu *pcp = zone->per_cpu_zonestats;
438 	s8 __percpu *p = pcp->vm_stat_diff + item;
439 	s8 v, t;
440 
441 	/* See __mod_node_page_state */
442 	preempt_disable_nested();
443 
444 	v = __this_cpu_inc_return(*p);
445 	t = __this_cpu_read(pcp->stat_threshold);
446 	if (unlikely(v > t)) {
447 		s8 overstep = t >> 1;
448 
449 		zone_page_state_add(v + overstep, zone, item);
450 		__this_cpu_write(*p, -overstep);
451 	}
452 
453 	preempt_enable_nested();
454 }
455 
456 void __inc_node_state(struct pglist_data *pgdat, enum node_stat_item item)
457 {
458 	struct per_cpu_nodestat __percpu *pcp = pgdat->per_cpu_nodestats;
459 	s8 __percpu *p = pcp->vm_node_stat_diff + item;
460 	s8 v, t;
461 
462 	VM_WARN_ON_ONCE(vmstat_item_in_bytes(item));
463 
464 	/* See __mod_node_page_state */
465 	preempt_disable_nested();
466 
467 	v = __this_cpu_inc_return(*p);
468 	t = __this_cpu_read(pcp->stat_threshold);
469 	if (unlikely(v > t)) {
470 		s8 overstep = t >> 1;
471 
472 		node_page_state_add(v + overstep, pgdat, item);
473 		__this_cpu_write(*p, -overstep);
474 	}
475 
476 	preempt_enable_nested();
477 }
478 
479 void __inc_zone_page_state(struct page *page, enum zone_stat_item item)
480 {
481 	__inc_zone_state(page_zone(page), item);
482 }
483 EXPORT_SYMBOL(__inc_zone_page_state);
484 
485 void __inc_node_page_state(struct page *page, enum node_stat_item item)
486 {
487 	__inc_node_state(page_pgdat(page), item);
488 }
489 EXPORT_SYMBOL(__inc_node_page_state);
490 
491 void __dec_zone_state(struct zone *zone, enum zone_stat_item item)
492 {
493 	struct per_cpu_zonestat __percpu *pcp = zone->per_cpu_zonestats;
494 	s8 __percpu *p = pcp->vm_stat_diff + item;
495 	s8 v, t;
496 
497 	/* See __mod_node_page_state */
498 	preempt_disable_nested();
499 
500 	v = __this_cpu_dec_return(*p);
501 	t = __this_cpu_read(pcp->stat_threshold);
502 	if (unlikely(v < - t)) {
503 		s8 overstep = t >> 1;
504 
505 		zone_page_state_add(v - overstep, zone, item);
506 		__this_cpu_write(*p, overstep);
507 	}
508 
509 	preempt_enable_nested();
510 }
511 
512 void __dec_node_state(struct pglist_data *pgdat, enum node_stat_item item)
513 {
514 	struct per_cpu_nodestat __percpu *pcp = pgdat->per_cpu_nodestats;
515 	s8 __percpu *p = pcp->vm_node_stat_diff + item;
516 	s8 v, t;
517 
518 	VM_WARN_ON_ONCE(vmstat_item_in_bytes(item));
519 
520 	/* See __mod_node_page_state */
521 	preempt_disable_nested();
522 
523 	v = __this_cpu_dec_return(*p);
524 	t = __this_cpu_read(pcp->stat_threshold);
525 	if (unlikely(v < - t)) {
526 		s8 overstep = t >> 1;
527 
528 		node_page_state_add(v - overstep, pgdat, item);
529 		__this_cpu_write(*p, overstep);
530 	}
531 
532 	preempt_enable_nested();
533 }
534 
535 void __dec_zone_page_state(struct page *page, enum zone_stat_item item)
536 {
537 	__dec_zone_state(page_zone(page), item);
538 }
539 EXPORT_SYMBOL(__dec_zone_page_state);
540 
541 void __dec_node_page_state(struct page *page, enum node_stat_item item)
542 {
543 	__dec_node_state(page_pgdat(page), item);
544 }
545 EXPORT_SYMBOL(__dec_node_page_state);
546 
547 #ifdef CONFIG_HAVE_CMPXCHG_LOCAL
548 /*
549  * If we have cmpxchg_local support then we do not need to incur the overhead
550  * that comes with local_irq_save/restore if we use this_cpu_cmpxchg.
551  *
552  * mod_state() modifies the zone counter state through atomic per cpu
553  * operations.
554  *
555  * Overstep mode specifies how overstep should handled:
556  *     0       No overstepping
557  *     1       Overstepping half of threshold
558  *     -1      Overstepping minus half of threshold
559 */
560 static inline void mod_zone_state(struct zone *zone,
561        enum zone_stat_item item, long delta, int overstep_mode)
562 {
563 	struct per_cpu_zonestat __percpu *pcp = zone->per_cpu_zonestats;
564 	s8 __percpu *p = pcp->vm_stat_diff + item;
565 	long n, t, z;
566 	s8 o;
567 
568 	o = this_cpu_read(*p);
569 	do {
570 		z = 0;  /* overflow to zone counters */
571 
572 		/*
573 		 * The fetching of the stat_threshold is racy. We may apply
574 		 * a counter threshold to the wrong the cpu if we get
575 		 * rescheduled while executing here. However, the next
576 		 * counter update will apply the threshold again and
577 		 * therefore bring the counter under the threshold again.
578 		 *
579 		 * Most of the time the thresholds are the same anyways
580 		 * for all cpus in a zone.
581 		 */
582 		t = this_cpu_read(pcp->stat_threshold);
583 
584 		n = delta + (long)o;
585 
586 		if (abs(n) > t) {
587 			int os = overstep_mode * (t >> 1) ;
588 
589 			/* Overflow must be added to zone counters */
590 			z = n + os;
591 			n = -os;
592 		}
593 	} while (!this_cpu_try_cmpxchg(*p, &o, n));
594 
595 	if (z)
596 		zone_page_state_add(z, zone, item);
597 }
598 
599 void mod_zone_page_state(struct zone *zone, enum zone_stat_item item,
600 			 long delta)
601 {
602 	mod_zone_state(zone, item, delta, 0);
603 }
604 EXPORT_SYMBOL(mod_zone_page_state);
605 
606 void inc_zone_page_state(struct page *page, enum zone_stat_item item)
607 {
608 	mod_zone_state(page_zone(page), item, 1, 1);
609 }
610 EXPORT_SYMBOL(inc_zone_page_state);
611 
612 void dec_zone_page_state(struct page *page, enum zone_stat_item item)
613 {
614 	mod_zone_state(page_zone(page), item, -1, -1);
615 }
616 EXPORT_SYMBOL(dec_zone_page_state);
617 
618 static inline void mod_node_state(struct pglist_data *pgdat,
619        enum node_stat_item item, int delta, int overstep_mode)
620 {
621 	struct per_cpu_nodestat __percpu *pcp = pgdat->per_cpu_nodestats;
622 	s8 __percpu *p = pcp->vm_node_stat_diff + item;
623 	long n, t, z;
624 	s8 o;
625 
626 	if (vmstat_item_in_bytes(item)) {
627 		/*
628 		 * Only cgroups use subpage accounting right now; at
629 		 * the global level, these items still change in
630 		 * multiples of whole pages. Store them as pages
631 		 * internally to keep the per-cpu counters compact.
632 		 */
633 		VM_WARN_ON_ONCE(delta & (PAGE_SIZE - 1));
634 		delta >>= PAGE_SHIFT;
635 	}
636 
637 	o = this_cpu_read(*p);
638 	do {
639 		z = 0;  /* overflow to node counters */
640 
641 		/*
642 		 * The fetching of the stat_threshold is racy. We may apply
643 		 * a counter threshold to the wrong the cpu if we get
644 		 * rescheduled while executing here. However, the next
645 		 * counter update will apply the threshold again and
646 		 * therefore bring the counter under the threshold again.
647 		 *
648 		 * Most of the time the thresholds are the same anyways
649 		 * for all cpus in a node.
650 		 */
651 		t = this_cpu_read(pcp->stat_threshold);
652 
653 		n = delta + (long)o;
654 
655 		if (abs(n) > t) {
656 			int os = overstep_mode * (t >> 1) ;
657 
658 			/* Overflow must be added to node counters */
659 			z = n + os;
660 			n = -os;
661 		}
662 	} while (!this_cpu_try_cmpxchg(*p, &o, n));
663 
664 	if (z)
665 		node_page_state_add(z, pgdat, item);
666 }
667 
668 void mod_node_page_state(struct pglist_data *pgdat, enum node_stat_item item,
669 					long delta)
670 {
671 	mod_node_state(pgdat, item, delta, 0);
672 }
673 EXPORT_SYMBOL(mod_node_page_state);
674 
675 void inc_node_state(struct pglist_data *pgdat, enum node_stat_item item)
676 {
677 	mod_node_state(pgdat, item, 1, 1);
678 }
679 
680 void inc_node_page_state(struct page *page, enum node_stat_item item)
681 {
682 	mod_node_state(page_pgdat(page), item, 1, 1);
683 }
684 EXPORT_SYMBOL(inc_node_page_state);
685 
686 void dec_node_page_state(struct page *page, enum node_stat_item item)
687 {
688 	mod_node_state(page_pgdat(page), item, -1, -1);
689 }
690 EXPORT_SYMBOL(dec_node_page_state);
691 #else
692 /*
693  * Use interrupt disable to serialize counter updates
694  */
695 void mod_zone_page_state(struct zone *zone, enum zone_stat_item item,
696 			 long delta)
697 {
698 	unsigned long flags;
699 
700 	local_irq_save(flags);
701 	__mod_zone_page_state(zone, item, delta);
702 	local_irq_restore(flags);
703 }
704 EXPORT_SYMBOL(mod_zone_page_state);
705 
706 void inc_zone_page_state(struct page *page, enum zone_stat_item item)
707 {
708 	unsigned long flags;
709 	struct zone *zone;
710 
711 	zone = page_zone(page);
712 	local_irq_save(flags);
713 	__inc_zone_state(zone, item);
714 	local_irq_restore(flags);
715 }
716 EXPORT_SYMBOL(inc_zone_page_state);
717 
718 void dec_zone_page_state(struct page *page, enum zone_stat_item item)
719 {
720 	unsigned long flags;
721 
722 	local_irq_save(flags);
723 	__dec_zone_page_state(page, item);
724 	local_irq_restore(flags);
725 }
726 EXPORT_SYMBOL(dec_zone_page_state);
727 
728 void inc_node_state(struct pglist_data *pgdat, enum node_stat_item item)
729 {
730 	unsigned long flags;
731 
732 	local_irq_save(flags);
733 	__inc_node_state(pgdat, item);
734 	local_irq_restore(flags);
735 }
736 EXPORT_SYMBOL(inc_node_state);
737 
738 void mod_node_page_state(struct pglist_data *pgdat, enum node_stat_item item,
739 					long delta)
740 {
741 	unsigned long flags;
742 
743 	local_irq_save(flags);
744 	__mod_node_page_state(pgdat, item, delta);
745 	local_irq_restore(flags);
746 }
747 EXPORT_SYMBOL(mod_node_page_state);
748 
749 void inc_node_page_state(struct page *page, enum node_stat_item item)
750 {
751 	unsigned long flags;
752 	struct pglist_data *pgdat;
753 
754 	pgdat = page_pgdat(page);
755 	local_irq_save(flags);
756 	__inc_node_state(pgdat, item);
757 	local_irq_restore(flags);
758 }
759 EXPORT_SYMBOL(inc_node_page_state);
760 
761 void dec_node_page_state(struct page *page, enum node_stat_item item)
762 {
763 	unsigned long flags;
764 
765 	local_irq_save(flags);
766 	__dec_node_page_state(page, item);
767 	local_irq_restore(flags);
768 }
769 EXPORT_SYMBOL(dec_node_page_state);
770 #endif
771 
772 /*
773  * Fold a differential into the global counters.
774  * Returns the number of counters updated.
775  */
776 static int fold_diff(int *zone_diff, int *node_diff)
777 {
778 	int i;
779 	int changes = 0;
780 
781 	for (i = 0; i < NR_VM_ZONE_STAT_ITEMS; i++)
782 		if (zone_diff[i]) {
783 			atomic_long_add(zone_diff[i], &vm_zone_stat[i]);
784 			changes++;
785 	}
786 
787 	for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
788 		if (node_diff[i]) {
789 			atomic_long_add(node_diff[i], &vm_node_stat[i]);
790 			changes++;
791 	}
792 	return changes;
793 }
794 
795 /*
796  * Update the zone counters for the current cpu.
797  *
798  * Note that refresh_cpu_vm_stats strives to only access
799  * node local memory. The per cpu pagesets on remote zones are placed
800  * in the memory local to the processor using that pageset. So the
801  * loop over all zones will access a series of cachelines local to
802  * the processor.
803  *
804  * The call to zone_page_state_add updates the cachelines with the
805  * statistics in the remote zone struct as well as the global cachelines
806  * with the global counters. These could cause remote node cache line
807  * bouncing and will have to be only done when necessary.
808  *
809  * The function returns the number of global counters updated.
810  */
811 static int refresh_cpu_vm_stats(bool do_pagesets)
812 {
813 	struct pglist_data *pgdat;
814 	struct zone *zone;
815 	int i;
816 	int global_zone_diff[NR_VM_ZONE_STAT_ITEMS] = { 0, };
817 	int global_node_diff[NR_VM_NODE_STAT_ITEMS] = { 0, };
818 	int changes = 0;
819 
820 	for_each_populated_zone(zone) {
821 		struct per_cpu_zonestat __percpu *pzstats = zone->per_cpu_zonestats;
822 		struct per_cpu_pages __percpu *pcp = zone->per_cpu_pageset;
823 
824 		for (i = 0; i < NR_VM_ZONE_STAT_ITEMS; i++) {
825 			int v;
826 
827 			v = this_cpu_xchg(pzstats->vm_stat_diff[i], 0);
828 			if (v) {
829 
830 				atomic_long_add(v, &zone->vm_stat[i]);
831 				global_zone_diff[i] += v;
832 #ifdef CONFIG_NUMA
833 				/* 3 seconds idle till flush */
834 				__this_cpu_write(pcp->expire, 3);
835 #endif
836 			}
837 		}
838 
839 		if (do_pagesets) {
840 			cond_resched();
841 
842 			changes += decay_pcp_high(zone, this_cpu_ptr(pcp));
843 #ifdef CONFIG_NUMA
844 			/*
845 			 * Deal with draining the remote pageset of this
846 			 * processor
847 			 *
848 			 * Check if there are pages remaining in this pageset
849 			 * if not then there is nothing to expire.
850 			 */
851 			if (!__this_cpu_read(pcp->expire) ||
852 			       !__this_cpu_read(pcp->count))
853 				continue;
854 
855 			/*
856 			 * We never drain zones local to this processor.
857 			 */
858 			if (zone_to_nid(zone) == numa_node_id()) {
859 				__this_cpu_write(pcp->expire, 0);
860 				continue;
861 			}
862 
863 			if (__this_cpu_dec_return(pcp->expire)) {
864 				changes++;
865 				continue;
866 			}
867 
868 			if (__this_cpu_read(pcp->count)) {
869 				drain_zone_pages(zone, this_cpu_ptr(pcp));
870 				changes++;
871 			}
872 #endif
873 		}
874 	}
875 
876 	for_each_online_pgdat(pgdat) {
877 		struct per_cpu_nodestat __percpu *p = pgdat->per_cpu_nodestats;
878 
879 		for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
880 			int v;
881 
882 			v = this_cpu_xchg(p->vm_node_stat_diff[i], 0);
883 			if (v) {
884 				atomic_long_add(v, &pgdat->vm_stat[i]);
885 				global_node_diff[i] += v;
886 			}
887 		}
888 	}
889 
890 	changes += fold_diff(global_zone_diff, global_node_diff);
891 	return changes;
892 }
893 
894 /*
895  * Fold the data for an offline cpu into the global array.
896  * There cannot be any access by the offline cpu and therefore
897  * synchronization is simplified.
898  */
899 void cpu_vm_stats_fold(int cpu)
900 {
901 	struct pglist_data *pgdat;
902 	struct zone *zone;
903 	int i;
904 	int global_zone_diff[NR_VM_ZONE_STAT_ITEMS] = { 0, };
905 	int global_node_diff[NR_VM_NODE_STAT_ITEMS] = { 0, };
906 
907 	for_each_populated_zone(zone) {
908 		struct per_cpu_zonestat *pzstats;
909 
910 		pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
911 
912 		for (i = 0; i < NR_VM_ZONE_STAT_ITEMS; i++) {
913 			if (pzstats->vm_stat_diff[i]) {
914 				int v;
915 
916 				v = pzstats->vm_stat_diff[i];
917 				pzstats->vm_stat_diff[i] = 0;
918 				atomic_long_add(v, &zone->vm_stat[i]);
919 				global_zone_diff[i] += v;
920 			}
921 		}
922 #ifdef CONFIG_NUMA
923 		for (i = 0; i < NR_VM_NUMA_EVENT_ITEMS; i++) {
924 			if (pzstats->vm_numa_event[i]) {
925 				unsigned long v;
926 
927 				v = pzstats->vm_numa_event[i];
928 				pzstats->vm_numa_event[i] = 0;
929 				zone_numa_event_add(v, zone, i);
930 			}
931 		}
932 #endif
933 	}
934 
935 	for_each_online_pgdat(pgdat) {
936 		struct per_cpu_nodestat *p;
937 
938 		p = per_cpu_ptr(pgdat->per_cpu_nodestats, cpu);
939 
940 		for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++)
941 			if (p->vm_node_stat_diff[i]) {
942 				int v;
943 
944 				v = p->vm_node_stat_diff[i];
945 				p->vm_node_stat_diff[i] = 0;
946 				atomic_long_add(v, &pgdat->vm_stat[i]);
947 				global_node_diff[i] += v;
948 			}
949 	}
950 
951 	fold_diff(global_zone_diff, global_node_diff);
952 }
953 
954 /*
955  * this is only called if !populated_zone(zone), which implies no other users of
956  * pset->vm_stat_diff[] exist.
957  */
958 void drain_zonestat(struct zone *zone, struct per_cpu_zonestat *pzstats)
959 {
960 	unsigned long v;
961 	int i;
962 
963 	for (i = 0; i < NR_VM_ZONE_STAT_ITEMS; i++) {
964 		if (pzstats->vm_stat_diff[i]) {
965 			v = pzstats->vm_stat_diff[i];
966 			pzstats->vm_stat_diff[i] = 0;
967 			zone_page_state_add(v, zone, i);
968 		}
969 	}
970 
971 #ifdef CONFIG_NUMA
972 	for (i = 0; i < NR_VM_NUMA_EVENT_ITEMS; i++) {
973 		if (pzstats->vm_numa_event[i]) {
974 			v = pzstats->vm_numa_event[i];
975 			pzstats->vm_numa_event[i] = 0;
976 			zone_numa_event_add(v, zone, i);
977 		}
978 	}
979 #endif
980 }
981 #endif
982 
983 #ifdef CONFIG_NUMA
984 /*
985  * Determine the per node value of a stat item. This function
986  * is called frequently in a NUMA machine, so try to be as
987  * frugal as possible.
988  */
989 unsigned long sum_zone_node_page_state(int node,
990 				 enum zone_stat_item item)
991 {
992 	struct zone *zones = NODE_DATA(node)->node_zones;
993 	int i;
994 	unsigned long count = 0;
995 
996 	for (i = 0; i < MAX_NR_ZONES; i++)
997 		count += zone_page_state(zones + i, item);
998 
999 	return count;
1000 }
1001 
1002 /* Determine the per node value of a numa stat item. */
1003 unsigned long sum_zone_numa_event_state(int node,
1004 				 enum numa_stat_item item)
1005 {
1006 	struct zone *zones = NODE_DATA(node)->node_zones;
1007 	unsigned long count = 0;
1008 	int i;
1009 
1010 	for (i = 0; i < MAX_NR_ZONES; i++)
1011 		count += zone_numa_event_state(zones + i, item);
1012 
1013 	return count;
1014 }
1015 
1016 /*
1017  * Determine the per node value of a stat item.
1018  */
1019 unsigned long node_page_state_pages(struct pglist_data *pgdat,
1020 				    enum node_stat_item item)
1021 {
1022 	long x = atomic_long_read(&pgdat->vm_stat[item]);
1023 #ifdef CONFIG_SMP
1024 	if (x < 0)
1025 		x = 0;
1026 #endif
1027 	return x;
1028 }
1029 
1030 unsigned long node_page_state(struct pglist_data *pgdat,
1031 			      enum node_stat_item item)
1032 {
1033 	VM_WARN_ON_ONCE(vmstat_item_in_bytes(item));
1034 
1035 	return node_page_state_pages(pgdat, item);
1036 }
1037 #endif
1038 
1039 /*
1040  * Count number of pages "struct page" and "struct page_ext" consume.
1041  * nr_memmap_boot_pages: # of pages allocated by boot allocator
1042  * nr_memmap_pages: # of pages that were allocated by buddy allocator
1043  */
1044 static atomic_long_t nr_memmap_boot_pages = ATOMIC_LONG_INIT(0);
1045 static atomic_long_t nr_memmap_pages = ATOMIC_LONG_INIT(0);
1046 
1047 void memmap_boot_pages_add(long delta)
1048 {
1049 	atomic_long_add(delta, &nr_memmap_boot_pages);
1050 }
1051 
1052 void memmap_pages_add(long delta)
1053 {
1054 	atomic_long_add(delta, &nr_memmap_pages);
1055 }
1056 
1057 #ifdef CONFIG_COMPACTION
1058 
1059 struct contig_page_info {
1060 	unsigned long free_pages;
1061 	unsigned long free_blocks_total;
1062 	unsigned long free_blocks_suitable;
1063 };
1064 
1065 /*
1066  * Calculate the number of free pages in a zone, how many contiguous
1067  * pages are free and how many are large enough to satisfy an allocation of
1068  * the target size. Note that this function makes no attempt to estimate
1069  * how many suitable free blocks there *might* be if MOVABLE pages were
1070  * migrated. Calculating that is possible, but expensive and can be
1071  * figured out from userspace
1072  */
1073 static void fill_contig_page_info(struct zone *zone,
1074 				unsigned int suitable_order,
1075 				struct contig_page_info *info)
1076 {
1077 	unsigned int order;
1078 
1079 	info->free_pages = 0;
1080 	info->free_blocks_total = 0;
1081 	info->free_blocks_suitable = 0;
1082 
1083 	for (order = 0; order < NR_PAGE_ORDERS; order++) {
1084 		unsigned long blocks;
1085 
1086 		/*
1087 		 * Count number of free blocks.
1088 		 *
1089 		 * Access to nr_free is lockless as nr_free is used only for
1090 		 * diagnostic purposes. Use data_race to avoid KCSAN warning.
1091 		 */
1092 		blocks = data_race(zone->free_area[order].nr_free);
1093 		info->free_blocks_total += blocks;
1094 
1095 		/* Count free base pages */
1096 		info->free_pages += blocks << order;
1097 
1098 		/* Count the suitable free blocks */
1099 		if (order >= suitable_order)
1100 			info->free_blocks_suitable += blocks <<
1101 						(order - suitable_order);
1102 	}
1103 }
1104 
1105 /*
1106  * A fragmentation index only makes sense if an allocation of a requested
1107  * size would fail. If that is true, the fragmentation index indicates
1108  * whether external fragmentation or a lack of memory was the problem.
1109  * The value can be used to determine if page reclaim or compaction
1110  * should be used
1111  */
1112 static int __fragmentation_index(unsigned int order, struct contig_page_info *info)
1113 {
1114 	unsigned long requested = 1UL << order;
1115 
1116 	if (WARN_ON_ONCE(order > MAX_PAGE_ORDER))
1117 		return 0;
1118 
1119 	if (!info->free_blocks_total)
1120 		return 0;
1121 
1122 	/* Fragmentation index only makes sense when a request would fail */
1123 	if (info->free_blocks_suitable)
1124 		return -1000;
1125 
1126 	/*
1127 	 * Index is between 0 and 1 so return within 3 decimal places
1128 	 *
1129 	 * 0 => allocation would fail due to lack of memory
1130 	 * 1 => allocation would fail due to fragmentation
1131 	 */
1132 	return 1000 - div_u64( (1000+(div_u64(info->free_pages * 1000ULL, requested))), info->free_blocks_total);
1133 }
1134 
1135 /*
1136  * Calculates external fragmentation within a zone wrt the given order.
1137  * It is defined as the percentage of pages found in blocks of size
1138  * less than 1 << order. It returns values in range [0, 100].
1139  */
1140 unsigned int extfrag_for_order(struct zone *zone, unsigned int order)
1141 {
1142 	struct contig_page_info info;
1143 
1144 	fill_contig_page_info(zone, order, &info);
1145 	if (info.free_pages == 0)
1146 		return 0;
1147 
1148 	return div_u64((info.free_pages -
1149 			(info.free_blocks_suitable << order)) * 100,
1150 			info.free_pages);
1151 }
1152 
1153 /* Same as __fragmentation index but allocs contig_page_info on stack */
1154 int fragmentation_index(struct zone *zone, unsigned int order)
1155 {
1156 	struct contig_page_info info;
1157 
1158 	fill_contig_page_info(zone, order, &info);
1159 	return __fragmentation_index(order, &info);
1160 }
1161 #endif
1162 
1163 #if defined(CONFIG_PROC_FS) || defined(CONFIG_SYSFS) || \
1164     defined(CONFIG_NUMA) || defined(CONFIG_MEMCG)
1165 #ifdef CONFIG_ZONE_DMA
1166 #define TEXT_FOR_DMA(xx) xx "_dma",
1167 #else
1168 #define TEXT_FOR_DMA(xx)
1169 #endif
1170 
1171 #ifdef CONFIG_ZONE_DMA32
1172 #define TEXT_FOR_DMA32(xx) xx "_dma32",
1173 #else
1174 #define TEXT_FOR_DMA32(xx)
1175 #endif
1176 
1177 #ifdef CONFIG_HIGHMEM
1178 #define TEXT_FOR_HIGHMEM(xx) xx "_high",
1179 #else
1180 #define TEXT_FOR_HIGHMEM(xx)
1181 #endif
1182 
1183 #ifdef CONFIG_ZONE_DEVICE
1184 #define TEXT_FOR_DEVICE(xx) xx "_device",
1185 #else
1186 #define TEXT_FOR_DEVICE(xx)
1187 #endif
1188 
1189 #define TEXTS_FOR_ZONES(xx) TEXT_FOR_DMA(xx) TEXT_FOR_DMA32(xx) xx "_normal", \
1190 					TEXT_FOR_HIGHMEM(xx) xx "_movable", \
1191 					TEXT_FOR_DEVICE(xx)
1192 
1193 const char * const vmstat_text[] = {
1194 	/* enum zone_stat_item counters */
1195 	"nr_free_pages",
1196 	"nr_zone_inactive_anon",
1197 	"nr_zone_active_anon",
1198 	"nr_zone_inactive_file",
1199 	"nr_zone_active_file",
1200 	"nr_zone_unevictable",
1201 	"nr_zone_write_pending",
1202 	"nr_mlock",
1203 	"nr_bounce",
1204 #if IS_ENABLED(CONFIG_ZSMALLOC)
1205 	"nr_zspages",
1206 #endif
1207 	"nr_free_cma",
1208 #ifdef CONFIG_UNACCEPTED_MEMORY
1209 	"nr_unaccepted",
1210 #endif
1211 
1212 	/* enum numa_stat_item counters */
1213 #ifdef CONFIG_NUMA
1214 	"numa_hit",
1215 	"numa_miss",
1216 	"numa_foreign",
1217 	"numa_interleave",
1218 	"numa_local",
1219 	"numa_other",
1220 #endif
1221 
1222 	/* enum node_stat_item counters */
1223 	"nr_inactive_anon",
1224 	"nr_active_anon",
1225 	"nr_inactive_file",
1226 	"nr_active_file",
1227 	"nr_unevictable",
1228 	"nr_slab_reclaimable",
1229 	"nr_slab_unreclaimable",
1230 	"nr_isolated_anon",
1231 	"nr_isolated_file",
1232 	"workingset_nodes",
1233 	"workingset_refault_anon",
1234 	"workingset_refault_file",
1235 	"workingset_activate_anon",
1236 	"workingset_activate_file",
1237 	"workingset_restore_anon",
1238 	"workingset_restore_file",
1239 	"workingset_nodereclaim",
1240 	"nr_anon_pages",
1241 	"nr_mapped",
1242 	"nr_file_pages",
1243 	"nr_dirty",
1244 	"nr_writeback",
1245 	"nr_writeback_temp",
1246 	"nr_shmem",
1247 	"nr_shmem_hugepages",
1248 	"nr_shmem_pmdmapped",
1249 	"nr_file_hugepages",
1250 	"nr_file_pmdmapped",
1251 	"nr_anon_transparent_hugepages",
1252 	"nr_vmscan_write",
1253 	"nr_vmscan_immediate_reclaim",
1254 	"nr_dirtied",
1255 	"nr_written",
1256 	"nr_throttled_written",
1257 	"nr_kernel_misc_reclaimable",
1258 	"nr_foll_pin_acquired",
1259 	"nr_foll_pin_released",
1260 	"nr_kernel_stack",
1261 #if IS_ENABLED(CONFIG_SHADOW_CALL_STACK)
1262 	"nr_shadow_call_stack",
1263 #endif
1264 	"nr_page_table_pages",
1265 	"nr_sec_page_table_pages",
1266 #ifdef CONFIG_IOMMU_SUPPORT
1267 	"nr_iommu_pages",
1268 #endif
1269 #ifdef CONFIG_SWAP
1270 	"nr_swapcached",
1271 #endif
1272 #ifdef CONFIG_NUMA_BALANCING
1273 	"pgpromote_success",
1274 	"pgpromote_candidate",
1275 #endif
1276 	"pgdemote_kswapd",
1277 	"pgdemote_direct",
1278 	"pgdemote_khugepaged",
1279 #ifdef CONFIG_HUGETLB_PAGE
1280 	"nr_hugetlb",
1281 #endif
1282 	/* system-wide enum vm_stat_item counters */
1283 	"nr_dirty_threshold",
1284 	"nr_dirty_background_threshold",
1285 	"nr_memmap_pages",
1286 	"nr_memmap_boot_pages",
1287 
1288 #if defined(CONFIG_VM_EVENT_COUNTERS) || defined(CONFIG_MEMCG)
1289 	/* enum vm_event_item counters */
1290 	"pgpgin",
1291 	"pgpgout",
1292 	"pswpin",
1293 	"pswpout",
1294 
1295 	TEXTS_FOR_ZONES("pgalloc")
1296 	TEXTS_FOR_ZONES("allocstall")
1297 	TEXTS_FOR_ZONES("pgskip")
1298 
1299 	"pgfree",
1300 	"pgactivate",
1301 	"pgdeactivate",
1302 	"pglazyfree",
1303 
1304 	"pgfault",
1305 	"pgmajfault",
1306 	"pglazyfreed",
1307 
1308 	"pgrefill",
1309 	"pgreuse",
1310 	"pgsteal_kswapd",
1311 	"pgsteal_direct",
1312 	"pgsteal_khugepaged",
1313 	"pgscan_kswapd",
1314 	"pgscan_direct",
1315 	"pgscan_khugepaged",
1316 	"pgscan_direct_throttle",
1317 	"pgscan_anon",
1318 	"pgscan_file",
1319 	"pgsteal_anon",
1320 	"pgsteal_file",
1321 
1322 #ifdef CONFIG_NUMA
1323 	"zone_reclaim_success",
1324 	"zone_reclaim_failed",
1325 #endif
1326 	"pginodesteal",
1327 	"slabs_scanned",
1328 	"kswapd_inodesteal",
1329 	"kswapd_low_wmark_hit_quickly",
1330 	"kswapd_high_wmark_hit_quickly",
1331 	"pageoutrun",
1332 
1333 	"pgrotated",
1334 
1335 	"drop_pagecache",
1336 	"drop_slab",
1337 	"oom_kill",
1338 
1339 #ifdef CONFIG_NUMA_BALANCING
1340 	"numa_pte_updates",
1341 	"numa_huge_pte_updates",
1342 	"numa_hint_faults",
1343 	"numa_hint_faults_local",
1344 	"numa_pages_migrated",
1345 #endif
1346 #ifdef CONFIG_MIGRATION
1347 	"pgmigrate_success",
1348 	"pgmigrate_fail",
1349 	"thp_migration_success",
1350 	"thp_migration_fail",
1351 	"thp_migration_split",
1352 #endif
1353 #ifdef CONFIG_COMPACTION
1354 	"compact_migrate_scanned",
1355 	"compact_free_scanned",
1356 	"compact_isolated",
1357 	"compact_stall",
1358 	"compact_fail",
1359 	"compact_success",
1360 	"compact_daemon_wake",
1361 	"compact_daemon_migrate_scanned",
1362 	"compact_daemon_free_scanned",
1363 #endif
1364 
1365 #ifdef CONFIG_HUGETLB_PAGE
1366 	"htlb_buddy_alloc_success",
1367 	"htlb_buddy_alloc_fail",
1368 #endif
1369 #ifdef CONFIG_CMA
1370 	"cma_alloc_success",
1371 	"cma_alloc_fail",
1372 #endif
1373 	"unevictable_pgs_culled",
1374 	"unevictable_pgs_scanned",
1375 	"unevictable_pgs_rescued",
1376 	"unevictable_pgs_mlocked",
1377 	"unevictable_pgs_munlocked",
1378 	"unevictable_pgs_cleared",
1379 	"unevictable_pgs_stranded",
1380 
1381 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1382 	"thp_fault_alloc",
1383 	"thp_fault_fallback",
1384 	"thp_fault_fallback_charge",
1385 	"thp_collapse_alloc",
1386 	"thp_collapse_alloc_failed",
1387 	"thp_file_alloc",
1388 	"thp_file_fallback",
1389 	"thp_file_fallback_charge",
1390 	"thp_file_mapped",
1391 	"thp_split_page",
1392 	"thp_split_page_failed",
1393 	"thp_deferred_split_page",
1394 	"thp_underused_split_page",
1395 	"thp_split_pmd",
1396 	"thp_scan_exceed_none_pte",
1397 	"thp_scan_exceed_swap_pte",
1398 	"thp_scan_exceed_share_pte",
1399 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
1400 	"thp_split_pud",
1401 #endif
1402 	"thp_zero_page_alloc",
1403 	"thp_zero_page_alloc_failed",
1404 	"thp_swpout",
1405 	"thp_swpout_fallback",
1406 #endif
1407 #ifdef CONFIG_MEMORY_BALLOON
1408 	"balloon_inflate",
1409 	"balloon_deflate",
1410 #ifdef CONFIG_BALLOON_COMPACTION
1411 	"balloon_migrate",
1412 #endif
1413 #endif /* CONFIG_MEMORY_BALLOON */
1414 #ifdef CONFIG_DEBUG_TLBFLUSH
1415 	"nr_tlb_remote_flush",
1416 	"nr_tlb_remote_flush_received",
1417 	"nr_tlb_local_flush_all",
1418 	"nr_tlb_local_flush_one",
1419 #endif /* CONFIG_DEBUG_TLBFLUSH */
1420 
1421 #ifdef CONFIG_SWAP
1422 	"swap_ra",
1423 	"swap_ra_hit",
1424 	"swpin_zero",
1425 	"swpout_zero",
1426 #ifdef CONFIG_KSM
1427 	"ksm_swpin_copy",
1428 #endif
1429 #endif
1430 #ifdef CONFIG_KSM
1431 	"cow_ksm",
1432 #endif
1433 #ifdef CONFIG_ZSWAP
1434 	"zswpin",
1435 	"zswpout",
1436 	"zswpwb",
1437 #endif
1438 #ifdef CONFIG_X86
1439 	"direct_map_level2_splits",
1440 	"direct_map_level3_splits",
1441 	"direct_map_level2_collapses",
1442 	"direct_map_level3_collapses",
1443 #endif
1444 #ifdef CONFIG_PER_VMA_LOCK_STATS
1445 	"vma_lock_success",
1446 	"vma_lock_abort",
1447 	"vma_lock_retry",
1448 	"vma_lock_miss",
1449 #endif
1450 #ifdef CONFIG_DEBUG_STACK_USAGE
1451 	"kstack_1k",
1452 #if THREAD_SIZE > 1024
1453 	"kstack_2k",
1454 #endif
1455 #if THREAD_SIZE > 2048
1456 	"kstack_4k",
1457 #endif
1458 #if THREAD_SIZE > 4096
1459 	"kstack_8k",
1460 #endif
1461 #if THREAD_SIZE > 8192
1462 	"kstack_16k",
1463 #endif
1464 #if THREAD_SIZE > 16384
1465 	"kstack_32k",
1466 #endif
1467 #if THREAD_SIZE > 32768
1468 	"kstack_64k",
1469 #endif
1470 #if THREAD_SIZE > 65536
1471 	"kstack_rest",
1472 #endif
1473 #endif
1474 #endif /* CONFIG_VM_EVENT_COUNTERS || CONFIG_MEMCG */
1475 };
1476 #endif /* CONFIG_PROC_FS || CONFIG_SYSFS || CONFIG_NUMA || CONFIG_MEMCG */
1477 
1478 #if (defined(CONFIG_DEBUG_FS) && defined(CONFIG_COMPACTION)) || \
1479      defined(CONFIG_PROC_FS)
1480 static void *frag_start(struct seq_file *m, loff_t *pos)
1481 {
1482 	pg_data_t *pgdat;
1483 	loff_t node = *pos;
1484 
1485 	for (pgdat = first_online_pgdat();
1486 	     pgdat && node;
1487 	     pgdat = next_online_pgdat(pgdat))
1488 		--node;
1489 
1490 	return pgdat;
1491 }
1492 
1493 static void *frag_next(struct seq_file *m, void *arg, loff_t *pos)
1494 {
1495 	pg_data_t *pgdat = (pg_data_t *)arg;
1496 
1497 	(*pos)++;
1498 	return next_online_pgdat(pgdat);
1499 }
1500 
1501 static void frag_stop(struct seq_file *m, void *arg)
1502 {
1503 }
1504 
1505 /*
1506  * Walk zones in a node and print using a callback.
1507  * If @assert_populated is true, only use callback for zones that are populated.
1508  */
1509 static void walk_zones_in_node(struct seq_file *m, pg_data_t *pgdat,
1510 		bool assert_populated, bool nolock,
1511 		void (*print)(struct seq_file *m, pg_data_t *, struct zone *))
1512 {
1513 	struct zone *zone;
1514 	struct zone *node_zones = pgdat->node_zones;
1515 	unsigned long flags;
1516 
1517 	for (zone = node_zones; zone - node_zones < MAX_NR_ZONES; ++zone) {
1518 		if (assert_populated && !populated_zone(zone))
1519 			continue;
1520 
1521 		if (!nolock)
1522 			spin_lock_irqsave(&zone->lock, flags);
1523 		print(m, pgdat, zone);
1524 		if (!nolock)
1525 			spin_unlock_irqrestore(&zone->lock, flags);
1526 	}
1527 }
1528 #endif
1529 
1530 #ifdef CONFIG_PROC_FS
1531 static void frag_show_print(struct seq_file *m, pg_data_t *pgdat,
1532 						struct zone *zone)
1533 {
1534 	int order;
1535 
1536 	seq_printf(m, "Node %d, zone %8s ", pgdat->node_id, zone->name);
1537 	for (order = 0; order < NR_PAGE_ORDERS; ++order)
1538 		/*
1539 		 * Access to nr_free is lockless as nr_free is used only for
1540 		 * printing purposes. Use data_race to avoid KCSAN warning.
1541 		 */
1542 		seq_printf(m, "%6lu ", data_race(zone->free_area[order].nr_free));
1543 	seq_putc(m, '\n');
1544 }
1545 
1546 /*
1547  * This walks the free areas for each zone.
1548  */
1549 static int frag_show(struct seq_file *m, void *arg)
1550 {
1551 	pg_data_t *pgdat = (pg_data_t *)arg;
1552 	walk_zones_in_node(m, pgdat, true, false, frag_show_print);
1553 	return 0;
1554 }
1555 
1556 static void pagetypeinfo_showfree_print(struct seq_file *m,
1557 					pg_data_t *pgdat, struct zone *zone)
1558 {
1559 	int order, mtype;
1560 
1561 	for (mtype = 0; mtype < MIGRATE_TYPES; mtype++) {
1562 		seq_printf(m, "Node %4d, zone %8s, type %12s ",
1563 					pgdat->node_id,
1564 					zone->name,
1565 					migratetype_names[mtype]);
1566 		for (order = 0; order < NR_PAGE_ORDERS; ++order) {
1567 			unsigned long freecount = 0;
1568 			struct free_area *area;
1569 			struct list_head *curr;
1570 			bool overflow = false;
1571 
1572 			area = &(zone->free_area[order]);
1573 
1574 			list_for_each(curr, &area->free_list[mtype]) {
1575 				/*
1576 				 * Cap the free_list iteration because it might
1577 				 * be really large and we are under a spinlock
1578 				 * so a long time spent here could trigger a
1579 				 * hard lockup detector. Anyway this is a
1580 				 * debugging tool so knowing there is a handful
1581 				 * of pages of this order should be more than
1582 				 * sufficient.
1583 				 */
1584 				if (++freecount >= 100000) {
1585 					overflow = true;
1586 					break;
1587 				}
1588 			}
1589 			seq_printf(m, "%s%6lu ", overflow ? ">" : "", freecount);
1590 			spin_unlock_irq(&zone->lock);
1591 			cond_resched();
1592 			spin_lock_irq(&zone->lock);
1593 		}
1594 		seq_putc(m, '\n');
1595 	}
1596 }
1597 
1598 /* Print out the free pages at each order for each migatetype */
1599 static void pagetypeinfo_showfree(struct seq_file *m, void *arg)
1600 {
1601 	int order;
1602 	pg_data_t *pgdat = (pg_data_t *)arg;
1603 
1604 	/* Print header */
1605 	seq_printf(m, "%-43s ", "Free pages count per migrate type at order");
1606 	for (order = 0; order < NR_PAGE_ORDERS; ++order)
1607 		seq_printf(m, "%6d ", order);
1608 	seq_putc(m, '\n');
1609 
1610 	walk_zones_in_node(m, pgdat, true, false, pagetypeinfo_showfree_print);
1611 }
1612 
1613 static void pagetypeinfo_showblockcount_print(struct seq_file *m,
1614 					pg_data_t *pgdat, struct zone *zone)
1615 {
1616 	int mtype;
1617 	unsigned long pfn;
1618 	unsigned long start_pfn = zone->zone_start_pfn;
1619 	unsigned long end_pfn = zone_end_pfn(zone);
1620 	unsigned long count[MIGRATE_TYPES] = { 0, };
1621 
1622 	for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
1623 		struct page *page;
1624 
1625 		page = pfn_to_online_page(pfn);
1626 		if (!page)
1627 			continue;
1628 
1629 		if (page_zone(page) != zone)
1630 			continue;
1631 
1632 		mtype = get_pageblock_migratetype(page);
1633 
1634 		if (mtype < MIGRATE_TYPES)
1635 			count[mtype]++;
1636 	}
1637 
1638 	/* Print counts */
1639 	seq_printf(m, "Node %d, zone %8s ", pgdat->node_id, zone->name);
1640 	for (mtype = 0; mtype < MIGRATE_TYPES; mtype++)
1641 		seq_printf(m, "%12lu ", count[mtype]);
1642 	seq_putc(m, '\n');
1643 }
1644 
1645 /* Print out the number of pageblocks for each migratetype */
1646 static void pagetypeinfo_showblockcount(struct seq_file *m, void *arg)
1647 {
1648 	int mtype;
1649 	pg_data_t *pgdat = (pg_data_t *)arg;
1650 
1651 	seq_printf(m, "\n%-23s", "Number of blocks type ");
1652 	for (mtype = 0; mtype < MIGRATE_TYPES; mtype++)
1653 		seq_printf(m, "%12s ", migratetype_names[mtype]);
1654 	seq_putc(m, '\n');
1655 	walk_zones_in_node(m, pgdat, true, false,
1656 		pagetypeinfo_showblockcount_print);
1657 }
1658 
1659 /*
1660  * Print out the number of pageblocks for each migratetype that contain pages
1661  * of other types. This gives an indication of how well fallbacks are being
1662  * contained by rmqueue_fallback(). It requires information from PAGE_OWNER
1663  * to determine what is going on
1664  */
1665 static void pagetypeinfo_showmixedcount(struct seq_file *m, pg_data_t *pgdat)
1666 {
1667 #ifdef CONFIG_PAGE_OWNER
1668 	int mtype;
1669 
1670 	if (!static_branch_unlikely(&page_owner_inited))
1671 		return;
1672 
1673 	drain_all_pages(NULL);
1674 
1675 	seq_printf(m, "\n%-23s", "Number of mixed blocks ");
1676 	for (mtype = 0; mtype < MIGRATE_TYPES; mtype++)
1677 		seq_printf(m, "%12s ", migratetype_names[mtype]);
1678 	seq_putc(m, '\n');
1679 
1680 	walk_zones_in_node(m, pgdat, true, true,
1681 		pagetypeinfo_showmixedcount_print);
1682 #endif /* CONFIG_PAGE_OWNER */
1683 }
1684 
1685 /*
1686  * This prints out statistics in relation to grouping pages by mobility.
1687  * It is expensive to collect so do not constantly read the file.
1688  */
1689 static int pagetypeinfo_show(struct seq_file *m, void *arg)
1690 {
1691 	pg_data_t *pgdat = (pg_data_t *)arg;
1692 
1693 	/* check memoryless node */
1694 	if (!node_state(pgdat->node_id, N_MEMORY))
1695 		return 0;
1696 
1697 	seq_printf(m, "Page block order: %d\n", pageblock_order);
1698 	seq_printf(m, "Pages per block:  %lu\n", pageblock_nr_pages);
1699 	seq_putc(m, '\n');
1700 	pagetypeinfo_showfree(m, pgdat);
1701 	pagetypeinfo_showblockcount(m, pgdat);
1702 	pagetypeinfo_showmixedcount(m, pgdat);
1703 
1704 	return 0;
1705 }
1706 
1707 static const struct seq_operations fragmentation_op = {
1708 	.start	= frag_start,
1709 	.next	= frag_next,
1710 	.stop	= frag_stop,
1711 	.show	= frag_show,
1712 };
1713 
1714 static const struct seq_operations pagetypeinfo_op = {
1715 	.start	= frag_start,
1716 	.next	= frag_next,
1717 	.stop	= frag_stop,
1718 	.show	= pagetypeinfo_show,
1719 };
1720 
1721 static bool is_zone_first_populated(pg_data_t *pgdat, struct zone *zone)
1722 {
1723 	int zid;
1724 
1725 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1726 		struct zone *compare = &pgdat->node_zones[zid];
1727 
1728 		if (populated_zone(compare))
1729 			return zone == compare;
1730 	}
1731 
1732 	return false;
1733 }
1734 
1735 static void zoneinfo_show_print(struct seq_file *m, pg_data_t *pgdat,
1736 							struct zone *zone)
1737 {
1738 	int i;
1739 	seq_printf(m, "Node %d, zone %8s", pgdat->node_id, zone->name);
1740 	if (is_zone_first_populated(pgdat, zone)) {
1741 		seq_printf(m, "\n  per-node stats");
1742 		for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
1743 			unsigned long pages = node_page_state_pages(pgdat, i);
1744 
1745 			if (vmstat_item_print_in_thp(i))
1746 				pages /= HPAGE_PMD_NR;
1747 			seq_printf(m, "\n      %-12s %lu", node_stat_name(i),
1748 				   pages);
1749 		}
1750 	}
1751 	seq_printf(m,
1752 		   "\n  pages free     %lu"
1753 		   "\n        boost    %lu"
1754 		   "\n        min      %lu"
1755 		   "\n        low      %lu"
1756 		   "\n        high     %lu"
1757 		   "\n        promo    %lu"
1758 		   "\n        spanned  %lu"
1759 		   "\n        present  %lu"
1760 		   "\n        managed  %lu"
1761 		   "\n        cma      %lu",
1762 		   zone_page_state(zone, NR_FREE_PAGES),
1763 		   zone->watermark_boost,
1764 		   min_wmark_pages(zone),
1765 		   low_wmark_pages(zone),
1766 		   high_wmark_pages(zone),
1767 		   promo_wmark_pages(zone),
1768 		   zone->spanned_pages,
1769 		   zone->present_pages,
1770 		   zone_managed_pages(zone),
1771 		   zone_cma_pages(zone));
1772 
1773 	seq_printf(m,
1774 		   "\n        protection: (%ld",
1775 		   zone->lowmem_reserve[0]);
1776 	for (i = 1; i < ARRAY_SIZE(zone->lowmem_reserve); i++)
1777 		seq_printf(m, ", %ld", zone->lowmem_reserve[i]);
1778 	seq_putc(m, ')');
1779 
1780 	/* If unpopulated, no other information is useful */
1781 	if (!populated_zone(zone)) {
1782 		seq_putc(m, '\n');
1783 		return;
1784 	}
1785 
1786 	for (i = 0; i < NR_VM_ZONE_STAT_ITEMS; i++)
1787 		seq_printf(m, "\n      %-12s %lu", zone_stat_name(i),
1788 			   zone_page_state(zone, i));
1789 
1790 #ifdef CONFIG_NUMA
1791 	fold_vm_zone_numa_events(zone);
1792 	for (i = 0; i < NR_VM_NUMA_EVENT_ITEMS; i++)
1793 		seq_printf(m, "\n      %-12s %lu", numa_stat_name(i),
1794 			   zone_numa_event_state(zone, i));
1795 #endif
1796 
1797 	seq_printf(m, "\n  pagesets");
1798 	for_each_online_cpu(i) {
1799 		struct per_cpu_pages *pcp;
1800 		struct per_cpu_zonestat __maybe_unused *pzstats;
1801 
1802 		pcp = per_cpu_ptr(zone->per_cpu_pageset, i);
1803 		seq_printf(m,
1804 			   "\n    cpu: %i"
1805 			   "\n              count:    %i"
1806 			   "\n              high:     %i"
1807 			   "\n              batch:    %i"
1808 			   "\n              high_min: %i"
1809 			   "\n              high_max: %i",
1810 			   i,
1811 			   pcp->count,
1812 			   pcp->high,
1813 			   pcp->batch,
1814 			   pcp->high_min,
1815 			   pcp->high_max);
1816 #ifdef CONFIG_SMP
1817 		pzstats = per_cpu_ptr(zone->per_cpu_zonestats, i);
1818 		seq_printf(m, "\n  vm stats threshold: %d",
1819 				pzstats->stat_threshold);
1820 #endif
1821 	}
1822 	seq_printf(m,
1823 		   "\n  node_unreclaimable:  %u"
1824 		   "\n  start_pfn:           %lu",
1825 		   pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES,
1826 		   zone->zone_start_pfn);
1827 	seq_putc(m, '\n');
1828 }
1829 
1830 /*
1831  * Output information about zones in @pgdat.  All zones are printed regardless
1832  * of whether they are populated or not: lowmem_reserve_ratio operates on the
1833  * set of all zones and userspace would not be aware of such zones if they are
1834  * suppressed here (zoneinfo displays the effect of lowmem_reserve_ratio).
1835  */
1836 static int zoneinfo_show(struct seq_file *m, void *arg)
1837 {
1838 	pg_data_t *pgdat = (pg_data_t *)arg;
1839 	walk_zones_in_node(m, pgdat, false, false, zoneinfo_show_print);
1840 	return 0;
1841 }
1842 
1843 static const struct seq_operations zoneinfo_op = {
1844 	.start	= frag_start, /* iterate over all zones. The same as in
1845 			       * fragmentation. */
1846 	.next	= frag_next,
1847 	.stop	= frag_stop,
1848 	.show	= zoneinfo_show,
1849 };
1850 
1851 #define NR_VMSTAT_ITEMS (NR_VM_ZONE_STAT_ITEMS + \
1852 			 NR_VM_NUMA_EVENT_ITEMS + \
1853 			 NR_VM_NODE_STAT_ITEMS + \
1854 			 NR_VM_STAT_ITEMS + \
1855 			 (IS_ENABLED(CONFIG_VM_EVENT_COUNTERS) ? \
1856 			  NR_VM_EVENT_ITEMS : 0))
1857 
1858 static void *vmstat_start(struct seq_file *m, loff_t *pos)
1859 {
1860 	unsigned long *v;
1861 	int i;
1862 
1863 	if (*pos >= NR_VMSTAT_ITEMS)
1864 		return NULL;
1865 
1866 	BUILD_BUG_ON(ARRAY_SIZE(vmstat_text) < NR_VMSTAT_ITEMS);
1867 	fold_vm_numa_events();
1868 	v = kmalloc_array(NR_VMSTAT_ITEMS, sizeof(unsigned long), GFP_KERNEL);
1869 	m->private = v;
1870 	if (!v)
1871 		return ERR_PTR(-ENOMEM);
1872 	for (i = 0; i < NR_VM_ZONE_STAT_ITEMS; i++)
1873 		v[i] = global_zone_page_state(i);
1874 	v += NR_VM_ZONE_STAT_ITEMS;
1875 
1876 #ifdef CONFIG_NUMA
1877 	for (i = 0; i < NR_VM_NUMA_EVENT_ITEMS; i++)
1878 		v[i] = global_numa_event_state(i);
1879 	v += NR_VM_NUMA_EVENT_ITEMS;
1880 #endif
1881 
1882 	for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
1883 		v[i] = global_node_page_state_pages(i);
1884 		if (vmstat_item_print_in_thp(i))
1885 			v[i] /= HPAGE_PMD_NR;
1886 	}
1887 	v += NR_VM_NODE_STAT_ITEMS;
1888 
1889 	global_dirty_limits(v + NR_DIRTY_BG_THRESHOLD,
1890 			    v + NR_DIRTY_THRESHOLD);
1891 	v[NR_MEMMAP_PAGES] = atomic_long_read(&nr_memmap_pages);
1892 	v[NR_MEMMAP_BOOT_PAGES] = atomic_long_read(&nr_memmap_boot_pages);
1893 	v += NR_VM_STAT_ITEMS;
1894 
1895 #ifdef CONFIG_VM_EVENT_COUNTERS
1896 	all_vm_events(v);
1897 	v[PGPGIN] /= 2;		/* sectors -> kbytes */
1898 	v[PGPGOUT] /= 2;
1899 #endif
1900 	return (unsigned long *)m->private + *pos;
1901 }
1902 
1903 static void *vmstat_next(struct seq_file *m, void *arg, loff_t *pos)
1904 {
1905 	(*pos)++;
1906 	if (*pos >= NR_VMSTAT_ITEMS)
1907 		return NULL;
1908 	return (unsigned long *)m->private + *pos;
1909 }
1910 
1911 static int vmstat_show(struct seq_file *m, void *arg)
1912 {
1913 	unsigned long *l = arg;
1914 	unsigned long off = l - (unsigned long *)m->private;
1915 
1916 	seq_puts(m, vmstat_text[off]);
1917 	seq_put_decimal_ull(m, " ", *l);
1918 	seq_putc(m, '\n');
1919 
1920 	if (off == NR_VMSTAT_ITEMS - 1) {
1921 		/*
1922 		 * We've come to the end - add any deprecated counters to avoid
1923 		 * breaking userspace which might depend on them being present.
1924 		 */
1925 		seq_puts(m, "nr_unstable 0\n");
1926 	}
1927 	return 0;
1928 }
1929 
1930 static void vmstat_stop(struct seq_file *m, void *arg)
1931 {
1932 	kfree(m->private);
1933 	m->private = NULL;
1934 }
1935 
1936 static const struct seq_operations vmstat_op = {
1937 	.start	= vmstat_start,
1938 	.next	= vmstat_next,
1939 	.stop	= vmstat_stop,
1940 	.show	= vmstat_show,
1941 };
1942 #endif /* CONFIG_PROC_FS */
1943 
1944 #ifdef CONFIG_SMP
1945 static DEFINE_PER_CPU(struct delayed_work, vmstat_work);
1946 static int sysctl_stat_interval __read_mostly = HZ;
1947 static int vmstat_late_init_done;
1948 
1949 #ifdef CONFIG_PROC_FS
1950 static void refresh_vm_stats(struct work_struct *work)
1951 {
1952 	refresh_cpu_vm_stats(true);
1953 }
1954 
1955 static int vmstat_refresh(const struct ctl_table *table, int write,
1956 		   void *buffer, size_t *lenp, loff_t *ppos)
1957 {
1958 	long val;
1959 	int err;
1960 	int i;
1961 
1962 	/*
1963 	 * The regular update, every sysctl_stat_interval, may come later
1964 	 * than expected: leaving a significant amount in per_cpu buckets.
1965 	 * This is particularly misleading when checking a quantity of HUGE
1966 	 * pages, immediately after running a test.  /proc/sys/vm/stat_refresh,
1967 	 * which can equally be echo'ed to or cat'ted from (by root),
1968 	 * can be used to update the stats just before reading them.
1969 	 *
1970 	 * Oh, and since global_zone_page_state() etc. are so careful to hide
1971 	 * transiently negative values, report an error here if any of
1972 	 * the stats is negative, so we know to go looking for imbalance.
1973 	 */
1974 	err = schedule_on_each_cpu(refresh_vm_stats);
1975 	if (err)
1976 		return err;
1977 	for (i = 0; i < NR_VM_ZONE_STAT_ITEMS; i++) {
1978 		/*
1979 		 * Skip checking stats known to go negative occasionally.
1980 		 */
1981 		switch (i) {
1982 		case NR_ZONE_WRITE_PENDING:
1983 		case NR_FREE_CMA_PAGES:
1984 			continue;
1985 		}
1986 		val = atomic_long_read(&vm_zone_stat[i]);
1987 		if (val < 0) {
1988 			pr_warn("%s: %s %ld\n",
1989 				__func__, zone_stat_name(i), val);
1990 		}
1991 	}
1992 	for (i = 0; i < NR_VM_NODE_STAT_ITEMS; i++) {
1993 		/*
1994 		 * Skip checking stats known to go negative occasionally.
1995 		 */
1996 		switch (i) {
1997 		case NR_WRITEBACK:
1998 			continue;
1999 		}
2000 		val = atomic_long_read(&vm_node_stat[i]);
2001 		if (val < 0) {
2002 			pr_warn("%s: %s %ld\n",
2003 				__func__, node_stat_name(i), val);
2004 		}
2005 	}
2006 	if (write)
2007 		*ppos += *lenp;
2008 	else
2009 		*lenp = 0;
2010 	return 0;
2011 }
2012 #endif /* CONFIG_PROC_FS */
2013 
2014 static void vmstat_update(struct work_struct *w)
2015 {
2016 	if (refresh_cpu_vm_stats(true)) {
2017 		/*
2018 		 * Counters were updated so we expect more updates
2019 		 * to occur in the future. Keep on running the
2020 		 * update worker thread.
2021 		 */
2022 		queue_delayed_work_on(smp_processor_id(), mm_percpu_wq,
2023 				this_cpu_ptr(&vmstat_work),
2024 				round_jiffies_relative(sysctl_stat_interval));
2025 	}
2026 }
2027 
2028 /*
2029  * Check if the diffs for a certain cpu indicate that
2030  * an update is needed.
2031  */
2032 static bool need_update(int cpu)
2033 {
2034 	pg_data_t *last_pgdat = NULL;
2035 	struct zone *zone;
2036 
2037 	for_each_populated_zone(zone) {
2038 		struct per_cpu_zonestat *pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
2039 		struct per_cpu_nodestat *n;
2040 
2041 		/*
2042 		 * The fast way of checking if there are any vmstat diffs.
2043 		 */
2044 		if (memchr_inv(pzstats->vm_stat_diff, 0, sizeof(pzstats->vm_stat_diff)))
2045 			return true;
2046 
2047 		if (last_pgdat == zone->zone_pgdat)
2048 			continue;
2049 		last_pgdat = zone->zone_pgdat;
2050 		n = per_cpu_ptr(zone->zone_pgdat->per_cpu_nodestats, cpu);
2051 		if (memchr_inv(n->vm_node_stat_diff, 0, sizeof(n->vm_node_stat_diff)))
2052 			return true;
2053 	}
2054 	return false;
2055 }
2056 
2057 /*
2058  * Switch off vmstat processing and then fold all the remaining differentials
2059  * until the diffs stay at zero. The function is used by NOHZ and can only be
2060  * invoked when tick processing is not active.
2061  */
2062 void quiet_vmstat(void)
2063 {
2064 	if (system_state != SYSTEM_RUNNING)
2065 		return;
2066 
2067 	if (!delayed_work_pending(this_cpu_ptr(&vmstat_work)))
2068 		return;
2069 
2070 	if (!need_update(smp_processor_id()))
2071 		return;
2072 
2073 	/*
2074 	 * Just refresh counters and do not care about the pending delayed
2075 	 * vmstat_update. It doesn't fire that often to matter and canceling
2076 	 * it would be too expensive from this path.
2077 	 * vmstat_shepherd will take care about that for us.
2078 	 */
2079 	refresh_cpu_vm_stats(false);
2080 }
2081 
2082 /*
2083  * Shepherd worker thread that checks the
2084  * differentials of processors that have their worker
2085  * threads for vm statistics updates disabled because of
2086  * inactivity.
2087  */
2088 static void vmstat_shepherd(struct work_struct *w);
2089 
2090 static DECLARE_DEFERRABLE_WORK(shepherd, vmstat_shepherd);
2091 
2092 static void vmstat_shepherd(struct work_struct *w)
2093 {
2094 	int cpu;
2095 
2096 	cpus_read_lock();
2097 	/* Check processors whose vmstat worker threads have been disabled */
2098 	for_each_online_cpu(cpu) {
2099 		struct delayed_work *dw = &per_cpu(vmstat_work, cpu);
2100 
2101 		/*
2102 		 * In kernel users of vmstat counters either require the precise value and
2103 		 * they are using zone_page_state_snapshot interface or they can live with
2104 		 * an imprecision as the regular flushing can happen at arbitrary time and
2105 		 * cumulative error can grow (see calculate_normal_threshold).
2106 		 *
2107 		 * From that POV the regular flushing can be postponed for CPUs that have
2108 		 * been isolated from the kernel interference without critical
2109 		 * infrastructure ever noticing. Skip regular flushing from vmstat_shepherd
2110 		 * for all isolated CPUs to avoid interference with the isolated workload.
2111 		 */
2112 		if (cpu_is_isolated(cpu))
2113 			continue;
2114 
2115 		if (!delayed_work_pending(dw) && need_update(cpu))
2116 			queue_delayed_work_on(cpu, mm_percpu_wq, dw, 0);
2117 
2118 		cond_resched();
2119 	}
2120 	cpus_read_unlock();
2121 
2122 	schedule_delayed_work(&shepherd,
2123 		round_jiffies_relative(sysctl_stat_interval));
2124 }
2125 
2126 static void __init start_shepherd_timer(void)
2127 {
2128 	int cpu;
2129 
2130 	for_each_possible_cpu(cpu) {
2131 		INIT_DEFERRABLE_WORK(per_cpu_ptr(&vmstat_work, cpu),
2132 			vmstat_update);
2133 
2134 		/*
2135 		 * For secondary CPUs during CPU hotplug scenarios,
2136 		 * vmstat_cpu_online() will enable the work.
2137 		 * mm/vmstat:online enables and disables vmstat_work
2138 		 * symmetrically during CPU hotplug events.
2139 		 */
2140 		if (!cpu_online(cpu))
2141 			disable_delayed_work_sync(&per_cpu(vmstat_work, cpu));
2142 	}
2143 
2144 	schedule_delayed_work(&shepherd,
2145 		round_jiffies_relative(sysctl_stat_interval));
2146 }
2147 
2148 static void __init init_cpu_node_state(void)
2149 {
2150 	int node;
2151 
2152 	for_each_online_node(node) {
2153 		if (!cpumask_empty(cpumask_of_node(node)))
2154 			node_set_state(node, N_CPU);
2155 	}
2156 }
2157 
2158 static int vmstat_cpu_online(unsigned int cpu)
2159 {
2160 	if (vmstat_late_init_done)
2161 		refresh_zone_stat_thresholds();
2162 
2163 	if (!node_state(cpu_to_node(cpu), N_CPU)) {
2164 		node_set_state(cpu_to_node(cpu), N_CPU);
2165 	}
2166 	enable_delayed_work(&per_cpu(vmstat_work, cpu));
2167 
2168 	return 0;
2169 }
2170 
2171 static int vmstat_cpu_down_prep(unsigned int cpu)
2172 {
2173 	disable_delayed_work_sync(&per_cpu(vmstat_work, cpu));
2174 	return 0;
2175 }
2176 
2177 static int vmstat_cpu_dead(unsigned int cpu)
2178 {
2179 	const struct cpumask *node_cpus;
2180 	int node;
2181 
2182 	node = cpu_to_node(cpu);
2183 
2184 	refresh_zone_stat_thresholds();
2185 	node_cpus = cpumask_of_node(node);
2186 	if (!cpumask_empty(node_cpus))
2187 		return 0;
2188 
2189 	node_clear_state(node, N_CPU);
2190 
2191 	return 0;
2192 }
2193 
2194 static int __init vmstat_late_init(void)
2195 {
2196 	refresh_zone_stat_thresholds();
2197 	vmstat_late_init_done = 1;
2198 
2199 	return 0;
2200 }
2201 late_initcall(vmstat_late_init);
2202 #endif
2203 
2204 #ifdef CONFIG_PROC_FS
2205 static const struct ctl_table vmstat_table[] = {
2206 #ifdef CONFIG_SMP
2207 	{
2208 		.procname	= "stat_interval",
2209 		.data		= &sysctl_stat_interval,
2210 		.maxlen		= sizeof(sysctl_stat_interval),
2211 		.mode		= 0644,
2212 		.proc_handler	= proc_dointvec_jiffies,
2213 	},
2214 	{
2215 		.procname	= "stat_refresh",
2216 		.data		= NULL,
2217 		.maxlen		= 0,
2218 		.mode		= 0600,
2219 		.proc_handler	= vmstat_refresh,
2220 	},
2221 #endif
2222 #ifdef CONFIG_NUMA
2223 	{
2224 		.procname	= "numa_stat",
2225 		.data		= &sysctl_vm_numa_stat,
2226 		.maxlen		= sizeof(int),
2227 		.mode		= 0644,
2228 		.proc_handler	= sysctl_vm_numa_stat_handler,
2229 		.extra1		= SYSCTL_ZERO,
2230 		.extra2		= SYSCTL_ONE,
2231 	},
2232 #endif
2233 };
2234 #endif
2235 
2236 struct workqueue_struct *mm_percpu_wq;
2237 
2238 void __init init_mm_internals(void)
2239 {
2240 	int ret __maybe_unused;
2241 
2242 	mm_percpu_wq = alloc_workqueue("mm_percpu_wq", WQ_MEM_RECLAIM, 0);
2243 
2244 #ifdef CONFIG_SMP
2245 	ret = cpuhp_setup_state_nocalls(CPUHP_MM_VMSTAT_DEAD, "mm/vmstat:dead",
2246 					NULL, vmstat_cpu_dead);
2247 	if (ret < 0)
2248 		pr_err("vmstat: failed to register 'dead' hotplug state\n");
2249 
2250 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "mm/vmstat:online",
2251 					vmstat_cpu_online,
2252 					vmstat_cpu_down_prep);
2253 	if (ret < 0)
2254 		pr_err("vmstat: failed to register 'online' hotplug state\n");
2255 
2256 	cpus_read_lock();
2257 	init_cpu_node_state();
2258 	cpus_read_unlock();
2259 
2260 	start_shepherd_timer();
2261 #endif
2262 #ifdef CONFIG_PROC_FS
2263 	proc_create_seq("buddyinfo", 0444, NULL, &fragmentation_op);
2264 	proc_create_seq("pagetypeinfo", 0400, NULL, &pagetypeinfo_op);
2265 	proc_create_seq("vmstat", 0444, NULL, &vmstat_op);
2266 	proc_create_seq("zoneinfo", 0444, NULL, &zoneinfo_op);
2267 	register_sysctl_init("vm", vmstat_table);
2268 #endif
2269 }
2270 
2271 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_COMPACTION)
2272 
2273 /*
2274  * Return an index indicating how much of the available free memory is
2275  * unusable for an allocation of the requested size.
2276  */
2277 static int unusable_free_index(unsigned int order,
2278 				struct contig_page_info *info)
2279 {
2280 	/* No free memory is interpreted as all free memory is unusable */
2281 	if (info->free_pages == 0)
2282 		return 1000;
2283 
2284 	/*
2285 	 * Index should be a value between 0 and 1. Return a value to 3
2286 	 * decimal places.
2287 	 *
2288 	 * 0 => no fragmentation
2289 	 * 1 => high fragmentation
2290 	 */
2291 	return div_u64((info->free_pages - (info->free_blocks_suitable << order)) * 1000ULL, info->free_pages);
2292 
2293 }
2294 
2295 static void unusable_show_print(struct seq_file *m,
2296 					pg_data_t *pgdat, struct zone *zone)
2297 {
2298 	unsigned int order;
2299 	int index;
2300 	struct contig_page_info info;
2301 
2302 	seq_printf(m, "Node %d, zone %8s ",
2303 				pgdat->node_id,
2304 				zone->name);
2305 	for (order = 0; order < NR_PAGE_ORDERS; ++order) {
2306 		fill_contig_page_info(zone, order, &info);
2307 		index = unusable_free_index(order, &info);
2308 		seq_printf(m, "%d.%03d ", index / 1000, index % 1000);
2309 	}
2310 
2311 	seq_putc(m, '\n');
2312 }
2313 
2314 /*
2315  * Display unusable free space index
2316  *
2317  * The unusable free space index measures how much of the available free
2318  * memory cannot be used to satisfy an allocation of a given size and is a
2319  * value between 0 and 1. The higher the value, the more of free memory is
2320  * unusable and by implication, the worse the external fragmentation is. This
2321  * can be expressed as a percentage by multiplying by 100.
2322  */
2323 static int unusable_show(struct seq_file *m, void *arg)
2324 {
2325 	pg_data_t *pgdat = (pg_data_t *)arg;
2326 
2327 	/* check memoryless node */
2328 	if (!node_state(pgdat->node_id, N_MEMORY))
2329 		return 0;
2330 
2331 	walk_zones_in_node(m, pgdat, true, false, unusable_show_print);
2332 
2333 	return 0;
2334 }
2335 
2336 static const struct seq_operations unusable_sops = {
2337 	.start	= frag_start,
2338 	.next	= frag_next,
2339 	.stop	= frag_stop,
2340 	.show	= unusable_show,
2341 };
2342 
2343 DEFINE_SEQ_ATTRIBUTE(unusable);
2344 
2345 static void extfrag_show_print(struct seq_file *m,
2346 					pg_data_t *pgdat, struct zone *zone)
2347 {
2348 	unsigned int order;
2349 	int index;
2350 
2351 	/* Alloc on stack as interrupts are disabled for zone walk */
2352 	struct contig_page_info info;
2353 
2354 	seq_printf(m, "Node %d, zone %8s ",
2355 				pgdat->node_id,
2356 				zone->name);
2357 	for (order = 0; order < NR_PAGE_ORDERS; ++order) {
2358 		fill_contig_page_info(zone, order, &info);
2359 		index = __fragmentation_index(order, &info);
2360 		seq_printf(m, "%2d.%03d ", index / 1000, index % 1000);
2361 	}
2362 
2363 	seq_putc(m, '\n');
2364 }
2365 
2366 /*
2367  * Display fragmentation index for orders that allocations would fail for
2368  */
2369 static int extfrag_show(struct seq_file *m, void *arg)
2370 {
2371 	pg_data_t *pgdat = (pg_data_t *)arg;
2372 
2373 	walk_zones_in_node(m, pgdat, true, false, extfrag_show_print);
2374 
2375 	return 0;
2376 }
2377 
2378 static const struct seq_operations extfrag_sops = {
2379 	.start	= frag_start,
2380 	.next	= frag_next,
2381 	.stop	= frag_stop,
2382 	.show	= extfrag_show,
2383 };
2384 
2385 DEFINE_SEQ_ATTRIBUTE(extfrag);
2386 
2387 static int __init extfrag_debug_init(void)
2388 {
2389 	struct dentry *extfrag_debug_root;
2390 
2391 	extfrag_debug_root = debugfs_create_dir("extfrag", NULL);
2392 
2393 	debugfs_create_file("unusable_index", 0444, extfrag_debug_root, NULL,
2394 			    &unusable_fops);
2395 
2396 	debugfs_create_file("extfrag_index", 0444, extfrag_debug_root, NULL,
2397 			    &extfrag_fops);
2398 
2399 	return 0;
2400 }
2401 
2402 module_init(extfrag_debug_init);
2403 
2404 #endif
2405