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. One additional list
668 * for THP which will usually be GFP_MOVABLE. Even if it is another type,
669 * it should not contribute to serious fragmentation causing THP allocation
670 * failures.
671 */
672 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
673 #define NR_PCP_THP 1
674 #else
675 #define NR_PCP_THP 0
676 #endif
677 #define NR_LOWORDER_PCP_LISTS (MIGRATE_PCPTYPES * (PAGE_ALLOC_COSTLY_ORDER + 1))
678 #define NR_PCP_LISTS (NR_LOWORDER_PCP_LISTS + NR_PCP_THP)
679
680 #define min_wmark_pages(z) (z->_watermark[WMARK_MIN] + z->watermark_boost)
681 #define low_wmark_pages(z) (z->_watermark[WMARK_LOW] + z->watermark_boost)
682 #define high_wmark_pages(z) (z->_watermark[WMARK_HIGH] + z->watermark_boost)
683 #define wmark_pages(z, i) (z->_watermark[i] + z->watermark_boost)
684
685 struct per_cpu_pages {
686 spinlock_t lock; /* Protects lists field */
687 int count; /* number of pages in the list */
688 int high; /* high watermark, emptying needed */
689 int batch; /* chunk size for buddy add/remove */
690 short free_factor; /* batch scaling factor during free */
691 #ifdef CONFIG_NUMA
692 short expire; /* When 0, remote pagesets are drained */
693 #endif
694
695 /* Lists of pages, one per migrate type stored on the pcp-lists */
696 struct list_head lists[NR_PCP_LISTS];
697 } ____cacheline_aligned_in_smp;
698
699 struct per_cpu_zonestat {
700 #ifdef CONFIG_SMP
701 s8 vm_stat_diff[NR_VM_ZONE_STAT_ITEMS];
702 s8 stat_threshold;
703 #endif
704 #ifdef CONFIG_NUMA
705 /*
706 * Low priority inaccurate counters that are only folded
707 * on demand. Use a large type to avoid the overhead of
708 * folding during refresh_cpu_vm_stats.
709 */
710 unsigned long vm_numa_event[NR_VM_NUMA_EVENT_ITEMS];
711 #endif
712 };
713
714 struct per_cpu_nodestat {
715 s8 stat_threshold;
716 s8 vm_node_stat_diff[NR_VM_NODE_STAT_ITEMS];
717 };
718
719 #endif /* !__GENERATING_BOUNDS.H */
720
721 enum zone_type {
722 /*
723 * ZONE_DMA and ZONE_DMA32 are used when there are peripherals not able
724 * to DMA to all of the addressable memory (ZONE_NORMAL).
725 * On architectures where this area covers the whole 32 bit address
726 * space ZONE_DMA32 is used. ZONE_DMA is left for the ones with smaller
727 * DMA addressing constraints. This distinction is important as a 32bit
728 * DMA mask is assumed when ZONE_DMA32 is defined. Some 64-bit
729 * platforms may need both zones as they support peripherals with
730 * different DMA addressing limitations.
731 */
732 #ifdef CONFIG_ZONE_DMA
733 ZONE_DMA,
734 #endif
735 #ifdef CONFIG_ZONE_DMA32
736 ZONE_DMA32,
737 #endif
738 /*
739 * Normal addressable memory is in ZONE_NORMAL. DMA operations can be
740 * performed on pages in ZONE_NORMAL if the DMA devices support
741 * transfers to all addressable memory.
742 */
743 ZONE_NORMAL,
744 #ifdef CONFIG_HIGHMEM
745 /*
746 * A memory area that is only addressable by the kernel through
747 * mapping portions into its own address space. This is for example
748 * used by i386 to allow the kernel to address the memory beyond
749 * 900MB. The kernel will set up special mappings (page
750 * table entries on i386) for each page that the kernel needs to
751 * access.
752 */
753 ZONE_HIGHMEM,
754 #endif
755 /*
756 * ZONE_MOVABLE is similar to ZONE_NORMAL, except that it contains
757 * movable pages with few exceptional cases described below. Main use
758 * cases for ZONE_MOVABLE are to make memory offlining/unplug more
759 * likely to succeed, and to locally limit unmovable allocations - e.g.,
760 * to increase the number of THP/huge pages. Notable special cases are:
761 *
762 * 1. Pinned pages: (long-term) pinning of movable pages might
763 * essentially turn such pages unmovable. Therefore, we do not allow
764 * pinning long-term pages in ZONE_MOVABLE. When pages are pinned and
765 * faulted, they come from the right zone right away. However, it is
766 * still possible that address space already has pages in
767 * ZONE_MOVABLE at the time when pages are pinned (i.e. user has
768 * touches that memory before pinning). In such case we migrate them
769 * to a different zone. When migration fails - pinning fails.
770 * 2. memblock allocations: kernelcore/movablecore setups might create
771 * situations where ZONE_MOVABLE contains unmovable allocations
772 * after boot. Memory offlining and allocations fail early.
773 * 3. Memory holes: kernelcore/movablecore setups might create very rare
774 * situations where ZONE_MOVABLE contains memory holes after boot,
775 * for example, if we have sections that are only partially
776 * populated. Memory offlining and allocations fail early.
777 * 4. PG_hwpoison pages: while poisoned pages can be skipped during
778 * memory offlining, such pages cannot be allocated.
779 * 5. Unmovable PG_offline pages: in paravirtualized environments,
780 * hotplugged memory blocks might only partially be managed by the
781 * buddy (e.g., via XEN-balloon, Hyper-V balloon, virtio-mem). The
782 * parts not manged by the buddy are unmovable PG_offline pages. In
783 * some cases (virtio-mem), such pages can be skipped during
784 * memory offlining, however, cannot be moved/allocated. These
785 * techniques might use alloc_contig_range() to hide previously
786 * exposed pages from the buddy again (e.g., to implement some sort
787 * of memory unplug in virtio-mem).
788 * 6. ZERO_PAGE(0), kernelcore/movablecore setups might create
789 * situations where ZERO_PAGE(0) which is allocated differently
790 * on different platforms may end up in a movable zone. ZERO_PAGE(0)
791 * cannot be migrated.
792 * 7. Memory-hotplug: when using memmap_on_memory and onlining the
793 * memory to the MOVABLE zone, the vmemmap pages are also placed in
794 * such zone. Such pages cannot be really moved around as they are
795 * self-stored in the range, but they are treated as movable when
796 * the range they describe is about to be offlined.
797 *
798 * In general, no unmovable allocations that degrade memory offlining
799 * should end up in ZONE_MOVABLE. Allocators (like alloc_contig_range())
800 * have to expect that migrating pages in ZONE_MOVABLE can fail (even
801 * if has_unmovable_pages() states that there are no unmovable pages,
802 * there can be false negatives).
803 */
804 ZONE_MOVABLE,
805 #ifdef CONFIG_ZONE_DEVICE
806 ZONE_DEVICE,
807 #endif
808 __MAX_NR_ZONES
809
810 };
811
812 #ifndef __GENERATING_BOUNDS_H
813
814 #define ASYNC_AND_SYNC 2
815
816 struct zone {
817 /* Read-mostly fields */
818
819 /* zone watermarks, access with *_wmark_pages(zone) macros */
820 unsigned long _watermark[NR_WMARK];
821 unsigned long watermark_boost;
822
823 unsigned long nr_reserved_highatomic;
824
825 /*
826 * We don't know if the memory that we're going to allocate will be
827 * freeable or/and it will be released eventually, so to avoid totally
828 * wasting several GB of ram we must reserve some of the lower zone
829 * memory (otherwise we risk to run OOM on the lower zones despite
830 * there being tons of freeable ram on the higher zones). This array is
831 * recalculated at runtime if the sysctl_lowmem_reserve_ratio sysctl
832 * changes.
833 */
834 long lowmem_reserve[MAX_NR_ZONES];
835
836 #ifdef CONFIG_NUMA
837 int node;
838 #endif
839 struct pglist_data *zone_pgdat;
840 struct per_cpu_pages __percpu *per_cpu_pageset;
841 struct per_cpu_zonestat __percpu *per_cpu_zonestats;
842 /*
843 * the high and batch values are copied to individual pagesets for
844 * faster access
845 */
846 int pageset_high;
847 int pageset_batch;
848
849 #ifndef CONFIG_SPARSEMEM
850 /*
851 * Flags for a pageblock_nr_pages block. See pageblock-flags.h.
852 * In SPARSEMEM, this map is stored in struct mem_section
853 */
854 unsigned long *pageblock_flags;
855 #endif /* CONFIG_SPARSEMEM */
856
857 /* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */
858 unsigned long zone_start_pfn;
859
860 /*
861 * spanned_pages is the total pages spanned by the zone, including
862 * holes, which is calculated as:
863 * spanned_pages = zone_end_pfn - zone_start_pfn;
864 *
865 * present_pages is physical pages existing within the zone, which
866 * is calculated as:
867 * present_pages = spanned_pages - absent_pages(pages in holes);
868 *
869 * present_early_pages is present pages existing within the zone
870 * located on memory available since early boot, excluding hotplugged
871 * memory.
872 *
873 * managed_pages is present pages managed by the buddy system, which
874 * is calculated as (reserved_pages includes pages allocated by the
875 * bootmem allocator):
876 * managed_pages = present_pages - reserved_pages;
877 *
878 * cma pages is present pages that are assigned for CMA use
879 * (MIGRATE_CMA).
880 *
881 * So present_pages may be used by memory hotplug or memory power
882 * management logic to figure out unmanaged pages by checking
883 * (present_pages - managed_pages). And managed_pages should be used
884 * by page allocator and vm scanner to calculate all kinds of watermarks
885 * and thresholds.
886 *
887 * Locking rules:
888 *
889 * zone_start_pfn and spanned_pages are protected by span_seqlock.
890 * It is a seqlock because it has to be read outside of zone->lock,
891 * and it is done in the main allocator path. But, it is written
892 * quite infrequently.
893 *
894 * The span_seq lock is declared along with zone->lock because it is
895 * frequently read in proximity to zone->lock. It's good to
896 * give them a chance of being in the same cacheline.
897 *
898 * Write access to present_pages at runtime should be protected by
899 * mem_hotplug_begin/done(). Any reader who can't tolerant drift of
900 * present_pages should use get_online_mems() to get a stable value.
901 */
902 atomic_long_t managed_pages;
903 unsigned long spanned_pages;
904 unsigned long present_pages;
905 #if defined(CONFIG_MEMORY_HOTPLUG)
906 unsigned long present_early_pages;
907 #endif
908 #ifdef CONFIG_CMA
909 unsigned long cma_pages;
910 #endif
911
912 const char *name;
913
914 #ifdef CONFIG_MEMORY_ISOLATION
915 /*
916 * Number of isolated pageblock. It is used to solve incorrect
917 * freepage counting problem due to racy retrieving migratetype
918 * of pageblock. Protected by zone->lock.
919 */
920 unsigned long nr_isolate_pageblock;
921 #endif
922
923 #ifdef CONFIG_MEMORY_HOTPLUG
924 /* see spanned/present_pages for more description */
925 seqlock_t span_seqlock;
926 #endif
927
928 int initialized;
929
930 /* Write-intensive fields used from the page allocator */
931 CACHELINE_PADDING(_pad1_);
932
933 /* free areas of different sizes */
934 struct free_area free_area[NR_PAGE_ORDERS];
935
936 #ifdef CONFIG_UNACCEPTED_MEMORY
937 /* Pages to be accepted. All pages on the list are MAX_ORDER */
938 struct list_head unaccepted_pages;
939 #endif
940
941 /* zone flags, see below */
942 unsigned long flags;
943
944 /* Primarily protects free_area */
945 spinlock_t lock;
946
947 /* Write-intensive fields used by compaction and vmstats. */
948 CACHELINE_PADDING(_pad2_);
949
950 /*
951 * When free pages are below this point, additional steps are taken
952 * when reading the number of free pages to avoid per-cpu counter
953 * drift allowing watermarks to be breached
954 */
955 unsigned long percpu_drift_mark;
956
957 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
958 /* pfn where compaction free scanner should start */
959 unsigned long compact_cached_free_pfn;
960 /* pfn where compaction migration scanner should start */
961 unsigned long compact_cached_migrate_pfn[ASYNC_AND_SYNC];
962 unsigned long compact_init_migrate_pfn;
963 unsigned long compact_init_free_pfn;
964 #endif
965
966 #ifdef CONFIG_COMPACTION
967 /*
968 * On compaction failure, 1<<compact_defer_shift compactions
969 * are skipped before trying again. The number attempted since
970 * last failure is tracked with compact_considered.
971 * compact_order_failed is the minimum compaction failed order.
972 */
973 unsigned int compact_considered;
974 unsigned int compact_defer_shift;
975 int compact_order_failed;
976 #endif
977
978 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
979 /* Set to true when the PG_migrate_skip bits should be cleared */
980 bool compact_blockskip_flush;
981 #endif
982
983 bool contiguous;
984
985 CACHELINE_PADDING(_pad3_);
986 /* Zone statistics */
987 atomic_long_t vm_stat[NR_VM_ZONE_STAT_ITEMS];
988 atomic_long_t vm_numa_event[NR_VM_NUMA_EVENT_ITEMS];
989 } ____cacheline_internodealigned_in_smp;
990
991 enum pgdat_flags {
992 PGDAT_DIRTY, /* reclaim scanning has recently found
993 * many dirty file pages at the tail
994 * of the LRU.
995 */
996 PGDAT_WRITEBACK, /* reclaim scanning has recently found
997 * many pages under writeback
998 */
999 PGDAT_RECLAIM_LOCKED, /* prevents concurrent reclaim */
1000 };
1001
1002 enum zone_flags {
1003 ZONE_BOOSTED_WATERMARK, /* zone recently boosted watermarks.
1004 * Cleared when kswapd is woken.
1005 */
1006 ZONE_RECLAIM_ACTIVE, /* kswapd may be scanning the zone. */
1007 };
1008
zone_managed_pages(struct zone * zone)1009 static inline unsigned long zone_managed_pages(struct zone *zone)
1010 {
1011 return (unsigned long)atomic_long_read(&zone->managed_pages);
1012 }
1013
zone_cma_pages(struct zone * zone)1014 static inline unsigned long zone_cma_pages(struct zone *zone)
1015 {
1016 #ifdef CONFIG_CMA
1017 return zone->cma_pages;
1018 #else
1019 return 0;
1020 #endif
1021 }
1022
zone_end_pfn(const struct zone * zone)1023 static inline unsigned long zone_end_pfn(const struct zone *zone)
1024 {
1025 return zone->zone_start_pfn + zone->spanned_pages;
1026 }
1027
zone_spans_pfn(const struct zone * zone,unsigned long pfn)1028 static inline bool zone_spans_pfn(const struct zone *zone, unsigned long pfn)
1029 {
1030 return zone->zone_start_pfn <= pfn && pfn < zone_end_pfn(zone);
1031 }
1032
zone_is_initialized(struct zone * zone)1033 static inline bool zone_is_initialized(struct zone *zone)
1034 {
1035 return zone->initialized;
1036 }
1037
zone_is_empty(struct zone * zone)1038 static inline bool zone_is_empty(struct zone *zone)
1039 {
1040 return zone->spanned_pages == 0;
1041 }
1042
1043 #ifndef BUILD_VDSO32_64
1044 /*
1045 * The zone field is never updated after free_area_init_core()
1046 * sets it, so none of the operations on it need to be atomic.
1047 */
1048
1049 /* Page flags: | [SECTION] | [NODE] | ZONE | [LAST_CPUPID] | ... | FLAGS | */
1050 #define SECTIONS_PGOFF ((sizeof(unsigned long)*8) - SECTIONS_WIDTH)
1051 #define NODES_PGOFF (SECTIONS_PGOFF - NODES_WIDTH)
1052 #define ZONES_PGOFF (NODES_PGOFF - ZONES_WIDTH)
1053 #define LAST_CPUPID_PGOFF (ZONES_PGOFF - LAST_CPUPID_WIDTH)
1054 #define KASAN_TAG_PGOFF (LAST_CPUPID_PGOFF - KASAN_TAG_WIDTH)
1055 #define LRU_GEN_PGOFF (KASAN_TAG_PGOFF - LRU_GEN_WIDTH)
1056 #define LRU_REFS_PGOFF (LRU_GEN_PGOFF - LRU_REFS_WIDTH)
1057
1058 /*
1059 * Define the bit shifts to access each section. For non-existent
1060 * sections we define the shift as 0; that plus a 0 mask ensures
1061 * the compiler will optimise away reference to them.
1062 */
1063 #define SECTIONS_PGSHIFT (SECTIONS_PGOFF * (SECTIONS_WIDTH != 0))
1064 #define NODES_PGSHIFT (NODES_PGOFF * (NODES_WIDTH != 0))
1065 #define ZONES_PGSHIFT (ZONES_PGOFF * (ZONES_WIDTH != 0))
1066 #define LAST_CPUPID_PGSHIFT (LAST_CPUPID_PGOFF * (LAST_CPUPID_WIDTH != 0))
1067 #define KASAN_TAG_PGSHIFT (KASAN_TAG_PGOFF * (KASAN_TAG_WIDTH != 0))
1068
1069 /* NODE:ZONE or SECTION:ZONE is used to ID a zone for the buddy allocator */
1070 #ifdef NODE_NOT_IN_PAGE_FLAGS
1071 #define ZONEID_SHIFT (SECTIONS_SHIFT + ZONES_SHIFT)
1072 #define ZONEID_PGOFF ((SECTIONS_PGOFF < ZONES_PGOFF) ? \
1073 SECTIONS_PGOFF : ZONES_PGOFF)
1074 #else
1075 #define ZONEID_SHIFT (NODES_SHIFT + ZONES_SHIFT)
1076 #define ZONEID_PGOFF ((NODES_PGOFF < ZONES_PGOFF) ? \
1077 NODES_PGOFF : ZONES_PGOFF)
1078 #endif
1079
1080 #define ZONEID_PGSHIFT (ZONEID_PGOFF * (ZONEID_SHIFT != 0))
1081
1082 #define ZONES_MASK ((1UL << ZONES_WIDTH) - 1)
1083 #define NODES_MASK ((1UL << NODES_WIDTH) - 1)
1084 #define SECTIONS_MASK ((1UL << SECTIONS_WIDTH) - 1)
1085 #define LAST_CPUPID_MASK ((1UL << LAST_CPUPID_SHIFT) - 1)
1086 #define KASAN_TAG_MASK ((1UL << KASAN_TAG_WIDTH) - 1)
1087 #define ZONEID_MASK ((1UL << ZONEID_SHIFT) - 1)
1088
page_zonenum(const struct page * page)1089 static inline enum zone_type page_zonenum(const struct page *page)
1090 {
1091 ASSERT_EXCLUSIVE_BITS(page->flags, ZONES_MASK << ZONES_PGSHIFT);
1092 return (page->flags >> ZONES_PGSHIFT) & ZONES_MASK;
1093 }
1094
folio_zonenum(const struct folio * folio)1095 static inline enum zone_type folio_zonenum(const struct folio *folio)
1096 {
1097 return page_zonenum(&folio->page);
1098 }
1099
1100 #ifdef CONFIG_ZONE_DEVICE
is_zone_device_page(const struct page * page)1101 static inline bool is_zone_device_page(const struct page *page)
1102 {
1103 return page_zonenum(page) == ZONE_DEVICE;
1104 }
1105
1106 /*
1107 * Consecutive zone device pages should not be merged into the same sgl
1108 * or bvec segment with other types of pages or if they belong to different
1109 * pgmaps. Otherwise getting the pgmap of a given segment is not possible
1110 * without scanning the entire segment. This helper returns true either if
1111 * both pages are not zone device pages or both pages are zone device pages
1112 * with the same pgmap.
1113 */
zone_device_pages_have_same_pgmap(const struct page * a,const struct page * b)1114 static inline bool zone_device_pages_have_same_pgmap(const struct page *a,
1115 const struct page *b)
1116 {
1117 if (is_zone_device_page(a) != is_zone_device_page(b))
1118 return false;
1119 if (!is_zone_device_page(a))
1120 return true;
1121 return a->pgmap == b->pgmap;
1122 }
1123
1124 extern void memmap_init_zone_device(struct zone *, unsigned long,
1125 unsigned long, struct dev_pagemap *);
1126 #else
is_zone_device_page(const struct page * page)1127 static inline bool is_zone_device_page(const struct page *page)
1128 {
1129 return false;
1130 }
zone_device_pages_have_same_pgmap(const struct page * a,const struct page * b)1131 static inline bool zone_device_pages_have_same_pgmap(const struct page *a,
1132 const struct page *b)
1133 {
1134 return true;
1135 }
1136 #endif
1137
folio_is_zone_device(const struct folio * folio)1138 static inline bool folio_is_zone_device(const struct folio *folio)
1139 {
1140 return is_zone_device_page(&folio->page);
1141 }
1142
is_zone_movable_page(const struct page * page)1143 static inline bool is_zone_movable_page(const struct page *page)
1144 {
1145 return page_zonenum(page) == ZONE_MOVABLE;
1146 }
1147
folio_is_zone_movable(const struct folio * folio)1148 static inline bool folio_is_zone_movable(const struct folio *folio)
1149 {
1150 return folio_zonenum(folio) == ZONE_MOVABLE;
1151 }
1152 #endif
1153
1154 /*
1155 * Return true if [start_pfn, start_pfn + nr_pages) range has a non-empty
1156 * intersection with the given zone
1157 */
zone_intersects(struct zone * zone,unsigned long start_pfn,unsigned long nr_pages)1158 static inline bool zone_intersects(struct zone *zone,
1159 unsigned long start_pfn, unsigned long nr_pages)
1160 {
1161 if (zone_is_empty(zone))
1162 return false;
1163 if (start_pfn >= zone_end_pfn(zone) ||
1164 start_pfn + nr_pages <= zone->zone_start_pfn)
1165 return false;
1166
1167 return true;
1168 }
1169
1170 /*
1171 * The "priority" of VM scanning is how much of the queues we will scan in one
1172 * go. A value of 12 for DEF_PRIORITY implies that we will scan 1/4096th of the
1173 * queues ("queue_length >> 12") during an aging round.
1174 */
1175 #define DEF_PRIORITY 12
1176
1177 /* Maximum number of zones on a zonelist */
1178 #define MAX_ZONES_PER_ZONELIST (MAX_NUMNODES * MAX_NR_ZONES)
1179
1180 enum {
1181 ZONELIST_FALLBACK, /* zonelist with fallback */
1182 #ifdef CONFIG_NUMA
1183 /*
1184 * The NUMA zonelists are doubled because we need zonelists that
1185 * restrict the allocations to a single node for __GFP_THISNODE.
1186 */
1187 ZONELIST_NOFALLBACK, /* zonelist without fallback (__GFP_THISNODE) */
1188 #endif
1189 MAX_ZONELISTS
1190 };
1191
1192 /*
1193 * This struct contains information about a zone in a zonelist. It is stored
1194 * here to avoid dereferences into large structures and lookups of tables
1195 */
1196 struct zoneref {
1197 struct zone *zone; /* Pointer to actual zone */
1198 int zone_idx; /* zone_idx(zoneref->zone) */
1199 };
1200
1201 /*
1202 * One allocation request operates on a zonelist. A zonelist
1203 * is a list of zones, the first one is the 'goal' of the
1204 * allocation, the other zones are fallback zones, in decreasing
1205 * priority.
1206 *
1207 * To speed the reading of the zonelist, the zonerefs contain the zone index
1208 * of the entry being read. Helper functions to access information given
1209 * a struct zoneref are
1210 *
1211 * zonelist_zone() - Return the struct zone * for an entry in _zonerefs
1212 * zonelist_zone_idx() - Return the index of the zone for an entry
1213 * zonelist_node_idx() - Return the index of the node for an entry
1214 */
1215 struct zonelist {
1216 struct zoneref _zonerefs[MAX_ZONES_PER_ZONELIST + 1];
1217 };
1218
1219 /*
1220 * The array of struct pages for flatmem.
1221 * It must be declared for SPARSEMEM as well because there are configurations
1222 * that rely on that.
1223 */
1224 extern struct page *mem_map;
1225
1226 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1227 struct deferred_split {
1228 spinlock_t split_queue_lock;
1229 struct list_head split_queue;
1230 unsigned long split_queue_len;
1231 };
1232 #endif
1233
1234 #ifdef CONFIG_MEMORY_FAILURE
1235 /*
1236 * Per NUMA node memory failure handling statistics.
1237 */
1238 struct memory_failure_stats {
1239 /*
1240 * Number of raw pages poisoned.
1241 * Cases not accounted: memory outside kernel control, offline page,
1242 * arch-specific memory_failure (SGX), hwpoison_filter() filtered
1243 * error events, and unpoison actions from hwpoison_unpoison.
1244 */
1245 unsigned long total;
1246 /*
1247 * Recovery results of poisoned raw pages handled by memory_failure,
1248 * in sync with mf_result.
1249 * total = ignored + failed + delayed + recovered.
1250 * total * PAGE_SIZE * #nodes = /proc/meminfo/HardwareCorrupted.
1251 */
1252 unsigned long ignored;
1253 unsigned long failed;
1254 unsigned long delayed;
1255 unsigned long recovered;
1256 };
1257 #endif
1258
1259 /*
1260 * On NUMA machines, each NUMA node would have a pg_data_t to describe
1261 * it's memory layout. On UMA machines there is a single pglist_data which
1262 * describes the whole memory.
1263 *
1264 * Memory statistics and page replacement data structures are maintained on a
1265 * per-zone basis.
1266 */
1267 typedef struct pglist_data {
1268 /*
1269 * node_zones contains just the zones for THIS node. Not all of the
1270 * zones may be populated, but it is the full list. It is referenced by
1271 * this node's node_zonelists as well as other node's node_zonelists.
1272 */
1273 struct zone node_zones[MAX_NR_ZONES];
1274
1275 /*
1276 * node_zonelists contains references to all zones in all nodes.
1277 * Generally the first zones will be references to this node's
1278 * node_zones.
1279 */
1280 struct zonelist node_zonelists[MAX_ZONELISTS];
1281
1282 int nr_zones; /* number of populated zones in this node */
1283 #ifdef CONFIG_FLATMEM /* means !SPARSEMEM */
1284 struct page *node_mem_map;
1285 #ifdef CONFIG_PAGE_EXTENSION
1286 struct page_ext *node_page_ext;
1287 #endif
1288 #endif
1289 #if defined(CONFIG_MEMORY_HOTPLUG) || defined(CONFIG_DEFERRED_STRUCT_PAGE_INIT)
1290 /*
1291 * Must be held any time you expect node_start_pfn,
1292 * node_present_pages, node_spanned_pages or nr_zones to stay constant.
1293 * Also synchronizes pgdat->first_deferred_pfn during deferred page
1294 * init.
1295 *
1296 * pgdat_resize_lock() and pgdat_resize_unlock() are provided to
1297 * manipulate node_size_lock without checking for CONFIG_MEMORY_HOTPLUG
1298 * or CONFIG_DEFERRED_STRUCT_PAGE_INIT.
1299 *
1300 * Nests above zone->lock and zone->span_seqlock
1301 */
1302 spinlock_t node_size_lock;
1303 #endif
1304 unsigned long node_start_pfn;
1305 unsigned long node_present_pages; /* total number of physical pages */
1306 unsigned long node_spanned_pages; /* total size of physical page
1307 range, including holes */
1308 int node_id;
1309 wait_queue_head_t kswapd_wait;
1310 wait_queue_head_t pfmemalloc_wait;
1311
1312 /* workqueues for throttling reclaim for different reasons. */
1313 wait_queue_head_t reclaim_wait[NR_VMSCAN_THROTTLE];
1314
1315 atomic_t nr_writeback_throttled;/* nr of writeback-throttled tasks */
1316 unsigned long nr_reclaim_start; /* nr pages written while throttled
1317 * when throttling started. */
1318 #ifdef CONFIG_MEMORY_HOTPLUG
1319 struct mutex kswapd_lock;
1320 #endif
1321 struct task_struct *kswapd; /* Protected by kswapd_lock */
1322 int kswapd_order;
1323 enum zone_type kswapd_highest_zoneidx;
1324
1325 int kswapd_failures; /* Number of 'reclaimed == 0' runs */
1326
1327 #ifdef CONFIG_COMPACTION
1328 int kcompactd_max_order;
1329 enum zone_type kcompactd_highest_zoneidx;
1330 wait_queue_head_t kcompactd_wait;
1331 struct task_struct *kcompactd;
1332 bool proactive_compact_trigger;
1333 #endif
1334 /*
1335 * This is a per-node reserve of pages that are not available
1336 * to userspace allocations.
1337 */
1338 unsigned long totalreserve_pages;
1339
1340 #ifdef CONFIG_NUMA
1341 /*
1342 * node reclaim becomes active if more unmapped pages exist.
1343 */
1344 unsigned long min_unmapped_pages;
1345 unsigned long min_slab_pages;
1346 #endif /* CONFIG_NUMA */
1347
1348 /* Write-intensive fields used by page reclaim */
1349 CACHELINE_PADDING(_pad1_);
1350
1351 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1352 /*
1353 * If memory initialisation on large machines is deferred then this
1354 * is the first PFN that needs to be initialised.
1355 */
1356 unsigned long first_deferred_pfn;
1357 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1358
1359 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1360 struct deferred_split deferred_split_queue;
1361 #endif
1362
1363 #ifdef CONFIG_NUMA_BALANCING
1364 /* start time in ms of current promote rate limit period */
1365 unsigned int nbp_rl_start;
1366 /* number of promote candidate pages at start time of current rate limit period */
1367 unsigned long nbp_rl_nr_cand;
1368 /* promote threshold in ms */
1369 unsigned int nbp_threshold;
1370 /* start time in ms of current promote threshold adjustment period */
1371 unsigned int nbp_th_start;
1372 /*
1373 * number of promote candidate pages at start time of current promote
1374 * threshold adjustment period
1375 */
1376 unsigned long nbp_th_nr_cand;
1377 #endif
1378 /* Fields commonly accessed by the page reclaim scanner */
1379
1380 /*
1381 * NOTE: THIS IS UNUSED IF MEMCG IS ENABLED.
1382 *
1383 * Use mem_cgroup_lruvec() to look up lruvecs.
1384 */
1385 struct lruvec __lruvec;
1386
1387 unsigned long flags;
1388
1389 #ifdef CONFIG_LRU_GEN
1390 /* kswap mm walk data */
1391 struct lru_gen_mm_walk mm_walk;
1392 /* lru_gen_folio list */
1393 struct lru_gen_memcg memcg_lru;
1394 #endif
1395
1396 CACHELINE_PADDING(_pad2_);
1397
1398 /* Per-node vmstats */
1399 struct per_cpu_nodestat __percpu *per_cpu_nodestats;
1400 atomic_long_t vm_stat[NR_VM_NODE_STAT_ITEMS];
1401 #ifdef CONFIG_NUMA
1402 struct memory_tier __rcu *memtier;
1403 #endif
1404 #ifdef CONFIG_MEMORY_FAILURE
1405 struct memory_failure_stats mf_stats;
1406 #endif
1407 } pg_data_t;
1408
1409 #define node_present_pages(nid) (NODE_DATA(nid)->node_present_pages)
1410 #define node_spanned_pages(nid) (NODE_DATA(nid)->node_spanned_pages)
1411
1412 #define node_start_pfn(nid) (NODE_DATA(nid)->node_start_pfn)
1413 #define node_end_pfn(nid) pgdat_end_pfn(NODE_DATA(nid))
1414
pgdat_end_pfn(pg_data_t * pgdat)1415 static inline unsigned long pgdat_end_pfn(pg_data_t *pgdat)
1416 {
1417 return pgdat->node_start_pfn + pgdat->node_spanned_pages;
1418 }
1419
1420 #include <linux/memory_hotplug.h>
1421
1422 void build_all_zonelists(pg_data_t *pgdat);
1423 void wakeup_kswapd(struct zone *zone, gfp_t gfp_mask, int order,
1424 enum zone_type highest_zoneidx);
1425 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
1426 int highest_zoneidx, unsigned int alloc_flags,
1427 long free_pages);
1428 bool zone_watermark_ok(struct zone *z, unsigned int order,
1429 unsigned long mark, int highest_zoneidx,
1430 unsigned int alloc_flags);
1431 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
1432 unsigned long mark, int highest_zoneidx);
1433 /*
1434 * Memory initialization context, use to differentiate memory added by
1435 * the platform statically or via memory hotplug interface.
1436 */
1437 enum meminit_context {
1438 MEMINIT_EARLY,
1439 MEMINIT_HOTPLUG,
1440 };
1441
1442 extern void init_currently_empty_zone(struct zone *zone, unsigned long start_pfn,
1443 unsigned long size);
1444
1445 extern void lruvec_init(struct lruvec *lruvec);
1446
lruvec_pgdat(struct lruvec * lruvec)1447 static inline struct pglist_data *lruvec_pgdat(struct lruvec *lruvec)
1448 {
1449 #ifdef CONFIG_MEMCG
1450 return lruvec->pgdat;
1451 #else
1452 return container_of(lruvec, struct pglist_data, __lruvec);
1453 #endif
1454 }
1455
1456 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
1457 int local_memory_node(int node_id);
1458 #else
local_memory_node(int node_id)1459 static inline int local_memory_node(int node_id) { return node_id; };
1460 #endif
1461
1462 /*
1463 * zone_idx() returns 0 for the ZONE_DMA zone, 1 for the ZONE_NORMAL zone, etc.
1464 */
1465 #define zone_idx(zone) ((zone) - (zone)->zone_pgdat->node_zones)
1466
1467 #ifdef CONFIG_ZONE_DEVICE
zone_is_zone_device(struct zone * zone)1468 static inline bool zone_is_zone_device(struct zone *zone)
1469 {
1470 return zone_idx(zone) == ZONE_DEVICE;
1471 }
1472 #else
zone_is_zone_device(struct zone * zone)1473 static inline bool zone_is_zone_device(struct zone *zone)
1474 {
1475 return false;
1476 }
1477 #endif
1478
1479 /*
1480 * Returns true if a zone has pages managed by the buddy allocator.
1481 * All the reclaim decisions have to use this function rather than
1482 * populated_zone(). If the whole zone is reserved then we can easily
1483 * end up with populated_zone() && !managed_zone().
1484 */
managed_zone(struct zone * zone)1485 static inline bool managed_zone(struct zone *zone)
1486 {
1487 return zone_managed_pages(zone);
1488 }
1489
1490 /* Returns true if a zone has memory */
populated_zone(struct zone * zone)1491 static inline bool populated_zone(struct zone *zone)
1492 {
1493 return zone->present_pages;
1494 }
1495
1496 #ifdef CONFIG_NUMA
zone_to_nid(struct zone * zone)1497 static inline int zone_to_nid(struct zone *zone)
1498 {
1499 return zone->node;
1500 }
1501
zone_set_nid(struct zone * zone,int nid)1502 static inline void zone_set_nid(struct zone *zone, int nid)
1503 {
1504 zone->node = nid;
1505 }
1506 #else
zone_to_nid(struct zone * zone)1507 static inline int zone_to_nid(struct zone *zone)
1508 {
1509 return 0;
1510 }
1511
zone_set_nid(struct zone * zone,int nid)1512 static inline void zone_set_nid(struct zone *zone, int nid) {}
1513 #endif
1514
1515 extern int movable_zone;
1516
is_highmem_idx(enum zone_type idx)1517 static inline int is_highmem_idx(enum zone_type idx)
1518 {
1519 #ifdef CONFIG_HIGHMEM
1520 return (idx == ZONE_HIGHMEM ||
1521 (idx == ZONE_MOVABLE && movable_zone == ZONE_HIGHMEM));
1522 #else
1523 return 0;
1524 #endif
1525 }
1526
1527 /**
1528 * is_highmem - helper function to quickly check if a struct zone is a
1529 * highmem zone or not. This is an attempt to keep references
1530 * to ZONE_{DMA/NORMAL/HIGHMEM/etc} in general code to a minimum.
1531 * @zone: pointer to struct zone variable
1532 * Return: 1 for a highmem zone, 0 otherwise
1533 */
is_highmem(struct zone * zone)1534 static inline int is_highmem(struct zone *zone)
1535 {
1536 return is_highmem_idx(zone_idx(zone));
1537 }
1538
1539 #ifdef CONFIG_ZONE_DMA
1540 bool has_managed_dma(void);
1541 #else
has_managed_dma(void)1542 static inline bool has_managed_dma(void)
1543 {
1544 return false;
1545 }
1546 #endif
1547
1548
1549 #ifndef CONFIG_NUMA
1550
1551 extern struct pglist_data contig_page_data;
NODE_DATA(int nid)1552 static inline struct pglist_data *NODE_DATA(int nid)
1553 {
1554 return &contig_page_data;
1555 }
1556
1557 #else /* CONFIG_NUMA */
1558
1559 #include <asm/mmzone.h>
1560
1561 #endif /* !CONFIG_NUMA */
1562
1563 extern struct pglist_data *first_online_pgdat(void);
1564 extern struct pglist_data *next_online_pgdat(struct pglist_data *pgdat);
1565 extern struct zone *next_zone(struct zone *zone);
1566
1567 /**
1568 * for_each_online_pgdat - helper macro to iterate over all online nodes
1569 * @pgdat: pointer to a pg_data_t variable
1570 */
1571 #define for_each_online_pgdat(pgdat) \
1572 for (pgdat = first_online_pgdat(); \
1573 pgdat; \
1574 pgdat = next_online_pgdat(pgdat))
1575 /**
1576 * for_each_zone - helper macro to iterate over all memory zones
1577 * @zone: pointer to struct zone variable
1578 *
1579 * The user only needs to declare the zone variable, for_each_zone
1580 * fills it in.
1581 */
1582 #define for_each_zone(zone) \
1583 for (zone = (first_online_pgdat())->node_zones; \
1584 zone; \
1585 zone = next_zone(zone))
1586
1587 #define for_each_populated_zone(zone) \
1588 for (zone = (first_online_pgdat())->node_zones; \
1589 zone; \
1590 zone = next_zone(zone)) \
1591 if (!populated_zone(zone)) \
1592 ; /* do nothing */ \
1593 else
1594
zonelist_zone(struct zoneref * zoneref)1595 static inline struct zone *zonelist_zone(struct zoneref *zoneref)
1596 {
1597 return zoneref->zone;
1598 }
1599
zonelist_zone_idx(struct zoneref * zoneref)1600 static inline int zonelist_zone_idx(struct zoneref *zoneref)
1601 {
1602 return zoneref->zone_idx;
1603 }
1604
zonelist_node_idx(struct zoneref * zoneref)1605 static inline int zonelist_node_idx(struct zoneref *zoneref)
1606 {
1607 return zone_to_nid(zoneref->zone);
1608 }
1609
1610 struct zoneref *__next_zones_zonelist(struct zoneref *z,
1611 enum zone_type highest_zoneidx,
1612 nodemask_t *nodes);
1613
1614 /**
1615 * 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
1616 * @z: The cursor used as a starting point for the search
1617 * @highest_zoneidx: The zone index of the highest zone to return
1618 * @nodes: An optional nodemask to filter the zonelist with
1619 *
1620 * This function returns the next zone at or below a given zone index that is
1621 * within the allowed nodemask using a cursor as the starting point for the
1622 * search. The zoneref returned is a cursor that represents the current zone
1623 * being examined. It should be advanced by one before calling
1624 * next_zones_zonelist again.
1625 *
1626 * Return: the next zone at or below highest_zoneidx within the allowed
1627 * nodemask using a cursor within a zonelist as a starting point
1628 */
next_zones_zonelist(struct zoneref * z,enum zone_type highest_zoneidx,nodemask_t * nodes)1629 static __always_inline struct zoneref *next_zones_zonelist(struct zoneref *z,
1630 enum zone_type highest_zoneidx,
1631 nodemask_t *nodes)
1632 {
1633 if (likely(!nodes && zonelist_zone_idx(z) <= highest_zoneidx))
1634 return z;
1635 return __next_zones_zonelist(z, highest_zoneidx, nodes);
1636 }
1637
1638 /**
1639 * first_zones_zonelist - Returns the first zone at or below highest_zoneidx within the allowed nodemask in a zonelist
1640 * @zonelist: The zonelist to search for a suitable zone
1641 * @highest_zoneidx: The zone index of the highest zone to return
1642 * @nodes: An optional nodemask to filter the zonelist with
1643 *
1644 * This function returns the first zone at or below a given zone index that is
1645 * within the allowed nodemask. The zoneref returned is a cursor that can be
1646 * used to iterate the zonelist with next_zones_zonelist by advancing it by
1647 * one before calling.
1648 *
1649 * When no eligible zone is found, zoneref->zone is NULL (zoneref itself is
1650 * never NULL). This may happen either genuinely, or due to concurrent nodemask
1651 * update due to cpuset modification.
1652 *
1653 * Return: Zoneref pointer for the first suitable zone found
1654 */
first_zones_zonelist(struct zonelist * zonelist,enum zone_type highest_zoneidx,nodemask_t * nodes)1655 static inline struct zoneref *first_zones_zonelist(struct zonelist *zonelist,
1656 enum zone_type highest_zoneidx,
1657 nodemask_t *nodes)
1658 {
1659 return next_zones_zonelist(zonelist->_zonerefs,
1660 highest_zoneidx, nodes);
1661 }
1662
1663 /**
1664 * 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
1665 * @zone: The current zone in the iterator
1666 * @z: The current pointer within zonelist->_zonerefs being iterated
1667 * @zlist: The zonelist being iterated
1668 * @highidx: The zone index of the highest zone to return
1669 * @nodemask: Nodemask allowed by the allocator
1670 *
1671 * This iterator iterates though all zones at or below a given zone index and
1672 * within a given nodemask
1673 */
1674 #define for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, nodemask) \
1675 for (z = first_zones_zonelist(zlist, highidx, nodemask), zone = zonelist_zone(z); \
1676 zone; \
1677 z = next_zones_zonelist(++z, highidx, nodemask), \
1678 zone = zonelist_zone(z))
1679
1680 #define for_next_zone_zonelist_nodemask(zone, z, highidx, nodemask) \
1681 for (zone = z->zone; \
1682 zone; \
1683 z = next_zones_zonelist(++z, highidx, nodemask), \
1684 zone = zonelist_zone(z))
1685
1686
1687 /**
1688 * for_each_zone_zonelist - helper macro to iterate over valid zones in a zonelist at or below a given zone index
1689 * @zone: The current zone in the iterator
1690 * @z: The current pointer within zonelist->zones being iterated
1691 * @zlist: The zonelist being iterated
1692 * @highidx: The zone index of the highest zone to return
1693 *
1694 * This iterator iterates though all zones at or below a given zone index.
1695 */
1696 #define for_each_zone_zonelist(zone, z, zlist, highidx) \
1697 for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, NULL)
1698
1699 /* Whether the 'nodes' are all movable nodes */
movable_only_nodes(nodemask_t * nodes)1700 static inline bool movable_only_nodes(nodemask_t *nodes)
1701 {
1702 struct zonelist *zonelist;
1703 struct zoneref *z;
1704 int nid;
1705
1706 if (nodes_empty(*nodes))
1707 return false;
1708
1709 /*
1710 * We can chose arbitrary node from the nodemask to get a
1711 * zonelist as they are interlinked. We just need to find
1712 * at least one zone that can satisfy kernel allocations.
1713 */
1714 nid = first_node(*nodes);
1715 zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
1716 z = first_zones_zonelist(zonelist, ZONE_NORMAL, nodes);
1717 return (!z->zone) ? true : false;
1718 }
1719
1720
1721 #ifdef CONFIG_SPARSEMEM
1722 #include <asm/sparsemem.h>
1723 #endif
1724
1725 #ifdef CONFIG_FLATMEM
1726 #define pfn_to_nid(pfn) (0)
1727 #endif
1728
1729 #ifdef CONFIG_SPARSEMEM
1730
1731 /*
1732 * PA_SECTION_SHIFT physical address to/from section number
1733 * PFN_SECTION_SHIFT pfn to/from section number
1734 */
1735 #define PA_SECTION_SHIFT (SECTION_SIZE_BITS)
1736 #define PFN_SECTION_SHIFT (SECTION_SIZE_BITS - PAGE_SHIFT)
1737
1738 #define NR_MEM_SECTIONS (1UL << SECTIONS_SHIFT)
1739
1740 #define PAGES_PER_SECTION (1UL << PFN_SECTION_SHIFT)
1741 #define PAGE_SECTION_MASK (~(PAGES_PER_SECTION-1))
1742
1743 #define SECTION_BLOCKFLAGS_BITS \
1744 ((1UL << (PFN_SECTION_SHIFT - pageblock_order)) * NR_PAGEBLOCK_BITS)
1745
1746 #if (MAX_ORDER + PAGE_SHIFT) > SECTION_SIZE_BITS
1747 #error Allocator MAX_ORDER exceeds SECTION_SIZE
1748 #endif
1749
pfn_to_section_nr(unsigned long pfn)1750 static inline unsigned long pfn_to_section_nr(unsigned long pfn)
1751 {
1752 return pfn >> PFN_SECTION_SHIFT;
1753 }
section_nr_to_pfn(unsigned long sec)1754 static inline unsigned long section_nr_to_pfn(unsigned long sec)
1755 {
1756 return sec << PFN_SECTION_SHIFT;
1757 }
1758
1759 #define SECTION_ALIGN_UP(pfn) (((pfn) + PAGES_PER_SECTION - 1) & PAGE_SECTION_MASK)
1760 #define SECTION_ALIGN_DOWN(pfn) ((pfn) & PAGE_SECTION_MASK)
1761
1762 #define SUBSECTION_SHIFT 21
1763 #define SUBSECTION_SIZE (1UL << SUBSECTION_SHIFT)
1764
1765 #define PFN_SUBSECTION_SHIFT (SUBSECTION_SHIFT - PAGE_SHIFT)
1766 #define PAGES_PER_SUBSECTION (1UL << PFN_SUBSECTION_SHIFT)
1767 #define PAGE_SUBSECTION_MASK (~(PAGES_PER_SUBSECTION-1))
1768
1769 #if SUBSECTION_SHIFT > SECTION_SIZE_BITS
1770 #error Subsection size exceeds section size
1771 #else
1772 #define SUBSECTIONS_PER_SECTION (1UL << (SECTION_SIZE_BITS - SUBSECTION_SHIFT))
1773 #endif
1774
1775 #define SUBSECTION_ALIGN_UP(pfn) ALIGN((pfn), PAGES_PER_SUBSECTION)
1776 #define SUBSECTION_ALIGN_DOWN(pfn) ((pfn) & PAGE_SUBSECTION_MASK)
1777
1778 struct mem_section_usage {
1779 struct rcu_head rcu;
1780 #ifdef CONFIG_SPARSEMEM_VMEMMAP
1781 DECLARE_BITMAP(subsection_map, SUBSECTIONS_PER_SECTION);
1782 #endif
1783 /* See declaration of similar field in struct zone */
1784 unsigned long pageblock_flags[0];
1785 };
1786
1787 void subsection_map_init(unsigned long pfn, unsigned long nr_pages);
1788
1789 struct page;
1790 struct page_ext;
1791 struct mem_section {
1792 /*
1793 * This is, logically, a pointer to an array of struct
1794 * pages. However, it is stored with some other magic.
1795 * (see sparse.c::sparse_init_one_section())
1796 *
1797 * Additionally during early boot we encode node id of
1798 * the location of the section here to guide allocation.
1799 * (see sparse.c::memory_present())
1800 *
1801 * Making it a UL at least makes someone do a cast
1802 * before using it wrong.
1803 */
1804 unsigned long section_mem_map;
1805
1806 struct mem_section_usage *usage;
1807 #ifdef CONFIG_PAGE_EXTENSION
1808 /*
1809 * If SPARSEMEM, pgdat doesn't have page_ext pointer. We use
1810 * section. (see page_ext.h about this.)
1811 */
1812 struct page_ext *page_ext;
1813 unsigned long pad;
1814 #endif
1815 /*
1816 * WARNING: mem_section must be a power-of-2 in size for the
1817 * calculation and use of SECTION_ROOT_MASK to make sense.
1818 */
1819 };
1820
1821 #ifdef CONFIG_SPARSEMEM_EXTREME
1822 #define SECTIONS_PER_ROOT (PAGE_SIZE / sizeof (struct mem_section))
1823 #else
1824 #define SECTIONS_PER_ROOT 1
1825 #endif
1826
1827 #define SECTION_NR_TO_ROOT(sec) ((sec) / SECTIONS_PER_ROOT)
1828 #define NR_SECTION_ROOTS DIV_ROUND_UP(NR_MEM_SECTIONS, SECTIONS_PER_ROOT)
1829 #define SECTION_ROOT_MASK (SECTIONS_PER_ROOT - 1)
1830
1831 #ifdef CONFIG_SPARSEMEM_EXTREME
1832 extern struct mem_section **mem_section;
1833 #else
1834 extern struct mem_section mem_section[NR_SECTION_ROOTS][SECTIONS_PER_ROOT];
1835 #endif
1836
section_to_usemap(struct mem_section * ms)1837 static inline unsigned long *section_to_usemap(struct mem_section *ms)
1838 {
1839 return ms->usage->pageblock_flags;
1840 }
1841
__nr_to_section(unsigned long nr)1842 static inline struct mem_section *__nr_to_section(unsigned long nr)
1843 {
1844 unsigned long root = SECTION_NR_TO_ROOT(nr);
1845
1846 if (unlikely(root >= NR_SECTION_ROOTS))
1847 return NULL;
1848
1849 #ifdef CONFIG_SPARSEMEM_EXTREME
1850 if (!mem_section || !mem_section[root])
1851 return NULL;
1852 #endif
1853 return &mem_section[root][nr & SECTION_ROOT_MASK];
1854 }
1855 extern size_t mem_section_usage_size(void);
1856
1857 /*
1858 * We use the lower bits of the mem_map pointer to store
1859 * a little bit of information. The pointer is calculated
1860 * as mem_map - section_nr_to_pfn(pnum). The result is
1861 * aligned to the minimum alignment of the two values:
1862 * 1. All mem_map arrays are page-aligned.
1863 * 2. section_nr_to_pfn() always clears PFN_SECTION_SHIFT
1864 * lowest bits. PFN_SECTION_SHIFT is arch-specific
1865 * (equal SECTION_SIZE_BITS - PAGE_SHIFT), and the
1866 * worst combination is powerpc with 256k pages,
1867 * which results in PFN_SECTION_SHIFT equal 6.
1868 * To sum it up, at least 6 bits are available on all architectures.
1869 * However, we can exceed 6 bits on some other architectures except
1870 * powerpc (e.g. 15 bits are available on x86_64, 13 bits are available
1871 * with the worst case of 64K pages on arm64) if we make sure the
1872 * exceeded bit is not applicable to powerpc.
1873 */
1874 enum {
1875 SECTION_MARKED_PRESENT_BIT,
1876 SECTION_HAS_MEM_MAP_BIT,
1877 SECTION_IS_ONLINE_BIT,
1878 SECTION_IS_EARLY_BIT,
1879 #ifdef CONFIG_ZONE_DEVICE
1880 SECTION_TAINT_ZONE_DEVICE_BIT,
1881 #endif
1882 SECTION_MAP_LAST_BIT,
1883 };
1884
1885 #define SECTION_MARKED_PRESENT BIT(SECTION_MARKED_PRESENT_BIT)
1886 #define SECTION_HAS_MEM_MAP BIT(SECTION_HAS_MEM_MAP_BIT)
1887 #define SECTION_IS_ONLINE BIT(SECTION_IS_ONLINE_BIT)
1888 #define SECTION_IS_EARLY BIT(SECTION_IS_EARLY_BIT)
1889 #ifdef CONFIG_ZONE_DEVICE
1890 #define SECTION_TAINT_ZONE_DEVICE BIT(SECTION_TAINT_ZONE_DEVICE_BIT)
1891 #endif
1892 #define SECTION_MAP_MASK (~(BIT(SECTION_MAP_LAST_BIT) - 1))
1893 #define SECTION_NID_SHIFT SECTION_MAP_LAST_BIT
1894
__section_mem_map_addr(struct mem_section * section)1895 static inline struct page *__section_mem_map_addr(struct mem_section *section)
1896 {
1897 unsigned long map = section->section_mem_map;
1898 map &= SECTION_MAP_MASK;
1899 return (struct page *)map;
1900 }
1901
present_section(struct mem_section * section)1902 static inline int present_section(struct mem_section *section)
1903 {
1904 return (section && (section->section_mem_map & SECTION_MARKED_PRESENT));
1905 }
1906
present_section_nr(unsigned long nr)1907 static inline int present_section_nr(unsigned long nr)
1908 {
1909 return present_section(__nr_to_section(nr));
1910 }
1911
valid_section(struct mem_section * section)1912 static inline int valid_section(struct mem_section *section)
1913 {
1914 return (section && (section->section_mem_map & SECTION_HAS_MEM_MAP));
1915 }
1916
early_section(struct mem_section * section)1917 static inline int early_section(struct mem_section *section)
1918 {
1919 return (section && (section->section_mem_map & SECTION_IS_EARLY));
1920 }
1921
valid_section_nr(unsigned long nr)1922 static inline int valid_section_nr(unsigned long nr)
1923 {
1924 return valid_section(__nr_to_section(nr));
1925 }
1926
online_section(struct mem_section * section)1927 static inline int online_section(struct mem_section *section)
1928 {
1929 return (section && (section->section_mem_map & SECTION_IS_ONLINE));
1930 }
1931
1932 #ifdef CONFIG_ZONE_DEVICE
online_device_section(struct mem_section * section)1933 static inline int online_device_section(struct mem_section *section)
1934 {
1935 unsigned long flags = SECTION_IS_ONLINE | SECTION_TAINT_ZONE_DEVICE;
1936
1937 return section && ((section->section_mem_map & flags) == flags);
1938 }
1939 #else
online_device_section(struct mem_section * section)1940 static inline int online_device_section(struct mem_section *section)
1941 {
1942 return 0;
1943 }
1944 #endif
1945
online_section_nr(unsigned long nr)1946 static inline int online_section_nr(unsigned long nr)
1947 {
1948 return online_section(__nr_to_section(nr));
1949 }
1950
1951 #ifdef CONFIG_MEMORY_HOTPLUG
1952 void online_mem_sections(unsigned long start_pfn, unsigned long end_pfn);
1953 void offline_mem_sections(unsigned long start_pfn, unsigned long end_pfn);
1954 #endif
1955
__pfn_to_section(unsigned long pfn)1956 static inline struct mem_section *__pfn_to_section(unsigned long pfn)
1957 {
1958 return __nr_to_section(pfn_to_section_nr(pfn));
1959 }
1960
1961 extern unsigned long __highest_present_section_nr;
1962
subsection_map_index(unsigned long pfn)1963 static inline int subsection_map_index(unsigned long pfn)
1964 {
1965 return (pfn & ~(PAGE_SECTION_MASK)) / PAGES_PER_SUBSECTION;
1966 }
1967
1968 #ifdef CONFIG_SPARSEMEM_VMEMMAP
pfn_section_valid(struct mem_section * ms,unsigned long pfn)1969 static inline int pfn_section_valid(struct mem_section *ms, unsigned long pfn)
1970 {
1971 int idx = subsection_map_index(pfn);
1972
1973 return test_bit(idx, READ_ONCE(ms->usage)->subsection_map);
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