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