xref: /linux-6.15/include/linux/mmzone.h (revision 75d60eb3)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_MMZONE_H
3 #define _LINUX_MMZONE_H
4 
5 #ifndef __ASSEMBLY__
6 #ifndef __GENERATING_BOUNDS_H
7 
8 #include <linux/spinlock.h>
9 #include <linux/list.h>
10 #include <linux/list_nulls.h>
11 #include <linux/wait.h>
12 #include <linux/bitops.h>
13 #include <linux/cache.h>
14 #include <linux/threads.h>
15 #include <linux/numa.h>
16 #include <linux/init.h>
17 #include <linux/seqlock.h>
18 #include <linux/nodemask.h>
19 #include <linux/pageblock-flags.h>
20 #include <linux/page-flags-layout.h>
21 #include <linux/atomic.h>
22 #include <linux/mm_types.h>
23 #include <linux/page-flags.h>
24 #include <linux/local_lock.h>
25 #include <linux/zswap.h>
26 #include <asm/page.h>
27 
28 /* Free memory management - zoned buddy allocator.  */
29 #ifndef CONFIG_ARCH_FORCE_MAX_ORDER
30 #define MAX_PAGE_ORDER 10
31 #else
32 #define MAX_PAGE_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
33 #endif
34 #define MAX_ORDER_NR_PAGES (1 << MAX_PAGE_ORDER)
35 
36 #define IS_MAX_ORDER_ALIGNED(pfn) IS_ALIGNED(pfn, MAX_ORDER_NR_PAGES)
37 
38 #define NR_PAGE_ORDERS (MAX_PAGE_ORDER + 1)
39 
40 /*
41  * PAGE_ALLOC_COSTLY_ORDER is the order at which allocations are deemed
42  * costly to service.  That is between allocation orders which should
43  * coalesce naturally under reasonable reclaim pressure and those which
44  * will not.
45  */
46 #define PAGE_ALLOC_COSTLY_ORDER 3
47 
48 enum migratetype {
49 	MIGRATE_UNMOVABLE,
50 	MIGRATE_MOVABLE,
51 	MIGRATE_RECLAIMABLE,
52 	MIGRATE_PCPTYPES,	/* the number of types on the pcp lists */
53 	MIGRATE_HIGHATOMIC = MIGRATE_PCPTYPES,
54 #ifdef CONFIG_CMA
55 	/*
56 	 * MIGRATE_CMA migration type is designed to mimic the way
57 	 * ZONE_MOVABLE works.  Only movable pages can be allocated
58 	 * from MIGRATE_CMA pageblocks and page allocator never
59 	 * implicitly change migration type of MIGRATE_CMA pageblock.
60 	 *
61 	 * The way to use it is to change migratetype of a range of
62 	 * pageblocks to MIGRATE_CMA which can be done by
63 	 * __free_pageblock_cma() function.
64 	 */
65 	MIGRATE_CMA,
66 #endif
67 #ifdef CONFIG_MEMORY_ISOLATION
68 	MIGRATE_ISOLATE,	/* can't allocate from here */
69 #endif
70 	MIGRATE_TYPES
71 };
72 
73 /* In mm/page_alloc.c; keep in sync also with show_migration_types() there */
74 extern const char * const migratetype_names[MIGRATE_TYPES];
75 
76 #ifdef CONFIG_CMA
77 #  define is_migrate_cma(migratetype) unlikely((migratetype) == MIGRATE_CMA)
78 #  define is_migrate_cma_page(_page) (get_pageblock_migratetype(_page) == MIGRATE_CMA)
79 #  define is_migrate_cma_folio(folio, pfn)	(MIGRATE_CMA ==		\
80 	get_pfnblock_flags_mask(&folio->page, pfn, MIGRATETYPE_MASK))
81 #else
82 #  define is_migrate_cma(migratetype) false
83 #  define is_migrate_cma_page(_page) false
84 #  define is_migrate_cma_folio(folio, pfn) false
85 #endif
86 
87 static inline bool is_migrate_movable(int mt)
88 {
89 	return is_migrate_cma(mt) || mt == MIGRATE_MOVABLE;
90 }
91 
92 /*
93  * Check whether a migratetype can be merged with another migratetype.
94  *
95  * It is only mergeable when it can fall back to other migratetypes for
96  * allocation. See fallbacks[MIGRATE_TYPES][3] in page_alloc.c.
97  */
98 static inline bool migratetype_is_mergeable(int mt)
99 {
100 	return mt < MIGRATE_PCPTYPES;
101 }
102 
103 #define for_each_migratetype_order(order, type) \
104 	for (order = 0; order < NR_PAGE_ORDERS; order++) \
105 		for (type = 0; type < MIGRATE_TYPES; type++)
106 
107 extern int page_group_by_mobility_disabled;
108 
109 #define MIGRATETYPE_MASK ((1UL << PB_migratetype_bits) - 1)
110 
111 #define get_pageblock_migratetype(page)					\
112 	get_pfnblock_flags_mask(page, page_to_pfn(page), MIGRATETYPE_MASK)
113 
114 #define folio_migratetype(folio)				\
115 	get_pfnblock_flags_mask(&folio->page, folio_pfn(folio),		\
116 			MIGRATETYPE_MASK)
117 struct free_area {
118 	struct list_head	free_list[MIGRATE_TYPES];
119 	unsigned long		nr_free;
120 };
121 
122 struct pglist_data;
123 
124 #ifdef CONFIG_NUMA
125 enum numa_stat_item {
126 	NUMA_HIT,		/* allocated in intended node */
127 	NUMA_MISS,		/* allocated in non intended node */
128 	NUMA_FOREIGN,		/* was intended here, hit elsewhere */
129 	NUMA_INTERLEAVE_HIT,	/* interleaver preferred this zone */
130 	NUMA_LOCAL,		/* allocation from local node */
131 	NUMA_OTHER,		/* allocation from other node */
132 	NR_VM_NUMA_EVENT_ITEMS
133 };
134 #else
135 #define NR_VM_NUMA_EVENT_ITEMS 0
136 #endif
137 
138 enum zone_stat_item {
139 	/* First 128 byte cacheline (assuming 64 bit words) */
140 	NR_FREE_PAGES,
141 	NR_ZONE_LRU_BASE, /* Used only for compaction and reclaim retry */
142 	NR_ZONE_INACTIVE_ANON = NR_ZONE_LRU_BASE,
143 	NR_ZONE_ACTIVE_ANON,
144 	NR_ZONE_INACTIVE_FILE,
145 	NR_ZONE_ACTIVE_FILE,
146 	NR_ZONE_UNEVICTABLE,
147 	NR_ZONE_WRITE_PENDING,	/* Count of dirty, writeback and unstable pages */
148 	NR_MLOCK,		/* mlock()ed pages found and moved off LRU */
149 	/* Second 128 byte cacheline */
150 	NR_BOUNCE,
151 #if IS_ENABLED(CONFIG_ZSMALLOC)
152 	NR_ZSPAGES,		/* allocated in zsmalloc */
153 #endif
154 	NR_FREE_CMA_PAGES,
155 #ifdef CONFIG_UNACCEPTED_MEMORY
156 	NR_UNACCEPTED,
157 #endif
158 	NR_VM_ZONE_STAT_ITEMS };
159 
160 enum node_stat_item {
161 	NR_LRU_BASE,
162 	NR_INACTIVE_ANON = NR_LRU_BASE, /* must match order of LRU_[IN]ACTIVE */
163 	NR_ACTIVE_ANON,		/*  "     "     "   "       "         */
164 	NR_INACTIVE_FILE,	/*  "     "     "   "       "         */
165 	NR_ACTIVE_FILE,		/*  "     "     "   "       "         */
166 	NR_UNEVICTABLE,		/*  "     "     "   "       "         */
167 	NR_SLAB_RECLAIMABLE_B,
168 	NR_SLAB_UNRECLAIMABLE_B,
169 	NR_ISOLATED_ANON,	/* Temporary isolated pages from anon lru */
170 	NR_ISOLATED_FILE,	/* Temporary isolated pages from file lru */
171 	WORKINGSET_NODES,
172 	WORKINGSET_REFAULT_BASE,
173 	WORKINGSET_REFAULT_ANON = WORKINGSET_REFAULT_BASE,
174 	WORKINGSET_REFAULT_FILE,
175 	WORKINGSET_ACTIVATE_BASE,
176 	WORKINGSET_ACTIVATE_ANON = WORKINGSET_ACTIVATE_BASE,
177 	WORKINGSET_ACTIVATE_FILE,
178 	WORKINGSET_RESTORE_BASE,
179 	WORKINGSET_RESTORE_ANON = WORKINGSET_RESTORE_BASE,
180 	WORKINGSET_RESTORE_FILE,
181 	WORKINGSET_NODERECLAIM,
182 	NR_ANON_MAPPED,	/* Mapped anonymous pages */
183 	NR_FILE_MAPPED,	/* pagecache pages mapped into pagetables.
184 			   only modified from process context */
185 	NR_FILE_PAGES,
186 	NR_FILE_DIRTY,
187 	NR_WRITEBACK,
188 	NR_WRITEBACK_TEMP,	/* Writeback using temporary buffers */
189 	NR_SHMEM,		/* shmem pages (included tmpfs/GEM pages) */
190 	NR_SHMEM_THPS,
191 	NR_SHMEM_PMDMAPPED,
192 	NR_FILE_THPS,
193 	NR_FILE_PMDMAPPED,
194 	NR_ANON_THPS,
195 	NR_VMSCAN_WRITE,
196 	NR_VMSCAN_IMMEDIATE,	/* Prioritise for reclaim when writeback ends */
197 	NR_DIRTIED,		/* page dirtyings since bootup */
198 	NR_WRITTEN,		/* page writings since bootup */
199 	NR_THROTTLED_WRITTEN,	/* NR_WRITTEN while reclaim throttled */
200 	NR_KERNEL_MISC_RECLAIMABLE,	/* reclaimable non-slab kernel pages */
201 	NR_FOLL_PIN_ACQUIRED,	/* via: pin_user_page(), gup flag: FOLL_PIN */
202 	NR_FOLL_PIN_RELEASED,	/* pages returned via unpin_user_page() */
203 	NR_KERNEL_STACK_KB,	/* measured in KiB */
204 #if IS_ENABLED(CONFIG_SHADOW_CALL_STACK)
205 	NR_KERNEL_SCS_KB,	/* measured in KiB */
206 #endif
207 	NR_PAGETABLE,		/* used for pagetables */
208 	NR_SECONDARY_PAGETABLE, /* secondary pagetables, KVM & IOMMU */
209 #ifdef CONFIG_IOMMU_SUPPORT
210 	NR_IOMMU_PAGES,		/* # of pages allocated by IOMMU */
211 #endif
212 #ifdef CONFIG_SWAP
213 	NR_SWAPCACHE,
214 #endif
215 #ifdef CONFIG_NUMA_BALANCING
216 	PGPROMOTE_SUCCESS,	/* promote successfully */
217 	PGPROMOTE_CANDIDATE,	/* candidate pages to promote */
218 #endif
219 	/* PGDEMOTE_*: pages demoted */
220 	PGDEMOTE_KSWAPD,
221 	PGDEMOTE_DIRECT,
222 	PGDEMOTE_KHUGEPAGED,
223 	NR_VM_NODE_STAT_ITEMS
224 };
225 
226 /*
227  * Returns true if the item should be printed in THPs (/proc/vmstat
228  * currently prints number of anon, file and shmem THPs. But the item
229  * is charged in pages).
230  */
231 static __always_inline bool vmstat_item_print_in_thp(enum node_stat_item item)
232 {
233 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
234 		return false;
235 
236 	return item == NR_ANON_THPS ||
237 	       item == NR_FILE_THPS ||
238 	       item == NR_SHMEM_THPS ||
239 	       item == NR_SHMEM_PMDMAPPED ||
240 	       item == NR_FILE_PMDMAPPED;
241 }
242 
243 /*
244  * Returns true if the value is measured in bytes (most vmstat values are
245  * measured in pages). This defines the API part, the internal representation
246  * might be different.
247  */
248 static __always_inline bool vmstat_item_in_bytes(int idx)
249 {
250 	/*
251 	 * Global and per-node slab counters track slab pages.
252 	 * It's expected that changes are multiples of PAGE_SIZE.
253 	 * Internally values are stored in pages.
254 	 *
255 	 * Per-memcg and per-lruvec counters track memory, consumed
256 	 * by individual slab objects. These counters are actually
257 	 * byte-precise.
258 	 */
259 	return (idx == NR_SLAB_RECLAIMABLE_B ||
260 		idx == NR_SLAB_UNRECLAIMABLE_B);
261 }
262 
263 /*
264  * We do arithmetic on the LRU lists in various places in the code,
265  * so it is important to keep the active lists LRU_ACTIVE higher in
266  * the array than the corresponding inactive lists, and to keep
267  * the *_FILE lists LRU_FILE higher than the corresponding _ANON lists.
268  *
269  * This has to be kept in sync with the statistics in zone_stat_item
270  * above and the descriptions in vmstat_text in mm/vmstat.c
271  */
272 #define LRU_BASE 0
273 #define LRU_ACTIVE 1
274 #define LRU_FILE 2
275 
276 enum lru_list {
277 	LRU_INACTIVE_ANON = LRU_BASE,
278 	LRU_ACTIVE_ANON = LRU_BASE + LRU_ACTIVE,
279 	LRU_INACTIVE_FILE = LRU_BASE + LRU_FILE,
280 	LRU_ACTIVE_FILE = LRU_BASE + LRU_FILE + LRU_ACTIVE,
281 	LRU_UNEVICTABLE,
282 	NR_LRU_LISTS
283 };
284 
285 enum vmscan_throttle_state {
286 	VMSCAN_THROTTLE_WRITEBACK,
287 	VMSCAN_THROTTLE_ISOLATED,
288 	VMSCAN_THROTTLE_NOPROGRESS,
289 	VMSCAN_THROTTLE_CONGESTED,
290 	NR_VMSCAN_THROTTLE,
291 };
292 
293 #define for_each_lru(lru) for (lru = 0; lru < NR_LRU_LISTS; lru++)
294 
295 #define for_each_evictable_lru(lru) for (lru = 0; lru <= LRU_ACTIVE_FILE; lru++)
296 
297 static inline bool is_file_lru(enum lru_list lru)
298 {
299 	return (lru == LRU_INACTIVE_FILE || lru == LRU_ACTIVE_FILE);
300 }
301 
302 static inline bool is_active_lru(enum lru_list lru)
303 {
304 	return (lru == LRU_ACTIVE_ANON || lru == LRU_ACTIVE_FILE);
305 }
306 
307 #define WORKINGSET_ANON 0
308 #define WORKINGSET_FILE 1
309 #define ANON_AND_FILE 2
310 
311 enum lruvec_flags {
312 	/*
313 	 * An lruvec has many dirty pages backed by a congested BDI:
314 	 * 1. LRUVEC_CGROUP_CONGESTED is set by cgroup-level reclaim.
315 	 *    It can be cleared by cgroup reclaim or kswapd.
316 	 * 2. LRUVEC_NODE_CONGESTED is set by kswapd node-level reclaim.
317 	 *    It can only be cleared by kswapd.
318 	 *
319 	 * Essentially, kswapd can unthrottle an lruvec throttled by cgroup
320 	 * reclaim, but not vice versa. This only applies to the root cgroup.
321 	 * The goal is to prevent cgroup reclaim on the root cgroup (e.g.
322 	 * memory.reclaim) to unthrottle an unbalanced node (that was throttled
323 	 * by kswapd).
324 	 */
325 	LRUVEC_CGROUP_CONGESTED,
326 	LRUVEC_NODE_CONGESTED,
327 };
328 
329 #endif /* !__GENERATING_BOUNDS_H */
330 
331 /*
332  * Evictable pages are divided into multiple generations. The youngest and the
333  * oldest generation numbers, max_seq and min_seq, are monotonically increasing.
334  * They form a sliding window of a variable size [MIN_NR_GENS, MAX_NR_GENS]. An
335  * offset within MAX_NR_GENS, i.e., gen, indexes the LRU list of the
336  * corresponding generation. The gen counter in folio->flags stores gen+1 while
337  * a page is on one of lrugen->folios[]. Otherwise it stores 0.
338  *
339  * A page is added to the youngest generation on faulting. The aging needs to
340  * check the accessed bit at least twice before handing this page over to the
341  * eviction. The first check takes care of the accessed bit set on the initial
342  * fault; the second check makes sure this page hasn't been used since then.
343  * This process, AKA second chance, requires a minimum of two generations,
344  * hence MIN_NR_GENS. And to maintain ABI compatibility with the active/inactive
345  * LRU, e.g., /proc/vmstat, these two generations are considered active; the
346  * rest of generations, if they exist, are considered inactive. See
347  * lru_gen_is_active().
348  *
349  * PG_active is always cleared while a page is on one of lrugen->folios[] so
350  * that the aging needs not to worry about it. And it's set again when a page
351  * considered active is isolated for non-reclaiming purposes, e.g., migration.
352  * See lru_gen_add_folio() and lru_gen_del_folio().
353  *
354  * MAX_NR_GENS is set to 4 so that the multi-gen LRU can support twice the
355  * number of categories of the active/inactive LRU when keeping track of
356  * accesses through page tables. This requires order_base_2(MAX_NR_GENS+1) bits
357  * in folio->flags.
358  */
359 #define MIN_NR_GENS		2U
360 #define MAX_NR_GENS		4U
361 
362 /*
363  * Each generation is divided into multiple tiers. A page accessed N times
364  * through file descriptors is in tier order_base_2(N). A page in the first tier
365  * (N=0,1) is marked by PG_referenced unless it was faulted in through page
366  * tables or read ahead. A page in any other tier (N>1) is marked by
367  * PG_referenced and PG_workingset. This implies a minimum of two tiers is
368  * supported without using additional bits in folio->flags.
369  *
370  * In contrast to moving across generations which requires the LRU lock, moving
371  * across tiers only involves atomic operations on folio->flags and therefore
372  * has a negligible cost in the buffered access path. In the eviction path,
373  * comparisons of refaulted/(evicted+protected) from the first tier and the
374  * rest infer whether pages accessed multiple times through file descriptors
375  * are statistically hot and thus worth protecting.
376  *
377  * MAX_NR_TIERS is set to 4 so that the multi-gen LRU can support twice the
378  * number of categories of the active/inactive LRU when keeping track of
379  * accesses through file descriptors. This uses MAX_NR_TIERS-2 spare bits in
380  * folio->flags.
381  */
382 #define MAX_NR_TIERS		4U
383 
384 #ifndef __GENERATING_BOUNDS_H
385 
386 struct lruvec;
387 struct page_vma_mapped_walk;
388 
389 #define LRU_GEN_MASK		((BIT(LRU_GEN_WIDTH) - 1) << LRU_GEN_PGOFF)
390 #define LRU_REFS_MASK		((BIT(LRU_REFS_WIDTH) - 1) << LRU_REFS_PGOFF)
391 
392 #ifdef CONFIG_LRU_GEN
393 
394 enum {
395 	LRU_GEN_ANON,
396 	LRU_GEN_FILE,
397 };
398 
399 enum {
400 	LRU_GEN_CORE,
401 	LRU_GEN_MM_WALK,
402 	LRU_GEN_NONLEAF_YOUNG,
403 	NR_LRU_GEN_CAPS
404 };
405 
406 #define LRU_REFS_FLAGS		(BIT(PG_referenced) | BIT(PG_workingset))
407 
408 #define MIN_LRU_BATCH		BITS_PER_LONG
409 #define MAX_LRU_BATCH		(MIN_LRU_BATCH * 64)
410 
411 /* whether to keep historical stats from evicted generations */
412 #ifdef CONFIG_LRU_GEN_STATS
413 #define NR_HIST_GENS		MAX_NR_GENS
414 #else
415 #define NR_HIST_GENS		1U
416 #endif
417 
418 /*
419  * The youngest generation number is stored in max_seq for both anon and file
420  * types as they are aged on an equal footing. The oldest generation numbers are
421  * stored in min_seq[] separately for anon and file types as clean file pages
422  * can be evicted regardless of swap constraints.
423  *
424  * Normally anon and file min_seq are in sync. But if swapping is constrained,
425  * e.g., out of swap space, file min_seq is allowed to advance and leave anon
426  * min_seq behind.
427  *
428  * The number of pages in each generation is eventually consistent and therefore
429  * can be transiently negative when reset_batch_size() is pending.
430  */
431 struct lru_gen_folio {
432 	/* the aging increments the youngest generation number */
433 	unsigned long max_seq;
434 	/* the eviction increments the oldest generation numbers */
435 	unsigned long min_seq[ANON_AND_FILE];
436 	/* the birth time of each generation in jiffies */
437 	unsigned long timestamps[MAX_NR_GENS];
438 	/* the multi-gen LRU lists, lazily sorted on eviction */
439 	struct list_head folios[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES];
440 	/* the multi-gen LRU sizes, eventually consistent */
441 	long nr_pages[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES];
442 	/* the exponential moving average of refaulted */
443 	unsigned long avg_refaulted[ANON_AND_FILE][MAX_NR_TIERS];
444 	/* the exponential moving average of evicted+protected */
445 	unsigned long avg_total[ANON_AND_FILE][MAX_NR_TIERS];
446 	/* the first tier doesn't need protection, hence the minus one */
447 	unsigned long protected[NR_HIST_GENS][ANON_AND_FILE][MAX_NR_TIERS - 1];
448 	/* can be modified without holding the LRU lock */
449 	atomic_long_t evicted[NR_HIST_GENS][ANON_AND_FILE][MAX_NR_TIERS];
450 	atomic_long_t refaulted[NR_HIST_GENS][ANON_AND_FILE][MAX_NR_TIERS];
451 	/* whether the multi-gen LRU is enabled */
452 	bool enabled;
453 	/* the memcg generation this lru_gen_folio belongs to */
454 	u8 gen;
455 	/* the list segment this lru_gen_folio belongs to */
456 	u8 seg;
457 	/* per-node lru_gen_folio list for global reclaim */
458 	struct hlist_nulls_node list;
459 };
460 
461 enum {
462 	MM_LEAF_TOTAL,		/* total leaf entries */
463 	MM_LEAF_YOUNG,		/* young leaf entries */
464 	MM_NONLEAF_FOUND,	/* non-leaf entries found in Bloom filters */
465 	MM_NONLEAF_ADDED,	/* non-leaf entries added to Bloom filters */
466 	NR_MM_STATS
467 };
468 
469 /* double-buffering Bloom filters */
470 #define NR_BLOOM_FILTERS	2
471 
472 struct lru_gen_mm_state {
473 	/* synced with max_seq after each iteration */
474 	unsigned long seq;
475 	/* where the current iteration continues after */
476 	struct list_head *head;
477 	/* where the last iteration ended before */
478 	struct list_head *tail;
479 	/* Bloom filters flip after each iteration */
480 	unsigned long *filters[NR_BLOOM_FILTERS];
481 	/* the mm stats for debugging */
482 	unsigned long stats[NR_HIST_GENS][NR_MM_STATS];
483 };
484 
485 struct lru_gen_mm_walk {
486 	/* the lruvec under reclaim */
487 	struct lruvec *lruvec;
488 	/* max_seq from lru_gen_folio: can be out of date */
489 	unsigned long seq;
490 	/* the next address within an mm to scan */
491 	unsigned long next_addr;
492 	/* to batch promoted pages */
493 	int nr_pages[MAX_NR_GENS][ANON_AND_FILE][MAX_NR_ZONES];
494 	/* to batch the mm stats */
495 	int mm_stats[NR_MM_STATS];
496 	/* total batched items */
497 	int batched;
498 	bool can_swap;
499 	bool force_scan;
500 };
501 
502 /*
503  * For each node, memcgs are divided into two generations: the old and the
504  * young. For each generation, memcgs are randomly sharded into multiple bins
505  * to improve scalability. For each bin, the hlist_nulls is virtually divided
506  * into three segments: the head, the tail and the default.
507  *
508  * An onlining memcg is added to the tail of a random bin in the old generation.
509  * The eviction starts at the head of a random bin in the old generation. The
510  * per-node memcg generation counter, whose reminder (mod MEMCG_NR_GENS) indexes
511  * the old generation, is incremented when all its bins become empty.
512  *
513  * There are four operations:
514  * 1. MEMCG_LRU_HEAD, which moves a memcg to the head of a random bin in its
515  *    current generation (old or young) and updates its "seg" to "head";
516  * 2. MEMCG_LRU_TAIL, which moves a memcg to the tail of a random bin in its
517  *    current generation (old or young) and updates its "seg" to "tail";
518  * 3. MEMCG_LRU_OLD, which moves a memcg to the head of a random bin in the old
519  *    generation, updates its "gen" to "old" and resets its "seg" to "default";
520  * 4. MEMCG_LRU_YOUNG, which moves a memcg to the tail of a random bin in the
521  *    young generation, updates its "gen" to "young" and resets its "seg" to
522  *    "default".
523  *
524  * The events that trigger the above operations are:
525  * 1. Exceeding the soft limit, which triggers MEMCG_LRU_HEAD;
526  * 2. The first attempt to reclaim a memcg below low, which triggers
527  *    MEMCG_LRU_TAIL;
528  * 3. The first attempt to reclaim a memcg offlined or below reclaimable size
529  *    threshold, which triggers MEMCG_LRU_TAIL;
530  * 4. The second attempt to reclaim a memcg offlined or below reclaimable size
531  *    threshold, which triggers MEMCG_LRU_YOUNG;
532  * 5. Attempting to reclaim a memcg below min, which triggers MEMCG_LRU_YOUNG;
533  * 6. Finishing the aging on the eviction path, which triggers MEMCG_LRU_YOUNG;
534  * 7. Offlining a memcg, which triggers MEMCG_LRU_OLD.
535  *
536  * Notes:
537  * 1. Memcg LRU only applies to global reclaim, and the round-robin incrementing
538  *    of their max_seq counters ensures the eventual fairness to all eligible
539  *    memcgs. For memcg reclaim, it still relies on mem_cgroup_iter().
540  * 2. There are only two valid generations: old (seq) and young (seq+1).
541  *    MEMCG_NR_GENS is set to three so that when reading the generation counter
542  *    locklessly, a stale value (seq-1) does not wraparound to young.
543  */
544 #define MEMCG_NR_GENS	3
545 #define MEMCG_NR_BINS	8
546 
547 struct lru_gen_memcg {
548 	/* the per-node memcg generation counter */
549 	unsigned long seq;
550 	/* each memcg has one lru_gen_folio per node */
551 	unsigned long nr_memcgs[MEMCG_NR_GENS];
552 	/* per-node lru_gen_folio list for global reclaim */
553 	struct hlist_nulls_head	fifo[MEMCG_NR_GENS][MEMCG_NR_BINS];
554 	/* protects the above */
555 	spinlock_t lock;
556 };
557 
558 void lru_gen_init_pgdat(struct pglist_data *pgdat);
559 void lru_gen_init_lruvec(struct lruvec *lruvec);
560 bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw);
561 
562 void lru_gen_init_memcg(struct mem_cgroup *memcg);
563 void lru_gen_exit_memcg(struct mem_cgroup *memcg);
564 void lru_gen_online_memcg(struct mem_cgroup *memcg);
565 void lru_gen_offline_memcg(struct mem_cgroup *memcg);
566 void lru_gen_release_memcg(struct mem_cgroup *memcg);
567 void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid);
568 
569 #else /* !CONFIG_LRU_GEN */
570 
571 static inline void lru_gen_init_pgdat(struct pglist_data *pgdat)
572 {
573 }
574 
575 static inline void lru_gen_init_lruvec(struct lruvec *lruvec)
576 {
577 }
578 
579 static inline bool lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
580 {
581 	return false;
582 }
583 
584 static inline void lru_gen_init_memcg(struct mem_cgroup *memcg)
585 {
586 }
587 
588 static inline void lru_gen_exit_memcg(struct mem_cgroup *memcg)
589 {
590 }
591 
592 static inline void lru_gen_online_memcg(struct mem_cgroup *memcg)
593 {
594 }
595 
596 static inline void lru_gen_offline_memcg(struct mem_cgroup *memcg)
597 {
598 }
599 
600 static inline void lru_gen_release_memcg(struct mem_cgroup *memcg)
601 {
602 }
603 
604 static inline void lru_gen_soft_reclaim(struct mem_cgroup *memcg, int nid)
605 {
606 }
607 
608 #endif /* CONFIG_LRU_GEN */
609 
610 struct lruvec {
611 	struct list_head		lists[NR_LRU_LISTS];
612 	/* per lruvec lru_lock for memcg */
613 	spinlock_t			lru_lock;
614 	/*
615 	 * These track the cost of reclaiming one LRU - file or anon -
616 	 * over the other. As the observed cost of reclaiming one LRU
617 	 * increases, the reclaim scan balance tips toward the other.
618 	 */
619 	unsigned long			anon_cost;
620 	unsigned long			file_cost;
621 	/* Non-resident age, driven by LRU movement */
622 	atomic_long_t			nonresident_age;
623 	/* Refaults at the time of last reclaim cycle */
624 	unsigned long			refaults[ANON_AND_FILE];
625 	/* Various lruvec state flags (enum lruvec_flags) */
626 	unsigned long			flags;
627 #ifdef CONFIG_LRU_GEN
628 	/* evictable pages divided into generations */
629 	struct lru_gen_folio		lrugen;
630 #ifdef CONFIG_LRU_GEN_WALKS_MMU
631 	/* to concurrently iterate lru_gen_mm_list */
632 	struct lru_gen_mm_state		mm_state;
633 #endif
634 #endif /* CONFIG_LRU_GEN */
635 #ifdef CONFIG_MEMCG
636 	struct pglist_data *pgdat;
637 #endif
638 	struct zswap_lruvec_state zswap_lruvec_state;
639 };
640 
641 /* Isolate for asynchronous migration */
642 #define ISOLATE_ASYNC_MIGRATE	((__force isolate_mode_t)0x4)
643 /* Isolate unevictable pages */
644 #define ISOLATE_UNEVICTABLE	((__force isolate_mode_t)0x8)
645 
646 /* LRU Isolation modes. */
647 typedef unsigned __bitwise isolate_mode_t;
648 
649 enum zone_watermarks {
650 	WMARK_MIN,
651 	WMARK_LOW,
652 	WMARK_HIGH,
653 	WMARK_PROMO,
654 	NR_WMARK
655 };
656 
657 /*
658  * One per migratetype for each PAGE_ALLOC_COSTLY_ORDER. Two additional lists
659  * are added for THP. One PCP list is used by GPF_MOVABLE, and the other PCP list
660  * is used by GFP_UNMOVABLE and GFP_RECLAIMABLE.
661  */
662 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
663 #define NR_PCP_THP 2
664 #else
665 #define NR_PCP_THP 0
666 #endif
667 #define NR_LOWORDER_PCP_LISTS (MIGRATE_PCPTYPES * (PAGE_ALLOC_COSTLY_ORDER + 1))
668 #define NR_PCP_LISTS (NR_LOWORDER_PCP_LISTS + NR_PCP_THP)
669 
670 /*
671  * Flags used in pcp->flags field.
672  *
673  * PCPF_PREV_FREE_HIGH_ORDER: a high-order page is freed in the
674  * previous page freeing.  To avoid to drain PCP for an accident
675  * high-order page freeing.
676  *
677  * PCPF_FREE_HIGH_BATCH: preserve "pcp->batch" pages in PCP before
678  * draining PCP for consecutive high-order pages freeing without
679  * allocation if data cache slice of CPU is large enough.  To reduce
680  * zone lock contention and keep cache-hot pages reusing.
681  */
682 #define	PCPF_PREV_FREE_HIGH_ORDER	BIT(0)
683 #define	PCPF_FREE_HIGH_BATCH		BIT(1)
684 
685 struct per_cpu_pages {
686 	spinlock_t lock;	/* Protects lists field */
687 	int count;		/* number of pages in the list */
688 	int high;		/* high watermark, emptying needed */
689 	int high_min;		/* min high watermark */
690 	int high_max;		/* max high watermark */
691 	int batch;		/* chunk size for buddy add/remove */
692 	u8 flags;		/* protected by pcp->lock */
693 	u8 alloc_factor;	/* batch scaling factor during allocate */
694 #ifdef CONFIG_NUMA
695 	u8 expire;		/* When 0, remote pagesets are drained */
696 #endif
697 	short free_count;	/* consecutive free count */
698 
699 	/* Lists of pages, one per migrate type stored on the pcp-lists */
700 	struct list_head lists[NR_PCP_LISTS];
701 } ____cacheline_aligned_in_smp;
702 
703 struct per_cpu_zonestat {
704 #ifdef CONFIG_SMP
705 	s8 vm_stat_diff[NR_VM_ZONE_STAT_ITEMS];
706 	s8 stat_threshold;
707 #endif
708 #ifdef CONFIG_NUMA
709 	/*
710 	 * Low priority inaccurate counters that are only folded
711 	 * on demand. Use a large type to avoid the overhead of
712 	 * folding during refresh_cpu_vm_stats.
713 	 */
714 	unsigned long vm_numa_event[NR_VM_NUMA_EVENT_ITEMS];
715 #endif
716 };
717 
718 struct per_cpu_nodestat {
719 	s8 stat_threshold;
720 	s8 vm_node_stat_diff[NR_VM_NODE_STAT_ITEMS];
721 };
722 
723 #endif /* !__GENERATING_BOUNDS.H */
724 
725 enum zone_type {
726 	/*
727 	 * ZONE_DMA and ZONE_DMA32 are used when there are peripherals not able
728 	 * to DMA to all of the addressable memory (ZONE_NORMAL).
729 	 * On architectures where this area covers the whole 32 bit address
730 	 * space ZONE_DMA32 is used. ZONE_DMA is left for the ones with smaller
731 	 * DMA addressing constraints. This distinction is important as a 32bit
732 	 * DMA mask is assumed when ZONE_DMA32 is defined. Some 64-bit
733 	 * platforms may need both zones as they support peripherals with
734 	 * different DMA addressing limitations.
735 	 */
736 #ifdef CONFIG_ZONE_DMA
737 	ZONE_DMA,
738 #endif
739 #ifdef CONFIG_ZONE_DMA32
740 	ZONE_DMA32,
741 #endif
742 	/*
743 	 * Normal addressable memory is in ZONE_NORMAL. DMA operations can be
744 	 * performed on pages in ZONE_NORMAL if the DMA devices support
745 	 * transfers to all addressable memory.
746 	 */
747 	ZONE_NORMAL,
748 #ifdef CONFIG_HIGHMEM
749 	/*
750 	 * A memory area that is only addressable by the kernel through
751 	 * mapping portions into its own address space. This is for example
752 	 * used by i386 to allow the kernel to address the memory beyond
753 	 * 900MB. The kernel will set up special mappings (page
754 	 * table entries on i386) for each page that the kernel needs to
755 	 * access.
756 	 */
757 	ZONE_HIGHMEM,
758 #endif
759 	/*
760 	 * ZONE_MOVABLE is similar to ZONE_NORMAL, except that it contains
761 	 * movable pages with few exceptional cases described below. Main use
762 	 * cases for ZONE_MOVABLE are to make memory offlining/unplug more
763 	 * likely to succeed, and to locally limit unmovable allocations - e.g.,
764 	 * to increase the number of THP/huge pages. Notable special cases are:
765 	 *
766 	 * 1. Pinned pages: (long-term) pinning of movable pages might
767 	 *    essentially turn such pages unmovable. Therefore, we do not allow
768 	 *    pinning long-term pages in ZONE_MOVABLE. When pages are pinned and
769 	 *    faulted, they come from the right zone right away. However, it is
770 	 *    still possible that address space already has pages in
771 	 *    ZONE_MOVABLE at the time when pages are pinned (i.e. user has
772 	 *    touches that memory before pinning). In such case we migrate them
773 	 *    to a different zone. When migration fails - pinning fails.
774 	 * 2. memblock allocations: kernelcore/movablecore setups might create
775 	 *    situations where ZONE_MOVABLE contains unmovable allocations
776 	 *    after boot. Memory offlining and allocations fail early.
777 	 * 3. Memory holes: kernelcore/movablecore setups might create very rare
778 	 *    situations where ZONE_MOVABLE contains memory holes after boot,
779 	 *    for example, if we have sections that are only partially
780 	 *    populated. Memory offlining and allocations fail early.
781 	 * 4. PG_hwpoison pages: while poisoned pages can be skipped during
782 	 *    memory offlining, such pages cannot be allocated.
783 	 * 5. Unmovable PG_offline pages: in paravirtualized environments,
784 	 *    hotplugged memory blocks might only partially be managed by the
785 	 *    buddy (e.g., via XEN-balloon, Hyper-V balloon, virtio-mem). The
786 	 *    parts not manged by the buddy are unmovable PG_offline pages. In
787 	 *    some cases (virtio-mem), such pages can be skipped during
788 	 *    memory offlining, however, cannot be moved/allocated. These
789 	 *    techniques might use alloc_contig_range() to hide previously
790 	 *    exposed pages from the buddy again (e.g., to implement some sort
791 	 *    of memory unplug in virtio-mem).
792 	 * 6. ZERO_PAGE(0), kernelcore/movablecore setups might create
793 	 *    situations where ZERO_PAGE(0) which is allocated differently
794 	 *    on different platforms may end up in a movable zone. ZERO_PAGE(0)
795 	 *    cannot be migrated.
796 	 * 7. Memory-hotplug: when using memmap_on_memory and onlining the
797 	 *    memory to the MOVABLE zone, the vmemmap pages are also placed in
798 	 *    such zone. Such pages cannot be really moved around as they are
799 	 *    self-stored in the range, but they are treated as movable when
800 	 *    the range they describe is about to be offlined.
801 	 *
802 	 * In general, no unmovable allocations that degrade memory offlining
803 	 * should end up in ZONE_MOVABLE. Allocators (like alloc_contig_range())
804 	 * have to expect that migrating pages in ZONE_MOVABLE can fail (even
805 	 * if has_unmovable_pages() states that there are no unmovable pages,
806 	 * there can be false negatives).
807 	 */
808 	ZONE_MOVABLE,
809 #ifdef CONFIG_ZONE_DEVICE
810 	ZONE_DEVICE,
811 #endif
812 	__MAX_NR_ZONES
813 
814 };
815 
816 #ifndef __GENERATING_BOUNDS_H
817 
818 #define ASYNC_AND_SYNC 2
819 
820 struct zone {
821 	/* Read-mostly fields */
822 
823 	/* zone watermarks, access with *_wmark_pages(zone) macros */
824 	unsigned long _watermark[NR_WMARK];
825 	unsigned long watermark_boost;
826 
827 	unsigned long nr_reserved_highatomic;
828 	unsigned long nr_free_highatomic;
829 
830 	/*
831 	 * We don't know if the memory that we're going to allocate will be
832 	 * freeable or/and it will be released eventually, so to avoid totally
833 	 * wasting several GB of ram we must reserve some of the lower zone
834 	 * memory (otherwise we risk to run OOM on the lower zones despite
835 	 * there being tons of freeable ram on the higher zones).  This array is
836 	 * recalculated at runtime if the sysctl_lowmem_reserve_ratio sysctl
837 	 * changes.
838 	 */
839 	long lowmem_reserve[MAX_NR_ZONES];
840 
841 #ifdef CONFIG_NUMA
842 	int node;
843 #endif
844 	struct pglist_data	*zone_pgdat;
845 	struct per_cpu_pages	__percpu *per_cpu_pageset;
846 	struct per_cpu_zonestat	__percpu *per_cpu_zonestats;
847 	/*
848 	 * the high and batch values are copied to individual pagesets for
849 	 * faster access
850 	 */
851 	int pageset_high_min;
852 	int pageset_high_max;
853 	int pageset_batch;
854 
855 #ifndef CONFIG_SPARSEMEM
856 	/*
857 	 * Flags for a pageblock_nr_pages block. See pageblock-flags.h.
858 	 * In SPARSEMEM, this map is stored in struct mem_section
859 	 */
860 	unsigned long		*pageblock_flags;
861 #endif /* CONFIG_SPARSEMEM */
862 
863 	/* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */
864 	unsigned long		zone_start_pfn;
865 
866 	/*
867 	 * spanned_pages is the total pages spanned by the zone, including
868 	 * holes, which is calculated as:
869 	 * 	spanned_pages = zone_end_pfn - zone_start_pfn;
870 	 *
871 	 * present_pages is physical pages existing within the zone, which
872 	 * is calculated as:
873 	 *	present_pages = spanned_pages - absent_pages(pages in holes);
874 	 *
875 	 * present_early_pages is present pages existing within the zone
876 	 * located on memory available since early boot, excluding hotplugged
877 	 * memory.
878 	 *
879 	 * managed_pages is present pages managed by the buddy system, which
880 	 * is calculated as (reserved_pages includes pages allocated by the
881 	 * bootmem allocator):
882 	 *	managed_pages = present_pages - reserved_pages;
883 	 *
884 	 * cma pages is present pages that are assigned for CMA use
885 	 * (MIGRATE_CMA).
886 	 *
887 	 * So present_pages may be used by memory hotplug or memory power
888 	 * management logic to figure out unmanaged pages by checking
889 	 * (present_pages - managed_pages). And managed_pages should be used
890 	 * by page allocator and vm scanner to calculate all kinds of watermarks
891 	 * and thresholds.
892 	 *
893 	 * Locking rules:
894 	 *
895 	 * zone_start_pfn and spanned_pages are protected by span_seqlock.
896 	 * It is a seqlock because it has to be read outside of zone->lock,
897 	 * and it is done in the main allocator path.  But, it is written
898 	 * quite infrequently.
899 	 *
900 	 * The span_seq lock is declared along with zone->lock because it is
901 	 * frequently read in proximity to zone->lock.  It's good to
902 	 * give them a chance of being in the same cacheline.
903 	 *
904 	 * Write access to present_pages at runtime should be protected by
905 	 * mem_hotplug_begin/done(). Any reader who can't tolerant drift of
906 	 * present_pages should use get_online_mems() to get a stable value.
907 	 */
908 	atomic_long_t		managed_pages;
909 	unsigned long		spanned_pages;
910 	unsigned long		present_pages;
911 #if defined(CONFIG_MEMORY_HOTPLUG)
912 	unsigned long		present_early_pages;
913 #endif
914 #ifdef CONFIG_CMA
915 	unsigned long		cma_pages;
916 #endif
917 
918 	const char		*name;
919 
920 #ifdef CONFIG_MEMORY_ISOLATION
921 	/*
922 	 * Number of isolated pageblock. It is used to solve incorrect
923 	 * freepage counting problem due to racy retrieving migratetype
924 	 * of pageblock. Protected by zone->lock.
925 	 */
926 	unsigned long		nr_isolate_pageblock;
927 #endif
928 
929 #ifdef CONFIG_MEMORY_HOTPLUG
930 	/* see spanned/present_pages for more description */
931 	seqlock_t		span_seqlock;
932 #endif
933 
934 	int initialized;
935 
936 	/* Write-intensive fields used from the page allocator */
937 	CACHELINE_PADDING(_pad1_);
938 
939 	/* free areas of different sizes */
940 	struct free_area	free_area[NR_PAGE_ORDERS];
941 
942 #ifdef CONFIG_UNACCEPTED_MEMORY
943 	/* Pages to be accepted. All pages on the list are MAX_PAGE_ORDER */
944 	struct list_head	unaccepted_pages;
945 #endif
946 
947 	/* zone flags, see below */
948 	unsigned long		flags;
949 
950 	/* Primarily protects free_area */
951 	spinlock_t		lock;
952 
953 	/* Write-intensive fields used by compaction and vmstats. */
954 	CACHELINE_PADDING(_pad2_);
955 
956 	/*
957 	 * When free pages are below this point, additional steps are taken
958 	 * when reading the number of free pages to avoid per-cpu counter
959 	 * drift allowing watermarks to be breached
960 	 */
961 	unsigned long percpu_drift_mark;
962 
963 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
964 	/* pfn where compaction free scanner should start */
965 	unsigned long		compact_cached_free_pfn;
966 	/* pfn where compaction migration scanner should start */
967 	unsigned long		compact_cached_migrate_pfn[ASYNC_AND_SYNC];
968 	unsigned long		compact_init_migrate_pfn;
969 	unsigned long		compact_init_free_pfn;
970 #endif
971 
972 #ifdef CONFIG_COMPACTION
973 	/*
974 	 * On compaction failure, 1<<compact_defer_shift compactions
975 	 * are skipped before trying again. The number attempted since
976 	 * last failure is tracked with compact_considered.
977 	 * compact_order_failed is the minimum compaction failed order.
978 	 */
979 	unsigned int		compact_considered;
980 	unsigned int		compact_defer_shift;
981 	int			compact_order_failed;
982 #endif
983 
984 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
985 	/* Set to true when the PG_migrate_skip bits should be cleared */
986 	bool			compact_blockskip_flush;
987 #endif
988 
989 	bool			contiguous;
990 
991 	CACHELINE_PADDING(_pad3_);
992 	/* Zone statistics */
993 	atomic_long_t		vm_stat[NR_VM_ZONE_STAT_ITEMS];
994 	atomic_long_t		vm_numa_event[NR_VM_NUMA_EVENT_ITEMS];
995 } ____cacheline_internodealigned_in_smp;
996 
997 enum pgdat_flags {
998 	PGDAT_DIRTY,			/* reclaim scanning has recently found
999 					 * many dirty file pages at the tail
1000 					 * of the LRU.
1001 					 */
1002 	PGDAT_WRITEBACK,		/* reclaim scanning has recently found
1003 					 * many pages under writeback
1004 					 */
1005 	PGDAT_RECLAIM_LOCKED,		/* prevents concurrent reclaim */
1006 };
1007 
1008 enum zone_flags {
1009 	ZONE_BOOSTED_WATERMARK,		/* zone recently boosted watermarks.
1010 					 * Cleared when kswapd is woken.
1011 					 */
1012 	ZONE_RECLAIM_ACTIVE,		/* kswapd may be scanning the zone. */
1013 	ZONE_BELOW_HIGH,		/* zone is below high watermark. */
1014 };
1015 
1016 static inline unsigned long wmark_pages(const struct zone *z,
1017 					enum zone_watermarks w)
1018 {
1019 	return z->_watermark[w] + z->watermark_boost;
1020 }
1021 
1022 static inline unsigned long min_wmark_pages(const struct zone *z)
1023 {
1024 	return wmark_pages(z, WMARK_MIN);
1025 }
1026 
1027 static inline unsigned long low_wmark_pages(const struct zone *z)
1028 {
1029 	return wmark_pages(z, WMARK_LOW);
1030 }
1031 
1032 static inline unsigned long high_wmark_pages(const struct zone *z)
1033 {
1034 	return wmark_pages(z, WMARK_HIGH);
1035 }
1036 
1037 static inline unsigned long promo_wmark_pages(const struct zone *z)
1038 {
1039 	return wmark_pages(z, WMARK_PROMO);
1040 }
1041 
1042 static inline unsigned long zone_managed_pages(struct zone *zone)
1043 {
1044 	return (unsigned long)atomic_long_read(&zone->managed_pages);
1045 }
1046 
1047 static inline unsigned long zone_cma_pages(struct zone *zone)
1048 {
1049 #ifdef CONFIG_CMA
1050 	return zone->cma_pages;
1051 #else
1052 	return 0;
1053 #endif
1054 }
1055 
1056 static inline unsigned long zone_end_pfn(const struct zone *zone)
1057 {
1058 	return zone->zone_start_pfn + zone->spanned_pages;
1059 }
1060 
1061 static inline bool zone_spans_pfn(const struct zone *zone, unsigned long pfn)
1062 {
1063 	return zone->zone_start_pfn <= pfn && pfn < zone_end_pfn(zone);
1064 }
1065 
1066 static inline bool zone_is_initialized(struct zone *zone)
1067 {
1068 	return zone->initialized;
1069 }
1070 
1071 static inline bool zone_is_empty(struct zone *zone)
1072 {
1073 	return zone->spanned_pages == 0;
1074 }
1075 
1076 #ifndef BUILD_VDSO32_64
1077 /*
1078  * The zone field is never updated after free_area_init_core()
1079  * sets it, so none of the operations on it need to be atomic.
1080  */
1081 
1082 /* Page flags: | [SECTION] | [NODE] | ZONE | [LAST_CPUPID] | ... | FLAGS | */
1083 #define SECTIONS_PGOFF		((sizeof(unsigned long)*8) - SECTIONS_WIDTH)
1084 #define NODES_PGOFF		(SECTIONS_PGOFF - NODES_WIDTH)
1085 #define ZONES_PGOFF		(NODES_PGOFF - ZONES_WIDTH)
1086 #define LAST_CPUPID_PGOFF	(ZONES_PGOFF - LAST_CPUPID_WIDTH)
1087 #define KASAN_TAG_PGOFF		(LAST_CPUPID_PGOFF - KASAN_TAG_WIDTH)
1088 #define LRU_GEN_PGOFF		(KASAN_TAG_PGOFF - LRU_GEN_WIDTH)
1089 #define LRU_REFS_PGOFF		(LRU_GEN_PGOFF - LRU_REFS_WIDTH)
1090 
1091 /*
1092  * Define the bit shifts to access each section.  For non-existent
1093  * sections we define the shift as 0; that plus a 0 mask ensures
1094  * the compiler will optimise away reference to them.
1095  */
1096 #define SECTIONS_PGSHIFT	(SECTIONS_PGOFF * (SECTIONS_WIDTH != 0))
1097 #define NODES_PGSHIFT		(NODES_PGOFF * (NODES_WIDTH != 0))
1098 #define ZONES_PGSHIFT		(ZONES_PGOFF * (ZONES_WIDTH != 0))
1099 #define LAST_CPUPID_PGSHIFT	(LAST_CPUPID_PGOFF * (LAST_CPUPID_WIDTH != 0))
1100 #define KASAN_TAG_PGSHIFT	(KASAN_TAG_PGOFF * (KASAN_TAG_WIDTH != 0))
1101 
1102 /* NODE:ZONE or SECTION:ZONE is used to ID a zone for the buddy allocator */
1103 #ifdef NODE_NOT_IN_PAGE_FLAGS
1104 #define ZONEID_SHIFT		(SECTIONS_SHIFT + ZONES_SHIFT)
1105 #define ZONEID_PGOFF		((SECTIONS_PGOFF < ZONES_PGOFF) ? \
1106 						SECTIONS_PGOFF : ZONES_PGOFF)
1107 #else
1108 #define ZONEID_SHIFT		(NODES_SHIFT + ZONES_SHIFT)
1109 #define ZONEID_PGOFF		((NODES_PGOFF < ZONES_PGOFF) ? \
1110 						NODES_PGOFF : ZONES_PGOFF)
1111 #endif
1112 
1113 #define ZONEID_PGSHIFT		(ZONEID_PGOFF * (ZONEID_SHIFT != 0))
1114 
1115 #define ZONES_MASK		((1UL << ZONES_WIDTH) - 1)
1116 #define NODES_MASK		((1UL << NODES_WIDTH) - 1)
1117 #define SECTIONS_MASK		((1UL << SECTIONS_WIDTH) - 1)
1118 #define LAST_CPUPID_MASK	((1UL << LAST_CPUPID_SHIFT) - 1)
1119 #define KASAN_TAG_MASK		((1UL << KASAN_TAG_WIDTH) - 1)
1120 #define ZONEID_MASK		((1UL << ZONEID_SHIFT) - 1)
1121 
1122 static inline enum zone_type page_zonenum(const struct page *page)
1123 {
1124 	ASSERT_EXCLUSIVE_BITS(page->flags, ZONES_MASK << ZONES_PGSHIFT);
1125 	return (page->flags >> ZONES_PGSHIFT) & ZONES_MASK;
1126 }
1127 
1128 static inline enum zone_type folio_zonenum(const struct folio *folio)
1129 {
1130 	return page_zonenum(&folio->page);
1131 }
1132 
1133 #ifdef CONFIG_ZONE_DEVICE
1134 static inline bool is_zone_device_page(const struct page *page)
1135 {
1136 	return page_zonenum(page) == ZONE_DEVICE;
1137 }
1138 
1139 /*
1140  * Consecutive zone device pages should not be merged into the same sgl
1141  * or bvec segment with other types of pages or if they belong to different
1142  * pgmaps. Otherwise getting the pgmap of a given segment is not possible
1143  * without scanning the entire segment. This helper returns true either if
1144  * both pages are not zone device pages or both pages are zone device pages
1145  * with the same pgmap.
1146  */
1147 static inline bool zone_device_pages_have_same_pgmap(const struct page *a,
1148 						     const struct page *b)
1149 {
1150 	if (is_zone_device_page(a) != is_zone_device_page(b))
1151 		return false;
1152 	if (!is_zone_device_page(a))
1153 		return true;
1154 	return a->pgmap == b->pgmap;
1155 }
1156 
1157 extern void memmap_init_zone_device(struct zone *, unsigned long,
1158 				    unsigned long, struct dev_pagemap *);
1159 #else
1160 static inline bool is_zone_device_page(const struct page *page)
1161 {
1162 	return false;
1163 }
1164 static inline bool zone_device_pages_have_same_pgmap(const struct page *a,
1165 						     const struct page *b)
1166 {
1167 	return true;
1168 }
1169 #endif
1170 
1171 static inline bool folio_is_zone_device(const struct folio *folio)
1172 {
1173 	return is_zone_device_page(&folio->page);
1174 }
1175 
1176 static inline bool is_zone_movable_page(const struct page *page)
1177 {
1178 	return page_zonenum(page) == ZONE_MOVABLE;
1179 }
1180 
1181 static inline bool folio_is_zone_movable(const struct folio *folio)
1182 {
1183 	return folio_zonenum(folio) == ZONE_MOVABLE;
1184 }
1185 #endif
1186 
1187 /*
1188  * Return true if [start_pfn, start_pfn + nr_pages) range has a non-empty
1189  * intersection with the given zone
1190  */
1191 static inline bool zone_intersects(struct zone *zone,
1192 		unsigned long start_pfn, unsigned long nr_pages)
1193 {
1194 	if (zone_is_empty(zone))
1195 		return false;
1196 	if (start_pfn >= zone_end_pfn(zone) ||
1197 	    start_pfn + nr_pages <= zone->zone_start_pfn)
1198 		return false;
1199 
1200 	return true;
1201 }
1202 
1203 /*
1204  * The "priority" of VM scanning is how much of the queues we will scan in one
1205  * go. A value of 12 for DEF_PRIORITY implies that we will scan 1/4096th of the
1206  * queues ("queue_length >> 12") during an aging round.
1207  */
1208 #define DEF_PRIORITY 12
1209 
1210 /* Maximum number of zones on a zonelist */
1211 #define MAX_ZONES_PER_ZONELIST (MAX_NUMNODES * MAX_NR_ZONES)
1212 
1213 enum {
1214 	ZONELIST_FALLBACK,	/* zonelist with fallback */
1215 #ifdef CONFIG_NUMA
1216 	/*
1217 	 * The NUMA zonelists are doubled because we need zonelists that
1218 	 * restrict the allocations to a single node for __GFP_THISNODE.
1219 	 */
1220 	ZONELIST_NOFALLBACK,	/* zonelist without fallback (__GFP_THISNODE) */
1221 #endif
1222 	MAX_ZONELISTS
1223 };
1224 
1225 /*
1226  * This struct contains information about a zone in a zonelist. It is stored
1227  * here to avoid dereferences into large structures and lookups of tables
1228  */
1229 struct zoneref {
1230 	struct zone *zone;	/* Pointer to actual zone */
1231 	int zone_idx;		/* zone_idx(zoneref->zone) */
1232 };
1233 
1234 /*
1235  * One allocation request operates on a zonelist. A zonelist
1236  * is a list of zones, the first one is the 'goal' of the
1237  * allocation, the other zones are fallback zones, in decreasing
1238  * priority.
1239  *
1240  * To speed the reading of the zonelist, the zonerefs contain the zone index
1241  * of the entry being read. Helper functions to access information given
1242  * a struct zoneref are
1243  *
1244  * zonelist_zone()	- Return the struct zone * for an entry in _zonerefs
1245  * zonelist_zone_idx()	- Return the index of the zone for an entry
1246  * zonelist_node_idx()	- Return the index of the node for an entry
1247  */
1248 struct zonelist {
1249 	struct zoneref _zonerefs[MAX_ZONES_PER_ZONELIST + 1];
1250 };
1251 
1252 /*
1253  * The array of struct pages for flatmem.
1254  * It must be declared for SPARSEMEM as well because there are configurations
1255  * that rely on that.
1256  */
1257 extern struct page *mem_map;
1258 
1259 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1260 struct deferred_split {
1261 	spinlock_t split_queue_lock;
1262 	struct list_head split_queue;
1263 	unsigned long split_queue_len;
1264 };
1265 #endif
1266 
1267 #ifdef CONFIG_MEMORY_FAILURE
1268 /*
1269  * Per NUMA node memory failure handling statistics.
1270  */
1271 struct memory_failure_stats {
1272 	/*
1273 	 * Number of raw pages poisoned.
1274 	 * Cases not accounted: memory outside kernel control, offline page,
1275 	 * arch-specific memory_failure (SGX), hwpoison_filter() filtered
1276 	 * error events, and unpoison actions from hwpoison_unpoison.
1277 	 */
1278 	unsigned long total;
1279 	/*
1280 	 * Recovery results of poisoned raw pages handled by memory_failure,
1281 	 * in sync with mf_result.
1282 	 * total = ignored + failed + delayed + recovered.
1283 	 * total * PAGE_SIZE * #nodes = /proc/meminfo/HardwareCorrupted.
1284 	 */
1285 	unsigned long ignored;
1286 	unsigned long failed;
1287 	unsigned long delayed;
1288 	unsigned long recovered;
1289 };
1290 #endif
1291 
1292 /*
1293  * On NUMA machines, each NUMA node would have a pg_data_t to describe
1294  * it's memory layout. On UMA machines there is a single pglist_data which
1295  * describes the whole memory.
1296  *
1297  * Memory statistics and page replacement data structures are maintained on a
1298  * per-zone basis.
1299  */
1300 typedef struct pglist_data {
1301 	/*
1302 	 * node_zones contains just the zones for THIS node. Not all of the
1303 	 * zones may be populated, but it is the full list. It is referenced by
1304 	 * this node's node_zonelists as well as other node's node_zonelists.
1305 	 */
1306 	struct zone node_zones[MAX_NR_ZONES];
1307 
1308 	/*
1309 	 * node_zonelists contains references to all zones in all nodes.
1310 	 * Generally the first zones will be references to this node's
1311 	 * node_zones.
1312 	 */
1313 	struct zonelist node_zonelists[MAX_ZONELISTS];
1314 
1315 	int nr_zones; /* number of populated zones in this node */
1316 #ifdef CONFIG_FLATMEM	/* means !SPARSEMEM */
1317 	struct page *node_mem_map;
1318 #ifdef CONFIG_PAGE_EXTENSION
1319 	struct page_ext *node_page_ext;
1320 #endif
1321 #endif
1322 #if defined(CONFIG_MEMORY_HOTPLUG) || defined(CONFIG_DEFERRED_STRUCT_PAGE_INIT)
1323 	/*
1324 	 * Must be held any time you expect node_start_pfn,
1325 	 * node_present_pages, node_spanned_pages or nr_zones to stay constant.
1326 	 * Also synchronizes pgdat->first_deferred_pfn during deferred page
1327 	 * init.
1328 	 *
1329 	 * pgdat_resize_lock() and pgdat_resize_unlock() are provided to
1330 	 * manipulate node_size_lock without checking for CONFIG_MEMORY_HOTPLUG
1331 	 * or CONFIG_DEFERRED_STRUCT_PAGE_INIT.
1332 	 *
1333 	 * Nests above zone->lock and zone->span_seqlock
1334 	 */
1335 	spinlock_t node_size_lock;
1336 #endif
1337 	unsigned long node_start_pfn;
1338 	unsigned long node_present_pages; /* total number of physical pages */
1339 	unsigned long node_spanned_pages; /* total size of physical page
1340 					     range, including holes */
1341 	int node_id;
1342 	wait_queue_head_t kswapd_wait;
1343 	wait_queue_head_t pfmemalloc_wait;
1344 
1345 	/* workqueues for throttling reclaim for different reasons. */
1346 	wait_queue_head_t reclaim_wait[NR_VMSCAN_THROTTLE];
1347 
1348 	atomic_t nr_writeback_throttled;/* nr of writeback-throttled tasks */
1349 	unsigned long nr_reclaim_start;	/* nr pages written while throttled
1350 					 * when throttling started. */
1351 #ifdef CONFIG_MEMORY_HOTPLUG
1352 	struct mutex kswapd_lock;
1353 #endif
1354 	struct task_struct *kswapd;	/* Protected by kswapd_lock */
1355 	int kswapd_order;
1356 	enum zone_type kswapd_highest_zoneidx;
1357 
1358 	int kswapd_failures;		/* Number of 'reclaimed == 0' runs */
1359 
1360 #ifdef CONFIG_COMPACTION
1361 	int kcompactd_max_order;
1362 	enum zone_type kcompactd_highest_zoneidx;
1363 	wait_queue_head_t kcompactd_wait;
1364 	struct task_struct *kcompactd;
1365 	bool proactive_compact_trigger;
1366 #endif
1367 	/*
1368 	 * This is a per-node reserve of pages that are not available
1369 	 * to userspace allocations.
1370 	 */
1371 	unsigned long		totalreserve_pages;
1372 
1373 #ifdef CONFIG_NUMA
1374 	/*
1375 	 * node reclaim becomes active if more unmapped pages exist.
1376 	 */
1377 	unsigned long		min_unmapped_pages;
1378 	unsigned long		min_slab_pages;
1379 #endif /* CONFIG_NUMA */
1380 
1381 	/* Write-intensive fields used by page reclaim */
1382 	CACHELINE_PADDING(_pad1_);
1383 
1384 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1385 	/*
1386 	 * If memory initialisation on large machines is deferred then this
1387 	 * is the first PFN that needs to be initialised.
1388 	 */
1389 	unsigned long first_deferred_pfn;
1390 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1391 
1392 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1393 	struct deferred_split deferred_split_queue;
1394 #endif
1395 
1396 #ifdef CONFIG_NUMA_BALANCING
1397 	/* start time in ms of current promote rate limit period */
1398 	unsigned int nbp_rl_start;
1399 	/* number of promote candidate pages at start time of current rate limit period */
1400 	unsigned long nbp_rl_nr_cand;
1401 	/* promote threshold in ms */
1402 	unsigned int nbp_threshold;
1403 	/* start time in ms of current promote threshold adjustment period */
1404 	unsigned int nbp_th_start;
1405 	/*
1406 	 * number of promote candidate pages at start time of current promote
1407 	 * threshold adjustment period
1408 	 */
1409 	unsigned long nbp_th_nr_cand;
1410 #endif
1411 	/* Fields commonly accessed by the page reclaim scanner */
1412 
1413 	/*
1414 	 * NOTE: THIS IS UNUSED IF MEMCG IS ENABLED.
1415 	 *
1416 	 * Use mem_cgroup_lruvec() to look up lruvecs.
1417 	 */
1418 	struct lruvec		__lruvec;
1419 
1420 	unsigned long		flags;
1421 
1422 #ifdef CONFIG_LRU_GEN
1423 	/* kswap mm walk data */
1424 	struct lru_gen_mm_walk mm_walk;
1425 	/* lru_gen_folio list */
1426 	struct lru_gen_memcg memcg_lru;
1427 #endif
1428 
1429 	CACHELINE_PADDING(_pad2_);
1430 
1431 	/* Per-node vmstats */
1432 	struct per_cpu_nodestat __percpu *per_cpu_nodestats;
1433 	atomic_long_t		vm_stat[NR_VM_NODE_STAT_ITEMS];
1434 #ifdef CONFIG_NUMA
1435 	struct memory_tier __rcu *memtier;
1436 #endif
1437 #ifdef CONFIG_MEMORY_FAILURE
1438 	struct memory_failure_stats mf_stats;
1439 #endif
1440 } pg_data_t;
1441 
1442 #define node_present_pages(nid)	(NODE_DATA(nid)->node_present_pages)
1443 #define node_spanned_pages(nid)	(NODE_DATA(nid)->node_spanned_pages)
1444 
1445 #define node_start_pfn(nid)	(NODE_DATA(nid)->node_start_pfn)
1446 #define node_end_pfn(nid) pgdat_end_pfn(NODE_DATA(nid))
1447 
1448 static inline unsigned long pgdat_end_pfn(pg_data_t *pgdat)
1449 {
1450 	return pgdat->node_start_pfn + pgdat->node_spanned_pages;
1451 }
1452 
1453 #include <linux/memory_hotplug.h>
1454 
1455 void build_all_zonelists(pg_data_t *pgdat);
1456 void wakeup_kswapd(struct zone *zone, gfp_t gfp_mask, int order,
1457 		   enum zone_type highest_zoneidx);
1458 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
1459 			 int highest_zoneidx, unsigned int alloc_flags,
1460 			 long free_pages);
1461 bool zone_watermark_ok(struct zone *z, unsigned int order,
1462 		unsigned long mark, int highest_zoneidx,
1463 		unsigned int alloc_flags);
1464 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
1465 		unsigned long mark, int highest_zoneidx);
1466 /*
1467  * Memory initialization context, use to differentiate memory added by
1468  * the platform statically or via memory hotplug interface.
1469  */
1470 enum meminit_context {
1471 	MEMINIT_EARLY,
1472 	MEMINIT_HOTPLUG,
1473 };
1474 
1475 extern void init_currently_empty_zone(struct zone *zone, unsigned long start_pfn,
1476 				     unsigned long size);
1477 
1478 extern void lruvec_init(struct lruvec *lruvec);
1479 
1480 static inline struct pglist_data *lruvec_pgdat(struct lruvec *lruvec)
1481 {
1482 #ifdef CONFIG_MEMCG
1483 	return lruvec->pgdat;
1484 #else
1485 	return container_of(lruvec, struct pglist_data, __lruvec);
1486 #endif
1487 }
1488 
1489 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
1490 int local_memory_node(int node_id);
1491 #else
1492 static inline int local_memory_node(int node_id) { return node_id; };
1493 #endif
1494 
1495 /*
1496  * zone_idx() returns 0 for the ZONE_DMA zone, 1 for the ZONE_NORMAL zone, etc.
1497  */
1498 #define zone_idx(zone)		((zone) - (zone)->zone_pgdat->node_zones)
1499 
1500 #ifdef CONFIG_ZONE_DEVICE
1501 static inline bool zone_is_zone_device(struct zone *zone)
1502 {
1503 	return zone_idx(zone) == ZONE_DEVICE;
1504 }
1505 #else
1506 static inline bool zone_is_zone_device(struct zone *zone)
1507 {
1508 	return false;
1509 }
1510 #endif
1511 
1512 /*
1513  * Returns true if a zone has pages managed by the buddy allocator.
1514  * All the reclaim decisions have to use this function rather than
1515  * populated_zone(). If the whole zone is reserved then we can easily
1516  * end up with populated_zone() && !managed_zone().
1517  */
1518 static inline bool managed_zone(struct zone *zone)
1519 {
1520 	return zone_managed_pages(zone);
1521 }
1522 
1523 /* Returns true if a zone has memory */
1524 static inline bool populated_zone(struct zone *zone)
1525 {
1526 	return zone->present_pages;
1527 }
1528 
1529 #ifdef CONFIG_NUMA
1530 static inline int zone_to_nid(struct zone *zone)
1531 {
1532 	return zone->node;
1533 }
1534 
1535 static inline void zone_set_nid(struct zone *zone, int nid)
1536 {
1537 	zone->node = nid;
1538 }
1539 #else
1540 static inline int zone_to_nid(struct zone *zone)
1541 {
1542 	return 0;
1543 }
1544 
1545 static inline void zone_set_nid(struct zone *zone, int nid) {}
1546 #endif
1547 
1548 extern int movable_zone;
1549 
1550 static inline int is_highmem_idx(enum zone_type idx)
1551 {
1552 #ifdef CONFIG_HIGHMEM
1553 	return (idx == ZONE_HIGHMEM ||
1554 		(idx == ZONE_MOVABLE && movable_zone == ZONE_HIGHMEM));
1555 #else
1556 	return 0;
1557 #endif
1558 }
1559 
1560 /**
1561  * is_highmem - helper function to quickly check if a struct zone is a
1562  *              highmem zone or not.  This is an attempt to keep references
1563  *              to ZONE_{DMA/NORMAL/HIGHMEM/etc} in general code to a minimum.
1564  * @zone: pointer to struct zone variable
1565  * Return: 1 for a highmem zone, 0 otherwise
1566  */
1567 static inline int is_highmem(struct zone *zone)
1568 {
1569 	return is_highmem_idx(zone_idx(zone));
1570 }
1571 
1572 #ifdef CONFIG_ZONE_DMA
1573 bool has_managed_dma(void);
1574 #else
1575 static inline bool has_managed_dma(void)
1576 {
1577 	return false;
1578 }
1579 #endif
1580 
1581 
1582 #ifndef CONFIG_NUMA
1583 
1584 extern struct pglist_data contig_page_data;
1585 static inline struct pglist_data *NODE_DATA(int nid)
1586 {
1587 	return &contig_page_data;
1588 }
1589 
1590 #else /* CONFIG_NUMA */
1591 
1592 #include <asm/mmzone.h>
1593 
1594 #endif /* !CONFIG_NUMA */
1595 
1596 extern struct pglist_data *first_online_pgdat(void);
1597 extern struct pglist_data *next_online_pgdat(struct pglist_data *pgdat);
1598 extern struct zone *next_zone(struct zone *zone);
1599 
1600 /**
1601  * for_each_online_pgdat - helper macro to iterate over all online nodes
1602  * @pgdat: pointer to a pg_data_t variable
1603  */
1604 #define for_each_online_pgdat(pgdat)			\
1605 	for (pgdat = first_online_pgdat();		\
1606 	     pgdat;					\
1607 	     pgdat = next_online_pgdat(pgdat))
1608 /**
1609  * for_each_zone - helper macro to iterate over all memory zones
1610  * @zone: pointer to struct zone variable
1611  *
1612  * The user only needs to declare the zone variable, for_each_zone
1613  * fills it in.
1614  */
1615 #define for_each_zone(zone)			        \
1616 	for (zone = (first_online_pgdat())->node_zones; \
1617 	     zone;					\
1618 	     zone = next_zone(zone))
1619 
1620 #define for_each_populated_zone(zone)		        \
1621 	for (zone = (first_online_pgdat())->node_zones; \
1622 	     zone;					\
1623 	     zone = next_zone(zone))			\
1624 		if (!populated_zone(zone))		\
1625 			; /* do nothing */		\
1626 		else
1627 
1628 static inline struct zone *zonelist_zone(struct zoneref *zoneref)
1629 {
1630 	return zoneref->zone;
1631 }
1632 
1633 static inline int zonelist_zone_idx(struct zoneref *zoneref)
1634 {
1635 	return zoneref->zone_idx;
1636 }
1637 
1638 static inline int zonelist_node_idx(struct zoneref *zoneref)
1639 {
1640 	return zone_to_nid(zoneref->zone);
1641 }
1642 
1643 struct zoneref *__next_zones_zonelist(struct zoneref *z,
1644 					enum zone_type highest_zoneidx,
1645 					nodemask_t *nodes);
1646 
1647 /**
1648  * next_zones_zonelist - Returns the next zone at or below highest_zoneidx within the allowed nodemask using a cursor within a zonelist as a starting point
1649  * @z: The cursor used as a starting point for the search
1650  * @highest_zoneidx: The zone index of the highest zone to return
1651  * @nodes: An optional nodemask to filter the zonelist with
1652  *
1653  * This function returns the next zone at or below a given zone index that is
1654  * within the allowed nodemask using a cursor as the starting point for the
1655  * search. The zoneref returned is a cursor that represents the current zone
1656  * being examined. It should be advanced by one before calling
1657  * next_zones_zonelist again.
1658  *
1659  * Return: the next zone at or below highest_zoneidx within the allowed
1660  * nodemask using a cursor within a zonelist as a starting point
1661  */
1662 static __always_inline struct zoneref *next_zones_zonelist(struct zoneref *z,
1663 					enum zone_type highest_zoneidx,
1664 					nodemask_t *nodes)
1665 {
1666 	if (likely(!nodes && zonelist_zone_idx(z) <= highest_zoneidx))
1667 		return z;
1668 	return __next_zones_zonelist(z, highest_zoneidx, nodes);
1669 }
1670 
1671 /**
1672  * first_zones_zonelist - Returns the first zone at or below highest_zoneidx within the allowed nodemask in a zonelist
1673  * @zonelist: The zonelist to search for a suitable zone
1674  * @highest_zoneidx: The zone index of the highest zone to return
1675  * @nodes: An optional nodemask to filter the zonelist with
1676  *
1677  * This function returns the first zone at or below a given zone index that is
1678  * within the allowed nodemask. The zoneref returned is a cursor that can be
1679  * used to iterate the zonelist with next_zones_zonelist by advancing it by
1680  * one before calling.
1681  *
1682  * When no eligible zone is found, zoneref->zone is NULL (zoneref itself is
1683  * never NULL). This may happen either genuinely, or due to concurrent nodemask
1684  * update due to cpuset modification.
1685  *
1686  * Return: Zoneref pointer for the first suitable zone found
1687  */
1688 static inline struct zoneref *first_zones_zonelist(struct zonelist *zonelist,
1689 					enum zone_type highest_zoneidx,
1690 					nodemask_t *nodes)
1691 {
1692 	return next_zones_zonelist(zonelist->_zonerefs,
1693 							highest_zoneidx, nodes);
1694 }
1695 
1696 /**
1697  * for_each_zone_zonelist_nodemask - helper macro to iterate over valid zones in a zonelist at or below a given zone index and within a nodemask
1698  * @zone: The current zone in the iterator
1699  * @z: The current pointer within zonelist->_zonerefs being iterated
1700  * @zlist: The zonelist being iterated
1701  * @highidx: The zone index of the highest zone to return
1702  * @nodemask: Nodemask allowed by the allocator
1703  *
1704  * This iterator iterates though all zones at or below a given zone index and
1705  * within a given nodemask
1706  */
1707 #define for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, nodemask) \
1708 	for (z = first_zones_zonelist(zlist, highidx, nodemask), zone = zonelist_zone(z);	\
1709 		zone;							\
1710 		z = next_zones_zonelist(++z, highidx, nodemask),	\
1711 			zone = zonelist_zone(z))
1712 
1713 #define for_next_zone_zonelist_nodemask(zone, z, highidx, nodemask) \
1714 	for (zone = zonelist_zone(z);	\
1715 		zone;							\
1716 		z = next_zones_zonelist(++z, highidx, nodemask),	\
1717 			zone = zonelist_zone(z))
1718 
1719 
1720 /**
1721  * for_each_zone_zonelist - helper macro to iterate over valid zones in a zonelist at or below a given zone index
1722  * @zone: The current zone in the iterator
1723  * @z: The current pointer within zonelist->zones being iterated
1724  * @zlist: The zonelist being iterated
1725  * @highidx: The zone index of the highest zone to return
1726  *
1727  * This iterator iterates though all zones at or below a given zone index.
1728  */
1729 #define for_each_zone_zonelist(zone, z, zlist, highidx) \
1730 	for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, NULL)
1731 
1732 /* Whether the 'nodes' are all movable nodes */
1733 static inline bool movable_only_nodes(nodemask_t *nodes)
1734 {
1735 	struct zonelist *zonelist;
1736 	struct zoneref *z;
1737 	int nid;
1738 
1739 	if (nodes_empty(*nodes))
1740 		return false;
1741 
1742 	/*
1743 	 * We can chose arbitrary node from the nodemask to get a
1744 	 * zonelist as they are interlinked. We just need to find
1745 	 * at least one zone that can satisfy kernel allocations.
1746 	 */
1747 	nid = first_node(*nodes);
1748 	zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
1749 	z = first_zones_zonelist(zonelist, ZONE_NORMAL,	nodes);
1750 	return (!zonelist_zone(z)) ? true : false;
1751 }
1752 
1753 
1754 #ifdef CONFIG_SPARSEMEM
1755 #include <asm/sparsemem.h>
1756 #endif
1757 
1758 #ifdef CONFIG_FLATMEM
1759 #define pfn_to_nid(pfn)		(0)
1760 #endif
1761 
1762 #ifdef CONFIG_SPARSEMEM
1763 
1764 /*
1765  * PA_SECTION_SHIFT		physical address to/from section number
1766  * PFN_SECTION_SHIFT		pfn to/from section number
1767  */
1768 #define PA_SECTION_SHIFT	(SECTION_SIZE_BITS)
1769 #define PFN_SECTION_SHIFT	(SECTION_SIZE_BITS - PAGE_SHIFT)
1770 
1771 #define NR_MEM_SECTIONS		(1UL << SECTIONS_SHIFT)
1772 
1773 #define PAGES_PER_SECTION       (1UL << PFN_SECTION_SHIFT)
1774 #define PAGE_SECTION_MASK	(~(PAGES_PER_SECTION-1))
1775 
1776 #define SECTION_BLOCKFLAGS_BITS \
1777 	((1UL << (PFN_SECTION_SHIFT - pageblock_order)) * NR_PAGEBLOCK_BITS)
1778 
1779 #if (MAX_PAGE_ORDER + PAGE_SHIFT) > SECTION_SIZE_BITS
1780 #error Allocator MAX_PAGE_ORDER exceeds SECTION_SIZE
1781 #endif
1782 
1783 static inline unsigned long pfn_to_section_nr(unsigned long pfn)
1784 {
1785 	return pfn >> PFN_SECTION_SHIFT;
1786 }
1787 static inline unsigned long section_nr_to_pfn(unsigned long sec)
1788 {
1789 	return sec << PFN_SECTION_SHIFT;
1790 }
1791 
1792 #define SECTION_ALIGN_UP(pfn)	(((pfn) + PAGES_PER_SECTION - 1) & PAGE_SECTION_MASK)
1793 #define SECTION_ALIGN_DOWN(pfn)	((pfn) & PAGE_SECTION_MASK)
1794 
1795 #define SUBSECTION_SHIFT 21
1796 #define SUBSECTION_SIZE (1UL << SUBSECTION_SHIFT)
1797 
1798 #define PFN_SUBSECTION_SHIFT (SUBSECTION_SHIFT - PAGE_SHIFT)
1799 #define PAGES_PER_SUBSECTION (1UL << PFN_SUBSECTION_SHIFT)
1800 #define PAGE_SUBSECTION_MASK (~(PAGES_PER_SUBSECTION-1))
1801 
1802 #if SUBSECTION_SHIFT > SECTION_SIZE_BITS
1803 #error Subsection size exceeds section size
1804 #else
1805 #define SUBSECTIONS_PER_SECTION (1UL << (SECTION_SIZE_BITS - SUBSECTION_SHIFT))
1806 #endif
1807 
1808 #define SUBSECTION_ALIGN_UP(pfn) ALIGN((pfn), PAGES_PER_SUBSECTION)
1809 #define SUBSECTION_ALIGN_DOWN(pfn) ((pfn) & PAGE_SUBSECTION_MASK)
1810 
1811 struct mem_section_usage {
1812 	struct rcu_head rcu;
1813 #ifdef CONFIG_SPARSEMEM_VMEMMAP
1814 	DECLARE_BITMAP(subsection_map, SUBSECTIONS_PER_SECTION);
1815 #endif
1816 	/* See declaration of similar field in struct zone */
1817 	unsigned long pageblock_flags[0];
1818 };
1819 
1820 void subsection_map_init(unsigned long pfn, unsigned long nr_pages);
1821 
1822 struct page;
1823 struct page_ext;
1824 struct mem_section {
1825 	/*
1826 	 * This is, logically, a pointer to an array of struct
1827 	 * pages.  However, it is stored with some other magic.
1828 	 * (see sparse.c::sparse_init_one_section())
1829 	 *
1830 	 * Additionally during early boot we encode node id of
1831 	 * the location of the section here to guide allocation.
1832 	 * (see sparse.c::memory_present())
1833 	 *
1834 	 * Making it a UL at least makes someone do a cast
1835 	 * before using it wrong.
1836 	 */
1837 	unsigned long section_mem_map;
1838 
1839 	struct mem_section_usage *usage;
1840 #ifdef CONFIG_PAGE_EXTENSION
1841 	/*
1842 	 * If SPARSEMEM, pgdat doesn't have page_ext pointer. We use
1843 	 * section. (see page_ext.h about this.)
1844 	 */
1845 	struct page_ext *page_ext;
1846 	unsigned long pad;
1847 #endif
1848 	/*
1849 	 * WARNING: mem_section must be a power-of-2 in size for the
1850 	 * calculation and use of SECTION_ROOT_MASK to make sense.
1851 	 */
1852 };
1853 
1854 #ifdef CONFIG_SPARSEMEM_EXTREME
1855 #define SECTIONS_PER_ROOT       (PAGE_SIZE / sizeof (struct mem_section))
1856 #else
1857 #define SECTIONS_PER_ROOT	1
1858 #endif
1859 
1860 #define SECTION_NR_TO_ROOT(sec)	((sec) / SECTIONS_PER_ROOT)
1861 #define NR_SECTION_ROOTS	DIV_ROUND_UP(NR_MEM_SECTIONS, SECTIONS_PER_ROOT)
1862 #define SECTION_ROOT_MASK	(SECTIONS_PER_ROOT - 1)
1863 
1864 #ifdef CONFIG_SPARSEMEM_EXTREME
1865 extern struct mem_section **mem_section;
1866 #else
1867 extern struct mem_section mem_section[NR_SECTION_ROOTS][SECTIONS_PER_ROOT];
1868 #endif
1869 
1870 static inline unsigned long *section_to_usemap(struct mem_section *ms)
1871 {
1872 	return ms->usage->pageblock_flags;
1873 }
1874 
1875 static inline struct mem_section *__nr_to_section(unsigned long nr)
1876 {
1877 	unsigned long root = SECTION_NR_TO_ROOT(nr);
1878 
1879 	if (unlikely(root >= NR_SECTION_ROOTS))
1880 		return NULL;
1881 
1882 #ifdef CONFIG_SPARSEMEM_EXTREME
1883 	if (!mem_section || !mem_section[root])
1884 		return NULL;
1885 #endif
1886 	return &mem_section[root][nr & SECTION_ROOT_MASK];
1887 }
1888 extern size_t mem_section_usage_size(void);
1889 
1890 /*
1891  * We use the lower bits of the mem_map pointer to store
1892  * a little bit of information.  The pointer is calculated
1893  * as mem_map - section_nr_to_pfn(pnum).  The result is
1894  * aligned to the minimum alignment of the two values:
1895  *   1. All mem_map arrays are page-aligned.
1896  *   2. section_nr_to_pfn() always clears PFN_SECTION_SHIFT
1897  *      lowest bits.  PFN_SECTION_SHIFT is arch-specific
1898  *      (equal SECTION_SIZE_BITS - PAGE_SHIFT), and the
1899  *      worst combination is powerpc with 256k pages,
1900  *      which results in PFN_SECTION_SHIFT equal 6.
1901  * To sum it up, at least 6 bits are available on all architectures.
1902  * However, we can exceed 6 bits on some other architectures except
1903  * powerpc (e.g. 15 bits are available on x86_64, 13 bits are available
1904  * with the worst case of 64K pages on arm64) if we make sure the
1905  * exceeded bit is not applicable to powerpc.
1906  */
1907 enum {
1908 	SECTION_MARKED_PRESENT_BIT,
1909 	SECTION_HAS_MEM_MAP_BIT,
1910 	SECTION_IS_ONLINE_BIT,
1911 	SECTION_IS_EARLY_BIT,
1912 #ifdef CONFIG_ZONE_DEVICE
1913 	SECTION_TAINT_ZONE_DEVICE_BIT,
1914 #endif
1915 	SECTION_MAP_LAST_BIT,
1916 };
1917 
1918 #define SECTION_MARKED_PRESENT		BIT(SECTION_MARKED_PRESENT_BIT)
1919 #define SECTION_HAS_MEM_MAP		BIT(SECTION_HAS_MEM_MAP_BIT)
1920 #define SECTION_IS_ONLINE		BIT(SECTION_IS_ONLINE_BIT)
1921 #define SECTION_IS_EARLY		BIT(SECTION_IS_EARLY_BIT)
1922 #ifdef CONFIG_ZONE_DEVICE
1923 #define SECTION_TAINT_ZONE_DEVICE	BIT(SECTION_TAINT_ZONE_DEVICE_BIT)
1924 #endif
1925 #define SECTION_MAP_MASK		(~(BIT(SECTION_MAP_LAST_BIT) - 1))
1926 #define SECTION_NID_SHIFT		SECTION_MAP_LAST_BIT
1927 
1928 static inline struct page *__section_mem_map_addr(struct mem_section *section)
1929 {
1930 	unsigned long map = section->section_mem_map;
1931 	map &= SECTION_MAP_MASK;
1932 	return (struct page *)map;
1933 }
1934 
1935 static inline int present_section(struct mem_section *section)
1936 {
1937 	return (section && (section->section_mem_map & SECTION_MARKED_PRESENT));
1938 }
1939 
1940 static inline int present_section_nr(unsigned long nr)
1941 {
1942 	return present_section(__nr_to_section(nr));
1943 }
1944 
1945 static inline int valid_section(struct mem_section *section)
1946 {
1947 	return (section && (section->section_mem_map & SECTION_HAS_MEM_MAP));
1948 }
1949 
1950 static inline int early_section(struct mem_section *section)
1951 {
1952 	return (section && (section->section_mem_map & SECTION_IS_EARLY));
1953 }
1954 
1955 static inline int valid_section_nr(unsigned long nr)
1956 {
1957 	return valid_section(__nr_to_section(nr));
1958 }
1959 
1960 static inline int online_section(struct mem_section *section)
1961 {
1962 	return (section && (section->section_mem_map & SECTION_IS_ONLINE));
1963 }
1964 
1965 #ifdef CONFIG_ZONE_DEVICE
1966 static inline int online_device_section(struct mem_section *section)
1967 {
1968 	unsigned long flags = SECTION_IS_ONLINE | SECTION_TAINT_ZONE_DEVICE;
1969 
1970 	return section && ((section->section_mem_map & flags) == flags);
1971 }
1972 #else
1973 static inline int online_device_section(struct mem_section *section)
1974 {
1975 	return 0;
1976 }
1977 #endif
1978 
1979 static inline int online_section_nr(unsigned long nr)
1980 {
1981 	return online_section(__nr_to_section(nr));
1982 }
1983 
1984 #ifdef CONFIG_MEMORY_HOTPLUG
1985 void online_mem_sections(unsigned long start_pfn, unsigned long end_pfn);
1986 void offline_mem_sections(unsigned long start_pfn, unsigned long end_pfn);
1987 #endif
1988 
1989 static inline struct mem_section *__pfn_to_section(unsigned long pfn)
1990 {
1991 	return __nr_to_section(pfn_to_section_nr(pfn));
1992 }
1993 
1994 extern unsigned long __highest_present_section_nr;
1995 
1996 static inline int subsection_map_index(unsigned long pfn)
1997 {
1998 	return (pfn & ~(PAGE_SECTION_MASK)) / PAGES_PER_SUBSECTION;
1999 }
2000 
2001 #ifdef CONFIG_SPARSEMEM_VMEMMAP
2002 static inline int pfn_section_valid(struct mem_section *ms, unsigned long pfn)
2003 {
2004 	int idx = subsection_map_index(pfn);
2005 	struct mem_section_usage *usage = READ_ONCE(ms->usage);
2006 
2007 	return usage ? test_bit(idx, usage->subsection_map) : 0;
2008 }
2009 #else
2010 static inline int pfn_section_valid(struct mem_section *ms, unsigned long pfn)
2011 {
2012 	return 1;
2013 }
2014 #endif
2015 
2016 #ifndef CONFIG_HAVE_ARCH_PFN_VALID
2017 /**
2018  * pfn_valid - check if there is a valid memory map entry for a PFN
2019  * @pfn: the page frame number to check
2020  *
2021  * Check if there is a valid memory map entry aka struct page for the @pfn.
2022  * Note, that availability of the memory map entry does not imply that
2023  * there is actual usable memory at that @pfn. The struct page may
2024  * represent a hole or an unusable page frame.
2025  *
2026  * Return: 1 for PFNs that have memory map entries and 0 otherwise
2027  */
2028 static inline int pfn_valid(unsigned long pfn)
2029 {
2030 	struct mem_section *ms;
2031 	int ret;
2032 
2033 	/*
2034 	 * Ensure the upper PAGE_SHIFT bits are clear in the
2035 	 * pfn. Else it might lead to false positives when
2036 	 * some of the upper bits are set, but the lower bits
2037 	 * match a valid pfn.
2038 	 */
2039 	if (PHYS_PFN(PFN_PHYS(pfn)) != pfn)
2040 		return 0;
2041 
2042 	if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS)
2043 		return 0;
2044 	ms = __pfn_to_section(pfn);
2045 	rcu_read_lock_sched();
2046 	if (!valid_section(ms)) {
2047 		rcu_read_unlock_sched();
2048 		return 0;
2049 	}
2050 	/*
2051 	 * Traditionally early sections always returned pfn_valid() for
2052 	 * the entire section-sized span.
2053 	 */
2054 	ret = early_section(ms) || pfn_section_valid(ms, pfn);
2055 	rcu_read_unlock_sched();
2056 
2057 	return ret;
2058 }
2059 #endif
2060 
2061 static inline int pfn_in_present_section(unsigned long pfn)
2062 {
2063 	if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS)
2064 		return 0;
2065 	return present_section(__pfn_to_section(pfn));
2066 }
2067 
2068 static inline unsigned long next_present_section_nr(unsigned long section_nr)
2069 {
2070 	while (++section_nr <= __highest_present_section_nr) {
2071 		if (present_section_nr(section_nr))
2072 			return section_nr;
2073 	}
2074 
2075 	return -1;
2076 }
2077 
2078 /*
2079  * These are _only_ used during initialisation, therefore they
2080  * can use __initdata ...  They could have names to indicate
2081  * this restriction.
2082  */
2083 #ifdef CONFIG_NUMA
2084 #define pfn_to_nid(pfn)							\
2085 ({									\
2086 	unsigned long __pfn_to_nid_pfn = (pfn);				\
2087 	page_to_nid(pfn_to_page(__pfn_to_nid_pfn));			\
2088 })
2089 #else
2090 #define pfn_to_nid(pfn)		(0)
2091 #endif
2092 
2093 void sparse_init(void);
2094 #else
2095 #define sparse_init()	do {} while (0)
2096 #define sparse_index_init(_sec, _nid)  do {} while (0)
2097 #define pfn_in_present_section pfn_valid
2098 #define subsection_map_init(_pfn, _nr_pages) do {} while (0)
2099 #endif /* CONFIG_SPARSEMEM */
2100 
2101 #endif /* !__GENERATING_BOUNDS.H */
2102 #endif /* !__ASSEMBLY__ */
2103 #endif /* _LINUX_MMZONE_H */
2104