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