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