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