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