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