1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * linux/mm/page_alloc.c 4 * 5 * Manages the free list, the system allocates free pages here. 6 * Note that kmalloc() lives in slab.c 7 * 8 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds 9 * Swap reorganised 29.12.95, Stephen Tweedie 10 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999 11 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999 12 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999 13 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000 14 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002 15 * (lots of bits borrowed from Ingo Molnar & Andrew Morton) 16 */ 17 18 #include <linux/stddef.h> 19 #include <linux/mm.h> 20 #include <linux/highmem.h> 21 #include <linux/swap.h> 22 #include <linux/swapops.h> 23 #include <linux/interrupt.h> 24 #include <linux/pagemap.h> 25 #include <linux/jiffies.h> 26 #include <linux/memblock.h> 27 #include <linux/compiler.h> 28 #include <linux/kernel.h> 29 #include <linux/kasan.h> 30 #include <linux/kmsan.h> 31 #include <linux/module.h> 32 #include <linux/suspend.h> 33 #include <linux/pagevec.h> 34 #include <linux/blkdev.h> 35 #include <linux/slab.h> 36 #include <linux/ratelimit.h> 37 #include <linux/oom.h> 38 #include <linux/topology.h> 39 #include <linux/sysctl.h> 40 #include <linux/cpu.h> 41 #include <linux/cpuset.h> 42 #include <linux/memory_hotplug.h> 43 #include <linux/nodemask.h> 44 #include <linux/vmalloc.h> 45 #include <linux/vmstat.h> 46 #include <linux/mempolicy.h> 47 #include <linux/memremap.h> 48 #include <linux/stop_machine.h> 49 #include <linux/random.h> 50 #include <linux/sort.h> 51 #include <linux/pfn.h> 52 #include <linux/backing-dev.h> 53 #include <linux/fault-inject.h> 54 #include <linux/page-isolation.h> 55 #include <linux/debugobjects.h> 56 #include <linux/kmemleak.h> 57 #include <linux/compaction.h> 58 #include <trace/events/kmem.h> 59 #include <trace/events/oom.h> 60 #include <linux/prefetch.h> 61 #include <linux/mm_inline.h> 62 #include <linux/mmu_notifier.h> 63 #include <linux/migrate.h> 64 #include <linux/hugetlb.h> 65 #include <linux/sched/rt.h> 66 #include <linux/sched/mm.h> 67 #include <linux/page_owner.h> 68 #include <linux/page_table_check.h> 69 #include <linux/kthread.h> 70 #include <linux/memcontrol.h> 71 #include <linux/ftrace.h> 72 #include <linux/lockdep.h> 73 #include <linux/nmi.h> 74 #include <linux/psi.h> 75 #include <linux/padata.h> 76 #include <linux/khugepaged.h> 77 #include <linux/buffer_head.h> 78 #include <linux/delayacct.h> 79 #include <asm/sections.h> 80 #include <asm/tlbflush.h> 81 #include <asm/div64.h> 82 #include "internal.h" 83 #include "shuffle.h" 84 #include "page_reporting.h" 85 #include "swap.h" 86 87 /* Free Page Internal flags: for internal, non-pcp variants of free_pages(). */ 88 typedef int __bitwise fpi_t; 89 90 /* No special request */ 91 #define FPI_NONE ((__force fpi_t)0) 92 93 /* 94 * Skip free page reporting notification for the (possibly merged) page. 95 * This does not hinder free page reporting from grabbing the page, 96 * reporting it and marking it "reported" - it only skips notifying 97 * the free page reporting infrastructure about a newly freed page. For 98 * example, used when temporarily pulling a page from a freelist and 99 * putting it back unmodified. 100 */ 101 #define FPI_SKIP_REPORT_NOTIFY ((__force fpi_t)BIT(0)) 102 103 /* 104 * Place the (possibly merged) page to the tail of the freelist. Will ignore 105 * page shuffling (relevant code - e.g., memory onlining - is expected to 106 * shuffle the whole zone). 107 * 108 * Note: No code should rely on this flag for correctness - it's purely 109 * to allow for optimizations when handing back either fresh pages 110 * (memory onlining) or untouched pages (page isolation, free page 111 * reporting). 112 */ 113 #define FPI_TO_TAIL ((__force fpi_t)BIT(1)) 114 115 /* 116 * Don't poison memory with KASAN (only for the tag-based modes). 117 * During boot, all non-reserved memblock memory is exposed to page_alloc. 118 * Poisoning all that memory lengthens boot time, especially on systems with 119 * large amount of RAM. This flag is used to skip that poisoning. 120 * This is only done for the tag-based KASAN modes, as those are able to 121 * detect memory corruptions with the memory tags assigned by default. 122 * All memory allocated normally after boot gets poisoned as usual. 123 */ 124 #define FPI_SKIP_KASAN_POISON ((__force fpi_t)BIT(2)) 125 126 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */ 127 static DEFINE_MUTEX(pcp_batch_high_lock); 128 #define MIN_PERCPU_PAGELIST_HIGH_FRACTION (8) 129 130 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT_RT) 131 /* 132 * On SMP, spin_trylock is sufficient protection. 133 * On PREEMPT_RT, spin_trylock is equivalent on both SMP and UP. 134 */ 135 #define pcp_trylock_prepare(flags) do { } while (0) 136 #define pcp_trylock_finish(flag) do { } while (0) 137 #else 138 139 /* UP spin_trylock always succeeds so disable IRQs to prevent re-entrancy. */ 140 #define pcp_trylock_prepare(flags) local_irq_save(flags) 141 #define pcp_trylock_finish(flags) local_irq_restore(flags) 142 #endif 143 144 /* 145 * Locking a pcp requires a PCP lookup followed by a spinlock. To avoid 146 * a migration causing the wrong PCP to be locked and remote memory being 147 * potentially allocated, pin the task to the CPU for the lookup+lock. 148 * preempt_disable is used on !RT because it is faster than migrate_disable. 149 * migrate_disable is used on RT because otherwise RT spinlock usage is 150 * interfered with and a high priority task cannot preempt the allocator. 151 */ 152 #ifndef CONFIG_PREEMPT_RT 153 #define pcpu_task_pin() preempt_disable() 154 #define pcpu_task_unpin() preempt_enable() 155 #else 156 #define pcpu_task_pin() migrate_disable() 157 #define pcpu_task_unpin() migrate_enable() 158 #endif 159 160 /* 161 * Generic helper to lookup and a per-cpu variable with an embedded spinlock. 162 * Return value should be used with equivalent unlock helper. 163 */ 164 #define pcpu_spin_lock(type, member, ptr) \ 165 ({ \ 166 type *_ret; \ 167 pcpu_task_pin(); \ 168 _ret = this_cpu_ptr(ptr); \ 169 spin_lock(&_ret->member); \ 170 _ret; \ 171 }) 172 173 #define pcpu_spin_trylock(type, member, ptr) \ 174 ({ \ 175 type *_ret; \ 176 pcpu_task_pin(); \ 177 _ret = this_cpu_ptr(ptr); \ 178 if (!spin_trylock(&_ret->member)) { \ 179 pcpu_task_unpin(); \ 180 _ret = NULL; \ 181 } \ 182 _ret; \ 183 }) 184 185 #define pcpu_spin_unlock(member, ptr) \ 186 ({ \ 187 spin_unlock(&ptr->member); \ 188 pcpu_task_unpin(); \ 189 }) 190 191 /* struct per_cpu_pages specific helpers. */ 192 #define pcp_spin_lock(ptr) \ 193 pcpu_spin_lock(struct per_cpu_pages, lock, ptr) 194 195 #define pcp_spin_trylock(ptr) \ 196 pcpu_spin_trylock(struct per_cpu_pages, lock, ptr) 197 198 #define pcp_spin_unlock(ptr) \ 199 pcpu_spin_unlock(lock, ptr) 200 201 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID 202 DEFINE_PER_CPU(int, numa_node); 203 EXPORT_PER_CPU_SYMBOL(numa_node); 204 #endif 205 206 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key); 207 208 #ifdef CONFIG_HAVE_MEMORYLESS_NODES 209 /* 210 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly. 211 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined. 212 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem() 213 * defined in <linux/topology.h>. 214 */ 215 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */ 216 EXPORT_PER_CPU_SYMBOL(_numa_mem_); 217 #endif 218 219 static DEFINE_MUTEX(pcpu_drain_mutex); 220 221 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY 222 volatile unsigned long latent_entropy __latent_entropy; 223 EXPORT_SYMBOL(latent_entropy); 224 #endif 225 226 /* 227 * Array of node states. 228 */ 229 nodemask_t node_states[NR_NODE_STATES] __read_mostly = { 230 [N_POSSIBLE] = NODE_MASK_ALL, 231 [N_ONLINE] = { { [0] = 1UL } }, 232 #ifndef CONFIG_NUMA 233 [N_NORMAL_MEMORY] = { { [0] = 1UL } }, 234 #ifdef CONFIG_HIGHMEM 235 [N_HIGH_MEMORY] = { { [0] = 1UL } }, 236 #endif 237 [N_MEMORY] = { { [0] = 1UL } }, 238 [N_CPU] = { { [0] = 1UL } }, 239 #endif /* NUMA */ 240 }; 241 EXPORT_SYMBOL(node_states); 242 243 atomic_long_t _totalram_pages __read_mostly; 244 EXPORT_SYMBOL(_totalram_pages); 245 unsigned long totalreserve_pages __read_mostly; 246 unsigned long totalcma_pages __read_mostly; 247 248 int percpu_pagelist_high_fraction; 249 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK; 250 DEFINE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_ALLOC_DEFAULT_ON, init_on_alloc); 251 EXPORT_SYMBOL(init_on_alloc); 252 253 DEFINE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_FREE_DEFAULT_ON, init_on_free); 254 EXPORT_SYMBOL(init_on_free); 255 256 static bool _init_on_alloc_enabled_early __read_mostly 257 = IS_ENABLED(CONFIG_INIT_ON_ALLOC_DEFAULT_ON); 258 static int __init early_init_on_alloc(char *buf) 259 { 260 261 return kstrtobool(buf, &_init_on_alloc_enabled_early); 262 } 263 early_param("init_on_alloc", early_init_on_alloc); 264 265 static bool _init_on_free_enabled_early __read_mostly 266 = IS_ENABLED(CONFIG_INIT_ON_FREE_DEFAULT_ON); 267 static int __init early_init_on_free(char *buf) 268 { 269 return kstrtobool(buf, &_init_on_free_enabled_early); 270 } 271 early_param("init_on_free", early_init_on_free); 272 273 /* 274 * A cached value of the page's pageblock's migratetype, used when the page is 275 * put on a pcplist. Used to avoid the pageblock migratetype lookup when 276 * freeing from pcplists in most cases, at the cost of possibly becoming stale. 277 * Also the migratetype set in the page does not necessarily match the pcplist 278 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any 279 * other index - this ensures that it will be put on the correct CMA freelist. 280 */ 281 static inline int get_pcppage_migratetype(struct page *page) 282 { 283 return page->index; 284 } 285 286 static inline void set_pcppage_migratetype(struct page *page, int migratetype) 287 { 288 page->index = migratetype; 289 } 290 291 #ifdef CONFIG_PM_SLEEP 292 /* 293 * The following functions are used by the suspend/hibernate code to temporarily 294 * change gfp_allowed_mask in order to avoid using I/O during memory allocations 295 * while devices are suspended. To avoid races with the suspend/hibernate code, 296 * they should always be called with system_transition_mutex held 297 * (gfp_allowed_mask also should only be modified with system_transition_mutex 298 * held, unless the suspend/hibernate code is guaranteed not to run in parallel 299 * with that modification). 300 */ 301 302 static gfp_t saved_gfp_mask; 303 304 void pm_restore_gfp_mask(void) 305 { 306 WARN_ON(!mutex_is_locked(&system_transition_mutex)); 307 if (saved_gfp_mask) { 308 gfp_allowed_mask = saved_gfp_mask; 309 saved_gfp_mask = 0; 310 } 311 } 312 313 void pm_restrict_gfp_mask(void) 314 { 315 WARN_ON(!mutex_is_locked(&system_transition_mutex)); 316 WARN_ON(saved_gfp_mask); 317 saved_gfp_mask = gfp_allowed_mask; 318 gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS); 319 } 320 321 bool pm_suspended_storage(void) 322 { 323 if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS)) 324 return false; 325 return true; 326 } 327 #endif /* CONFIG_PM_SLEEP */ 328 329 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE 330 unsigned int pageblock_order __read_mostly; 331 #endif 332 333 static void __free_pages_ok(struct page *page, unsigned int order, 334 fpi_t fpi_flags); 335 336 /* 337 * results with 256, 32 in the lowmem_reserve sysctl: 338 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high) 339 * 1G machine -> (16M dma, 784M normal, 224M high) 340 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA 341 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL 342 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA 343 * 344 * TBD: should special case ZONE_DMA32 machines here - in those we normally 345 * don't need any ZONE_NORMAL reservation 346 */ 347 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = { 348 #ifdef CONFIG_ZONE_DMA 349 [ZONE_DMA] = 256, 350 #endif 351 #ifdef CONFIG_ZONE_DMA32 352 [ZONE_DMA32] = 256, 353 #endif 354 [ZONE_NORMAL] = 32, 355 #ifdef CONFIG_HIGHMEM 356 [ZONE_HIGHMEM] = 0, 357 #endif 358 [ZONE_MOVABLE] = 0, 359 }; 360 361 static char * const zone_names[MAX_NR_ZONES] = { 362 #ifdef CONFIG_ZONE_DMA 363 "DMA", 364 #endif 365 #ifdef CONFIG_ZONE_DMA32 366 "DMA32", 367 #endif 368 "Normal", 369 #ifdef CONFIG_HIGHMEM 370 "HighMem", 371 #endif 372 "Movable", 373 #ifdef CONFIG_ZONE_DEVICE 374 "Device", 375 #endif 376 }; 377 378 const char * const migratetype_names[MIGRATE_TYPES] = { 379 "Unmovable", 380 "Movable", 381 "Reclaimable", 382 "HighAtomic", 383 #ifdef CONFIG_CMA 384 "CMA", 385 #endif 386 #ifdef CONFIG_MEMORY_ISOLATION 387 "Isolate", 388 #endif 389 }; 390 391 compound_page_dtor * const compound_page_dtors[NR_COMPOUND_DTORS] = { 392 [NULL_COMPOUND_DTOR] = NULL, 393 [COMPOUND_PAGE_DTOR] = free_compound_page, 394 #ifdef CONFIG_HUGETLB_PAGE 395 [HUGETLB_PAGE_DTOR] = free_huge_page, 396 #endif 397 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 398 [TRANSHUGE_PAGE_DTOR] = free_transhuge_page, 399 #endif 400 }; 401 402 int min_free_kbytes = 1024; 403 int user_min_free_kbytes = -1; 404 int watermark_boost_factor __read_mostly = 15000; 405 int watermark_scale_factor = 10; 406 407 static unsigned long nr_kernel_pages __initdata; 408 static unsigned long nr_all_pages __initdata; 409 static unsigned long dma_reserve __initdata; 410 411 static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata; 412 static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata; 413 static unsigned long required_kernelcore __initdata; 414 static unsigned long required_kernelcore_percent __initdata; 415 static unsigned long required_movablecore __initdata; 416 static unsigned long required_movablecore_percent __initdata; 417 static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata; 418 bool mirrored_kernelcore __initdata_memblock; 419 420 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */ 421 int movable_zone; 422 EXPORT_SYMBOL(movable_zone); 423 424 #if MAX_NUMNODES > 1 425 unsigned int nr_node_ids __read_mostly = MAX_NUMNODES; 426 unsigned int nr_online_nodes __read_mostly = 1; 427 EXPORT_SYMBOL(nr_node_ids); 428 EXPORT_SYMBOL(nr_online_nodes); 429 #endif 430 431 int page_group_by_mobility_disabled __read_mostly; 432 433 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 434 /* 435 * During boot we initialize deferred pages on-demand, as needed, but once 436 * page_alloc_init_late() has finished, the deferred pages are all initialized, 437 * and we can permanently disable that path. 438 */ 439 static DEFINE_STATIC_KEY_TRUE(deferred_pages); 440 441 static inline bool deferred_pages_enabled(void) 442 { 443 return static_branch_unlikely(&deferred_pages); 444 } 445 446 /* Returns true if the struct page for the pfn is initialised */ 447 static inline bool __meminit early_page_initialised(unsigned long pfn) 448 { 449 int nid = early_pfn_to_nid(pfn); 450 451 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn) 452 return false; 453 454 return true; 455 } 456 457 /* 458 * Returns true when the remaining initialisation should be deferred until 459 * later in the boot cycle when it can be parallelised. 460 */ 461 static bool __meminit 462 defer_init(int nid, unsigned long pfn, unsigned long end_pfn) 463 { 464 static unsigned long prev_end_pfn, nr_initialised; 465 466 if (early_page_ext_enabled()) 467 return false; 468 /* 469 * prev_end_pfn static that contains the end of previous zone 470 * No need to protect because called very early in boot before smp_init. 471 */ 472 if (prev_end_pfn != end_pfn) { 473 prev_end_pfn = end_pfn; 474 nr_initialised = 0; 475 } 476 477 /* Always populate low zones for address-constrained allocations */ 478 if (end_pfn < pgdat_end_pfn(NODE_DATA(nid))) 479 return false; 480 481 if (NODE_DATA(nid)->first_deferred_pfn != ULONG_MAX) 482 return true; 483 /* 484 * We start only with one section of pages, more pages are added as 485 * needed until the rest of deferred pages are initialized. 486 */ 487 nr_initialised++; 488 if ((nr_initialised > PAGES_PER_SECTION) && 489 (pfn & (PAGES_PER_SECTION - 1)) == 0) { 490 NODE_DATA(nid)->first_deferred_pfn = pfn; 491 return true; 492 } 493 return false; 494 } 495 #else 496 static inline bool deferred_pages_enabled(void) 497 { 498 return false; 499 } 500 501 static inline bool early_page_initialised(unsigned long pfn) 502 { 503 return true; 504 } 505 506 static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn) 507 { 508 return false; 509 } 510 #endif 511 512 /* Return a pointer to the bitmap storing bits affecting a block of pages */ 513 static inline unsigned long *get_pageblock_bitmap(const struct page *page, 514 unsigned long pfn) 515 { 516 #ifdef CONFIG_SPARSEMEM 517 return section_to_usemap(__pfn_to_section(pfn)); 518 #else 519 return page_zone(page)->pageblock_flags; 520 #endif /* CONFIG_SPARSEMEM */ 521 } 522 523 static inline int pfn_to_bitidx(const struct page *page, unsigned long pfn) 524 { 525 #ifdef CONFIG_SPARSEMEM 526 pfn &= (PAGES_PER_SECTION-1); 527 #else 528 pfn = pfn - pageblock_start_pfn(page_zone(page)->zone_start_pfn); 529 #endif /* CONFIG_SPARSEMEM */ 530 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS; 531 } 532 533 static __always_inline 534 unsigned long __get_pfnblock_flags_mask(const struct page *page, 535 unsigned long pfn, 536 unsigned long mask) 537 { 538 unsigned long *bitmap; 539 unsigned long bitidx, word_bitidx; 540 unsigned long word; 541 542 bitmap = get_pageblock_bitmap(page, pfn); 543 bitidx = pfn_to_bitidx(page, pfn); 544 word_bitidx = bitidx / BITS_PER_LONG; 545 bitidx &= (BITS_PER_LONG-1); 546 /* 547 * This races, without locks, with set_pfnblock_flags_mask(). Ensure 548 * a consistent read of the memory array, so that results, even though 549 * racy, are not corrupted. 550 */ 551 word = READ_ONCE(bitmap[word_bitidx]); 552 return (word >> bitidx) & mask; 553 } 554 555 /** 556 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages 557 * @page: The page within the block of interest 558 * @pfn: The target page frame number 559 * @mask: mask of bits that the caller is interested in 560 * 561 * Return: pageblock_bits flags 562 */ 563 unsigned long get_pfnblock_flags_mask(const struct page *page, 564 unsigned long pfn, unsigned long mask) 565 { 566 return __get_pfnblock_flags_mask(page, pfn, mask); 567 } 568 569 static __always_inline int get_pfnblock_migratetype(const struct page *page, 570 unsigned long pfn) 571 { 572 return __get_pfnblock_flags_mask(page, pfn, MIGRATETYPE_MASK); 573 } 574 575 /** 576 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages 577 * @page: The page within the block of interest 578 * @flags: The flags to set 579 * @pfn: The target page frame number 580 * @mask: mask of bits that the caller is interested in 581 */ 582 void set_pfnblock_flags_mask(struct page *page, unsigned long flags, 583 unsigned long pfn, 584 unsigned long mask) 585 { 586 unsigned long *bitmap; 587 unsigned long bitidx, word_bitidx; 588 unsigned long word; 589 590 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4); 591 BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits)); 592 593 bitmap = get_pageblock_bitmap(page, pfn); 594 bitidx = pfn_to_bitidx(page, pfn); 595 word_bitidx = bitidx / BITS_PER_LONG; 596 bitidx &= (BITS_PER_LONG-1); 597 598 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page); 599 600 mask <<= bitidx; 601 flags <<= bitidx; 602 603 word = READ_ONCE(bitmap[word_bitidx]); 604 do { 605 } while (!try_cmpxchg(&bitmap[word_bitidx], &word, (word & ~mask) | flags)); 606 } 607 608 void set_pageblock_migratetype(struct page *page, int migratetype) 609 { 610 if (unlikely(page_group_by_mobility_disabled && 611 migratetype < MIGRATE_PCPTYPES)) 612 migratetype = MIGRATE_UNMOVABLE; 613 614 set_pfnblock_flags_mask(page, (unsigned long)migratetype, 615 page_to_pfn(page), MIGRATETYPE_MASK); 616 } 617 618 #ifdef CONFIG_DEBUG_VM 619 static int page_outside_zone_boundaries(struct zone *zone, struct page *page) 620 { 621 int ret = 0; 622 unsigned seq; 623 unsigned long pfn = page_to_pfn(page); 624 unsigned long sp, start_pfn; 625 626 do { 627 seq = zone_span_seqbegin(zone); 628 start_pfn = zone->zone_start_pfn; 629 sp = zone->spanned_pages; 630 if (!zone_spans_pfn(zone, pfn)) 631 ret = 1; 632 } while (zone_span_seqretry(zone, seq)); 633 634 if (ret) 635 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n", 636 pfn, zone_to_nid(zone), zone->name, 637 start_pfn, start_pfn + sp); 638 639 return ret; 640 } 641 642 static int page_is_consistent(struct zone *zone, struct page *page) 643 { 644 if (zone != page_zone(page)) 645 return 0; 646 647 return 1; 648 } 649 /* 650 * Temporary debugging check for pages not lying within a given zone. 651 */ 652 static int __maybe_unused bad_range(struct zone *zone, struct page *page) 653 { 654 if (page_outside_zone_boundaries(zone, page)) 655 return 1; 656 if (!page_is_consistent(zone, page)) 657 return 1; 658 659 return 0; 660 } 661 #else 662 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page) 663 { 664 return 0; 665 } 666 #endif 667 668 static void bad_page(struct page *page, const char *reason) 669 { 670 static unsigned long resume; 671 static unsigned long nr_shown; 672 static unsigned long nr_unshown; 673 674 /* 675 * Allow a burst of 60 reports, then keep quiet for that minute; 676 * or allow a steady drip of one report per second. 677 */ 678 if (nr_shown == 60) { 679 if (time_before(jiffies, resume)) { 680 nr_unshown++; 681 goto out; 682 } 683 if (nr_unshown) { 684 pr_alert( 685 "BUG: Bad page state: %lu messages suppressed\n", 686 nr_unshown); 687 nr_unshown = 0; 688 } 689 nr_shown = 0; 690 } 691 if (nr_shown++ == 0) 692 resume = jiffies + 60 * HZ; 693 694 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n", 695 current->comm, page_to_pfn(page)); 696 dump_page(page, reason); 697 698 print_modules(); 699 dump_stack(); 700 out: 701 /* Leave bad fields for debug, except PageBuddy could make trouble */ 702 page_mapcount_reset(page); /* remove PageBuddy */ 703 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); 704 } 705 706 static inline unsigned int order_to_pindex(int migratetype, int order) 707 { 708 int base = order; 709 710 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 711 if (order > PAGE_ALLOC_COSTLY_ORDER) { 712 VM_BUG_ON(order != pageblock_order); 713 return NR_LOWORDER_PCP_LISTS; 714 } 715 #else 716 VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER); 717 #endif 718 719 return (MIGRATE_PCPTYPES * base) + migratetype; 720 } 721 722 static inline int pindex_to_order(unsigned int pindex) 723 { 724 int order = pindex / MIGRATE_PCPTYPES; 725 726 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 727 if (pindex == NR_LOWORDER_PCP_LISTS) 728 order = pageblock_order; 729 #else 730 VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER); 731 #endif 732 733 return order; 734 } 735 736 static inline bool pcp_allowed_order(unsigned int order) 737 { 738 if (order <= PAGE_ALLOC_COSTLY_ORDER) 739 return true; 740 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 741 if (order == pageblock_order) 742 return true; 743 #endif 744 return false; 745 } 746 747 static inline void free_the_page(struct page *page, unsigned int order) 748 { 749 if (pcp_allowed_order(order)) /* Via pcp? */ 750 free_unref_page(page, order); 751 else 752 __free_pages_ok(page, order, FPI_NONE); 753 } 754 755 /* 756 * Higher-order pages are called "compound pages". They are structured thusly: 757 * 758 * The first PAGE_SIZE page is called the "head page" and have PG_head set. 759 * 760 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded 761 * in bit 0 of page->compound_head. The rest of bits is pointer to head page. 762 * 763 * The first tail page's ->compound_dtor holds the offset in array of compound 764 * page destructors. See compound_page_dtors. 765 * 766 * The first tail page's ->compound_order holds the order of allocation. 767 * This usage means that zero-order pages may not be compound. 768 */ 769 770 void free_compound_page(struct page *page) 771 { 772 mem_cgroup_uncharge(page_folio(page)); 773 free_the_page(page, compound_order(page)); 774 } 775 776 static void prep_compound_head(struct page *page, unsigned int order) 777 { 778 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR); 779 set_compound_order(page, order); 780 atomic_set(compound_mapcount_ptr(page), -1); 781 atomic_set(subpages_mapcount_ptr(page), 0); 782 atomic_set(compound_pincount_ptr(page), 0); 783 } 784 785 static void prep_compound_tail(struct page *head, int tail_idx) 786 { 787 struct page *p = head + tail_idx; 788 789 p->mapping = TAIL_MAPPING; 790 set_compound_head(p, head); 791 set_page_private(p, 0); 792 } 793 794 void prep_compound_page(struct page *page, unsigned int order) 795 { 796 int i; 797 int nr_pages = 1 << order; 798 799 __SetPageHead(page); 800 for (i = 1; i < nr_pages; i++) 801 prep_compound_tail(page, i); 802 803 prep_compound_head(page, order); 804 } 805 806 void destroy_large_folio(struct folio *folio) 807 { 808 enum compound_dtor_id dtor = folio_page(folio, 1)->compound_dtor; 809 810 VM_BUG_ON_FOLIO(dtor >= NR_COMPOUND_DTORS, folio); 811 compound_page_dtors[dtor](&folio->page); 812 } 813 814 #ifdef CONFIG_DEBUG_PAGEALLOC 815 unsigned int _debug_guardpage_minorder; 816 817 bool _debug_pagealloc_enabled_early __read_mostly 818 = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT); 819 EXPORT_SYMBOL(_debug_pagealloc_enabled_early); 820 DEFINE_STATIC_KEY_FALSE(_debug_pagealloc_enabled); 821 EXPORT_SYMBOL(_debug_pagealloc_enabled); 822 823 DEFINE_STATIC_KEY_FALSE(_debug_guardpage_enabled); 824 825 static int __init early_debug_pagealloc(char *buf) 826 { 827 return kstrtobool(buf, &_debug_pagealloc_enabled_early); 828 } 829 early_param("debug_pagealloc", early_debug_pagealloc); 830 831 static int __init debug_guardpage_minorder_setup(char *buf) 832 { 833 unsigned long res; 834 835 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) { 836 pr_err("Bad debug_guardpage_minorder value\n"); 837 return 0; 838 } 839 _debug_guardpage_minorder = res; 840 pr_info("Setting debug_guardpage_minorder to %lu\n", res); 841 return 0; 842 } 843 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup); 844 845 static inline bool set_page_guard(struct zone *zone, struct page *page, 846 unsigned int order, int migratetype) 847 { 848 if (!debug_guardpage_enabled()) 849 return false; 850 851 if (order >= debug_guardpage_minorder()) 852 return false; 853 854 __SetPageGuard(page); 855 INIT_LIST_HEAD(&page->buddy_list); 856 set_page_private(page, order); 857 /* Guard pages are not available for any usage */ 858 if (!is_migrate_isolate(migratetype)) 859 __mod_zone_freepage_state(zone, -(1 << order), migratetype); 860 861 return true; 862 } 863 864 static inline void clear_page_guard(struct zone *zone, struct page *page, 865 unsigned int order, int migratetype) 866 { 867 if (!debug_guardpage_enabled()) 868 return; 869 870 __ClearPageGuard(page); 871 872 set_page_private(page, 0); 873 if (!is_migrate_isolate(migratetype)) 874 __mod_zone_freepage_state(zone, (1 << order), migratetype); 875 } 876 #else 877 static inline bool set_page_guard(struct zone *zone, struct page *page, 878 unsigned int order, int migratetype) { return false; } 879 static inline void clear_page_guard(struct zone *zone, struct page *page, 880 unsigned int order, int migratetype) {} 881 #endif 882 883 /* 884 * Enable static keys related to various memory debugging and hardening options. 885 * Some override others, and depend on early params that are evaluated in the 886 * order of appearance. So we need to first gather the full picture of what was 887 * enabled, and then make decisions. 888 */ 889 void __init init_mem_debugging_and_hardening(void) 890 { 891 bool page_poisoning_requested = false; 892 893 #ifdef CONFIG_PAGE_POISONING 894 /* 895 * Page poisoning is debug page alloc for some arches. If 896 * either of those options are enabled, enable poisoning. 897 */ 898 if (page_poisoning_enabled() || 899 (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_DEBUG_PAGEALLOC) && 900 debug_pagealloc_enabled())) { 901 static_branch_enable(&_page_poisoning_enabled); 902 page_poisoning_requested = true; 903 } 904 #endif 905 906 if ((_init_on_alloc_enabled_early || _init_on_free_enabled_early) && 907 page_poisoning_requested) { 908 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, " 909 "will take precedence over init_on_alloc and init_on_free\n"); 910 _init_on_alloc_enabled_early = false; 911 _init_on_free_enabled_early = false; 912 } 913 914 if (_init_on_alloc_enabled_early) 915 static_branch_enable(&init_on_alloc); 916 else 917 static_branch_disable(&init_on_alloc); 918 919 if (_init_on_free_enabled_early) 920 static_branch_enable(&init_on_free); 921 else 922 static_branch_disable(&init_on_free); 923 924 if (IS_ENABLED(CONFIG_KMSAN) && 925 (_init_on_alloc_enabled_early || _init_on_free_enabled_early)) 926 pr_info("mem auto-init: please make sure init_on_alloc and init_on_free are disabled when running KMSAN\n"); 927 928 #ifdef CONFIG_DEBUG_PAGEALLOC 929 if (!debug_pagealloc_enabled()) 930 return; 931 932 static_branch_enable(&_debug_pagealloc_enabled); 933 934 if (!debug_guardpage_minorder()) 935 return; 936 937 static_branch_enable(&_debug_guardpage_enabled); 938 #endif 939 } 940 941 static inline void set_buddy_order(struct page *page, unsigned int order) 942 { 943 set_page_private(page, order); 944 __SetPageBuddy(page); 945 } 946 947 #ifdef CONFIG_COMPACTION 948 static inline struct capture_control *task_capc(struct zone *zone) 949 { 950 struct capture_control *capc = current->capture_control; 951 952 return unlikely(capc) && 953 !(current->flags & PF_KTHREAD) && 954 !capc->page && 955 capc->cc->zone == zone ? capc : NULL; 956 } 957 958 static inline bool 959 compaction_capture(struct capture_control *capc, struct page *page, 960 int order, int migratetype) 961 { 962 if (!capc || order != capc->cc->order) 963 return false; 964 965 /* Do not accidentally pollute CMA or isolated regions*/ 966 if (is_migrate_cma(migratetype) || 967 is_migrate_isolate(migratetype)) 968 return false; 969 970 /* 971 * Do not let lower order allocations pollute a movable pageblock. 972 * This might let an unmovable request use a reclaimable pageblock 973 * and vice-versa but no more than normal fallback logic which can 974 * have trouble finding a high-order free page. 975 */ 976 if (order < pageblock_order && migratetype == MIGRATE_MOVABLE) 977 return false; 978 979 capc->page = page; 980 return true; 981 } 982 983 #else 984 static inline struct capture_control *task_capc(struct zone *zone) 985 { 986 return NULL; 987 } 988 989 static inline bool 990 compaction_capture(struct capture_control *capc, struct page *page, 991 int order, int migratetype) 992 { 993 return false; 994 } 995 #endif /* CONFIG_COMPACTION */ 996 997 /* Used for pages not on another list */ 998 static inline void add_to_free_list(struct page *page, struct zone *zone, 999 unsigned int order, int migratetype) 1000 { 1001 struct free_area *area = &zone->free_area[order]; 1002 1003 list_add(&page->buddy_list, &area->free_list[migratetype]); 1004 area->nr_free++; 1005 } 1006 1007 /* Used for pages not on another list */ 1008 static inline void add_to_free_list_tail(struct page *page, struct zone *zone, 1009 unsigned int order, int migratetype) 1010 { 1011 struct free_area *area = &zone->free_area[order]; 1012 1013 list_add_tail(&page->buddy_list, &area->free_list[migratetype]); 1014 area->nr_free++; 1015 } 1016 1017 /* 1018 * Used for pages which are on another list. Move the pages to the tail 1019 * of the list - so the moved pages won't immediately be considered for 1020 * allocation again (e.g., optimization for memory onlining). 1021 */ 1022 static inline void move_to_free_list(struct page *page, struct zone *zone, 1023 unsigned int order, int migratetype) 1024 { 1025 struct free_area *area = &zone->free_area[order]; 1026 1027 list_move_tail(&page->buddy_list, &area->free_list[migratetype]); 1028 } 1029 1030 static inline void del_page_from_free_list(struct page *page, struct zone *zone, 1031 unsigned int order) 1032 { 1033 /* clear reported state and update reported page count */ 1034 if (page_reported(page)) 1035 __ClearPageReported(page); 1036 1037 list_del(&page->buddy_list); 1038 __ClearPageBuddy(page); 1039 set_page_private(page, 0); 1040 zone->free_area[order].nr_free--; 1041 } 1042 1043 /* 1044 * If this is not the largest possible page, check if the buddy 1045 * of the next-highest order is free. If it is, it's possible 1046 * that pages are being freed that will coalesce soon. In case, 1047 * that is happening, add the free page to the tail of the list 1048 * so it's less likely to be used soon and more likely to be merged 1049 * as a higher order page 1050 */ 1051 static inline bool 1052 buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn, 1053 struct page *page, unsigned int order) 1054 { 1055 unsigned long higher_page_pfn; 1056 struct page *higher_page; 1057 1058 if (order >= MAX_ORDER - 2) 1059 return false; 1060 1061 higher_page_pfn = buddy_pfn & pfn; 1062 higher_page = page + (higher_page_pfn - pfn); 1063 1064 return find_buddy_page_pfn(higher_page, higher_page_pfn, order + 1, 1065 NULL) != NULL; 1066 } 1067 1068 /* 1069 * Freeing function for a buddy system allocator. 1070 * 1071 * The concept of a buddy system is to maintain direct-mapped table 1072 * (containing bit values) for memory blocks of various "orders". 1073 * The bottom level table contains the map for the smallest allocatable 1074 * units of memory (here, pages), and each level above it describes 1075 * pairs of units from the levels below, hence, "buddies". 1076 * At a high level, all that happens here is marking the table entry 1077 * at the bottom level available, and propagating the changes upward 1078 * as necessary, plus some accounting needed to play nicely with other 1079 * parts of the VM system. 1080 * At each level, we keep a list of pages, which are heads of continuous 1081 * free pages of length of (1 << order) and marked with PageBuddy. 1082 * Page's order is recorded in page_private(page) field. 1083 * So when we are allocating or freeing one, we can derive the state of the 1084 * other. That is, if we allocate a small block, and both were 1085 * free, the remainder of the region must be split into blocks. 1086 * If a block is freed, and its buddy is also free, then this 1087 * triggers coalescing into a block of larger size. 1088 * 1089 * -- nyc 1090 */ 1091 1092 static inline void __free_one_page(struct page *page, 1093 unsigned long pfn, 1094 struct zone *zone, unsigned int order, 1095 int migratetype, fpi_t fpi_flags) 1096 { 1097 struct capture_control *capc = task_capc(zone); 1098 unsigned long buddy_pfn = 0; 1099 unsigned long combined_pfn; 1100 struct page *buddy; 1101 bool to_tail; 1102 1103 VM_BUG_ON(!zone_is_initialized(zone)); 1104 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page); 1105 1106 VM_BUG_ON(migratetype == -1); 1107 if (likely(!is_migrate_isolate(migratetype))) 1108 __mod_zone_freepage_state(zone, 1 << order, migratetype); 1109 1110 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page); 1111 VM_BUG_ON_PAGE(bad_range(zone, page), page); 1112 1113 while (order < MAX_ORDER - 1) { 1114 if (compaction_capture(capc, page, order, migratetype)) { 1115 __mod_zone_freepage_state(zone, -(1 << order), 1116 migratetype); 1117 return; 1118 } 1119 1120 buddy = find_buddy_page_pfn(page, pfn, order, &buddy_pfn); 1121 if (!buddy) 1122 goto done_merging; 1123 1124 if (unlikely(order >= pageblock_order)) { 1125 /* 1126 * We want to prevent merge between freepages on pageblock 1127 * without fallbacks and normal pageblock. Without this, 1128 * pageblock isolation could cause incorrect freepage or CMA 1129 * accounting or HIGHATOMIC accounting. 1130 */ 1131 int buddy_mt = get_pageblock_migratetype(buddy); 1132 1133 if (migratetype != buddy_mt 1134 && (!migratetype_is_mergeable(migratetype) || 1135 !migratetype_is_mergeable(buddy_mt))) 1136 goto done_merging; 1137 } 1138 1139 /* 1140 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page, 1141 * merge with it and move up one order. 1142 */ 1143 if (page_is_guard(buddy)) 1144 clear_page_guard(zone, buddy, order, migratetype); 1145 else 1146 del_page_from_free_list(buddy, zone, order); 1147 combined_pfn = buddy_pfn & pfn; 1148 page = page + (combined_pfn - pfn); 1149 pfn = combined_pfn; 1150 order++; 1151 } 1152 1153 done_merging: 1154 set_buddy_order(page, order); 1155 1156 if (fpi_flags & FPI_TO_TAIL) 1157 to_tail = true; 1158 else if (is_shuffle_order(order)) 1159 to_tail = shuffle_pick_tail(); 1160 else 1161 to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order); 1162 1163 if (to_tail) 1164 add_to_free_list_tail(page, zone, order, migratetype); 1165 else 1166 add_to_free_list(page, zone, order, migratetype); 1167 1168 /* Notify page reporting subsystem of freed page */ 1169 if (!(fpi_flags & FPI_SKIP_REPORT_NOTIFY)) 1170 page_reporting_notify_free(order); 1171 } 1172 1173 /** 1174 * split_free_page() -- split a free page at split_pfn_offset 1175 * @free_page: the original free page 1176 * @order: the order of the page 1177 * @split_pfn_offset: split offset within the page 1178 * 1179 * Return -ENOENT if the free page is changed, otherwise 0 1180 * 1181 * It is used when the free page crosses two pageblocks with different migratetypes 1182 * at split_pfn_offset within the page. The split free page will be put into 1183 * separate migratetype lists afterwards. Otherwise, the function achieves 1184 * nothing. 1185 */ 1186 int split_free_page(struct page *free_page, 1187 unsigned int order, unsigned long split_pfn_offset) 1188 { 1189 struct zone *zone = page_zone(free_page); 1190 unsigned long free_page_pfn = page_to_pfn(free_page); 1191 unsigned long pfn; 1192 unsigned long flags; 1193 int free_page_order; 1194 int mt; 1195 int ret = 0; 1196 1197 if (split_pfn_offset == 0) 1198 return ret; 1199 1200 spin_lock_irqsave(&zone->lock, flags); 1201 1202 if (!PageBuddy(free_page) || buddy_order(free_page) != order) { 1203 ret = -ENOENT; 1204 goto out; 1205 } 1206 1207 mt = get_pageblock_migratetype(free_page); 1208 if (likely(!is_migrate_isolate(mt))) 1209 __mod_zone_freepage_state(zone, -(1UL << order), mt); 1210 1211 del_page_from_free_list(free_page, zone, order); 1212 for (pfn = free_page_pfn; 1213 pfn < free_page_pfn + (1UL << order);) { 1214 int mt = get_pfnblock_migratetype(pfn_to_page(pfn), pfn); 1215 1216 free_page_order = min_t(unsigned int, 1217 pfn ? __ffs(pfn) : order, 1218 __fls(split_pfn_offset)); 1219 __free_one_page(pfn_to_page(pfn), pfn, zone, free_page_order, 1220 mt, FPI_NONE); 1221 pfn += 1UL << free_page_order; 1222 split_pfn_offset -= (1UL << free_page_order); 1223 /* we have done the first part, now switch to second part */ 1224 if (split_pfn_offset == 0) 1225 split_pfn_offset = (1UL << order) - (pfn - free_page_pfn); 1226 } 1227 out: 1228 spin_unlock_irqrestore(&zone->lock, flags); 1229 return ret; 1230 } 1231 /* 1232 * A bad page could be due to a number of fields. Instead of multiple branches, 1233 * try and check multiple fields with one check. The caller must do a detailed 1234 * check if necessary. 1235 */ 1236 static inline bool page_expected_state(struct page *page, 1237 unsigned long check_flags) 1238 { 1239 if (unlikely(atomic_read(&page->_mapcount) != -1)) 1240 return false; 1241 1242 if (unlikely((unsigned long)page->mapping | 1243 page_ref_count(page) | 1244 #ifdef CONFIG_MEMCG 1245 page->memcg_data | 1246 #endif 1247 (page->flags & check_flags))) 1248 return false; 1249 1250 return true; 1251 } 1252 1253 static const char *page_bad_reason(struct page *page, unsigned long flags) 1254 { 1255 const char *bad_reason = NULL; 1256 1257 if (unlikely(atomic_read(&page->_mapcount) != -1)) 1258 bad_reason = "nonzero mapcount"; 1259 if (unlikely(page->mapping != NULL)) 1260 bad_reason = "non-NULL mapping"; 1261 if (unlikely(page_ref_count(page) != 0)) 1262 bad_reason = "nonzero _refcount"; 1263 if (unlikely(page->flags & flags)) { 1264 if (flags == PAGE_FLAGS_CHECK_AT_PREP) 1265 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag(s) set"; 1266 else 1267 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set"; 1268 } 1269 #ifdef CONFIG_MEMCG 1270 if (unlikely(page->memcg_data)) 1271 bad_reason = "page still charged to cgroup"; 1272 #endif 1273 return bad_reason; 1274 } 1275 1276 static void free_page_is_bad_report(struct page *page) 1277 { 1278 bad_page(page, 1279 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_FREE)); 1280 } 1281 1282 static inline bool free_page_is_bad(struct page *page) 1283 { 1284 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE))) 1285 return false; 1286 1287 /* Something has gone sideways, find it */ 1288 free_page_is_bad_report(page); 1289 return true; 1290 } 1291 1292 static int free_tail_pages_check(struct page *head_page, struct page *page) 1293 { 1294 int ret = 1; 1295 1296 /* 1297 * We rely page->lru.next never has bit 0 set, unless the page 1298 * is PageTail(). Let's make sure that's true even for poisoned ->lru. 1299 */ 1300 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1); 1301 1302 if (!IS_ENABLED(CONFIG_DEBUG_VM)) { 1303 ret = 0; 1304 goto out; 1305 } 1306 switch (page - head_page) { 1307 case 1: 1308 /* the first tail page: these may be in place of ->mapping */ 1309 if (unlikely(head_compound_mapcount(head_page))) { 1310 bad_page(page, "nonzero compound_mapcount"); 1311 goto out; 1312 } 1313 if (unlikely(atomic_read(subpages_mapcount_ptr(head_page)))) { 1314 bad_page(page, "nonzero subpages_mapcount"); 1315 goto out; 1316 } 1317 if (unlikely(head_compound_pincount(head_page))) { 1318 bad_page(page, "nonzero compound_pincount"); 1319 goto out; 1320 } 1321 break; 1322 case 2: 1323 /* 1324 * the second tail page: ->mapping is 1325 * deferred_list.next -- ignore value. 1326 */ 1327 break; 1328 default: 1329 if (page->mapping != TAIL_MAPPING) { 1330 bad_page(page, "corrupted mapping in tail page"); 1331 goto out; 1332 } 1333 break; 1334 } 1335 if (unlikely(!PageTail(page))) { 1336 bad_page(page, "PageTail not set"); 1337 goto out; 1338 } 1339 if (unlikely(compound_head(page) != head_page)) { 1340 bad_page(page, "compound_head not consistent"); 1341 goto out; 1342 } 1343 ret = 0; 1344 out: 1345 page->mapping = NULL; 1346 clear_compound_head(page); 1347 return ret; 1348 } 1349 1350 /* 1351 * Skip KASAN memory poisoning when either: 1352 * 1353 * 1. Deferred memory initialization has not yet completed, 1354 * see the explanation below. 1355 * 2. Skipping poisoning is requested via FPI_SKIP_KASAN_POISON, 1356 * see the comment next to it. 1357 * 3. Skipping poisoning is requested via __GFP_SKIP_KASAN_POISON, 1358 * see the comment next to it. 1359 * 4. The allocation is excluded from being checked due to sampling, 1360 * see the call to kasan_unpoison_pages. 1361 * 1362 * Poisoning pages during deferred memory init will greatly lengthen the 1363 * process and cause problem in large memory systems as the deferred pages 1364 * initialization is done with interrupt disabled. 1365 * 1366 * Assuming that there will be no reference to those newly initialized 1367 * pages before they are ever allocated, this should have no effect on 1368 * KASAN memory tracking as the poison will be properly inserted at page 1369 * allocation time. The only corner case is when pages are allocated by 1370 * on-demand allocation and then freed again before the deferred pages 1371 * initialization is done, but this is not likely to happen. 1372 */ 1373 static inline bool should_skip_kasan_poison(struct page *page, fpi_t fpi_flags) 1374 { 1375 return deferred_pages_enabled() || 1376 (!IS_ENABLED(CONFIG_KASAN_GENERIC) && 1377 (fpi_flags & FPI_SKIP_KASAN_POISON)) || 1378 PageSkipKASanPoison(page); 1379 } 1380 1381 static void kernel_init_pages(struct page *page, int numpages) 1382 { 1383 int i; 1384 1385 /* s390's use of memset() could override KASAN redzones. */ 1386 kasan_disable_current(); 1387 for (i = 0; i < numpages; i++) 1388 clear_highpage_kasan_tagged(page + i); 1389 kasan_enable_current(); 1390 } 1391 1392 static __always_inline bool free_pages_prepare(struct page *page, 1393 unsigned int order, bool check_free, fpi_t fpi_flags) 1394 { 1395 int bad = 0; 1396 bool init = want_init_on_free(); 1397 1398 VM_BUG_ON_PAGE(PageTail(page), page); 1399 1400 trace_mm_page_free(page, order); 1401 kmsan_free_page(page, order); 1402 1403 if (unlikely(PageHWPoison(page)) && !order) { 1404 /* 1405 * Do not let hwpoison pages hit pcplists/buddy 1406 * Untie memcg state and reset page's owner 1407 */ 1408 if (memcg_kmem_enabled() && PageMemcgKmem(page)) 1409 __memcg_kmem_uncharge_page(page, order); 1410 reset_page_owner(page, order); 1411 page_table_check_free(page, order); 1412 return false; 1413 } 1414 1415 /* 1416 * Check tail pages before head page information is cleared to 1417 * avoid checking PageCompound for order-0 pages. 1418 */ 1419 if (unlikely(order)) { 1420 bool compound = PageCompound(page); 1421 int i; 1422 1423 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page); 1424 1425 if (compound) 1426 ClearPageHasHWPoisoned(page); 1427 for (i = 1; i < (1 << order); i++) { 1428 if (compound) 1429 bad += free_tail_pages_check(page, page + i); 1430 if (unlikely(free_page_is_bad(page + i))) { 1431 bad++; 1432 continue; 1433 } 1434 (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP; 1435 } 1436 } 1437 if (PageMappingFlags(page)) 1438 page->mapping = NULL; 1439 if (memcg_kmem_enabled() && PageMemcgKmem(page)) 1440 __memcg_kmem_uncharge_page(page, order); 1441 if (check_free && free_page_is_bad(page)) 1442 bad++; 1443 if (bad) 1444 return false; 1445 1446 page_cpupid_reset_last(page); 1447 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP; 1448 reset_page_owner(page, order); 1449 page_table_check_free(page, order); 1450 1451 if (!PageHighMem(page)) { 1452 debug_check_no_locks_freed(page_address(page), 1453 PAGE_SIZE << order); 1454 debug_check_no_obj_freed(page_address(page), 1455 PAGE_SIZE << order); 1456 } 1457 1458 kernel_poison_pages(page, 1 << order); 1459 1460 /* 1461 * As memory initialization might be integrated into KASAN, 1462 * KASAN poisoning and memory initialization code must be 1463 * kept together to avoid discrepancies in behavior. 1464 * 1465 * With hardware tag-based KASAN, memory tags must be set before the 1466 * page becomes unavailable via debug_pagealloc or arch_free_page. 1467 */ 1468 if (!should_skip_kasan_poison(page, fpi_flags)) { 1469 kasan_poison_pages(page, order, init); 1470 1471 /* Memory is already initialized if KASAN did it internally. */ 1472 if (kasan_has_integrated_init()) 1473 init = false; 1474 } 1475 if (init) 1476 kernel_init_pages(page, 1 << order); 1477 1478 /* 1479 * arch_free_page() can make the page's contents inaccessible. s390 1480 * does this. So nothing which can access the page's contents should 1481 * happen after this. 1482 */ 1483 arch_free_page(page, order); 1484 1485 debug_pagealloc_unmap_pages(page, 1 << order); 1486 1487 return true; 1488 } 1489 1490 #ifdef CONFIG_DEBUG_VM 1491 /* 1492 * With DEBUG_VM enabled, order-0 pages are checked immediately when being freed 1493 * to pcp lists. With debug_pagealloc also enabled, they are also rechecked when 1494 * moved from pcp lists to free lists. 1495 */ 1496 static bool free_pcp_prepare(struct page *page, unsigned int order) 1497 { 1498 return free_pages_prepare(page, order, true, FPI_NONE); 1499 } 1500 1501 /* return true if this page has an inappropriate state */ 1502 static bool bulkfree_pcp_prepare(struct page *page) 1503 { 1504 if (debug_pagealloc_enabled_static()) 1505 return free_page_is_bad(page); 1506 else 1507 return false; 1508 } 1509 #else 1510 /* 1511 * With DEBUG_VM disabled, order-0 pages being freed are checked only when 1512 * moving from pcp lists to free list in order to reduce overhead. With 1513 * debug_pagealloc enabled, they are checked also immediately when being freed 1514 * to the pcp lists. 1515 */ 1516 static bool free_pcp_prepare(struct page *page, unsigned int order) 1517 { 1518 if (debug_pagealloc_enabled_static()) 1519 return free_pages_prepare(page, order, true, FPI_NONE); 1520 else 1521 return free_pages_prepare(page, order, false, FPI_NONE); 1522 } 1523 1524 static bool bulkfree_pcp_prepare(struct page *page) 1525 { 1526 return free_page_is_bad(page); 1527 } 1528 #endif /* CONFIG_DEBUG_VM */ 1529 1530 /* 1531 * Frees a number of pages from the PCP lists 1532 * Assumes all pages on list are in same zone. 1533 * count is the number of pages to free. 1534 */ 1535 static void free_pcppages_bulk(struct zone *zone, int count, 1536 struct per_cpu_pages *pcp, 1537 int pindex) 1538 { 1539 unsigned long flags; 1540 int min_pindex = 0; 1541 int max_pindex = NR_PCP_LISTS - 1; 1542 unsigned int order; 1543 bool isolated_pageblocks; 1544 struct page *page; 1545 1546 /* 1547 * Ensure proper count is passed which otherwise would stuck in the 1548 * below while (list_empty(list)) loop. 1549 */ 1550 count = min(pcp->count, count); 1551 1552 /* Ensure requested pindex is drained first. */ 1553 pindex = pindex - 1; 1554 1555 spin_lock_irqsave(&zone->lock, flags); 1556 isolated_pageblocks = has_isolate_pageblock(zone); 1557 1558 while (count > 0) { 1559 struct list_head *list; 1560 int nr_pages; 1561 1562 /* Remove pages from lists in a round-robin fashion. */ 1563 do { 1564 if (++pindex > max_pindex) 1565 pindex = min_pindex; 1566 list = &pcp->lists[pindex]; 1567 if (!list_empty(list)) 1568 break; 1569 1570 if (pindex == max_pindex) 1571 max_pindex--; 1572 if (pindex == min_pindex) 1573 min_pindex++; 1574 } while (1); 1575 1576 order = pindex_to_order(pindex); 1577 nr_pages = 1 << order; 1578 do { 1579 int mt; 1580 1581 page = list_last_entry(list, struct page, pcp_list); 1582 mt = get_pcppage_migratetype(page); 1583 1584 /* must delete to avoid corrupting pcp list */ 1585 list_del(&page->pcp_list); 1586 count -= nr_pages; 1587 pcp->count -= nr_pages; 1588 1589 if (bulkfree_pcp_prepare(page)) 1590 continue; 1591 1592 /* MIGRATE_ISOLATE page should not go to pcplists */ 1593 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page); 1594 /* Pageblock could have been isolated meanwhile */ 1595 if (unlikely(isolated_pageblocks)) 1596 mt = get_pageblock_migratetype(page); 1597 1598 __free_one_page(page, page_to_pfn(page), zone, order, mt, FPI_NONE); 1599 trace_mm_page_pcpu_drain(page, order, mt); 1600 } while (count > 0 && !list_empty(list)); 1601 } 1602 1603 spin_unlock_irqrestore(&zone->lock, flags); 1604 } 1605 1606 static void free_one_page(struct zone *zone, 1607 struct page *page, unsigned long pfn, 1608 unsigned int order, 1609 int migratetype, fpi_t fpi_flags) 1610 { 1611 unsigned long flags; 1612 1613 spin_lock_irqsave(&zone->lock, flags); 1614 if (unlikely(has_isolate_pageblock(zone) || 1615 is_migrate_isolate(migratetype))) { 1616 migratetype = get_pfnblock_migratetype(page, pfn); 1617 } 1618 __free_one_page(page, pfn, zone, order, migratetype, fpi_flags); 1619 spin_unlock_irqrestore(&zone->lock, flags); 1620 } 1621 1622 static void __meminit __init_single_page(struct page *page, unsigned long pfn, 1623 unsigned long zone, int nid) 1624 { 1625 mm_zero_struct_page(page); 1626 set_page_links(page, zone, nid, pfn); 1627 init_page_count(page); 1628 page_mapcount_reset(page); 1629 page_cpupid_reset_last(page); 1630 page_kasan_tag_reset(page); 1631 1632 INIT_LIST_HEAD(&page->lru); 1633 #ifdef WANT_PAGE_VIRTUAL 1634 /* The shift won't overflow because ZONE_NORMAL is below 4G. */ 1635 if (!is_highmem_idx(zone)) 1636 set_page_address(page, __va(pfn << PAGE_SHIFT)); 1637 #endif 1638 } 1639 1640 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 1641 static void __meminit init_reserved_page(unsigned long pfn) 1642 { 1643 pg_data_t *pgdat; 1644 int nid, zid; 1645 1646 if (early_page_initialised(pfn)) 1647 return; 1648 1649 nid = early_pfn_to_nid(pfn); 1650 pgdat = NODE_DATA(nid); 1651 1652 for (zid = 0; zid < MAX_NR_ZONES; zid++) { 1653 struct zone *zone = &pgdat->node_zones[zid]; 1654 1655 if (zone_spans_pfn(zone, pfn)) 1656 break; 1657 } 1658 __init_single_page(pfn_to_page(pfn), pfn, zid, nid); 1659 } 1660 #else 1661 static inline void init_reserved_page(unsigned long pfn) 1662 { 1663 } 1664 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */ 1665 1666 /* 1667 * Initialised pages do not have PageReserved set. This function is 1668 * called for each range allocated by the bootmem allocator and 1669 * marks the pages PageReserved. The remaining valid pages are later 1670 * sent to the buddy page allocator. 1671 */ 1672 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end) 1673 { 1674 unsigned long start_pfn = PFN_DOWN(start); 1675 unsigned long end_pfn = PFN_UP(end); 1676 1677 for (; start_pfn < end_pfn; start_pfn++) { 1678 if (pfn_valid(start_pfn)) { 1679 struct page *page = pfn_to_page(start_pfn); 1680 1681 init_reserved_page(start_pfn); 1682 1683 /* Avoid false-positive PageTail() */ 1684 INIT_LIST_HEAD(&page->lru); 1685 1686 /* 1687 * no need for atomic set_bit because the struct 1688 * page is not visible yet so nobody should 1689 * access it yet. 1690 */ 1691 __SetPageReserved(page); 1692 } 1693 } 1694 } 1695 1696 static void __free_pages_ok(struct page *page, unsigned int order, 1697 fpi_t fpi_flags) 1698 { 1699 unsigned long flags; 1700 int migratetype; 1701 unsigned long pfn = page_to_pfn(page); 1702 struct zone *zone = page_zone(page); 1703 1704 if (!free_pages_prepare(page, order, true, fpi_flags)) 1705 return; 1706 1707 /* 1708 * Calling get_pfnblock_migratetype() without spin_lock_irqsave() here 1709 * is used to avoid calling get_pfnblock_migratetype() under the lock. 1710 * This will reduce the lock holding time. 1711 */ 1712 migratetype = get_pfnblock_migratetype(page, pfn); 1713 1714 spin_lock_irqsave(&zone->lock, flags); 1715 if (unlikely(has_isolate_pageblock(zone) || 1716 is_migrate_isolate(migratetype))) { 1717 migratetype = get_pfnblock_migratetype(page, pfn); 1718 } 1719 __free_one_page(page, pfn, zone, order, migratetype, fpi_flags); 1720 spin_unlock_irqrestore(&zone->lock, flags); 1721 1722 __count_vm_events(PGFREE, 1 << order); 1723 } 1724 1725 void __free_pages_core(struct page *page, unsigned int order) 1726 { 1727 unsigned int nr_pages = 1 << order; 1728 struct page *p = page; 1729 unsigned int loop; 1730 1731 /* 1732 * When initializing the memmap, __init_single_page() sets the refcount 1733 * of all pages to 1 ("allocated"/"not free"). We have to set the 1734 * refcount of all involved pages to 0. 1735 */ 1736 prefetchw(p); 1737 for (loop = 0; loop < (nr_pages - 1); loop++, p++) { 1738 prefetchw(p + 1); 1739 __ClearPageReserved(p); 1740 set_page_count(p, 0); 1741 } 1742 __ClearPageReserved(p); 1743 set_page_count(p, 0); 1744 1745 atomic_long_add(nr_pages, &page_zone(page)->managed_pages); 1746 1747 /* 1748 * Bypass PCP and place fresh pages right to the tail, primarily 1749 * relevant for memory onlining. 1750 */ 1751 __free_pages_ok(page, order, FPI_TO_TAIL | FPI_SKIP_KASAN_POISON); 1752 } 1753 1754 #ifdef CONFIG_NUMA 1755 1756 /* 1757 * During memory init memblocks map pfns to nids. The search is expensive and 1758 * this caches recent lookups. The implementation of __early_pfn_to_nid 1759 * treats start/end as pfns. 1760 */ 1761 struct mminit_pfnnid_cache { 1762 unsigned long last_start; 1763 unsigned long last_end; 1764 int last_nid; 1765 }; 1766 1767 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata; 1768 1769 /* 1770 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on. 1771 */ 1772 static int __meminit __early_pfn_to_nid(unsigned long pfn, 1773 struct mminit_pfnnid_cache *state) 1774 { 1775 unsigned long start_pfn, end_pfn; 1776 int nid; 1777 1778 if (state->last_start <= pfn && pfn < state->last_end) 1779 return state->last_nid; 1780 1781 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn); 1782 if (nid != NUMA_NO_NODE) { 1783 state->last_start = start_pfn; 1784 state->last_end = end_pfn; 1785 state->last_nid = nid; 1786 } 1787 1788 return nid; 1789 } 1790 1791 int __meminit early_pfn_to_nid(unsigned long pfn) 1792 { 1793 static DEFINE_SPINLOCK(early_pfn_lock); 1794 int nid; 1795 1796 spin_lock(&early_pfn_lock); 1797 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache); 1798 if (nid < 0) 1799 nid = first_online_node; 1800 spin_unlock(&early_pfn_lock); 1801 1802 return nid; 1803 } 1804 #endif /* CONFIG_NUMA */ 1805 1806 void __init memblock_free_pages(struct page *page, unsigned long pfn, 1807 unsigned int order) 1808 { 1809 if (!early_page_initialised(pfn)) 1810 return; 1811 if (!kmsan_memblock_free_pages(page, order)) { 1812 /* KMSAN will take care of these pages. */ 1813 return; 1814 } 1815 __free_pages_core(page, order); 1816 } 1817 1818 /* 1819 * Check that the whole (or subset of) a pageblock given by the interval of 1820 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it 1821 * with the migration of free compaction scanner. 1822 * 1823 * Return struct page pointer of start_pfn, or NULL if checks were not passed. 1824 * 1825 * It's possible on some configurations to have a setup like node0 node1 node0 1826 * i.e. it's possible that all pages within a zones range of pages do not 1827 * belong to a single zone. We assume that a border between node0 and node1 1828 * can occur within a single pageblock, but not a node0 node1 node0 1829 * interleaving within a single pageblock. It is therefore sufficient to check 1830 * the first and last page of a pageblock and avoid checking each individual 1831 * page in a pageblock. 1832 */ 1833 struct page *__pageblock_pfn_to_page(unsigned long start_pfn, 1834 unsigned long end_pfn, struct zone *zone) 1835 { 1836 struct page *start_page; 1837 struct page *end_page; 1838 1839 /* end_pfn is one past the range we are checking */ 1840 end_pfn--; 1841 1842 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn)) 1843 return NULL; 1844 1845 start_page = pfn_to_online_page(start_pfn); 1846 if (!start_page) 1847 return NULL; 1848 1849 if (page_zone(start_page) != zone) 1850 return NULL; 1851 1852 end_page = pfn_to_page(end_pfn); 1853 1854 /* This gives a shorter code than deriving page_zone(end_page) */ 1855 if (page_zone_id(start_page) != page_zone_id(end_page)) 1856 return NULL; 1857 1858 return start_page; 1859 } 1860 1861 void set_zone_contiguous(struct zone *zone) 1862 { 1863 unsigned long block_start_pfn = zone->zone_start_pfn; 1864 unsigned long block_end_pfn; 1865 1866 block_end_pfn = pageblock_end_pfn(block_start_pfn); 1867 for (; block_start_pfn < zone_end_pfn(zone); 1868 block_start_pfn = block_end_pfn, 1869 block_end_pfn += pageblock_nr_pages) { 1870 1871 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone)); 1872 1873 if (!__pageblock_pfn_to_page(block_start_pfn, 1874 block_end_pfn, zone)) 1875 return; 1876 cond_resched(); 1877 } 1878 1879 /* We confirm that there is no hole */ 1880 zone->contiguous = true; 1881 } 1882 1883 void clear_zone_contiguous(struct zone *zone) 1884 { 1885 zone->contiguous = false; 1886 } 1887 1888 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 1889 static void __init deferred_free_range(unsigned long pfn, 1890 unsigned long nr_pages) 1891 { 1892 struct page *page; 1893 unsigned long i; 1894 1895 if (!nr_pages) 1896 return; 1897 1898 page = pfn_to_page(pfn); 1899 1900 /* Free a large naturally-aligned chunk if possible */ 1901 if (nr_pages == pageblock_nr_pages && pageblock_aligned(pfn)) { 1902 set_pageblock_migratetype(page, MIGRATE_MOVABLE); 1903 __free_pages_core(page, pageblock_order); 1904 return; 1905 } 1906 1907 for (i = 0; i < nr_pages; i++, page++, pfn++) { 1908 if (pageblock_aligned(pfn)) 1909 set_pageblock_migratetype(page, MIGRATE_MOVABLE); 1910 __free_pages_core(page, 0); 1911 } 1912 } 1913 1914 /* Completion tracking for deferred_init_memmap() threads */ 1915 static atomic_t pgdat_init_n_undone __initdata; 1916 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp); 1917 1918 static inline void __init pgdat_init_report_one_done(void) 1919 { 1920 if (atomic_dec_and_test(&pgdat_init_n_undone)) 1921 complete(&pgdat_init_all_done_comp); 1922 } 1923 1924 /* 1925 * Returns true if page needs to be initialized or freed to buddy allocator. 1926 * 1927 * We check if a current large page is valid by only checking the validity 1928 * of the head pfn. 1929 */ 1930 static inline bool __init deferred_pfn_valid(unsigned long pfn) 1931 { 1932 if (pageblock_aligned(pfn) && !pfn_valid(pfn)) 1933 return false; 1934 return true; 1935 } 1936 1937 /* 1938 * Free pages to buddy allocator. Try to free aligned pages in 1939 * pageblock_nr_pages sizes. 1940 */ 1941 static void __init deferred_free_pages(unsigned long pfn, 1942 unsigned long end_pfn) 1943 { 1944 unsigned long nr_free = 0; 1945 1946 for (; pfn < end_pfn; pfn++) { 1947 if (!deferred_pfn_valid(pfn)) { 1948 deferred_free_range(pfn - nr_free, nr_free); 1949 nr_free = 0; 1950 } else if (pageblock_aligned(pfn)) { 1951 deferred_free_range(pfn - nr_free, nr_free); 1952 nr_free = 1; 1953 } else { 1954 nr_free++; 1955 } 1956 } 1957 /* Free the last block of pages to allocator */ 1958 deferred_free_range(pfn - nr_free, nr_free); 1959 } 1960 1961 /* 1962 * Initialize struct pages. We minimize pfn page lookups and scheduler checks 1963 * by performing it only once every pageblock_nr_pages. 1964 * Return number of pages initialized. 1965 */ 1966 static unsigned long __init deferred_init_pages(struct zone *zone, 1967 unsigned long pfn, 1968 unsigned long end_pfn) 1969 { 1970 int nid = zone_to_nid(zone); 1971 unsigned long nr_pages = 0; 1972 int zid = zone_idx(zone); 1973 struct page *page = NULL; 1974 1975 for (; pfn < end_pfn; pfn++) { 1976 if (!deferred_pfn_valid(pfn)) { 1977 page = NULL; 1978 continue; 1979 } else if (!page || pageblock_aligned(pfn)) { 1980 page = pfn_to_page(pfn); 1981 } else { 1982 page++; 1983 } 1984 __init_single_page(page, pfn, zid, nid); 1985 nr_pages++; 1986 } 1987 return (nr_pages); 1988 } 1989 1990 /* 1991 * This function is meant to pre-load the iterator for the zone init. 1992 * Specifically it walks through the ranges until we are caught up to the 1993 * first_init_pfn value and exits there. If we never encounter the value we 1994 * return false indicating there are no valid ranges left. 1995 */ 1996 static bool __init 1997 deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone, 1998 unsigned long *spfn, unsigned long *epfn, 1999 unsigned long first_init_pfn) 2000 { 2001 u64 j; 2002 2003 /* 2004 * Start out by walking through the ranges in this zone that have 2005 * already been initialized. We don't need to do anything with them 2006 * so we just need to flush them out of the system. 2007 */ 2008 for_each_free_mem_pfn_range_in_zone(j, zone, spfn, epfn) { 2009 if (*epfn <= first_init_pfn) 2010 continue; 2011 if (*spfn < first_init_pfn) 2012 *spfn = first_init_pfn; 2013 *i = j; 2014 return true; 2015 } 2016 2017 return false; 2018 } 2019 2020 /* 2021 * Initialize and free pages. We do it in two loops: first we initialize 2022 * struct page, then free to buddy allocator, because while we are 2023 * freeing pages we can access pages that are ahead (computing buddy 2024 * page in __free_one_page()). 2025 * 2026 * In order to try and keep some memory in the cache we have the loop 2027 * broken along max page order boundaries. This way we will not cause 2028 * any issues with the buddy page computation. 2029 */ 2030 static unsigned long __init 2031 deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn, 2032 unsigned long *end_pfn) 2033 { 2034 unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES); 2035 unsigned long spfn = *start_pfn, epfn = *end_pfn; 2036 unsigned long nr_pages = 0; 2037 u64 j = *i; 2038 2039 /* First we loop through and initialize the page values */ 2040 for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) { 2041 unsigned long t; 2042 2043 if (mo_pfn <= *start_pfn) 2044 break; 2045 2046 t = min(mo_pfn, *end_pfn); 2047 nr_pages += deferred_init_pages(zone, *start_pfn, t); 2048 2049 if (mo_pfn < *end_pfn) { 2050 *start_pfn = mo_pfn; 2051 break; 2052 } 2053 } 2054 2055 /* Reset values and now loop through freeing pages as needed */ 2056 swap(j, *i); 2057 2058 for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) { 2059 unsigned long t; 2060 2061 if (mo_pfn <= spfn) 2062 break; 2063 2064 t = min(mo_pfn, epfn); 2065 deferred_free_pages(spfn, t); 2066 2067 if (mo_pfn <= epfn) 2068 break; 2069 } 2070 2071 return nr_pages; 2072 } 2073 2074 static void __init 2075 deferred_init_memmap_chunk(unsigned long start_pfn, unsigned long end_pfn, 2076 void *arg) 2077 { 2078 unsigned long spfn, epfn; 2079 struct zone *zone = arg; 2080 u64 i; 2081 2082 deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, start_pfn); 2083 2084 /* 2085 * Initialize and free pages in MAX_ORDER sized increments so that we 2086 * can avoid introducing any issues with the buddy allocator. 2087 */ 2088 while (spfn < end_pfn) { 2089 deferred_init_maxorder(&i, zone, &spfn, &epfn); 2090 cond_resched(); 2091 } 2092 } 2093 2094 /* An arch may override for more concurrency. */ 2095 __weak int __init 2096 deferred_page_init_max_threads(const struct cpumask *node_cpumask) 2097 { 2098 return 1; 2099 } 2100 2101 /* Initialise remaining memory on a node */ 2102 static int __init deferred_init_memmap(void *data) 2103 { 2104 pg_data_t *pgdat = data; 2105 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id); 2106 unsigned long spfn = 0, epfn = 0; 2107 unsigned long first_init_pfn, flags; 2108 unsigned long start = jiffies; 2109 struct zone *zone; 2110 int zid, max_threads; 2111 u64 i; 2112 2113 /* Bind memory initialisation thread to a local node if possible */ 2114 if (!cpumask_empty(cpumask)) 2115 set_cpus_allowed_ptr(current, cpumask); 2116 2117 pgdat_resize_lock(pgdat, &flags); 2118 first_init_pfn = pgdat->first_deferred_pfn; 2119 if (first_init_pfn == ULONG_MAX) { 2120 pgdat_resize_unlock(pgdat, &flags); 2121 pgdat_init_report_one_done(); 2122 return 0; 2123 } 2124 2125 /* Sanity check boundaries */ 2126 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn); 2127 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat)); 2128 pgdat->first_deferred_pfn = ULONG_MAX; 2129 2130 /* 2131 * Once we unlock here, the zone cannot be grown anymore, thus if an 2132 * interrupt thread must allocate this early in boot, zone must be 2133 * pre-grown prior to start of deferred page initialization. 2134 */ 2135 pgdat_resize_unlock(pgdat, &flags); 2136 2137 /* Only the highest zone is deferred so find it */ 2138 for (zid = 0; zid < MAX_NR_ZONES; zid++) { 2139 zone = pgdat->node_zones + zid; 2140 if (first_init_pfn < zone_end_pfn(zone)) 2141 break; 2142 } 2143 2144 /* If the zone is empty somebody else may have cleared out the zone */ 2145 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, 2146 first_init_pfn)) 2147 goto zone_empty; 2148 2149 max_threads = deferred_page_init_max_threads(cpumask); 2150 2151 while (spfn < epfn) { 2152 unsigned long epfn_align = ALIGN(epfn, PAGES_PER_SECTION); 2153 struct padata_mt_job job = { 2154 .thread_fn = deferred_init_memmap_chunk, 2155 .fn_arg = zone, 2156 .start = spfn, 2157 .size = epfn_align - spfn, 2158 .align = PAGES_PER_SECTION, 2159 .min_chunk = PAGES_PER_SECTION, 2160 .max_threads = max_threads, 2161 }; 2162 2163 padata_do_multithreaded(&job); 2164 deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, 2165 epfn_align); 2166 } 2167 zone_empty: 2168 /* Sanity check that the next zone really is unpopulated */ 2169 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone)); 2170 2171 pr_info("node %d deferred pages initialised in %ums\n", 2172 pgdat->node_id, jiffies_to_msecs(jiffies - start)); 2173 2174 pgdat_init_report_one_done(); 2175 return 0; 2176 } 2177 2178 /* 2179 * If this zone has deferred pages, try to grow it by initializing enough 2180 * deferred pages to satisfy the allocation specified by order, rounded up to 2181 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments 2182 * of SECTION_SIZE bytes by initializing struct pages in increments of 2183 * PAGES_PER_SECTION * sizeof(struct page) bytes. 2184 * 2185 * Return true when zone was grown, otherwise return false. We return true even 2186 * when we grow less than requested, to let the caller decide if there are 2187 * enough pages to satisfy the allocation. 2188 * 2189 * Note: We use noinline because this function is needed only during boot, and 2190 * it is called from a __ref function _deferred_grow_zone. This way we are 2191 * making sure that it is not inlined into permanent text section. 2192 */ 2193 static noinline bool __init 2194 deferred_grow_zone(struct zone *zone, unsigned int order) 2195 { 2196 unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION); 2197 pg_data_t *pgdat = zone->zone_pgdat; 2198 unsigned long first_deferred_pfn = pgdat->first_deferred_pfn; 2199 unsigned long spfn, epfn, flags; 2200 unsigned long nr_pages = 0; 2201 u64 i; 2202 2203 /* Only the last zone may have deferred pages */ 2204 if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat)) 2205 return false; 2206 2207 pgdat_resize_lock(pgdat, &flags); 2208 2209 /* 2210 * If someone grew this zone while we were waiting for spinlock, return 2211 * true, as there might be enough pages already. 2212 */ 2213 if (first_deferred_pfn != pgdat->first_deferred_pfn) { 2214 pgdat_resize_unlock(pgdat, &flags); 2215 return true; 2216 } 2217 2218 /* If the zone is empty somebody else may have cleared out the zone */ 2219 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, 2220 first_deferred_pfn)) { 2221 pgdat->first_deferred_pfn = ULONG_MAX; 2222 pgdat_resize_unlock(pgdat, &flags); 2223 /* Retry only once. */ 2224 return first_deferred_pfn != ULONG_MAX; 2225 } 2226 2227 /* 2228 * Initialize and free pages in MAX_ORDER sized increments so 2229 * that we can avoid introducing any issues with the buddy 2230 * allocator. 2231 */ 2232 while (spfn < epfn) { 2233 /* update our first deferred PFN for this section */ 2234 first_deferred_pfn = spfn; 2235 2236 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn); 2237 touch_nmi_watchdog(); 2238 2239 /* We should only stop along section boundaries */ 2240 if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION) 2241 continue; 2242 2243 /* If our quota has been met we can stop here */ 2244 if (nr_pages >= nr_pages_needed) 2245 break; 2246 } 2247 2248 pgdat->first_deferred_pfn = spfn; 2249 pgdat_resize_unlock(pgdat, &flags); 2250 2251 return nr_pages > 0; 2252 } 2253 2254 /* 2255 * deferred_grow_zone() is __init, but it is called from 2256 * get_page_from_freelist() during early boot until deferred_pages permanently 2257 * disables this call. This is why we have refdata wrapper to avoid warning, 2258 * and to ensure that the function body gets unloaded. 2259 */ 2260 static bool __ref 2261 _deferred_grow_zone(struct zone *zone, unsigned int order) 2262 { 2263 return deferred_grow_zone(zone, order); 2264 } 2265 2266 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */ 2267 2268 void __init page_alloc_init_late(void) 2269 { 2270 struct zone *zone; 2271 int nid; 2272 2273 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 2274 2275 /* There will be num_node_state(N_MEMORY) threads */ 2276 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY)); 2277 for_each_node_state(nid, N_MEMORY) { 2278 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid); 2279 } 2280 2281 /* Block until all are initialised */ 2282 wait_for_completion(&pgdat_init_all_done_comp); 2283 2284 /* 2285 * We initialized the rest of the deferred pages. Permanently disable 2286 * on-demand struct page initialization. 2287 */ 2288 static_branch_disable(&deferred_pages); 2289 2290 /* Reinit limits that are based on free pages after the kernel is up */ 2291 files_maxfiles_init(); 2292 #endif 2293 2294 buffer_init(); 2295 2296 /* Discard memblock private memory */ 2297 memblock_discard(); 2298 2299 for_each_node_state(nid, N_MEMORY) 2300 shuffle_free_memory(NODE_DATA(nid)); 2301 2302 for_each_populated_zone(zone) 2303 set_zone_contiguous(zone); 2304 } 2305 2306 #ifdef CONFIG_CMA 2307 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */ 2308 void __init init_cma_reserved_pageblock(struct page *page) 2309 { 2310 unsigned i = pageblock_nr_pages; 2311 struct page *p = page; 2312 2313 do { 2314 __ClearPageReserved(p); 2315 set_page_count(p, 0); 2316 } while (++p, --i); 2317 2318 set_pageblock_migratetype(page, MIGRATE_CMA); 2319 set_page_refcounted(page); 2320 __free_pages(page, pageblock_order); 2321 2322 adjust_managed_page_count(page, pageblock_nr_pages); 2323 page_zone(page)->cma_pages += pageblock_nr_pages; 2324 } 2325 #endif 2326 2327 /* 2328 * The order of subdivision here is critical for the IO subsystem. 2329 * Please do not alter this order without good reasons and regression 2330 * testing. Specifically, as large blocks of memory are subdivided, 2331 * the order in which smaller blocks are delivered depends on the order 2332 * they're subdivided in this function. This is the primary factor 2333 * influencing the order in which pages are delivered to the IO 2334 * subsystem according to empirical testing, and this is also justified 2335 * by considering the behavior of a buddy system containing a single 2336 * large block of memory acted on by a series of small allocations. 2337 * This behavior is a critical factor in sglist merging's success. 2338 * 2339 * -- nyc 2340 */ 2341 static inline void expand(struct zone *zone, struct page *page, 2342 int low, int high, int migratetype) 2343 { 2344 unsigned long size = 1 << high; 2345 2346 while (high > low) { 2347 high--; 2348 size >>= 1; 2349 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]); 2350 2351 /* 2352 * Mark as guard pages (or page), that will allow to 2353 * merge back to allocator when buddy will be freed. 2354 * Corresponding page table entries will not be touched, 2355 * pages will stay not present in virtual address space 2356 */ 2357 if (set_page_guard(zone, &page[size], high, migratetype)) 2358 continue; 2359 2360 add_to_free_list(&page[size], zone, high, migratetype); 2361 set_buddy_order(&page[size], high); 2362 } 2363 } 2364 2365 static void check_new_page_bad(struct page *page) 2366 { 2367 if (unlikely(page->flags & __PG_HWPOISON)) { 2368 /* Don't complain about hwpoisoned pages */ 2369 page_mapcount_reset(page); /* remove PageBuddy */ 2370 return; 2371 } 2372 2373 bad_page(page, 2374 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_PREP)); 2375 } 2376 2377 /* 2378 * This page is about to be returned from the page allocator 2379 */ 2380 static inline int check_new_page(struct page *page) 2381 { 2382 if (likely(page_expected_state(page, 2383 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON))) 2384 return 0; 2385 2386 check_new_page_bad(page); 2387 return 1; 2388 } 2389 2390 static bool check_new_pages(struct page *page, unsigned int order) 2391 { 2392 int i; 2393 for (i = 0; i < (1 << order); i++) { 2394 struct page *p = page + i; 2395 2396 if (unlikely(check_new_page(p))) 2397 return true; 2398 } 2399 2400 return false; 2401 } 2402 2403 #ifdef CONFIG_DEBUG_VM 2404 /* 2405 * With DEBUG_VM enabled, order-0 pages are checked for expected state when 2406 * being allocated from pcp lists. With debug_pagealloc also enabled, they are 2407 * also checked when pcp lists are refilled from the free lists. 2408 */ 2409 static inline bool check_pcp_refill(struct page *page, unsigned int order) 2410 { 2411 if (debug_pagealloc_enabled_static()) 2412 return check_new_pages(page, order); 2413 else 2414 return false; 2415 } 2416 2417 static inline bool check_new_pcp(struct page *page, unsigned int order) 2418 { 2419 return check_new_pages(page, order); 2420 } 2421 #else 2422 /* 2423 * With DEBUG_VM disabled, free order-0 pages are checked for expected state 2424 * when pcp lists are being refilled from the free lists. With debug_pagealloc 2425 * enabled, they are also checked when being allocated from the pcp lists. 2426 */ 2427 static inline bool check_pcp_refill(struct page *page, unsigned int order) 2428 { 2429 return check_new_pages(page, order); 2430 } 2431 static inline bool check_new_pcp(struct page *page, unsigned int order) 2432 { 2433 if (debug_pagealloc_enabled_static()) 2434 return check_new_pages(page, order); 2435 else 2436 return false; 2437 } 2438 #endif /* CONFIG_DEBUG_VM */ 2439 2440 static inline bool should_skip_kasan_unpoison(gfp_t flags) 2441 { 2442 /* Don't skip if a software KASAN mode is enabled. */ 2443 if (IS_ENABLED(CONFIG_KASAN_GENERIC) || 2444 IS_ENABLED(CONFIG_KASAN_SW_TAGS)) 2445 return false; 2446 2447 /* Skip, if hardware tag-based KASAN is not enabled. */ 2448 if (!kasan_hw_tags_enabled()) 2449 return true; 2450 2451 /* 2452 * With hardware tag-based KASAN enabled, skip if this has been 2453 * requested via __GFP_SKIP_KASAN_UNPOISON. 2454 */ 2455 return flags & __GFP_SKIP_KASAN_UNPOISON; 2456 } 2457 2458 static inline bool should_skip_init(gfp_t flags) 2459 { 2460 /* Don't skip, if hardware tag-based KASAN is not enabled. */ 2461 if (!kasan_hw_tags_enabled()) 2462 return false; 2463 2464 /* For hardware tag-based KASAN, skip if requested. */ 2465 return (flags & __GFP_SKIP_ZERO); 2466 } 2467 2468 inline void post_alloc_hook(struct page *page, unsigned int order, 2469 gfp_t gfp_flags) 2470 { 2471 bool init = !want_init_on_free() && want_init_on_alloc(gfp_flags) && 2472 !should_skip_init(gfp_flags); 2473 bool zero_tags = init && (gfp_flags & __GFP_ZEROTAGS); 2474 bool reset_tags = !zero_tags; 2475 int i; 2476 2477 set_page_private(page, 0); 2478 set_page_refcounted(page); 2479 2480 arch_alloc_page(page, order); 2481 debug_pagealloc_map_pages(page, 1 << order); 2482 2483 /* 2484 * Page unpoisoning must happen before memory initialization. 2485 * Otherwise, the poison pattern will be overwritten for __GFP_ZERO 2486 * allocations and the page unpoisoning code will complain. 2487 */ 2488 kernel_unpoison_pages(page, 1 << order); 2489 2490 /* 2491 * As memory initialization might be integrated into KASAN, 2492 * KASAN unpoisoning and memory initializion code must be 2493 * kept together to avoid discrepancies in behavior. 2494 */ 2495 2496 /* 2497 * If memory tags should be zeroed 2498 * (which happens only when memory should be initialized as well). 2499 */ 2500 if (zero_tags) { 2501 /* Initialize both memory and tags. */ 2502 for (i = 0; i != 1 << order; ++i) 2503 tag_clear_highpage(page + i); 2504 2505 /* Take note that memory was initialized by the loop above. */ 2506 init = false; 2507 } 2508 if (!should_skip_kasan_unpoison(gfp_flags)) { 2509 /* Try unpoisoning (or setting tags) and initializing memory. */ 2510 if (kasan_unpoison_pages(page, order, init)) { 2511 /* Take note that memory was initialized by KASAN. */ 2512 if (kasan_has_integrated_init()) 2513 init = false; 2514 /* Take note that memory tags were set by KASAN. */ 2515 reset_tags = false; 2516 } else { 2517 /* 2518 * KASAN decided to exclude this allocation from being 2519 * poisoned due to sampling. Skip poisoning as well. 2520 */ 2521 SetPageSkipKASanPoison(page); 2522 } 2523 } 2524 /* 2525 * If memory tags have not been set, reset the page tags to ensure 2526 * page_address() dereferencing does not fault. 2527 */ 2528 if (reset_tags) { 2529 for (i = 0; i != 1 << order; ++i) 2530 page_kasan_tag_reset(page + i); 2531 } 2532 /* If memory is still not initialized, initialize it now. */ 2533 if (init) 2534 kernel_init_pages(page, 1 << order); 2535 /* Propagate __GFP_SKIP_KASAN_POISON to page flags. */ 2536 if (kasan_hw_tags_enabled() && (gfp_flags & __GFP_SKIP_KASAN_POISON)) 2537 SetPageSkipKASanPoison(page); 2538 2539 set_page_owner(page, order, gfp_flags); 2540 page_table_check_alloc(page, order); 2541 } 2542 2543 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags, 2544 unsigned int alloc_flags) 2545 { 2546 post_alloc_hook(page, order, gfp_flags); 2547 2548 if (order && (gfp_flags & __GFP_COMP)) 2549 prep_compound_page(page, order); 2550 2551 /* 2552 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to 2553 * allocate the page. The expectation is that the caller is taking 2554 * steps that will free more memory. The caller should avoid the page 2555 * being used for !PFMEMALLOC purposes. 2556 */ 2557 if (alloc_flags & ALLOC_NO_WATERMARKS) 2558 set_page_pfmemalloc(page); 2559 else 2560 clear_page_pfmemalloc(page); 2561 } 2562 2563 /* 2564 * Go through the free lists for the given migratetype and remove 2565 * the smallest available page from the freelists 2566 */ 2567 static __always_inline 2568 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order, 2569 int migratetype) 2570 { 2571 unsigned int current_order; 2572 struct free_area *area; 2573 struct page *page; 2574 2575 /* Find a page of the appropriate size in the preferred list */ 2576 for (current_order = order; current_order < MAX_ORDER; ++current_order) { 2577 area = &(zone->free_area[current_order]); 2578 page = get_page_from_free_area(area, migratetype); 2579 if (!page) 2580 continue; 2581 del_page_from_free_list(page, zone, current_order); 2582 expand(zone, page, order, current_order, migratetype); 2583 set_pcppage_migratetype(page, migratetype); 2584 trace_mm_page_alloc_zone_locked(page, order, migratetype, 2585 pcp_allowed_order(order) && 2586 migratetype < MIGRATE_PCPTYPES); 2587 return page; 2588 } 2589 2590 return NULL; 2591 } 2592 2593 2594 /* 2595 * This array describes the order lists are fallen back to when 2596 * the free lists for the desirable migrate type are depleted 2597 * 2598 * The other migratetypes do not have fallbacks. 2599 */ 2600 static int fallbacks[MIGRATE_TYPES][3] = { 2601 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES }, 2602 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES }, 2603 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES }, 2604 }; 2605 2606 #ifdef CONFIG_CMA 2607 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone, 2608 unsigned int order) 2609 { 2610 return __rmqueue_smallest(zone, order, MIGRATE_CMA); 2611 } 2612 #else 2613 static inline struct page *__rmqueue_cma_fallback(struct zone *zone, 2614 unsigned int order) { return NULL; } 2615 #endif 2616 2617 /* 2618 * Move the free pages in a range to the freelist tail of the requested type. 2619 * Note that start_page and end_pages are not aligned on a pageblock 2620 * boundary. If alignment is required, use move_freepages_block() 2621 */ 2622 static int move_freepages(struct zone *zone, 2623 unsigned long start_pfn, unsigned long end_pfn, 2624 int migratetype, int *num_movable) 2625 { 2626 struct page *page; 2627 unsigned long pfn; 2628 unsigned int order; 2629 int pages_moved = 0; 2630 2631 for (pfn = start_pfn; pfn <= end_pfn;) { 2632 page = pfn_to_page(pfn); 2633 if (!PageBuddy(page)) { 2634 /* 2635 * We assume that pages that could be isolated for 2636 * migration are movable. But we don't actually try 2637 * isolating, as that would be expensive. 2638 */ 2639 if (num_movable && 2640 (PageLRU(page) || __PageMovable(page))) 2641 (*num_movable)++; 2642 pfn++; 2643 continue; 2644 } 2645 2646 /* Make sure we are not inadvertently changing nodes */ 2647 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page); 2648 VM_BUG_ON_PAGE(page_zone(page) != zone, page); 2649 2650 order = buddy_order(page); 2651 move_to_free_list(page, zone, order, migratetype); 2652 pfn += 1 << order; 2653 pages_moved += 1 << order; 2654 } 2655 2656 return pages_moved; 2657 } 2658 2659 int move_freepages_block(struct zone *zone, struct page *page, 2660 int migratetype, int *num_movable) 2661 { 2662 unsigned long start_pfn, end_pfn, pfn; 2663 2664 if (num_movable) 2665 *num_movable = 0; 2666 2667 pfn = page_to_pfn(page); 2668 start_pfn = pageblock_start_pfn(pfn); 2669 end_pfn = pageblock_end_pfn(pfn) - 1; 2670 2671 /* Do not cross zone boundaries */ 2672 if (!zone_spans_pfn(zone, start_pfn)) 2673 start_pfn = pfn; 2674 if (!zone_spans_pfn(zone, end_pfn)) 2675 return 0; 2676 2677 return move_freepages(zone, start_pfn, end_pfn, migratetype, 2678 num_movable); 2679 } 2680 2681 static void change_pageblock_range(struct page *pageblock_page, 2682 int start_order, int migratetype) 2683 { 2684 int nr_pageblocks = 1 << (start_order - pageblock_order); 2685 2686 while (nr_pageblocks--) { 2687 set_pageblock_migratetype(pageblock_page, migratetype); 2688 pageblock_page += pageblock_nr_pages; 2689 } 2690 } 2691 2692 /* 2693 * When we are falling back to another migratetype during allocation, try to 2694 * steal extra free pages from the same pageblocks to satisfy further 2695 * allocations, instead of polluting multiple pageblocks. 2696 * 2697 * If we are stealing a relatively large buddy page, it is likely there will 2698 * be more free pages in the pageblock, so try to steal them all. For 2699 * reclaimable and unmovable allocations, we steal regardless of page size, 2700 * as fragmentation caused by those allocations polluting movable pageblocks 2701 * is worse than movable allocations stealing from unmovable and reclaimable 2702 * pageblocks. 2703 */ 2704 static bool can_steal_fallback(unsigned int order, int start_mt) 2705 { 2706 /* 2707 * Leaving this order check is intended, although there is 2708 * relaxed order check in next check. The reason is that 2709 * we can actually steal whole pageblock if this condition met, 2710 * but, below check doesn't guarantee it and that is just heuristic 2711 * so could be changed anytime. 2712 */ 2713 if (order >= pageblock_order) 2714 return true; 2715 2716 if (order >= pageblock_order / 2 || 2717 start_mt == MIGRATE_RECLAIMABLE || 2718 start_mt == MIGRATE_UNMOVABLE || 2719 page_group_by_mobility_disabled) 2720 return true; 2721 2722 return false; 2723 } 2724 2725 static inline bool boost_watermark(struct zone *zone) 2726 { 2727 unsigned long max_boost; 2728 2729 if (!watermark_boost_factor) 2730 return false; 2731 /* 2732 * Don't bother in zones that are unlikely to produce results. 2733 * On small machines, including kdump capture kernels running 2734 * in a small area, boosting the watermark can cause an out of 2735 * memory situation immediately. 2736 */ 2737 if ((pageblock_nr_pages * 4) > zone_managed_pages(zone)) 2738 return false; 2739 2740 max_boost = mult_frac(zone->_watermark[WMARK_HIGH], 2741 watermark_boost_factor, 10000); 2742 2743 /* 2744 * high watermark may be uninitialised if fragmentation occurs 2745 * very early in boot so do not boost. We do not fall 2746 * through and boost by pageblock_nr_pages as failing 2747 * allocations that early means that reclaim is not going 2748 * to help and it may even be impossible to reclaim the 2749 * boosted watermark resulting in a hang. 2750 */ 2751 if (!max_boost) 2752 return false; 2753 2754 max_boost = max(pageblock_nr_pages, max_boost); 2755 2756 zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages, 2757 max_boost); 2758 2759 return true; 2760 } 2761 2762 /* 2763 * This function implements actual steal behaviour. If order is large enough, 2764 * we can steal whole pageblock. If not, we first move freepages in this 2765 * pageblock to our migratetype and determine how many already-allocated pages 2766 * are there in the pageblock with a compatible migratetype. If at least half 2767 * of pages are free or compatible, we can change migratetype of the pageblock 2768 * itself, so pages freed in the future will be put on the correct free list. 2769 */ 2770 static void steal_suitable_fallback(struct zone *zone, struct page *page, 2771 unsigned int alloc_flags, int start_type, bool whole_block) 2772 { 2773 unsigned int current_order = buddy_order(page); 2774 int free_pages, movable_pages, alike_pages; 2775 int old_block_type; 2776 2777 old_block_type = get_pageblock_migratetype(page); 2778 2779 /* 2780 * This can happen due to races and we want to prevent broken 2781 * highatomic accounting. 2782 */ 2783 if (is_migrate_highatomic(old_block_type)) 2784 goto single_page; 2785 2786 /* Take ownership for orders >= pageblock_order */ 2787 if (current_order >= pageblock_order) { 2788 change_pageblock_range(page, current_order, start_type); 2789 goto single_page; 2790 } 2791 2792 /* 2793 * Boost watermarks to increase reclaim pressure to reduce the 2794 * likelihood of future fallbacks. Wake kswapd now as the node 2795 * may be balanced overall and kswapd will not wake naturally. 2796 */ 2797 if (boost_watermark(zone) && (alloc_flags & ALLOC_KSWAPD)) 2798 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags); 2799 2800 /* We are not allowed to try stealing from the whole block */ 2801 if (!whole_block) 2802 goto single_page; 2803 2804 free_pages = move_freepages_block(zone, page, start_type, 2805 &movable_pages); 2806 /* 2807 * Determine how many pages are compatible with our allocation. 2808 * For movable allocation, it's the number of movable pages which 2809 * we just obtained. For other types it's a bit more tricky. 2810 */ 2811 if (start_type == MIGRATE_MOVABLE) { 2812 alike_pages = movable_pages; 2813 } else { 2814 /* 2815 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation 2816 * to MOVABLE pageblock, consider all non-movable pages as 2817 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or 2818 * vice versa, be conservative since we can't distinguish the 2819 * exact migratetype of non-movable pages. 2820 */ 2821 if (old_block_type == MIGRATE_MOVABLE) 2822 alike_pages = pageblock_nr_pages 2823 - (free_pages + movable_pages); 2824 else 2825 alike_pages = 0; 2826 } 2827 2828 /* moving whole block can fail due to zone boundary conditions */ 2829 if (!free_pages) 2830 goto single_page; 2831 2832 /* 2833 * If a sufficient number of pages in the block are either free or of 2834 * comparable migratability as our allocation, claim the whole block. 2835 */ 2836 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) || 2837 page_group_by_mobility_disabled) 2838 set_pageblock_migratetype(page, start_type); 2839 2840 return; 2841 2842 single_page: 2843 move_to_free_list(page, zone, current_order, start_type); 2844 } 2845 2846 /* 2847 * Check whether there is a suitable fallback freepage with requested order. 2848 * If only_stealable is true, this function returns fallback_mt only if 2849 * we can steal other freepages all together. This would help to reduce 2850 * fragmentation due to mixed migratetype pages in one pageblock. 2851 */ 2852 int find_suitable_fallback(struct free_area *area, unsigned int order, 2853 int migratetype, bool only_stealable, bool *can_steal) 2854 { 2855 int i; 2856 int fallback_mt; 2857 2858 if (area->nr_free == 0) 2859 return -1; 2860 2861 *can_steal = false; 2862 for (i = 0;; i++) { 2863 fallback_mt = fallbacks[migratetype][i]; 2864 if (fallback_mt == MIGRATE_TYPES) 2865 break; 2866 2867 if (free_area_empty(area, fallback_mt)) 2868 continue; 2869 2870 if (can_steal_fallback(order, migratetype)) 2871 *can_steal = true; 2872 2873 if (!only_stealable) 2874 return fallback_mt; 2875 2876 if (*can_steal) 2877 return fallback_mt; 2878 } 2879 2880 return -1; 2881 } 2882 2883 /* 2884 * Reserve a pageblock for exclusive use of high-order atomic allocations if 2885 * there are no empty page blocks that contain a page with a suitable order 2886 */ 2887 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone, 2888 unsigned int alloc_order) 2889 { 2890 int mt; 2891 unsigned long max_managed, flags; 2892 2893 /* 2894 * Limit the number reserved to 1 pageblock or roughly 1% of a zone. 2895 * Check is race-prone but harmless. 2896 */ 2897 max_managed = (zone_managed_pages(zone) / 100) + pageblock_nr_pages; 2898 if (zone->nr_reserved_highatomic >= max_managed) 2899 return; 2900 2901 spin_lock_irqsave(&zone->lock, flags); 2902 2903 /* Recheck the nr_reserved_highatomic limit under the lock */ 2904 if (zone->nr_reserved_highatomic >= max_managed) 2905 goto out_unlock; 2906 2907 /* Yoink! */ 2908 mt = get_pageblock_migratetype(page); 2909 /* Only reserve normal pageblocks (i.e., they can merge with others) */ 2910 if (migratetype_is_mergeable(mt)) { 2911 zone->nr_reserved_highatomic += pageblock_nr_pages; 2912 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC); 2913 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL); 2914 } 2915 2916 out_unlock: 2917 spin_unlock_irqrestore(&zone->lock, flags); 2918 } 2919 2920 /* 2921 * Used when an allocation is about to fail under memory pressure. This 2922 * potentially hurts the reliability of high-order allocations when under 2923 * intense memory pressure but failed atomic allocations should be easier 2924 * to recover from than an OOM. 2925 * 2926 * If @force is true, try to unreserve a pageblock even though highatomic 2927 * pageblock is exhausted. 2928 */ 2929 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac, 2930 bool force) 2931 { 2932 struct zonelist *zonelist = ac->zonelist; 2933 unsigned long flags; 2934 struct zoneref *z; 2935 struct zone *zone; 2936 struct page *page; 2937 int order; 2938 bool ret; 2939 2940 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->highest_zoneidx, 2941 ac->nodemask) { 2942 /* 2943 * Preserve at least one pageblock unless memory pressure 2944 * is really high. 2945 */ 2946 if (!force && zone->nr_reserved_highatomic <= 2947 pageblock_nr_pages) 2948 continue; 2949 2950 spin_lock_irqsave(&zone->lock, flags); 2951 for (order = 0; order < MAX_ORDER; order++) { 2952 struct free_area *area = &(zone->free_area[order]); 2953 2954 page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC); 2955 if (!page) 2956 continue; 2957 2958 /* 2959 * In page freeing path, migratetype change is racy so 2960 * we can counter several free pages in a pageblock 2961 * in this loop although we changed the pageblock type 2962 * from highatomic to ac->migratetype. So we should 2963 * adjust the count once. 2964 */ 2965 if (is_migrate_highatomic_page(page)) { 2966 /* 2967 * It should never happen but changes to 2968 * locking could inadvertently allow a per-cpu 2969 * drain to add pages to MIGRATE_HIGHATOMIC 2970 * while unreserving so be safe and watch for 2971 * underflows. 2972 */ 2973 zone->nr_reserved_highatomic -= min( 2974 pageblock_nr_pages, 2975 zone->nr_reserved_highatomic); 2976 } 2977 2978 /* 2979 * Convert to ac->migratetype and avoid the normal 2980 * pageblock stealing heuristics. Minimally, the caller 2981 * is doing the work and needs the pages. More 2982 * importantly, if the block was always converted to 2983 * MIGRATE_UNMOVABLE or another type then the number 2984 * of pageblocks that cannot be completely freed 2985 * may increase. 2986 */ 2987 set_pageblock_migratetype(page, ac->migratetype); 2988 ret = move_freepages_block(zone, page, ac->migratetype, 2989 NULL); 2990 if (ret) { 2991 spin_unlock_irqrestore(&zone->lock, flags); 2992 return ret; 2993 } 2994 } 2995 spin_unlock_irqrestore(&zone->lock, flags); 2996 } 2997 2998 return false; 2999 } 3000 3001 /* 3002 * Try finding a free buddy page on the fallback list and put it on the free 3003 * list of requested migratetype, possibly along with other pages from the same 3004 * block, depending on fragmentation avoidance heuristics. Returns true if 3005 * fallback was found so that __rmqueue_smallest() can grab it. 3006 * 3007 * The use of signed ints for order and current_order is a deliberate 3008 * deviation from the rest of this file, to make the for loop 3009 * condition simpler. 3010 */ 3011 static __always_inline bool 3012 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype, 3013 unsigned int alloc_flags) 3014 { 3015 struct free_area *area; 3016 int current_order; 3017 int min_order = order; 3018 struct page *page; 3019 int fallback_mt; 3020 bool can_steal; 3021 3022 /* 3023 * Do not steal pages from freelists belonging to other pageblocks 3024 * i.e. orders < pageblock_order. If there are no local zones free, 3025 * the zonelists will be reiterated without ALLOC_NOFRAGMENT. 3026 */ 3027 if (order < pageblock_order && alloc_flags & ALLOC_NOFRAGMENT) 3028 min_order = pageblock_order; 3029 3030 /* 3031 * Find the largest available free page in the other list. This roughly 3032 * approximates finding the pageblock with the most free pages, which 3033 * would be too costly to do exactly. 3034 */ 3035 for (current_order = MAX_ORDER - 1; current_order >= min_order; 3036 --current_order) { 3037 area = &(zone->free_area[current_order]); 3038 fallback_mt = find_suitable_fallback(area, current_order, 3039 start_migratetype, false, &can_steal); 3040 if (fallback_mt == -1) 3041 continue; 3042 3043 /* 3044 * We cannot steal all free pages from the pageblock and the 3045 * requested migratetype is movable. In that case it's better to 3046 * steal and split the smallest available page instead of the 3047 * largest available page, because even if the next movable 3048 * allocation falls back into a different pageblock than this 3049 * one, it won't cause permanent fragmentation. 3050 */ 3051 if (!can_steal && start_migratetype == MIGRATE_MOVABLE 3052 && current_order > order) 3053 goto find_smallest; 3054 3055 goto do_steal; 3056 } 3057 3058 return false; 3059 3060 find_smallest: 3061 for (current_order = order; current_order < MAX_ORDER; 3062 current_order++) { 3063 area = &(zone->free_area[current_order]); 3064 fallback_mt = find_suitable_fallback(area, current_order, 3065 start_migratetype, false, &can_steal); 3066 if (fallback_mt != -1) 3067 break; 3068 } 3069 3070 /* 3071 * This should not happen - we already found a suitable fallback 3072 * when looking for the largest page. 3073 */ 3074 VM_BUG_ON(current_order == MAX_ORDER); 3075 3076 do_steal: 3077 page = get_page_from_free_area(area, fallback_mt); 3078 3079 steal_suitable_fallback(zone, page, alloc_flags, start_migratetype, 3080 can_steal); 3081 3082 trace_mm_page_alloc_extfrag(page, order, current_order, 3083 start_migratetype, fallback_mt); 3084 3085 return true; 3086 3087 } 3088 3089 /* 3090 * Do the hard work of removing an element from the buddy allocator. 3091 * Call me with the zone->lock already held. 3092 */ 3093 static __always_inline struct page * 3094 __rmqueue(struct zone *zone, unsigned int order, int migratetype, 3095 unsigned int alloc_flags) 3096 { 3097 struct page *page; 3098 3099 if (IS_ENABLED(CONFIG_CMA)) { 3100 /* 3101 * Balance movable allocations between regular and CMA areas by 3102 * allocating from CMA when over half of the zone's free memory 3103 * is in the CMA area. 3104 */ 3105 if (alloc_flags & ALLOC_CMA && 3106 zone_page_state(zone, NR_FREE_CMA_PAGES) > 3107 zone_page_state(zone, NR_FREE_PAGES) / 2) { 3108 page = __rmqueue_cma_fallback(zone, order); 3109 if (page) 3110 return page; 3111 } 3112 } 3113 retry: 3114 page = __rmqueue_smallest(zone, order, migratetype); 3115 if (unlikely(!page)) { 3116 if (alloc_flags & ALLOC_CMA) 3117 page = __rmqueue_cma_fallback(zone, order); 3118 3119 if (!page && __rmqueue_fallback(zone, order, migratetype, 3120 alloc_flags)) 3121 goto retry; 3122 } 3123 return page; 3124 } 3125 3126 /* 3127 * Obtain a specified number of elements from the buddy allocator, all under 3128 * a single hold of the lock, for efficiency. Add them to the supplied list. 3129 * Returns the number of new pages which were placed at *list. 3130 */ 3131 static int rmqueue_bulk(struct zone *zone, unsigned int order, 3132 unsigned long count, struct list_head *list, 3133 int migratetype, unsigned int alloc_flags) 3134 { 3135 unsigned long flags; 3136 int i, allocated = 0; 3137 3138 spin_lock_irqsave(&zone->lock, flags); 3139 for (i = 0; i < count; ++i) { 3140 struct page *page = __rmqueue(zone, order, migratetype, 3141 alloc_flags); 3142 if (unlikely(page == NULL)) 3143 break; 3144 3145 if (unlikely(check_pcp_refill(page, order))) 3146 continue; 3147 3148 /* 3149 * Split buddy pages returned by expand() are received here in 3150 * physical page order. The page is added to the tail of 3151 * caller's list. From the callers perspective, the linked list 3152 * is ordered by page number under some conditions. This is 3153 * useful for IO devices that can forward direction from the 3154 * head, thus also in the physical page order. This is useful 3155 * for IO devices that can merge IO requests if the physical 3156 * pages are ordered properly. 3157 */ 3158 list_add_tail(&page->pcp_list, list); 3159 allocated++; 3160 if (is_migrate_cma(get_pcppage_migratetype(page))) 3161 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES, 3162 -(1 << order)); 3163 } 3164 3165 /* 3166 * i pages were removed from the buddy list even if some leak due 3167 * to check_pcp_refill failing so adjust NR_FREE_PAGES based 3168 * on i. Do not confuse with 'allocated' which is the number of 3169 * pages added to the pcp list. 3170 */ 3171 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order)); 3172 spin_unlock_irqrestore(&zone->lock, flags); 3173 return allocated; 3174 } 3175 3176 #ifdef CONFIG_NUMA 3177 /* 3178 * Called from the vmstat counter updater to drain pagesets of this 3179 * currently executing processor on remote nodes after they have 3180 * expired. 3181 */ 3182 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp) 3183 { 3184 int to_drain, batch; 3185 3186 batch = READ_ONCE(pcp->batch); 3187 to_drain = min(pcp->count, batch); 3188 if (to_drain > 0) { 3189 spin_lock(&pcp->lock); 3190 free_pcppages_bulk(zone, to_drain, pcp, 0); 3191 spin_unlock(&pcp->lock); 3192 } 3193 } 3194 #endif 3195 3196 /* 3197 * Drain pcplists of the indicated processor and zone. 3198 */ 3199 static void drain_pages_zone(unsigned int cpu, struct zone *zone) 3200 { 3201 struct per_cpu_pages *pcp; 3202 3203 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 3204 if (pcp->count) { 3205 spin_lock(&pcp->lock); 3206 free_pcppages_bulk(zone, pcp->count, pcp, 0); 3207 spin_unlock(&pcp->lock); 3208 } 3209 } 3210 3211 /* 3212 * Drain pcplists of all zones on the indicated processor. 3213 */ 3214 static void drain_pages(unsigned int cpu) 3215 { 3216 struct zone *zone; 3217 3218 for_each_populated_zone(zone) { 3219 drain_pages_zone(cpu, zone); 3220 } 3221 } 3222 3223 /* 3224 * Spill all of this CPU's per-cpu pages back into the buddy allocator. 3225 */ 3226 void drain_local_pages(struct zone *zone) 3227 { 3228 int cpu = smp_processor_id(); 3229 3230 if (zone) 3231 drain_pages_zone(cpu, zone); 3232 else 3233 drain_pages(cpu); 3234 } 3235 3236 /* 3237 * The implementation of drain_all_pages(), exposing an extra parameter to 3238 * drain on all cpus. 3239 * 3240 * drain_all_pages() is optimized to only execute on cpus where pcplists are 3241 * not empty. The check for non-emptiness can however race with a free to 3242 * pcplist that has not yet increased the pcp->count from 0 to 1. Callers 3243 * that need the guarantee that every CPU has drained can disable the 3244 * optimizing racy check. 3245 */ 3246 static void __drain_all_pages(struct zone *zone, bool force_all_cpus) 3247 { 3248 int cpu; 3249 3250 /* 3251 * Allocate in the BSS so we won't require allocation in 3252 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y 3253 */ 3254 static cpumask_t cpus_with_pcps; 3255 3256 /* 3257 * Do not drain if one is already in progress unless it's specific to 3258 * a zone. Such callers are primarily CMA and memory hotplug and need 3259 * the drain to be complete when the call returns. 3260 */ 3261 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) { 3262 if (!zone) 3263 return; 3264 mutex_lock(&pcpu_drain_mutex); 3265 } 3266 3267 /* 3268 * We don't care about racing with CPU hotplug event 3269 * as offline notification will cause the notified 3270 * cpu to drain that CPU pcps and on_each_cpu_mask 3271 * disables preemption as part of its processing 3272 */ 3273 for_each_online_cpu(cpu) { 3274 struct per_cpu_pages *pcp; 3275 struct zone *z; 3276 bool has_pcps = false; 3277 3278 if (force_all_cpus) { 3279 /* 3280 * The pcp.count check is racy, some callers need a 3281 * guarantee that no cpu is missed. 3282 */ 3283 has_pcps = true; 3284 } else if (zone) { 3285 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 3286 if (pcp->count) 3287 has_pcps = true; 3288 } else { 3289 for_each_populated_zone(z) { 3290 pcp = per_cpu_ptr(z->per_cpu_pageset, cpu); 3291 if (pcp->count) { 3292 has_pcps = true; 3293 break; 3294 } 3295 } 3296 } 3297 3298 if (has_pcps) 3299 cpumask_set_cpu(cpu, &cpus_with_pcps); 3300 else 3301 cpumask_clear_cpu(cpu, &cpus_with_pcps); 3302 } 3303 3304 for_each_cpu(cpu, &cpus_with_pcps) { 3305 if (zone) 3306 drain_pages_zone(cpu, zone); 3307 else 3308 drain_pages(cpu); 3309 } 3310 3311 mutex_unlock(&pcpu_drain_mutex); 3312 } 3313 3314 /* 3315 * Spill all the per-cpu pages from all CPUs back into the buddy allocator. 3316 * 3317 * When zone parameter is non-NULL, spill just the single zone's pages. 3318 */ 3319 void drain_all_pages(struct zone *zone) 3320 { 3321 __drain_all_pages(zone, false); 3322 } 3323 3324 #ifdef CONFIG_HIBERNATION 3325 3326 /* 3327 * Touch the watchdog for every WD_PAGE_COUNT pages. 3328 */ 3329 #define WD_PAGE_COUNT (128*1024) 3330 3331 void mark_free_pages(struct zone *zone) 3332 { 3333 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT; 3334 unsigned long flags; 3335 unsigned int order, t; 3336 struct page *page; 3337 3338 if (zone_is_empty(zone)) 3339 return; 3340 3341 spin_lock_irqsave(&zone->lock, flags); 3342 3343 max_zone_pfn = zone_end_pfn(zone); 3344 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) 3345 if (pfn_valid(pfn)) { 3346 page = pfn_to_page(pfn); 3347 3348 if (!--page_count) { 3349 touch_nmi_watchdog(); 3350 page_count = WD_PAGE_COUNT; 3351 } 3352 3353 if (page_zone(page) != zone) 3354 continue; 3355 3356 if (!swsusp_page_is_forbidden(page)) 3357 swsusp_unset_page_free(page); 3358 } 3359 3360 for_each_migratetype_order(order, t) { 3361 list_for_each_entry(page, 3362 &zone->free_area[order].free_list[t], buddy_list) { 3363 unsigned long i; 3364 3365 pfn = page_to_pfn(page); 3366 for (i = 0; i < (1UL << order); i++) { 3367 if (!--page_count) { 3368 touch_nmi_watchdog(); 3369 page_count = WD_PAGE_COUNT; 3370 } 3371 swsusp_set_page_free(pfn_to_page(pfn + i)); 3372 } 3373 } 3374 } 3375 spin_unlock_irqrestore(&zone->lock, flags); 3376 } 3377 #endif /* CONFIG_PM */ 3378 3379 static bool free_unref_page_prepare(struct page *page, unsigned long pfn, 3380 unsigned int order) 3381 { 3382 int migratetype; 3383 3384 if (!free_pcp_prepare(page, order)) 3385 return false; 3386 3387 migratetype = get_pfnblock_migratetype(page, pfn); 3388 set_pcppage_migratetype(page, migratetype); 3389 return true; 3390 } 3391 3392 static int nr_pcp_free(struct per_cpu_pages *pcp, int high, int batch, 3393 bool free_high) 3394 { 3395 int min_nr_free, max_nr_free; 3396 3397 /* Free everything if batch freeing high-order pages. */ 3398 if (unlikely(free_high)) 3399 return pcp->count; 3400 3401 /* Check for PCP disabled or boot pageset */ 3402 if (unlikely(high < batch)) 3403 return 1; 3404 3405 /* Leave at least pcp->batch pages on the list */ 3406 min_nr_free = batch; 3407 max_nr_free = high - batch; 3408 3409 /* 3410 * Double the number of pages freed each time there is subsequent 3411 * freeing of pages without any allocation. 3412 */ 3413 batch <<= pcp->free_factor; 3414 if (batch < max_nr_free) 3415 pcp->free_factor++; 3416 batch = clamp(batch, min_nr_free, max_nr_free); 3417 3418 return batch; 3419 } 3420 3421 static int nr_pcp_high(struct per_cpu_pages *pcp, struct zone *zone, 3422 bool free_high) 3423 { 3424 int high = READ_ONCE(pcp->high); 3425 3426 if (unlikely(!high || free_high)) 3427 return 0; 3428 3429 if (!test_bit(ZONE_RECLAIM_ACTIVE, &zone->flags)) 3430 return high; 3431 3432 /* 3433 * If reclaim is active, limit the number of pages that can be 3434 * stored on pcp lists 3435 */ 3436 return min(READ_ONCE(pcp->batch) << 2, high); 3437 } 3438 3439 static void free_unref_page_commit(struct zone *zone, struct per_cpu_pages *pcp, 3440 struct page *page, int migratetype, 3441 unsigned int order) 3442 { 3443 int high; 3444 int pindex; 3445 bool free_high; 3446 3447 __count_vm_events(PGFREE, 1 << order); 3448 pindex = order_to_pindex(migratetype, order); 3449 list_add(&page->pcp_list, &pcp->lists[pindex]); 3450 pcp->count += 1 << order; 3451 3452 /* 3453 * As high-order pages other than THP's stored on PCP can contribute 3454 * to fragmentation, limit the number stored when PCP is heavily 3455 * freeing without allocation. The remainder after bulk freeing 3456 * stops will be drained from vmstat refresh context. 3457 */ 3458 free_high = (pcp->free_factor && order && order <= PAGE_ALLOC_COSTLY_ORDER); 3459 3460 high = nr_pcp_high(pcp, zone, free_high); 3461 if (pcp->count >= high) { 3462 int batch = READ_ONCE(pcp->batch); 3463 3464 free_pcppages_bulk(zone, nr_pcp_free(pcp, high, batch, free_high), pcp, pindex); 3465 } 3466 } 3467 3468 /* 3469 * Free a pcp page 3470 */ 3471 void free_unref_page(struct page *page, unsigned int order) 3472 { 3473 unsigned long __maybe_unused UP_flags; 3474 struct per_cpu_pages *pcp; 3475 struct zone *zone; 3476 unsigned long pfn = page_to_pfn(page); 3477 int migratetype; 3478 3479 if (!free_unref_page_prepare(page, pfn, order)) 3480 return; 3481 3482 /* 3483 * We only track unmovable, reclaimable and movable on pcp lists. 3484 * Place ISOLATE pages on the isolated list because they are being 3485 * offlined but treat HIGHATOMIC as movable pages so we can get those 3486 * areas back if necessary. Otherwise, we may have to free 3487 * excessively into the page allocator 3488 */ 3489 migratetype = get_pcppage_migratetype(page); 3490 if (unlikely(migratetype >= MIGRATE_PCPTYPES)) { 3491 if (unlikely(is_migrate_isolate(migratetype))) { 3492 free_one_page(page_zone(page), page, pfn, order, migratetype, FPI_NONE); 3493 return; 3494 } 3495 migratetype = MIGRATE_MOVABLE; 3496 } 3497 3498 zone = page_zone(page); 3499 pcp_trylock_prepare(UP_flags); 3500 pcp = pcp_spin_trylock(zone->per_cpu_pageset); 3501 if (pcp) { 3502 free_unref_page_commit(zone, pcp, page, migratetype, order); 3503 pcp_spin_unlock(pcp); 3504 } else { 3505 free_one_page(zone, page, pfn, order, migratetype, FPI_NONE); 3506 } 3507 pcp_trylock_finish(UP_flags); 3508 } 3509 3510 /* 3511 * Free a list of 0-order pages 3512 */ 3513 void free_unref_page_list(struct list_head *list) 3514 { 3515 unsigned long __maybe_unused UP_flags; 3516 struct page *page, *next; 3517 struct per_cpu_pages *pcp = NULL; 3518 struct zone *locked_zone = NULL; 3519 int batch_count = 0; 3520 int migratetype; 3521 3522 /* Prepare pages for freeing */ 3523 list_for_each_entry_safe(page, next, list, lru) { 3524 unsigned long pfn = page_to_pfn(page); 3525 if (!free_unref_page_prepare(page, pfn, 0)) { 3526 list_del(&page->lru); 3527 continue; 3528 } 3529 3530 /* 3531 * Free isolated pages directly to the allocator, see 3532 * comment in free_unref_page. 3533 */ 3534 migratetype = get_pcppage_migratetype(page); 3535 if (unlikely(is_migrate_isolate(migratetype))) { 3536 list_del(&page->lru); 3537 free_one_page(page_zone(page), page, pfn, 0, migratetype, FPI_NONE); 3538 continue; 3539 } 3540 } 3541 3542 list_for_each_entry_safe(page, next, list, lru) { 3543 struct zone *zone = page_zone(page); 3544 3545 list_del(&page->lru); 3546 migratetype = get_pcppage_migratetype(page); 3547 3548 /* 3549 * Either different zone requiring a different pcp lock or 3550 * excessive lock hold times when freeing a large list of 3551 * pages. 3552 */ 3553 if (zone != locked_zone || batch_count == SWAP_CLUSTER_MAX) { 3554 if (pcp) { 3555 pcp_spin_unlock(pcp); 3556 pcp_trylock_finish(UP_flags); 3557 } 3558 3559 batch_count = 0; 3560 3561 /* 3562 * trylock is necessary as pages may be getting freed 3563 * from IRQ or SoftIRQ context after an IO completion. 3564 */ 3565 pcp_trylock_prepare(UP_flags); 3566 pcp = pcp_spin_trylock(zone->per_cpu_pageset); 3567 if (unlikely(!pcp)) { 3568 pcp_trylock_finish(UP_flags); 3569 free_one_page(zone, page, page_to_pfn(page), 3570 0, migratetype, FPI_NONE); 3571 locked_zone = NULL; 3572 continue; 3573 } 3574 locked_zone = zone; 3575 } 3576 3577 /* 3578 * Non-isolated types over MIGRATE_PCPTYPES get added 3579 * to the MIGRATE_MOVABLE pcp list. 3580 */ 3581 if (unlikely(migratetype >= MIGRATE_PCPTYPES)) 3582 migratetype = MIGRATE_MOVABLE; 3583 3584 trace_mm_page_free_batched(page); 3585 free_unref_page_commit(zone, pcp, page, migratetype, 0); 3586 batch_count++; 3587 } 3588 3589 if (pcp) { 3590 pcp_spin_unlock(pcp); 3591 pcp_trylock_finish(UP_flags); 3592 } 3593 } 3594 3595 /* 3596 * split_page takes a non-compound higher-order page, and splits it into 3597 * n (1<<order) sub-pages: page[0..n] 3598 * Each sub-page must be freed individually. 3599 * 3600 * Note: this is probably too low level an operation for use in drivers. 3601 * Please consult with lkml before using this in your driver. 3602 */ 3603 void split_page(struct page *page, unsigned int order) 3604 { 3605 int i; 3606 3607 VM_BUG_ON_PAGE(PageCompound(page), page); 3608 VM_BUG_ON_PAGE(!page_count(page), page); 3609 3610 for (i = 1; i < (1 << order); i++) 3611 set_page_refcounted(page + i); 3612 split_page_owner(page, 1 << order); 3613 split_page_memcg(page, 1 << order); 3614 } 3615 EXPORT_SYMBOL_GPL(split_page); 3616 3617 int __isolate_free_page(struct page *page, unsigned int order) 3618 { 3619 struct zone *zone = page_zone(page); 3620 int mt = get_pageblock_migratetype(page); 3621 3622 if (!is_migrate_isolate(mt)) { 3623 unsigned long watermark; 3624 /* 3625 * Obey watermarks as if the page was being allocated. We can 3626 * emulate a high-order watermark check with a raised order-0 3627 * watermark, because we already know our high-order page 3628 * exists. 3629 */ 3630 watermark = zone->_watermark[WMARK_MIN] + (1UL << order); 3631 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA)) 3632 return 0; 3633 3634 __mod_zone_freepage_state(zone, -(1UL << order), mt); 3635 } 3636 3637 del_page_from_free_list(page, zone, order); 3638 3639 /* 3640 * Set the pageblock if the isolated page is at least half of a 3641 * pageblock 3642 */ 3643 if (order >= pageblock_order - 1) { 3644 struct page *endpage = page + (1 << order) - 1; 3645 for (; page < endpage; page += pageblock_nr_pages) { 3646 int mt = get_pageblock_migratetype(page); 3647 /* 3648 * Only change normal pageblocks (i.e., they can merge 3649 * with others) 3650 */ 3651 if (migratetype_is_mergeable(mt)) 3652 set_pageblock_migratetype(page, 3653 MIGRATE_MOVABLE); 3654 } 3655 } 3656 3657 return 1UL << order; 3658 } 3659 3660 /** 3661 * __putback_isolated_page - Return a now-isolated page back where we got it 3662 * @page: Page that was isolated 3663 * @order: Order of the isolated page 3664 * @mt: The page's pageblock's migratetype 3665 * 3666 * This function is meant to return a page pulled from the free lists via 3667 * __isolate_free_page back to the free lists they were pulled from. 3668 */ 3669 void __putback_isolated_page(struct page *page, unsigned int order, int mt) 3670 { 3671 struct zone *zone = page_zone(page); 3672 3673 /* zone lock should be held when this function is called */ 3674 lockdep_assert_held(&zone->lock); 3675 3676 /* Return isolated page to tail of freelist. */ 3677 __free_one_page(page, page_to_pfn(page), zone, order, mt, 3678 FPI_SKIP_REPORT_NOTIFY | FPI_TO_TAIL); 3679 } 3680 3681 /* 3682 * Update NUMA hit/miss statistics 3683 */ 3684 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z, 3685 long nr_account) 3686 { 3687 #ifdef CONFIG_NUMA 3688 enum numa_stat_item local_stat = NUMA_LOCAL; 3689 3690 /* skip numa counters update if numa stats is disabled */ 3691 if (!static_branch_likely(&vm_numa_stat_key)) 3692 return; 3693 3694 if (zone_to_nid(z) != numa_node_id()) 3695 local_stat = NUMA_OTHER; 3696 3697 if (zone_to_nid(z) == zone_to_nid(preferred_zone)) 3698 __count_numa_events(z, NUMA_HIT, nr_account); 3699 else { 3700 __count_numa_events(z, NUMA_MISS, nr_account); 3701 __count_numa_events(preferred_zone, NUMA_FOREIGN, nr_account); 3702 } 3703 __count_numa_events(z, local_stat, nr_account); 3704 #endif 3705 } 3706 3707 static __always_inline 3708 struct page *rmqueue_buddy(struct zone *preferred_zone, struct zone *zone, 3709 unsigned int order, unsigned int alloc_flags, 3710 int migratetype) 3711 { 3712 struct page *page; 3713 unsigned long flags; 3714 3715 do { 3716 page = NULL; 3717 spin_lock_irqsave(&zone->lock, flags); 3718 /* 3719 * order-0 request can reach here when the pcplist is skipped 3720 * due to non-CMA allocation context. HIGHATOMIC area is 3721 * reserved for high-order atomic allocation, so order-0 3722 * request should skip it. 3723 */ 3724 if (order > 0 && alloc_flags & ALLOC_HARDER) 3725 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC); 3726 if (!page) { 3727 page = __rmqueue(zone, order, migratetype, alloc_flags); 3728 if (!page) { 3729 spin_unlock_irqrestore(&zone->lock, flags); 3730 return NULL; 3731 } 3732 } 3733 __mod_zone_freepage_state(zone, -(1 << order), 3734 get_pcppage_migratetype(page)); 3735 spin_unlock_irqrestore(&zone->lock, flags); 3736 } while (check_new_pages(page, order)); 3737 3738 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order); 3739 zone_statistics(preferred_zone, zone, 1); 3740 3741 return page; 3742 } 3743 3744 /* Remove page from the per-cpu list, caller must protect the list */ 3745 static inline 3746 struct page *__rmqueue_pcplist(struct zone *zone, unsigned int order, 3747 int migratetype, 3748 unsigned int alloc_flags, 3749 struct per_cpu_pages *pcp, 3750 struct list_head *list) 3751 { 3752 struct page *page; 3753 3754 do { 3755 if (list_empty(list)) { 3756 int batch = READ_ONCE(pcp->batch); 3757 int alloced; 3758 3759 /* 3760 * Scale batch relative to order if batch implies 3761 * free pages can be stored on the PCP. Batch can 3762 * be 1 for small zones or for boot pagesets which 3763 * should never store free pages as the pages may 3764 * belong to arbitrary zones. 3765 */ 3766 if (batch > 1) 3767 batch = max(batch >> order, 2); 3768 alloced = rmqueue_bulk(zone, order, 3769 batch, list, 3770 migratetype, alloc_flags); 3771 3772 pcp->count += alloced << order; 3773 if (unlikely(list_empty(list))) 3774 return NULL; 3775 } 3776 3777 page = list_first_entry(list, struct page, pcp_list); 3778 list_del(&page->pcp_list); 3779 pcp->count -= 1 << order; 3780 } while (check_new_pcp(page, order)); 3781 3782 return page; 3783 } 3784 3785 /* Lock and remove page from the per-cpu list */ 3786 static struct page *rmqueue_pcplist(struct zone *preferred_zone, 3787 struct zone *zone, unsigned int order, 3788 int migratetype, unsigned int alloc_flags) 3789 { 3790 struct per_cpu_pages *pcp; 3791 struct list_head *list; 3792 struct page *page; 3793 unsigned long __maybe_unused UP_flags; 3794 3795 /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */ 3796 pcp_trylock_prepare(UP_flags); 3797 pcp = pcp_spin_trylock(zone->per_cpu_pageset); 3798 if (!pcp) { 3799 pcp_trylock_finish(UP_flags); 3800 return NULL; 3801 } 3802 3803 /* 3804 * On allocation, reduce the number of pages that are batch freed. 3805 * See nr_pcp_free() where free_factor is increased for subsequent 3806 * frees. 3807 */ 3808 pcp->free_factor >>= 1; 3809 list = &pcp->lists[order_to_pindex(migratetype, order)]; 3810 page = __rmqueue_pcplist(zone, order, migratetype, alloc_flags, pcp, list); 3811 pcp_spin_unlock(pcp); 3812 pcp_trylock_finish(UP_flags); 3813 if (page) { 3814 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order); 3815 zone_statistics(preferred_zone, zone, 1); 3816 } 3817 return page; 3818 } 3819 3820 /* 3821 * Allocate a page from the given zone. 3822 * Use pcplists for THP or "cheap" high-order allocations. 3823 */ 3824 3825 /* 3826 * Do not instrument rmqueue() with KMSAN. This function may call 3827 * __msan_poison_alloca() through a call to set_pfnblock_flags_mask(). 3828 * If __msan_poison_alloca() attempts to allocate pages for the stack depot, it 3829 * may call rmqueue() again, which will result in a deadlock. 3830 */ 3831 __no_sanitize_memory 3832 static inline 3833 struct page *rmqueue(struct zone *preferred_zone, 3834 struct zone *zone, unsigned int order, 3835 gfp_t gfp_flags, unsigned int alloc_flags, 3836 int migratetype) 3837 { 3838 struct page *page; 3839 3840 /* 3841 * We most definitely don't want callers attempting to 3842 * allocate greater than order-1 page units with __GFP_NOFAIL. 3843 */ 3844 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1)); 3845 3846 if (likely(pcp_allowed_order(order))) { 3847 /* 3848 * MIGRATE_MOVABLE pcplist could have the pages on CMA area and 3849 * we need to skip it when CMA area isn't allowed. 3850 */ 3851 if (!IS_ENABLED(CONFIG_CMA) || alloc_flags & ALLOC_CMA || 3852 migratetype != MIGRATE_MOVABLE) { 3853 page = rmqueue_pcplist(preferred_zone, zone, order, 3854 migratetype, alloc_flags); 3855 if (likely(page)) 3856 goto out; 3857 } 3858 } 3859 3860 page = rmqueue_buddy(preferred_zone, zone, order, alloc_flags, 3861 migratetype); 3862 3863 out: 3864 /* Separate test+clear to avoid unnecessary atomics */ 3865 if (unlikely(test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags))) { 3866 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags); 3867 wakeup_kswapd(zone, 0, 0, zone_idx(zone)); 3868 } 3869 3870 VM_BUG_ON_PAGE(page && bad_range(zone, page), page); 3871 return page; 3872 } 3873 3874 #ifdef CONFIG_FAIL_PAGE_ALLOC 3875 3876 static struct { 3877 struct fault_attr attr; 3878 3879 bool ignore_gfp_highmem; 3880 bool ignore_gfp_reclaim; 3881 u32 min_order; 3882 } fail_page_alloc = { 3883 .attr = FAULT_ATTR_INITIALIZER, 3884 .ignore_gfp_reclaim = true, 3885 .ignore_gfp_highmem = true, 3886 .min_order = 1, 3887 }; 3888 3889 static int __init setup_fail_page_alloc(char *str) 3890 { 3891 return setup_fault_attr(&fail_page_alloc.attr, str); 3892 } 3893 __setup("fail_page_alloc=", setup_fail_page_alloc); 3894 3895 static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order) 3896 { 3897 int flags = 0; 3898 3899 if (order < fail_page_alloc.min_order) 3900 return false; 3901 if (gfp_mask & __GFP_NOFAIL) 3902 return false; 3903 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM)) 3904 return false; 3905 if (fail_page_alloc.ignore_gfp_reclaim && 3906 (gfp_mask & __GFP_DIRECT_RECLAIM)) 3907 return false; 3908 3909 /* See comment in __should_failslab() */ 3910 if (gfp_mask & __GFP_NOWARN) 3911 flags |= FAULT_NOWARN; 3912 3913 return should_fail_ex(&fail_page_alloc.attr, 1 << order, flags); 3914 } 3915 3916 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS 3917 3918 static int __init fail_page_alloc_debugfs(void) 3919 { 3920 umode_t mode = S_IFREG | 0600; 3921 struct dentry *dir; 3922 3923 dir = fault_create_debugfs_attr("fail_page_alloc", NULL, 3924 &fail_page_alloc.attr); 3925 3926 debugfs_create_bool("ignore-gfp-wait", mode, dir, 3927 &fail_page_alloc.ignore_gfp_reclaim); 3928 debugfs_create_bool("ignore-gfp-highmem", mode, dir, 3929 &fail_page_alloc.ignore_gfp_highmem); 3930 debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order); 3931 3932 return 0; 3933 } 3934 3935 late_initcall(fail_page_alloc_debugfs); 3936 3937 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */ 3938 3939 #else /* CONFIG_FAIL_PAGE_ALLOC */ 3940 3941 static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order) 3942 { 3943 return false; 3944 } 3945 3946 #endif /* CONFIG_FAIL_PAGE_ALLOC */ 3947 3948 noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order) 3949 { 3950 return __should_fail_alloc_page(gfp_mask, order); 3951 } 3952 ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE); 3953 3954 static inline long __zone_watermark_unusable_free(struct zone *z, 3955 unsigned int order, unsigned int alloc_flags) 3956 { 3957 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM)); 3958 long unusable_free = (1 << order) - 1; 3959 3960 /* 3961 * If the caller does not have rights to ALLOC_HARDER then subtract 3962 * the high-atomic reserves. This will over-estimate the size of the 3963 * atomic reserve but it avoids a search. 3964 */ 3965 if (likely(!alloc_harder)) 3966 unusable_free += z->nr_reserved_highatomic; 3967 3968 #ifdef CONFIG_CMA 3969 /* If allocation can't use CMA areas don't use free CMA pages */ 3970 if (!(alloc_flags & ALLOC_CMA)) 3971 unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES); 3972 #endif 3973 3974 return unusable_free; 3975 } 3976 3977 /* 3978 * Return true if free base pages are above 'mark'. For high-order checks it 3979 * will return true of the order-0 watermark is reached and there is at least 3980 * one free page of a suitable size. Checking now avoids taking the zone lock 3981 * to check in the allocation paths if no pages are free. 3982 */ 3983 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark, 3984 int highest_zoneidx, unsigned int alloc_flags, 3985 long free_pages) 3986 { 3987 long min = mark; 3988 int o; 3989 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM)); 3990 3991 /* free_pages may go negative - that's OK */ 3992 free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags); 3993 3994 if (alloc_flags & ALLOC_HIGH) 3995 min -= min / 2; 3996 3997 if (unlikely(alloc_harder)) { 3998 /* 3999 * OOM victims can try even harder than normal ALLOC_HARDER 4000 * users on the grounds that it's definitely going to be in 4001 * the exit path shortly and free memory. Any allocation it 4002 * makes during the free path will be small and short-lived. 4003 */ 4004 if (alloc_flags & ALLOC_OOM) 4005 min -= min / 2; 4006 else 4007 min -= min / 4; 4008 } 4009 4010 /* 4011 * Check watermarks for an order-0 allocation request. If these 4012 * are not met, then a high-order request also cannot go ahead 4013 * even if a suitable page happened to be free. 4014 */ 4015 if (free_pages <= min + z->lowmem_reserve[highest_zoneidx]) 4016 return false; 4017 4018 /* If this is an order-0 request then the watermark is fine */ 4019 if (!order) 4020 return true; 4021 4022 /* For a high-order request, check at least one suitable page is free */ 4023 for (o = order; o < MAX_ORDER; o++) { 4024 struct free_area *area = &z->free_area[o]; 4025 int mt; 4026 4027 if (!area->nr_free) 4028 continue; 4029 4030 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) { 4031 if (!free_area_empty(area, mt)) 4032 return true; 4033 } 4034 4035 #ifdef CONFIG_CMA 4036 if ((alloc_flags & ALLOC_CMA) && 4037 !free_area_empty(area, MIGRATE_CMA)) { 4038 return true; 4039 } 4040 #endif 4041 if (alloc_harder && !free_area_empty(area, MIGRATE_HIGHATOMIC)) 4042 return true; 4043 } 4044 return false; 4045 } 4046 4047 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark, 4048 int highest_zoneidx, unsigned int alloc_flags) 4049 { 4050 return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags, 4051 zone_page_state(z, NR_FREE_PAGES)); 4052 } 4053 4054 static inline bool zone_watermark_fast(struct zone *z, unsigned int order, 4055 unsigned long mark, int highest_zoneidx, 4056 unsigned int alloc_flags, gfp_t gfp_mask) 4057 { 4058 long free_pages; 4059 4060 free_pages = zone_page_state(z, NR_FREE_PAGES); 4061 4062 /* 4063 * Fast check for order-0 only. If this fails then the reserves 4064 * need to be calculated. 4065 */ 4066 if (!order) { 4067 long usable_free; 4068 long reserved; 4069 4070 usable_free = free_pages; 4071 reserved = __zone_watermark_unusable_free(z, 0, alloc_flags); 4072 4073 /* reserved may over estimate high-atomic reserves. */ 4074 usable_free -= min(usable_free, reserved); 4075 if (usable_free > mark + z->lowmem_reserve[highest_zoneidx]) 4076 return true; 4077 } 4078 4079 if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags, 4080 free_pages)) 4081 return true; 4082 /* 4083 * Ignore watermark boosting for GFP_ATOMIC order-0 allocations 4084 * when checking the min watermark. The min watermark is the 4085 * point where boosting is ignored so that kswapd is woken up 4086 * when below the low watermark. 4087 */ 4088 if (unlikely(!order && (gfp_mask & __GFP_ATOMIC) && z->watermark_boost 4089 && ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) { 4090 mark = z->_watermark[WMARK_MIN]; 4091 return __zone_watermark_ok(z, order, mark, highest_zoneidx, 4092 alloc_flags, free_pages); 4093 } 4094 4095 return false; 4096 } 4097 4098 bool zone_watermark_ok_safe(struct zone *z, unsigned int order, 4099 unsigned long mark, int highest_zoneidx) 4100 { 4101 long free_pages = zone_page_state(z, NR_FREE_PAGES); 4102 4103 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark) 4104 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES); 4105 4106 return __zone_watermark_ok(z, order, mark, highest_zoneidx, 0, 4107 free_pages); 4108 } 4109 4110 #ifdef CONFIG_NUMA 4111 int __read_mostly node_reclaim_distance = RECLAIM_DISTANCE; 4112 4113 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone) 4114 { 4115 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <= 4116 node_reclaim_distance; 4117 } 4118 #else /* CONFIG_NUMA */ 4119 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone) 4120 { 4121 return true; 4122 } 4123 #endif /* CONFIG_NUMA */ 4124 4125 /* 4126 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid 4127 * fragmentation is subtle. If the preferred zone was HIGHMEM then 4128 * premature use of a lower zone may cause lowmem pressure problems that 4129 * are worse than fragmentation. If the next zone is ZONE_DMA then it is 4130 * probably too small. It only makes sense to spread allocations to avoid 4131 * fragmentation between the Normal and DMA32 zones. 4132 */ 4133 static inline unsigned int 4134 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask) 4135 { 4136 unsigned int alloc_flags; 4137 4138 /* 4139 * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD 4140 * to save a branch. 4141 */ 4142 alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM); 4143 4144 #ifdef CONFIG_ZONE_DMA32 4145 if (!zone) 4146 return alloc_flags; 4147 4148 if (zone_idx(zone) != ZONE_NORMAL) 4149 return alloc_flags; 4150 4151 /* 4152 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and 4153 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume 4154 * on UMA that if Normal is populated then so is DMA32. 4155 */ 4156 BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1); 4157 if (nr_online_nodes > 1 && !populated_zone(--zone)) 4158 return alloc_flags; 4159 4160 alloc_flags |= ALLOC_NOFRAGMENT; 4161 #endif /* CONFIG_ZONE_DMA32 */ 4162 return alloc_flags; 4163 } 4164 4165 /* Must be called after current_gfp_context() which can change gfp_mask */ 4166 static inline unsigned int gfp_to_alloc_flags_cma(gfp_t gfp_mask, 4167 unsigned int alloc_flags) 4168 { 4169 #ifdef CONFIG_CMA 4170 if (gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE) 4171 alloc_flags |= ALLOC_CMA; 4172 #endif 4173 return alloc_flags; 4174 } 4175 4176 /* 4177 * get_page_from_freelist goes through the zonelist trying to allocate 4178 * a page. 4179 */ 4180 static struct page * 4181 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, 4182 const struct alloc_context *ac) 4183 { 4184 struct zoneref *z; 4185 struct zone *zone; 4186 struct pglist_data *last_pgdat = NULL; 4187 bool last_pgdat_dirty_ok = false; 4188 bool no_fallback; 4189 4190 retry: 4191 /* 4192 * Scan zonelist, looking for a zone with enough free. 4193 * See also __cpuset_node_allowed() comment in kernel/cgroup/cpuset.c. 4194 */ 4195 no_fallback = alloc_flags & ALLOC_NOFRAGMENT; 4196 z = ac->preferred_zoneref; 4197 for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx, 4198 ac->nodemask) { 4199 struct page *page; 4200 unsigned long mark; 4201 4202 if (cpusets_enabled() && 4203 (alloc_flags & ALLOC_CPUSET) && 4204 !__cpuset_zone_allowed(zone, gfp_mask)) 4205 continue; 4206 /* 4207 * When allocating a page cache page for writing, we 4208 * want to get it from a node that is within its dirty 4209 * limit, such that no single node holds more than its 4210 * proportional share of globally allowed dirty pages. 4211 * The dirty limits take into account the node's 4212 * lowmem reserves and high watermark so that kswapd 4213 * should be able to balance it without having to 4214 * write pages from its LRU list. 4215 * 4216 * XXX: For now, allow allocations to potentially 4217 * exceed the per-node dirty limit in the slowpath 4218 * (spread_dirty_pages unset) before going into reclaim, 4219 * which is important when on a NUMA setup the allowed 4220 * nodes are together not big enough to reach the 4221 * global limit. The proper fix for these situations 4222 * will require awareness of nodes in the 4223 * dirty-throttling and the flusher threads. 4224 */ 4225 if (ac->spread_dirty_pages) { 4226 if (last_pgdat != zone->zone_pgdat) { 4227 last_pgdat = zone->zone_pgdat; 4228 last_pgdat_dirty_ok = node_dirty_ok(zone->zone_pgdat); 4229 } 4230 4231 if (!last_pgdat_dirty_ok) 4232 continue; 4233 } 4234 4235 if (no_fallback && nr_online_nodes > 1 && 4236 zone != ac->preferred_zoneref->zone) { 4237 int local_nid; 4238 4239 /* 4240 * If moving to a remote node, retry but allow 4241 * fragmenting fallbacks. Locality is more important 4242 * than fragmentation avoidance. 4243 */ 4244 local_nid = zone_to_nid(ac->preferred_zoneref->zone); 4245 if (zone_to_nid(zone) != local_nid) { 4246 alloc_flags &= ~ALLOC_NOFRAGMENT; 4247 goto retry; 4248 } 4249 } 4250 4251 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK); 4252 if (!zone_watermark_fast(zone, order, mark, 4253 ac->highest_zoneidx, alloc_flags, 4254 gfp_mask)) { 4255 int ret; 4256 4257 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 4258 /* 4259 * Watermark failed for this zone, but see if we can 4260 * grow this zone if it contains deferred pages. 4261 */ 4262 if (static_branch_unlikely(&deferred_pages)) { 4263 if (_deferred_grow_zone(zone, order)) 4264 goto try_this_zone; 4265 } 4266 #endif 4267 /* Checked here to keep the fast path fast */ 4268 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK); 4269 if (alloc_flags & ALLOC_NO_WATERMARKS) 4270 goto try_this_zone; 4271 4272 if (!node_reclaim_enabled() || 4273 !zone_allows_reclaim(ac->preferred_zoneref->zone, zone)) 4274 continue; 4275 4276 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order); 4277 switch (ret) { 4278 case NODE_RECLAIM_NOSCAN: 4279 /* did not scan */ 4280 continue; 4281 case NODE_RECLAIM_FULL: 4282 /* scanned but unreclaimable */ 4283 continue; 4284 default: 4285 /* did we reclaim enough */ 4286 if (zone_watermark_ok(zone, order, mark, 4287 ac->highest_zoneidx, alloc_flags)) 4288 goto try_this_zone; 4289 4290 continue; 4291 } 4292 } 4293 4294 try_this_zone: 4295 page = rmqueue(ac->preferred_zoneref->zone, zone, order, 4296 gfp_mask, alloc_flags, ac->migratetype); 4297 if (page) { 4298 prep_new_page(page, order, gfp_mask, alloc_flags); 4299 4300 /* 4301 * If this is a high-order atomic allocation then check 4302 * if the pageblock should be reserved for the future 4303 */ 4304 if (unlikely(order && (alloc_flags & ALLOC_HARDER))) 4305 reserve_highatomic_pageblock(page, zone, order); 4306 4307 return page; 4308 } else { 4309 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 4310 /* Try again if zone has deferred pages */ 4311 if (static_branch_unlikely(&deferred_pages)) { 4312 if (_deferred_grow_zone(zone, order)) 4313 goto try_this_zone; 4314 } 4315 #endif 4316 } 4317 } 4318 4319 /* 4320 * It's possible on a UMA machine to get through all zones that are 4321 * fragmented. If avoiding fragmentation, reset and try again. 4322 */ 4323 if (no_fallback) { 4324 alloc_flags &= ~ALLOC_NOFRAGMENT; 4325 goto retry; 4326 } 4327 4328 return NULL; 4329 } 4330 4331 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask) 4332 { 4333 unsigned int filter = SHOW_MEM_FILTER_NODES; 4334 4335 /* 4336 * This documents exceptions given to allocations in certain 4337 * contexts that are allowed to allocate outside current's set 4338 * of allowed nodes. 4339 */ 4340 if (!(gfp_mask & __GFP_NOMEMALLOC)) 4341 if (tsk_is_oom_victim(current) || 4342 (current->flags & (PF_MEMALLOC | PF_EXITING))) 4343 filter &= ~SHOW_MEM_FILTER_NODES; 4344 if (!in_task() || !(gfp_mask & __GFP_DIRECT_RECLAIM)) 4345 filter &= ~SHOW_MEM_FILTER_NODES; 4346 4347 __show_mem(filter, nodemask, gfp_zone(gfp_mask)); 4348 } 4349 4350 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...) 4351 { 4352 struct va_format vaf; 4353 va_list args; 4354 static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1); 4355 4356 if ((gfp_mask & __GFP_NOWARN) || 4357 !__ratelimit(&nopage_rs) || 4358 ((gfp_mask & __GFP_DMA) && !has_managed_dma())) 4359 return; 4360 4361 va_start(args, fmt); 4362 vaf.fmt = fmt; 4363 vaf.va = &args; 4364 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl", 4365 current->comm, &vaf, gfp_mask, &gfp_mask, 4366 nodemask_pr_args(nodemask)); 4367 va_end(args); 4368 4369 cpuset_print_current_mems_allowed(); 4370 pr_cont("\n"); 4371 dump_stack(); 4372 warn_alloc_show_mem(gfp_mask, nodemask); 4373 } 4374 4375 static inline struct page * 4376 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order, 4377 unsigned int alloc_flags, 4378 const struct alloc_context *ac) 4379 { 4380 struct page *page; 4381 4382 page = get_page_from_freelist(gfp_mask, order, 4383 alloc_flags|ALLOC_CPUSET, ac); 4384 /* 4385 * fallback to ignore cpuset restriction if our nodes 4386 * are depleted 4387 */ 4388 if (!page) 4389 page = get_page_from_freelist(gfp_mask, order, 4390 alloc_flags, ac); 4391 4392 return page; 4393 } 4394 4395 static inline struct page * 4396 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order, 4397 const struct alloc_context *ac, unsigned long *did_some_progress) 4398 { 4399 struct oom_control oc = { 4400 .zonelist = ac->zonelist, 4401 .nodemask = ac->nodemask, 4402 .memcg = NULL, 4403 .gfp_mask = gfp_mask, 4404 .order = order, 4405 }; 4406 struct page *page; 4407 4408 *did_some_progress = 0; 4409 4410 /* 4411 * Acquire the oom lock. If that fails, somebody else is 4412 * making progress for us. 4413 */ 4414 if (!mutex_trylock(&oom_lock)) { 4415 *did_some_progress = 1; 4416 schedule_timeout_uninterruptible(1); 4417 return NULL; 4418 } 4419 4420 /* 4421 * Go through the zonelist yet one more time, keep very high watermark 4422 * here, this is only to catch a parallel oom killing, we must fail if 4423 * we're still under heavy pressure. But make sure that this reclaim 4424 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY 4425 * allocation which will never fail due to oom_lock already held. 4426 */ 4427 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) & 4428 ~__GFP_DIRECT_RECLAIM, order, 4429 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac); 4430 if (page) 4431 goto out; 4432 4433 /* Coredumps can quickly deplete all memory reserves */ 4434 if (current->flags & PF_DUMPCORE) 4435 goto out; 4436 /* The OOM killer will not help higher order allocs */ 4437 if (order > PAGE_ALLOC_COSTLY_ORDER) 4438 goto out; 4439 /* 4440 * We have already exhausted all our reclaim opportunities without any 4441 * success so it is time to admit defeat. We will skip the OOM killer 4442 * because it is very likely that the caller has a more reasonable 4443 * fallback than shooting a random task. 4444 * 4445 * The OOM killer may not free memory on a specific node. 4446 */ 4447 if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE)) 4448 goto out; 4449 /* The OOM killer does not needlessly kill tasks for lowmem */ 4450 if (ac->highest_zoneidx < ZONE_NORMAL) 4451 goto out; 4452 if (pm_suspended_storage()) 4453 goto out; 4454 /* 4455 * XXX: GFP_NOFS allocations should rather fail than rely on 4456 * other request to make a forward progress. 4457 * We are in an unfortunate situation where out_of_memory cannot 4458 * do much for this context but let's try it to at least get 4459 * access to memory reserved if the current task is killed (see 4460 * out_of_memory). Once filesystems are ready to handle allocation 4461 * failures more gracefully we should just bail out here. 4462 */ 4463 4464 /* Exhausted what can be done so it's blame time */ 4465 if (out_of_memory(&oc) || 4466 WARN_ON_ONCE_GFP(gfp_mask & __GFP_NOFAIL, gfp_mask)) { 4467 *did_some_progress = 1; 4468 4469 /* 4470 * Help non-failing allocations by giving them access to memory 4471 * reserves 4472 */ 4473 if (gfp_mask & __GFP_NOFAIL) 4474 page = __alloc_pages_cpuset_fallback(gfp_mask, order, 4475 ALLOC_NO_WATERMARKS, ac); 4476 } 4477 out: 4478 mutex_unlock(&oom_lock); 4479 return page; 4480 } 4481 4482 /* 4483 * Maximum number of compaction retries with a progress before OOM 4484 * killer is consider as the only way to move forward. 4485 */ 4486 #define MAX_COMPACT_RETRIES 16 4487 4488 #ifdef CONFIG_COMPACTION 4489 /* Try memory compaction for high-order allocations before reclaim */ 4490 static struct page * 4491 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order, 4492 unsigned int alloc_flags, const struct alloc_context *ac, 4493 enum compact_priority prio, enum compact_result *compact_result) 4494 { 4495 struct page *page = NULL; 4496 unsigned long pflags; 4497 unsigned int noreclaim_flag; 4498 4499 if (!order) 4500 return NULL; 4501 4502 psi_memstall_enter(&pflags); 4503 delayacct_compact_start(); 4504 noreclaim_flag = memalloc_noreclaim_save(); 4505 4506 *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac, 4507 prio, &page); 4508 4509 memalloc_noreclaim_restore(noreclaim_flag); 4510 psi_memstall_leave(&pflags); 4511 delayacct_compact_end(); 4512 4513 if (*compact_result == COMPACT_SKIPPED) 4514 return NULL; 4515 /* 4516 * At least in one zone compaction wasn't deferred or skipped, so let's 4517 * count a compaction stall 4518 */ 4519 count_vm_event(COMPACTSTALL); 4520 4521 /* Prep a captured page if available */ 4522 if (page) 4523 prep_new_page(page, order, gfp_mask, alloc_flags); 4524 4525 /* Try get a page from the freelist if available */ 4526 if (!page) 4527 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 4528 4529 if (page) { 4530 struct zone *zone = page_zone(page); 4531 4532 zone->compact_blockskip_flush = false; 4533 compaction_defer_reset(zone, order, true); 4534 count_vm_event(COMPACTSUCCESS); 4535 return page; 4536 } 4537 4538 /* 4539 * It's bad if compaction run occurs and fails. The most likely reason 4540 * is that pages exist, but not enough to satisfy watermarks. 4541 */ 4542 count_vm_event(COMPACTFAIL); 4543 4544 cond_resched(); 4545 4546 return NULL; 4547 } 4548 4549 static inline bool 4550 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags, 4551 enum compact_result compact_result, 4552 enum compact_priority *compact_priority, 4553 int *compaction_retries) 4554 { 4555 int max_retries = MAX_COMPACT_RETRIES; 4556 int min_priority; 4557 bool ret = false; 4558 int retries = *compaction_retries; 4559 enum compact_priority priority = *compact_priority; 4560 4561 if (!order) 4562 return false; 4563 4564 if (fatal_signal_pending(current)) 4565 return false; 4566 4567 if (compaction_made_progress(compact_result)) 4568 (*compaction_retries)++; 4569 4570 /* 4571 * compaction considers all the zone as desperately out of memory 4572 * so it doesn't really make much sense to retry except when the 4573 * failure could be caused by insufficient priority 4574 */ 4575 if (compaction_failed(compact_result)) 4576 goto check_priority; 4577 4578 /* 4579 * compaction was skipped because there are not enough order-0 pages 4580 * to work with, so we retry only if it looks like reclaim can help. 4581 */ 4582 if (compaction_needs_reclaim(compact_result)) { 4583 ret = compaction_zonelist_suitable(ac, order, alloc_flags); 4584 goto out; 4585 } 4586 4587 /* 4588 * make sure the compaction wasn't deferred or didn't bail out early 4589 * due to locks contention before we declare that we should give up. 4590 * But the next retry should use a higher priority if allowed, so 4591 * we don't just keep bailing out endlessly. 4592 */ 4593 if (compaction_withdrawn(compact_result)) { 4594 goto check_priority; 4595 } 4596 4597 /* 4598 * !costly requests are much more important than __GFP_RETRY_MAYFAIL 4599 * costly ones because they are de facto nofail and invoke OOM 4600 * killer to move on while costly can fail and users are ready 4601 * to cope with that. 1/4 retries is rather arbitrary but we 4602 * would need much more detailed feedback from compaction to 4603 * make a better decision. 4604 */ 4605 if (order > PAGE_ALLOC_COSTLY_ORDER) 4606 max_retries /= 4; 4607 if (*compaction_retries <= max_retries) { 4608 ret = true; 4609 goto out; 4610 } 4611 4612 /* 4613 * Make sure there are attempts at the highest priority if we exhausted 4614 * all retries or failed at the lower priorities. 4615 */ 4616 check_priority: 4617 min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ? 4618 MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY; 4619 4620 if (*compact_priority > min_priority) { 4621 (*compact_priority)--; 4622 *compaction_retries = 0; 4623 ret = true; 4624 } 4625 out: 4626 trace_compact_retry(order, priority, compact_result, retries, max_retries, ret); 4627 return ret; 4628 } 4629 #else 4630 static inline struct page * 4631 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order, 4632 unsigned int alloc_flags, const struct alloc_context *ac, 4633 enum compact_priority prio, enum compact_result *compact_result) 4634 { 4635 *compact_result = COMPACT_SKIPPED; 4636 return NULL; 4637 } 4638 4639 static inline bool 4640 should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags, 4641 enum compact_result compact_result, 4642 enum compact_priority *compact_priority, 4643 int *compaction_retries) 4644 { 4645 struct zone *zone; 4646 struct zoneref *z; 4647 4648 if (!order || order > PAGE_ALLOC_COSTLY_ORDER) 4649 return false; 4650 4651 /* 4652 * There are setups with compaction disabled which would prefer to loop 4653 * inside the allocator rather than hit the oom killer prematurely. 4654 * Let's give them a good hope and keep retrying while the order-0 4655 * watermarks are OK. 4656 */ 4657 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, 4658 ac->highest_zoneidx, ac->nodemask) { 4659 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone), 4660 ac->highest_zoneidx, alloc_flags)) 4661 return true; 4662 } 4663 return false; 4664 } 4665 #endif /* CONFIG_COMPACTION */ 4666 4667 #ifdef CONFIG_LOCKDEP 4668 static struct lockdep_map __fs_reclaim_map = 4669 STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map); 4670 4671 static bool __need_reclaim(gfp_t gfp_mask) 4672 { 4673 /* no reclaim without waiting on it */ 4674 if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) 4675 return false; 4676 4677 /* this guy won't enter reclaim */ 4678 if (current->flags & PF_MEMALLOC) 4679 return false; 4680 4681 if (gfp_mask & __GFP_NOLOCKDEP) 4682 return false; 4683 4684 return true; 4685 } 4686 4687 void __fs_reclaim_acquire(unsigned long ip) 4688 { 4689 lock_acquire_exclusive(&__fs_reclaim_map, 0, 0, NULL, ip); 4690 } 4691 4692 void __fs_reclaim_release(unsigned long ip) 4693 { 4694 lock_release(&__fs_reclaim_map, ip); 4695 } 4696 4697 void fs_reclaim_acquire(gfp_t gfp_mask) 4698 { 4699 gfp_mask = current_gfp_context(gfp_mask); 4700 4701 if (__need_reclaim(gfp_mask)) { 4702 if (gfp_mask & __GFP_FS) 4703 __fs_reclaim_acquire(_RET_IP_); 4704 4705 #ifdef CONFIG_MMU_NOTIFIER 4706 lock_map_acquire(&__mmu_notifier_invalidate_range_start_map); 4707 lock_map_release(&__mmu_notifier_invalidate_range_start_map); 4708 #endif 4709 4710 } 4711 } 4712 EXPORT_SYMBOL_GPL(fs_reclaim_acquire); 4713 4714 void fs_reclaim_release(gfp_t gfp_mask) 4715 { 4716 gfp_mask = current_gfp_context(gfp_mask); 4717 4718 if (__need_reclaim(gfp_mask)) { 4719 if (gfp_mask & __GFP_FS) 4720 __fs_reclaim_release(_RET_IP_); 4721 } 4722 } 4723 EXPORT_SYMBOL_GPL(fs_reclaim_release); 4724 #endif 4725 4726 /* 4727 * Zonelists may change due to hotplug during allocation. Detect when zonelists 4728 * have been rebuilt so allocation retries. Reader side does not lock and 4729 * retries the allocation if zonelist changes. Writer side is protected by the 4730 * embedded spin_lock. 4731 */ 4732 static DEFINE_SEQLOCK(zonelist_update_seq); 4733 4734 static unsigned int zonelist_iter_begin(void) 4735 { 4736 if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) 4737 return read_seqbegin(&zonelist_update_seq); 4738 4739 return 0; 4740 } 4741 4742 static unsigned int check_retry_zonelist(unsigned int seq) 4743 { 4744 if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) 4745 return read_seqretry(&zonelist_update_seq, seq); 4746 4747 return seq; 4748 } 4749 4750 /* Perform direct synchronous page reclaim */ 4751 static unsigned long 4752 __perform_reclaim(gfp_t gfp_mask, unsigned int order, 4753 const struct alloc_context *ac) 4754 { 4755 unsigned int noreclaim_flag; 4756 unsigned long progress; 4757 4758 cond_resched(); 4759 4760 /* We now go into synchronous reclaim */ 4761 cpuset_memory_pressure_bump(); 4762 fs_reclaim_acquire(gfp_mask); 4763 noreclaim_flag = memalloc_noreclaim_save(); 4764 4765 progress = try_to_free_pages(ac->zonelist, order, gfp_mask, 4766 ac->nodemask); 4767 4768 memalloc_noreclaim_restore(noreclaim_flag); 4769 fs_reclaim_release(gfp_mask); 4770 4771 cond_resched(); 4772 4773 return progress; 4774 } 4775 4776 /* The really slow allocator path where we enter direct reclaim */ 4777 static inline struct page * 4778 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order, 4779 unsigned int alloc_flags, const struct alloc_context *ac, 4780 unsigned long *did_some_progress) 4781 { 4782 struct page *page = NULL; 4783 unsigned long pflags; 4784 bool drained = false; 4785 4786 psi_memstall_enter(&pflags); 4787 *did_some_progress = __perform_reclaim(gfp_mask, order, ac); 4788 if (unlikely(!(*did_some_progress))) 4789 goto out; 4790 4791 retry: 4792 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 4793 4794 /* 4795 * If an allocation failed after direct reclaim, it could be because 4796 * pages are pinned on the per-cpu lists or in high alloc reserves. 4797 * Shrink them and try again 4798 */ 4799 if (!page && !drained) { 4800 unreserve_highatomic_pageblock(ac, false); 4801 drain_all_pages(NULL); 4802 drained = true; 4803 goto retry; 4804 } 4805 out: 4806 psi_memstall_leave(&pflags); 4807 4808 return page; 4809 } 4810 4811 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask, 4812 const struct alloc_context *ac) 4813 { 4814 struct zoneref *z; 4815 struct zone *zone; 4816 pg_data_t *last_pgdat = NULL; 4817 enum zone_type highest_zoneidx = ac->highest_zoneidx; 4818 4819 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx, 4820 ac->nodemask) { 4821 if (!managed_zone(zone)) 4822 continue; 4823 if (last_pgdat != zone->zone_pgdat) { 4824 wakeup_kswapd(zone, gfp_mask, order, highest_zoneidx); 4825 last_pgdat = zone->zone_pgdat; 4826 } 4827 } 4828 } 4829 4830 static inline unsigned int 4831 gfp_to_alloc_flags(gfp_t gfp_mask) 4832 { 4833 unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET; 4834 4835 /* 4836 * __GFP_HIGH is assumed to be the same as ALLOC_HIGH 4837 * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD 4838 * to save two branches. 4839 */ 4840 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH); 4841 BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD); 4842 4843 /* 4844 * The caller may dip into page reserves a bit more if the caller 4845 * cannot run direct reclaim, or if the caller has realtime scheduling 4846 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will 4847 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH). 4848 */ 4849 alloc_flags |= (__force int) 4850 (gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM)); 4851 4852 if (gfp_mask & __GFP_ATOMIC) { 4853 /* 4854 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even 4855 * if it can't schedule. 4856 */ 4857 if (!(gfp_mask & __GFP_NOMEMALLOC)) 4858 alloc_flags |= ALLOC_HARDER; 4859 /* 4860 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the 4861 * comment for __cpuset_node_allowed(). 4862 */ 4863 alloc_flags &= ~ALLOC_CPUSET; 4864 } else if (unlikely(rt_task(current)) && in_task()) 4865 alloc_flags |= ALLOC_HARDER; 4866 4867 alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, alloc_flags); 4868 4869 return alloc_flags; 4870 } 4871 4872 static bool oom_reserves_allowed(struct task_struct *tsk) 4873 { 4874 if (!tsk_is_oom_victim(tsk)) 4875 return false; 4876 4877 /* 4878 * !MMU doesn't have oom reaper so give access to memory reserves 4879 * only to the thread with TIF_MEMDIE set 4880 */ 4881 if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE)) 4882 return false; 4883 4884 return true; 4885 } 4886 4887 /* 4888 * Distinguish requests which really need access to full memory 4889 * reserves from oom victims which can live with a portion of it 4890 */ 4891 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask) 4892 { 4893 if (unlikely(gfp_mask & __GFP_NOMEMALLOC)) 4894 return 0; 4895 if (gfp_mask & __GFP_MEMALLOC) 4896 return ALLOC_NO_WATERMARKS; 4897 if (in_serving_softirq() && (current->flags & PF_MEMALLOC)) 4898 return ALLOC_NO_WATERMARKS; 4899 if (!in_interrupt()) { 4900 if (current->flags & PF_MEMALLOC) 4901 return ALLOC_NO_WATERMARKS; 4902 else if (oom_reserves_allowed(current)) 4903 return ALLOC_OOM; 4904 } 4905 4906 return 0; 4907 } 4908 4909 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask) 4910 { 4911 return !!__gfp_pfmemalloc_flags(gfp_mask); 4912 } 4913 4914 /* 4915 * Checks whether it makes sense to retry the reclaim to make a forward progress 4916 * for the given allocation request. 4917 * 4918 * We give up when we either have tried MAX_RECLAIM_RETRIES in a row 4919 * without success, or when we couldn't even meet the watermark if we 4920 * reclaimed all remaining pages on the LRU lists. 4921 * 4922 * Returns true if a retry is viable or false to enter the oom path. 4923 */ 4924 static inline bool 4925 should_reclaim_retry(gfp_t gfp_mask, unsigned order, 4926 struct alloc_context *ac, int alloc_flags, 4927 bool did_some_progress, int *no_progress_loops) 4928 { 4929 struct zone *zone; 4930 struct zoneref *z; 4931 bool ret = false; 4932 4933 /* 4934 * Costly allocations might have made a progress but this doesn't mean 4935 * their order will become available due to high fragmentation so 4936 * always increment the no progress counter for them 4937 */ 4938 if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER) 4939 *no_progress_loops = 0; 4940 else 4941 (*no_progress_loops)++; 4942 4943 /* 4944 * Make sure we converge to OOM if we cannot make any progress 4945 * several times in the row. 4946 */ 4947 if (*no_progress_loops > MAX_RECLAIM_RETRIES) { 4948 /* Before OOM, exhaust highatomic_reserve */ 4949 return unreserve_highatomic_pageblock(ac, true); 4950 } 4951 4952 /* 4953 * Keep reclaiming pages while there is a chance this will lead 4954 * somewhere. If none of the target zones can satisfy our allocation 4955 * request even if all reclaimable pages are considered then we are 4956 * screwed and have to go OOM. 4957 */ 4958 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, 4959 ac->highest_zoneidx, ac->nodemask) { 4960 unsigned long available; 4961 unsigned long reclaimable; 4962 unsigned long min_wmark = min_wmark_pages(zone); 4963 bool wmark; 4964 4965 available = reclaimable = zone_reclaimable_pages(zone); 4966 available += zone_page_state_snapshot(zone, NR_FREE_PAGES); 4967 4968 /* 4969 * Would the allocation succeed if we reclaimed all 4970 * reclaimable pages? 4971 */ 4972 wmark = __zone_watermark_ok(zone, order, min_wmark, 4973 ac->highest_zoneidx, alloc_flags, available); 4974 trace_reclaim_retry_zone(z, order, reclaimable, 4975 available, min_wmark, *no_progress_loops, wmark); 4976 if (wmark) { 4977 ret = true; 4978 break; 4979 } 4980 } 4981 4982 /* 4983 * Memory allocation/reclaim might be called from a WQ context and the 4984 * current implementation of the WQ concurrency control doesn't 4985 * recognize that a particular WQ is congested if the worker thread is 4986 * looping without ever sleeping. Therefore we have to do a short sleep 4987 * here rather than calling cond_resched(). 4988 */ 4989 if (current->flags & PF_WQ_WORKER) 4990 schedule_timeout_uninterruptible(1); 4991 else 4992 cond_resched(); 4993 return ret; 4994 } 4995 4996 static inline bool 4997 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac) 4998 { 4999 /* 5000 * It's possible that cpuset's mems_allowed and the nodemask from 5001 * mempolicy don't intersect. This should be normally dealt with by 5002 * policy_nodemask(), but it's possible to race with cpuset update in 5003 * such a way the check therein was true, and then it became false 5004 * before we got our cpuset_mems_cookie here. 5005 * This assumes that for all allocations, ac->nodemask can come only 5006 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored 5007 * when it does not intersect with the cpuset restrictions) or the 5008 * caller can deal with a violated nodemask. 5009 */ 5010 if (cpusets_enabled() && ac->nodemask && 5011 !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) { 5012 ac->nodemask = NULL; 5013 return true; 5014 } 5015 5016 /* 5017 * When updating a task's mems_allowed or mempolicy nodemask, it is 5018 * possible to race with parallel threads in such a way that our 5019 * allocation can fail while the mask is being updated. If we are about 5020 * to fail, check if the cpuset changed during allocation and if so, 5021 * retry. 5022 */ 5023 if (read_mems_allowed_retry(cpuset_mems_cookie)) 5024 return true; 5025 5026 return false; 5027 } 5028 5029 static inline struct page * 5030 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order, 5031 struct alloc_context *ac) 5032 { 5033 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM; 5034 const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER; 5035 struct page *page = NULL; 5036 unsigned int alloc_flags; 5037 unsigned long did_some_progress; 5038 enum compact_priority compact_priority; 5039 enum compact_result compact_result; 5040 int compaction_retries; 5041 int no_progress_loops; 5042 unsigned int cpuset_mems_cookie; 5043 unsigned int zonelist_iter_cookie; 5044 int reserve_flags; 5045 5046 /* 5047 * We also sanity check to catch abuse of atomic reserves being used by 5048 * callers that are not in atomic context. 5049 */ 5050 if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) == 5051 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM))) 5052 gfp_mask &= ~__GFP_ATOMIC; 5053 5054 restart: 5055 compaction_retries = 0; 5056 no_progress_loops = 0; 5057 compact_priority = DEF_COMPACT_PRIORITY; 5058 cpuset_mems_cookie = read_mems_allowed_begin(); 5059 zonelist_iter_cookie = zonelist_iter_begin(); 5060 5061 /* 5062 * The fast path uses conservative alloc_flags to succeed only until 5063 * kswapd needs to be woken up, and to avoid the cost of setting up 5064 * alloc_flags precisely. So we do that now. 5065 */ 5066 alloc_flags = gfp_to_alloc_flags(gfp_mask); 5067 5068 /* 5069 * We need to recalculate the starting point for the zonelist iterator 5070 * because we might have used different nodemask in the fast path, or 5071 * there was a cpuset modification and we are retrying - otherwise we 5072 * could end up iterating over non-eligible zones endlessly. 5073 */ 5074 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist, 5075 ac->highest_zoneidx, ac->nodemask); 5076 if (!ac->preferred_zoneref->zone) 5077 goto nopage; 5078 5079 /* 5080 * Check for insane configurations where the cpuset doesn't contain 5081 * any suitable zone to satisfy the request - e.g. non-movable 5082 * GFP_HIGHUSER allocations from MOVABLE nodes only. 5083 */ 5084 if (cpusets_insane_config() && (gfp_mask & __GFP_HARDWALL)) { 5085 struct zoneref *z = first_zones_zonelist(ac->zonelist, 5086 ac->highest_zoneidx, 5087 &cpuset_current_mems_allowed); 5088 if (!z->zone) 5089 goto nopage; 5090 } 5091 5092 if (alloc_flags & ALLOC_KSWAPD) 5093 wake_all_kswapds(order, gfp_mask, ac); 5094 5095 /* 5096 * The adjusted alloc_flags might result in immediate success, so try 5097 * that first 5098 */ 5099 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 5100 if (page) 5101 goto got_pg; 5102 5103 /* 5104 * For costly allocations, try direct compaction first, as it's likely 5105 * that we have enough base pages and don't need to reclaim. For non- 5106 * movable high-order allocations, do that as well, as compaction will 5107 * try prevent permanent fragmentation by migrating from blocks of the 5108 * same migratetype. 5109 * Don't try this for allocations that are allowed to ignore 5110 * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen. 5111 */ 5112 if (can_direct_reclaim && 5113 (costly_order || 5114 (order > 0 && ac->migratetype != MIGRATE_MOVABLE)) 5115 && !gfp_pfmemalloc_allowed(gfp_mask)) { 5116 page = __alloc_pages_direct_compact(gfp_mask, order, 5117 alloc_flags, ac, 5118 INIT_COMPACT_PRIORITY, 5119 &compact_result); 5120 if (page) 5121 goto got_pg; 5122 5123 /* 5124 * Checks for costly allocations with __GFP_NORETRY, which 5125 * includes some THP page fault allocations 5126 */ 5127 if (costly_order && (gfp_mask & __GFP_NORETRY)) { 5128 /* 5129 * If allocating entire pageblock(s) and compaction 5130 * failed because all zones are below low watermarks 5131 * or is prohibited because it recently failed at this 5132 * order, fail immediately unless the allocator has 5133 * requested compaction and reclaim retry. 5134 * 5135 * Reclaim is 5136 * - potentially very expensive because zones are far 5137 * below their low watermarks or this is part of very 5138 * bursty high order allocations, 5139 * - not guaranteed to help because isolate_freepages() 5140 * may not iterate over freed pages as part of its 5141 * linear scan, and 5142 * - unlikely to make entire pageblocks free on its 5143 * own. 5144 */ 5145 if (compact_result == COMPACT_SKIPPED || 5146 compact_result == COMPACT_DEFERRED) 5147 goto nopage; 5148 5149 /* 5150 * Looks like reclaim/compaction is worth trying, but 5151 * sync compaction could be very expensive, so keep 5152 * using async compaction. 5153 */ 5154 compact_priority = INIT_COMPACT_PRIORITY; 5155 } 5156 } 5157 5158 retry: 5159 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */ 5160 if (alloc_flags & ALLOC_KSWAPD) 5161 wake_all_kswapds(order, gfp_mask, ac); 5162 5163 reserve_flags = __gfp_pfmemalloc_flags(gfp_mask); 5164 if (reserve_flags) 5165 alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, reserve_flags) | 5166 (alloc_flags & ALLOC_KSWAPD); 5167 5168 /* 5169 * Reset the nodemask and zonelist iterators if memory policies can be 5170 * ignored. These allocations are high priority and system rather than 5171 * user oriented. 5172 */ 5173 if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) { 5174 ac->nodemask = NULL; 5175 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist, 5176 ac->highest_zoneidx, ac->nodemask); 5177 } 5178 5179 /* Attempt with potentially adjusted zonelist and alloc_flags */ 5180 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 5181 if (page) 5182 goto got_pg; 5183 5184 /* Caller is not willing to reclaim, we can't balance anything */ 5185 if (!can_direct_reclaim) 5186 goto nopage; 5187 5188 /* Avoid recursion of direct reclaim */ 5189 if (current->flags & PF_MEMALLOC) 5190 goto nopage; 5191 5192 /* Try direct reclaim and then allocating */ 5193 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac, 5194 &did_some_progress); 5195 if (page) 5196 goto got_pg; 5197 5198 /* Try direct compaction and then allocating */ 5199 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac, 5200 compact_priority, &compact_result); 5201 if (page) 5202 goto got_pg; 5203 5204 /* Do not loop if specifically requested */ 5205 if (gfp_mask & __GFP_NORETRY) 5206 goto nopage; 5207 5208 /* 5209 * Do not retry costly high order allocations unless they are 5210 * __GFP_RETRY_MAYFAIL 5211 */ 5212 if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL)) 5213 goto nopage; 5214 5215 if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags, 5216 did_some_progress > 0, &no_progress_loops)) 5217 goto retry; 5218 5219 /* 5220 * It doesn't make any sense to retry for the compaction if the order-0 5221 * reclaim is not able to make any progress because the current 5222 * implementation of the compaction depends on the sufficient amount 5223 * of free memory (see __compaction_suitable) 5224 */ 5225 if (did_some_progress > 0 && 5226 should_compact_retry(ac, order, alloc_flags, 5227 compact_result, &compact_priority, 5228 &compaction_retries)) 5229 goto retry; 5230 5231 5232 /* 5233 * Deal with possible cpuset update races or zonelist updates to avoid 5234 * a unnecessary OOM kill. 5235 */ 5236 if (check_retry_cpuset(cpuset_mems_cookie, ac) || 5237 check_retry_zonelist(zonelist_iter_cookie)) 5238 goto restart; 5239 5240 /* Reclaim has failed us, start killing things */ 5241 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress); 5242 if (page) 5243 goto got_pg; 5244 5245 /* Avoid allocations with no watermarks from looping endlessly */ 5246 if (tsk_is_oom_victim(current) && 5247 (alloc_flags & ALLOC_OOM || 5248 (gfp_mask & __GFP_NOMEMALLOC))) 5249 goto nopage; 5250 5251 /* Retry as long as the OOM killer is making progress */ 5252 if (did_some_progress) { 5253 no_progress_loops = 0; 5254 goto retry; 5255 } 5256 5257 nopage: 5258 /* 5259 * Deal with possible cpuset update races or zonelist updates to avoid 5260 * a unnecessary OOM kill. 5261 */ 5262 if (check_retry_cpuset(cpuset_mems_cookie, ac) || 5263 check_retry_zonelist(zonelist_iter_cookie)) 5264 goto restart; 5265 5266 /* 5267 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure 5268 * we always retry 5269 */ 5270 if (gfp_mask & __GFP_NOFAIL) { 5271 /* 5272 * All existing users of the __GFP_NOFAIL are blockable, so warn 5273 * of any new users that actually require GFP_NOWAIT 5274 */ 5275 if (WARN_ON_ONCE_GFP(!can_direct_reclaim, gfp_mask)) 5276 goto fail; 5277 5278 /* 5279 * PF_MEMALLOC request from this context is rather bizarre 5280 * because we cannot reclaim anything and only can loop waiting 5281 * for somebody to do a work for us 5282 */ 5283 WARN_ON_ONCE_GFP(current->flags & PF_MEMALLOC, gfp_mask); 5284 5285 /* 5286 * non failing costly orders are a hard requirement which we 5287 * are not prepared for much so let's warn about these users 5288 * so that we can identify them and convert them to something 5289 * else. 5290 */ 5291 WARN_ON_ONCE_GFP(costly_order, gfp_mask); 5292 5293 /* 5294 * Help non-failing allocations by giving them access to memory 5295 * reserves but do not use ALLOC_NO_WATERMARKS because this 5296 * could deplete whole memory reserves which would just make 5297 * the situation worse 5298 */ 5299 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac); 5300 if (page) 5301 goto got_pg; 5302 5303 cond_resched(); 5304 goto retry; 5305 } 5306 fail: 5307 warn_alloc(gfp_mask, ac->nodemask, 5308 "page allocation failure: order:%u", order); 5309 got_pg: 5310 return page; 5311 } 5312 5313 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order, 5314 int preferred_nid, nodemask_t *nodemask, 5315 struct alloc_context *ac, gfp_t *alloc_gfp, 5316 unsigned int *alloc_flags) 5317 { 5318 ac->highest_zoneidx = gfp_zone(gfp_mask); 5319 ac->zonelist = node_zonelist(preferred_nid, gfp_mask); 5320 ac->nodemask = nodemask; 5321 ac->migratetype = gfp_migratetype(gfp_mask); 5322 5323 if (cpusets_enabled()) { 5324 *alloc_gfp |= __GFP_HARDWALL; 5325 /* 5326 * When we are in the interrupt context, it is irrelevant 5327 * to the current task context. It means that any node ok. 5328 */ 5329 if (in_task() && !ac->nodemask) 5330 ac->nodemask = &cpuset_current_mems_allowed; 5331 else 5332 *alloc_flags |= ALLOC_CPUSET; 5333 } 5334 5335 might_alloc(gfp_mask); 5336 5337 if (should_fail_alloc_page(gfp_mask, order)) 5338 return false; 5339 5340 *alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, *alloc_flags); 5341 5342 /* Dirty zone balancing only done in the fast path */ 5343 ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE); 5344 5345 /* 5346 * The preferred zone is used for statistics but crucially it is 5347 * also used as the starting point for the zonelist iterator. It 5348 * may get reset for allocations that ignore memory policies. 5349 */ 5350 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist, 5351 ac->highest_zoneidx, ac->nodemask); 5352 5353 return true; 5354 } 5355 5356 /* 5357 * __alloc_pages_bulk - Allocate a number of order-0 pages to a list or array 5358 * @gfp: GFP flags for the allocation 5359 * @preferred_nid: The preferred NUMA node ID to allocate from 5360 * @nodemask: Set of nodes to allocate from, may be NULL 5361 * @nr_pages: The number of pages desired on the list or array 5362 * @page_list: Optional list to store the allocated pages 5363 * @page_array: Optional array to store the pages 5364 * 5365 * This is a batched version of the page allocator that attempts to 5366 * allocate nr_pages quickly. Pages are added to page_list if page_list 5367 * is not NULL, otherwise it is assumed that the page_array is valid. 5368 * 5369 * For lists, nr_pages is the number of pages that should be allocated. 5370 * 5371 * For arrays, only NULL elements are populated with pages and nr_pages 5372 * is the maximum number of pages that will be stored in the array. 5373 * 5374 * Returns the number of pages on the list or array. 5375 */ 5376 unsigned long __alloc_pages_bulk(gfp_t gfp, int preferred_nid, 5377 nodemask_t *nodemask, int nr_pages, 5378 struct list_head *page_list, 5379 struct page **page_array) 5380 { 5381 struct page *page; 5382 unsigned long __maybe_unused UP_flags; 5383 struct zone *zone; 5384 struct zoneref *z; 5385 struct per_cpu_pages *pcp; 5386 struct list_head *pcp_list; 5387 struct alloc_context ac; 5388 gfp_t alloc_gfp; 5389 unsigned int alloc_flags = ALLOC_WMARK_LOW; 5390 int nr_populated = 0, nr_account = 0; 5391 5392 /* 5393 * Skip populated array elements to determine if any pages need 5394 * to be allocated before disabling IRQs. 5395 */ 5396 while (page_array && nr_populated < nr_pages && page_array[nr_populated]) 5397 nr_populated++; 5398 5399 /* No pages requested? */ 5400 if (unlikely(nr_pages <= 0)) 5401 goto out; 5402 5403 /* Already populated array? */ 5404 if (unlikely(page_array && nr_pages - nr_populated == 0)) 5405 goto out; 5406 5407 /* Bulk allocator does not support memcg accounting. */ 5408 if (memcg_kmem_enabled() && (gfp & __GFP_ACCOUNT)) 5409 goto failed; 5410 5411 /* Use the single page allocator for one page. */ 5412 if (nr_pages - nr_populated == 1) 5413 goto failed; 5414 5415 #ifdef CONFIG_PAGE_OWNER 5416 /* 5417 * PAGE_OWNER may recurse into the allocator to allocate space to 5418 * save the stack with pagesets.lock held. Releasing/reacquiring 5419 * removes much of the performance benefit of bulk allocation so 5420 * force the caller to allocate one page at a time as it'll have 5421 * similar performance to added complexity to the bulk allocator. 5422 */ 5423 if (static_branch_unlikely(&page_owner_inited)) 5424 goto failed; 5425 #endif 5426 5427 /* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */ 5428 gfp &= gfp_allowed_mask; 5429 alloc_gfp = gfp; 5430 if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &alloc_gfp, &alloc_flags)) 5431 goto out; 5432 gfp = alloc_gfp; 5433 5434 /* Find an allowed local zone that meets the low watermark. */ 5435 for_each_zone_zonelist_nodemask(zone, z, ac.zonelist, ac.highest_zoneidx, ac.nodemask) { 5436 unsigned long mark; 5437 5438 if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) && 5439 !__cpuset_zone_allowed(zone, gfp)) { 5440 continue; 5441 } 5442 5443 if (nr_online_nodes > 1 && zone != ac.preferred_zoneref->zone && 5444 zone_to_nid(zone) != zone_to_nid(ac.preferred_zoneref->zone)) { 5445 goto failed; 5446 } 5447 5448 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages; 5449 if (zone_watermark_fast(zone, 0, mark, 5450 zonelist_zone_idx(ac.preferred_zoneref), 5451 alloc_flags, gfp)) { 5452 break; 5453 } 5454 } 5455 5456 /* 5457 * If there are no allowed local zones that meets the watermarks then 5458 * try to allocate a single page and reclaim if necessary. 5459 */ 5460 if (unlikely(!zone)) 5461 goto failed; 5462 5463 /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */ 5464 pcp_trylock_prepare(UP_flags); 5465 pcp = pcp_spin_trylock(zone->per_cpu_pageset); 5466 if (!pcp) 5467 goto failed_irq; 5468 5469 /* Attempt the batch allocation */ 5470 pcp_list = &pcp->lists[order_to_pindex(ac.migratetype, 0)]; 5471 while (nr_populated < nr_pages) { 5472 5473 /* Skip existing pages */ 5474 if (page_array && page_array[nr_populated]) { 5475 nr_populated++; 5476 continue; 5477 } 5478 5479 page = __rmqueue_pcplist(zone, 0, ac.migratetype, alloc_flags, 5480 pcp, pcp_list); 5481 if (unlikely(!page)) { 5482 /* Try and allocate at least one page */ 5483 if (!nr_account) { 5484 pcp_spin_unlock(pcp); 5485 goto failed_irq; 5486 } 5487 break; 5488 } 5489 nr_account++; 5490 5491 prep_new_page(page, 0, gfp, 0); 5492 if (page_list) 5493 list_add(&page->lru, page_list); 5494 else 5495 page_array[nr_populated] = page; 5496 nr_populated++; 5497 } 5498 5499 pcp_spin_unlock(pcp); 5500 pcp_trylock_finish(UP_flags); 5501 5502 __count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account); 5503 zone_statistics(ac.preferred_zoneref->zone, zone, nr_account); 5504 5505 out: 5506 return nr_populated; 5507 5508 failed_irq: 5509 pcp_trylock_finish(UP_flags); 5510 5511 failed: 5512 page = __alloc_pages(gfp, 0, preferred_nid, nodemask); 5513 if (page) { 5514 if (page_list) 5515 list_add(&page->lru, page_list); 5516 else 5517 page_array[nr_populated] = page; 5518 nr_populated++; 5519 } 5520 5521 goto out; 5522 } 5523 EXPORT_SYMBOL_GPL(__alloc_pages_bulk); 5524 5525 /* 5526 * This is the 'heart' of the zoned buddy allocator. 5527 */ 5528 struct page *__alloc_pages(gfp_t gfp, unsigned int order, int preferred_nid, 5529 nodemask_t *nodemask) 5530 { 5531 struct page *page; 5532 unsigned int alloc_flags = ALLOC_WMARK_LOW; 5533 gfp_t alloc_gfp; /* The gfp_t that was actually used for allocation */ 5534 struct alloc_context ac = { }; 5535 5536 /* 5537 * There are several places where we assume that the order value is sane 5538 * so bail out early if the request is out of bound. 5539 */ 5540 if (WARN_ON_ONCE_GFP(order >= MAX_ORDER, gfp)) 5541 return NULL; 5542 5543 gfp &= gfp_allowed_mask; 5544 /* 5545 * Apply scoped allocation constraints. This is mainly about GFP_NOFS 5546 * resp. GFP_NOIO which has to be inherited for all allocation requests 5547 * from a particular context which has been marked by 5548 * memalloc_no{fs,io}_{save,restore}. And PF_MEMALLOC_PIN which ensures 5549 * movable zones are not used during allocation. 5550 */ 5551 gfp = current_gfp_context(gfp); 5552 alloc_gfp = gfp; 5553 if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac, 5554 &alloc_gfp, &alloc_flags)) 5555 return NULL; 5556 5557 /* 5558 * Forbid the first pass from falling back to types that fragment 5559 * memory until all local zones are considered. 5560 */ 5561 alloc_flags |= alloc_flags_nofragment(ac.preferred_zoneref->zone, gfp); 5562 5563 /* First allocation attempt */ 5564 page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac); 5565 if (likely(page)) 5566 goto out; 5567 5568 alloc_gfp = gfp; 5569 ac.spread_dirty_pages = false; 5570 5571 /* 5572 * Restore the original nodemask if it was potentially replaced with 5573 * &cpuset_current_mems_allowed to optimize the fast-path attempt. 5574 */ 5575 ac.nodemask = nodemask; 5576 5577 page = __alloc_pages_slowpath(alloc_gfp, order, &ac); 5578 5579 out: 5580 if (memcg_kmem_enabled() && (gfp & __GFP_ACCOUNT) && page && 5581 unlikely(__memcg_kmem_charge_page(page, gfp, order) != 0)) { 5582 __free_pages(page, order); 5583 page = NULL; 5584 } 5585 5586 trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype); 5587 kmsan_alloc_page(page, order, alloc_gfp); 5588 5589 return page; 5590 } 5591 EXPORT_SYMBOL(__alloc_pages); 5592 5593 struct folio *__folio_alloc(gfp_t gfp, unsigned int order, int preferred_nid, 5594 nodemask_t *nodemask) 5595 { 5596 struct page *page = __alloc_pages(gfp | __GFP_COMP, order, 5597 preferred_nid, nodemask); 5598 5599 if (page && order > 1) 5600 prep_transhuge_page(page); 5601 return (struct folio *)page; 5602 } 5603 EXPORT_SYMBOL(__folio_alloc); 5604 5605 /* 5606 * Common helper functions. Never use with __GFP_HIGHMEM because the returned 5607 * address cannot represent highmem pages. Use alloc_pages and then kmap if 5608 * you need to access high mem. 5609 */ 5610 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order) 5611 { 5612 struct page *page; 5613 5614 page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order); 5615 if (!page) 5616 return 0; 5617 return (unsigned long) page_address(page); 5618 } 5619 EXPORT_SYMBOL(__get_free_pages); 5620 5621 unsigned long get_zeroed_page(gfp_t gfp_mask) 5622 { 5623 return __get_free_pages(gfp_mask | __GFP_ZERO, 0); 5624 } 5625 EXPORT_SYMBOL(get_zeroed_page); 5626 5627 /** 5628 * __free_pages - Free pages allocated with alloc_pages(). 5629 * @page: The page pointer returned from alloc_pages(). 5630 * @order: The order of the allocation. 5631 * 5632 * This function can free multi-page allocations that are not compound 5633 * pages. It does not check that the @order passed in matches that of 5634 * the allocation, so it is easy to leak memory. Freeing more memory 5635 * than was allocated will probably emit a warning. 5636 * 5637 * If the last reference to this page is speculative, it will be released 5638 * by put_page() which only frees the first page of a non-compound 5639 * allocation. To prevent the remaining pages from being leaked, we free 5640 * the subsequent pages here. If you want to use the page's reference 5641 * count to decide when to free the allocation, you should allocate a 5642 * compound page, and use put_page() instead of __free_pages(). 5643 * 5644 * Context: May be called in interrupt context or while holding a normal 5645 * spinlock, but not in NMI context or while holding a raw spinlock. 5646 */ 5647 void __free_pages(struct page *page, unsigned int order) 5648 { 5649 if (put_page_testzero(page)) 5650 free_the_page(page, order); 5651 else if (!PageHead(page)) 5652 while (order-- > 0) 5653 free_the_page(page + (1 << order), order); 5654 } 5655 EXPORT_SYMBOL(__free_pages); 5656 5657 void free_pages(unsigned long addr, unsigned int order) 5658 { 5659 if (addr != 0) { 5660 VM_BUG_ON(!virt_addr_valid((void *)addr)); 5661 __free_pages(virt_to_page((void *)addr), order); 5662 } 5663 } 5664 5665 EXPORT_SYMBOL(free_pages); 5666 5667 /* 5668 * Page Fragment: 5669 * An arbitrary-length arbitrary-offset area of memory which resides 5670 * within a 0 or higher order page. Multiple fragments within that page 5671 * are individually refcounted, in the page's reference counter. 5672 * 5673 * The page_frag functions below provide a simple allocation framework for 5674 * page fragments. This is used by the network stack and network device 5675 * drivers to provide a backing region of memory for use as either an 5676 * sk_buff->head, or to be used in the "frags" portion of skb_shared_info. 5677 */ 5678 static struct page *__page_frag_cache_refill(struct page_frag_cache *nc, 5679 gfp_t gfp_mask) 5680 { 5681 struct page *page = NULL; 5682 gfp_t gfp = gfp_mask; 5683 5684 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE) 5685 gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY | 5686 __GFP_NOMEMALLOC; 5687 page = alloc_pages_node(NUMA_NO_NODE, gfp_mask, 5688 PAGE_FRAG_CACHE_MAX_ORDER); 5689 nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE; 5690 #endif 5691 if (unlikely(!page)) 5692 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0); 5693 5694 nc->va = page ? page_address(page) : NULL; 5695 5696 return page; 5697 } 5698 5699 void __page_frag_cache_drain(struct page *page, unsigned int count) 5700 { 5701 VM_BUG_ON_PAGE(page_ref_count(page) == 0, page); 5702 5703 if (page_ref_sub_and_test(page, count)) 5704 free_the_page(page, compound_order(page)); 5705 } 5706 EXPORT_SYMBOL(__page_frag_cache_drain); 5707 5708 void *page_frag_alloc_align(struct page_frag_cache *nc, 5709 unsigned int fragsz, gfp_t gfp_mask, 5710 unsigned int align_mask) 5711 { 5712 unsigned int size = PAGE_SIZE; 5713 struct page *page; 5714 int offset; 5715 5716 if (unlikely(!nc->va)) { 5717 refill: 5718 page = __page_frag_cache_refill(nc, gfp_mask); 5719 if (!page) 5720 return NULL; 5721 5722 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE) 5723 /* if size can vary use size else just use PAGE_SIZE */ 5724 size = nc->size; 5725 #endif 5726 /* Even if we own the page, we do not use atomic_set(). 5727 * This would break get_page_unless_zero() users. 5728 */ 5729 page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE); 5730 5731 /* reset page count bias and offset to start of new frag */ 5732 nc->pfmemalloc = page_is_pfmemalloc(page); 5733 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1; 5734 nc->offset = size; 5735 } 5736 5737 offset = nc->offset - fragsz; 5738 if (unlikely(offset < 0)) { 5739 page = virt_to_page(nc->va); 5740 5741 if (!page_ref_sub_and_test(page, nc->pagecnt_bias)) 5742 goto refill; 5743 5744 if (unlikely(nc->pfmemalloc)) { 5745 free_the_page(page, compound_order(page)); 5746 goto refill; 5747 } 5748 5749 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE) 5750 /* if size can vary use size else just use PAGE_SIZE */ 5751 size = nc->size; 5752 #endif 5753 /* OK, page count is 0, we can safely set it */ 5754 set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1); 5755 5756 /* reset page count bias and offset to start of new frag */ 5757 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1; 5758 offset = size - fragsz; 5759 if (unlikely(offset < 0)) { 5760 /* 5761 * The caller is trying to allocate a fragment 5762 * with fragsz > PAGE_SIZE but the cache isn't big 5763 * enough to satisfy the request, this may 5764 * happen in low memory conditions. 5765 * We don't release the cache page because 5766 * it could make memory pressure worse 5767 * so we simply return NULL here. 5768 */ 5769 return NULL; 5770 } 5771 } 5772 5773 nc->pagecnt_bias--; 5774 offset &= align_mask; 5775 nc->offset = offset; 5776 5777 return nc->va + offset; 5778 } 5779 EXPORT_SYMBOL(page_frag_alloc_align); 5780 5781 /* 5782 * Frees a page fragment allocated out of either a compound or order 0 page. 5783 */ 5784 void page_frag_free(void *addr) 5785 { 5786 struct page *page = virt_to_head_page(addr); 5787 5788 if (unlikely(put_page_testzero(page))) 5789 free_the_page(page, compound_order(page)); 5790 } 5791 EXPORT_SYMBOL(page_frag_free); 5792 5793 static void *make_alloc_exact(unsigned long addr, unsigned int order, 5794 size_t size) 5795 { 5796 if (addr) { 5797 unsigned long nr = DIV_ROUND_UP(size, PAGE_SIZE); 5798 struct page *page = virt_to_page((void *)addr); 5799 struct page *last = page + nr; 5800 5801 split_page_owner(page, 1 << order); 5802 split_page_memcg(page, 1 << order); 5803 while (page < --last) 5804 set_page_refcounted(last); 5805 5806 last = page + (1UL << order); 5807 for (page += nr; page < last; page++) 5808 __free_pages_ok(page, 0, FPI_TO_TAIL); 5809 } 5810 return (void *)addr; 5811 } 5812 5813 /** 5814 * alloc_pages_exact - allocate an exact number physically-contiguous pages. 5815 * @size: the number of bytes to allocate 5816 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP 5817 * 5818 * This function is similar to alloc_pages(), except that it allocates the 5819 * minimum number of pages to satisfy the request. alloc_pages() can only 5820 * allocate memory in power-of-two pages. 5821 * 5822 * This function is also limited by MAX_ORDER. 5823 * 5824 * Memory allocated by this function must be released by free_pages_exact(). 5825 * 5826 * Return: pointer to the allocated area or %NULL in case of error. 5827 */ 5828 void *alloc_pages_exact(size_t size, gfp_t gfp_mask) 5829 { 5830 unsigned int order = get_order(size); 5831 unsigned long addr; 5832 5833 if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM))) 5834 gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM); 5835 5836 addr = __get_free_pages(gfp_mask, order); 5837 return make_alloc_exact(addr, order, size); 5838 } 5839 EXPORT_SYMBOL(alloc_pages_exact); 5840 5841 /** 5842 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous 5843 * pages on a node. 5844 * @nid: the preferred node ID where memory should be allocated 5845 * @size: the number of bytes to allocate 5846 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP 5847 * 5848 * Like alloc_pages_exact(), but try to allocate on node nid first before falling 5849 * back. 5850 * 5851 * Return: pointer to the allocated area or %NULL in case of error. 5852 */ 5853 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask) 5854 { 5855 unsigned int order = get_order(size); 5856 struct page *p; 5857 5858 if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM))) 5859 gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM); 5860 5861 p = alloc_pages_node(nid, gfp_mask, order); 5862 if (!p) 5863 return NULL; 5864 return make_alloc_exact((unsigned long)page_address(p), order, size); 5865 } 5866 5867 /** 5868 * free_pages_exact - release memory allocated via alloc_pages_exact() 5869 * @virt: the value returned by alloc_pages_exact. 5870 * @size: size of allocation, same value as passed to alloc_pages_exact(). 5871 * 5872 * Release the memory allocated by a previous call to alloc_pages_exact. 5873 */ 5874 void free_pages_exact(void *virt, size_t size) 5875 { 5876 unsigned long addr = (unsigned long)virt; 5877 unsigned long end = addr + PAGE_ALIGN(size); 5878 5879 while (addr < end) { 5880 free_page(addr); 5881 addr += PAGE_SIZE; 5882 } 5883 } 5884 EXPORT_SYMBOL(free_pages_exact); 5885 5886 /** 5887 * nr_free_zone_pages - count number of pages beyond high watermark 5888 * @offset: The zone index of the highest zone 5889 * 5890 * nr_free_zone_pages() counts the number of pages which are beyond the 5891 * high watermark within all zones at or below a given zone index. For each 5892 * zone, the number of pages is calculated as: 5893 * 5894 * nr_free_zone_pages = managed_pages - high_pages 5895 * 5896 * Return: number of pages beyond high watermark. 5897 */ 5898 static unsigned long nr_free_zone_pages(int offset) 5899 { 5900 struct zoneref *z; 5901 struct zone *zone; 5902 5903 /* Just pick one node, since fallback list is circular */ 5904 unsigned long sum = 0; 5905 5906 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL); 5907 5908 for_each_zone_zonelist(zone, z, zonelist, offset) { 5909 unsigned long size = zone_managed_pages(zone); 5910 unsigned long high = high_wmark_pages(zone); 5911 if (size > high) 5912 sum += size - high; 5913 } 5914 5915 return sum; 5916 } 5917 5918 /** 5919 * nr_free_buffer_pages - count number of pages beyond high watermark 5920 * 5921 * nr_free_buffer_pages() counts the number of pages which are beyond the high 5922 * watermark within ZONE_DMA and ZONE_NORMAL. 5923 * 5924 * Return: number of pages beyond high watermark within ZONE_DMA and 5925 * ZONE_NORMAL. 5926 */ 5927 unsigned long nr_free_buffer_pages(void) 5928 { 5929 return nr_free_zone_pages(gfp_zone(GFP_USER)); 5930 } 5931 EXPORT_SYMBOL_GPL(nr_free_buffer_pages); 5932 5933 static inline void show_node(struct zone *zone) 5934 { 5935 if (IS_ENABLED(CONFIG_NUMA)) 5936 printk("Node %d ", zone_to_nid(zone)); 5937 } 5938 5939 long si_mem_available(void) 5940 { 5941 long available; 5942 unsigned long pagecache; 5943 unsigned long wmark_low = 0; 5944 unsigned long pages[NR_LRU_LISTS]; 5945 unsigned long reclaimable; 5946 struct zone *zone; 5947 int lru; 5948 5949 for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++) 5950 pages[lru] = global_node_page_state(NR_LRU_BASE + lru); 5951 5952 for_each_zone(zone) 5953 wmark_low += low_wmark_pages(zone); 5954 5955 /* 5956 * Estimate the amount of memory available for userspace allocations, 5957 * without causing swapping or OOM. 5958 */ 5959 available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages; 5960 5961 /* 5962 * Not all the page cache can be freed, otherwise the system will 5963 * start swapping or thrashing. Assume at least half of the page 5964 * cache, or the low watermark worth of cache, needs to stay. 5965 */ 5966 pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE]; 5967 pagecache -= min(pagecache / 2, wmark_low); 5968 available += pagecache; 5969 5970 /* 5971 * Part of the reclaimable slab and other kernel memory consists of 5972 * items that are in use, and cannot be freed. Cap this estimate at the 5973 * low watermark. 5974 */ 5975 reclaimable = global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B) + 5976 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE); 5977 available += reclaimable - min(reclaimable / 2, wmark_low); 5978 5979 if (available < 0) 5980 available = 0; 5981 return available; 5982 } 5983 EXPORT_SYMBOL_GPL(si_mem_available); 5984 5985 void si_meminfo(struct sysinfo *val) 5986 { 5987 val->totalram = totalram_pages(); 5988 val->sharedram = global_node_page_state(NR_SHMEM); 5989 val->freeram = global_zone_page_state(NR_FREE_PAGES); 5990 val->bufferram = nr_blockdev_pages(); 5991 val->totalhigh = totalhigh_pages(); 5992 val->freehigh = nr_free_highpages(); 5993 val->mem_unit = PAGE_SIZE; 5994 } 5995 5996 EXPORT_SYMBOL(si_meminfo); 5997 5998 #ifdef CONFIG_NUMA 5999 void si_meminfo_node(struct sysinfo *val, int nid) 6000 { 6001 int zone_type; /* needs to be signed */ 6002 unsigned long managed_pages = 0; 6003 unsigned long managed_highpages = 0; 6004 unsigned long free_highpages = 0; 6005 pg_data_t *pgdat = NODE_DATA(nid); 6006 6007 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) 6008 managed_pages += zone_managed_pages(&pgdat->node_zones[zone_type]); 6009 val->totalram = managed_pages; 6010 val->sharedram = node_page_state(pgdat, NR_SHMEM); 6011 val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES); 6012 #ifdef CONFIG_HIGHMEM 6013 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) { 6014 struct zone *zone = &pgdat->node_zones[zone_type]; 6015 6016 if (is_highmem(zone)) { 6017 managed_highpages += zone_managed_pages(zone); 6018 free_highpages += zone_page_state(zone, NR_FREE_PAGES); 6019 } 6020 } 6021 val->totalhigh = managed_highpages; 6022 val->freehigh = free_highpages; 6023 #else 6024 val->totalhigh = managed_highpages; 6025 val->freehigh = free_highpages; 6026 #endif 6027 val->mem_unit = PAGE_SIZE; 6028 } 6029 #endif 6030 6031 /* 6032 * Determine whether the node should be displayed or not, depending on whether 6033 * SHOW_MEM_FILTER_NODES was passed to show_free_areas(). 6034 */ 6035 static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask) 6036 { 6037 if (!(flags & SHOW_MEM_FILTER_NODES)) 6038 return false; 6039 6040 /* 6041 * no node mask - aka implicit memory numa policy. Do not bother with 6042 * the synchronization - read_mems_allowed_begin - because we do not 6043 * have to be precise here. 6044 */ 6045 if (!nodemask) 6046 nodemask = &cpuset_current_mems_allowed; 6047 6048 return !node_isset(nid, *nodemask); 6049 } 6050 6051 #define K(x) ((x) << (PAGE_SHIFT-10)) 6052 6053 static void show_migration_types(unsigned char type) 6054 { 6055 static const char types[MIGRATE_TYPES] = { 6056 [MIGRATE_UNMOVABLE] = 'U', 6057 [MIGRATE_MOVABLE] = 'M', 6058 [MIGRATE_RECLAIMABLE] = 'E', 6059 [MIGRATE_HIGHATOMIC] = 'H', 6060 #ifdef CONFIG_CMA 6061 [MIGRATE_CMA] = 'C', 6062 #endif 6063 #ifdef CONFIG_MEMORY_ISOLATION 6064 [MIGRATE_ISOLATE] = 'I', 6065 #endif 6066 }; 6067 char tmp[MIGRATE_TYPES + 1]; 6068 char *p = tmp; 6069 int i; 6070 6071 for (i = 0; i < MIGRATE_TYPES; i++) { 6072 if (type & (1 << i)) 6073 *p++ = types[i]; 6074 } 6075 6076 *p = '\0'; 6077 printk(KERN_CONT "(%s) ", tmp); 6078 } 6079 6080 static bool node_has_managed_zones(pg_data_t *pgdat, int max_zone_idx) 6081 { 6082 int zone_idx; 6083 for (zone_idx = 0; zone_idx <= max_zone_idx; zone_idx++) 6084 if (zone_managed_pages(pgdat->node_zones + zone_idx)) 6085 return true; 6086 return false; 6087 } 6088 6089 /* 6090 * Show free area list (used inside shift_scroll-lock stuff) 6091 * We also calculate the percentage fragmentation. We do this by counting the 6092 * memory on each free list with the exception of the first item on the list. 6093 * 6094 * Bits in @filter: 6095 * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's 6096 * cpuset. 6097 */ 6098 void __show_free_areas(unsigned int filter, nodemask_t *nodemask, int max_zone_idx) 6099 { 6100 unsigned long free_pcp = 0; 6101 int cpu, nid; 6102 struct zone *zone; 6103 pg_data_t *pgdat; 6104 6105 for_each_populated_zone(zone) { 6106 if (zone_idx(zone) > max_zone_idx) 6107 continue; 6108 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask)) 6109 continue; 6110 6111 for_each_online_cpu(cpu) 6112 free_pcp += per_cpu_ptr(zone->per_cpu_pageset, cpu)->count; 6113 } 6114 6115 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n" 6116 " active_file:%lu inactive_file:%lu isolated_file:%lu\n" 6117 " unevictable:%lu dirty:%lu writeback:%lu\n" 6118 " slab_reclaimable:%lu slab_unreclaimable:%lu\n" 6119 " mapped:%lu shmem:%lu pagetables:%lu\n" 6120 " sec_pagetables:%lu bounce:%lu\n" 6121 " kernel_misc_reclaimable:%lu\n" 6122 " free:%lu free_pcp:%lu free_cma:%lu\n", 6123 global_node_page_state(NR_ACTIVE_ANON), 6124 global_node_page_state(NR_INACTIVE_ANON), 6125 global_node_page_state(NR_ISOLATED_ANON), 6126 global_node_page_state(NR_ACTIVE_FILE), 6127 global_node_page_state(NR_INACTIVE_FILE), 6128 global_node_page_state(NR_ISOLATED_FILE), 6129 global_node_page_state(NR_UNEVICTABLE), 6130 global_node_page_state(NR_FILE_DIRTY), 6131 global_node_page_state(NR_WRITEBACK), 6132 global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B), 6133 global_node_page_state_pages(NR_SLAB_UNRECLAIMABLE_B), 6134 global_node_page_state(NR_FILE_MAPPED), 6135 global_node_page_state(NR_SHMEM), 6136 global_node_page_state(NR_PAGETABLE), 6137 global_node_page_state(NR_SECONDARY_PAGETABLE), 6138 global_zone_page_state(NR_BOUNCE), 6139 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE), 6140 global_zone_page_state(NR_FREE_PAGES), 6141 free_pcp, 6142 global_zone_page_state(NR_FREE_CMA_PAGES)); 6143 6144 for_each_online_pgdat(pgdat) { 6145 if (show_mem_node_skip(filter, pgdat->node_id, nodemask)) 6146 continue; 6147 if (!node_has_managed_zones(pgdat, max_zone_idx)) 6148 continue; 6149 6150 printk("Node %d" 6151 " active_anon:%lukB" 6152 " inactive_anon:%lukB" 6153 " active_file:%lukB" 6154 " inactive_file:%lukB" 6155 " unevictable:%lukB" 6156 " isolated(anon):%lukB" 6157 " isolated(file):%lukB" 6158 " mapped:%lukB" 6159 " dirty:%lukB" 6160 " writeback:%lukB" 6161 " shmem:%lukB" 6162 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 6163 " shmem_thp: %lukB" 6164 " shmem_pmdmapped: %lukB" 6165 " anon_thp: %lukB" 6166 #endif 6167 " writeback_tmp:%lukB" 6168 " kernel_stack:%lukB" 6169 #ifdef CONFIG_SHADOW_CALL_STACK 6170 " shadow_call_stack:%lukB" 6171 #endif 6172 " pagetables:%lukB" 6173 " sec_pagetables:%lukB" 6174 " all_unreclaimable? %s" 6175 "\n", 6176 pgdat->node_id, 6177 K(node_page_state(pgdat, NR_ACTIVE_ANON)), 6178 K(node_page_state(pgdat, NR_INACTIVE_ANON)), 6179 K(node_page_state(pgdat, NR_ACTIVE_FILE)), 6180 K(node_page_state(pgdat, NR_INACTIVE_FILE)), 6181 K(node_page_state(pgdat, NR_UNEVICTABLE)), 6182 K(node_page_state(pgdat, NR_ISOLATED_ANON)), 6183 K(node_page_state(pgdat, NR_ISOLATED_FILE)), 6184 K(node_page_state(pgdat, NR_FILE_MAPPED)), 6185 K(node_page_state(pgdat, NR_FILE_DIRTY)), 6186 K(node_page_state(pgdat, NR_WRITEBACK)), 6187 K(node_page_state(pgdat, NR_SHMEM)), 6188 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 6189 K(node_page_state(pgdat, NR_SHMEM_THPS)), 6190 K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED)), 6191 K(node_page_state(pgdat, NR_ANON_THPS)), 6192 #endif 6193 K(node_page_state(pgdat, NR_WRITEBACK_TEMP)), 6194 node_page_state(pgdat, NR_KERNEL_STACK_KB), 6195 #ifdef CONFIG_SHADOW_CALL_STACK 6196 node_page_state(pgdat, NR_KERNEL_SCS_KB), 6197 #endif 6198 K(node_page_state(pgdat, NR_PAGETABLE)), 6199 K(node_page_state(pgdat, NR_SECONDARY_PAGETABLE)), 6200 pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ? 6201 "yes" : "no"); 6202 } 6203 6204 for_each_populated_zone(zone) { 6205 int i; 6206 6207 if (zone_idx(zone) > max_zone_idx) 6208 continue; 6209 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask)) 6210 continue; 6211 6212 free_pcp = 0; 6213 for_each_online_cpu(cpu) 6214 free_pcp += per_cpu_ptr(zone->per_cpu_pageset, cpu)->count; 6215 6216 show_node(zone); 6217 printk(KERN_CONT 6218 "%s" 6219 " free:%lukB" 6220 " boost:%lukB" 6221 " min:%lukB" 6222 " low:%lukB" 6223 " high:%lukB" 6224 " reserved_highatomic:%luKB" 6225 " active_anon:%lukB" 6226 " inactive_anon:%lukB" 6227 " active_file:%lukB" 6228 " inactive_file:%lukB" 6229 " unevictable:%lukB" 6230 " writepending:%lukB" 6231 " present:%lukB" 6232 " managed:%lukB" 6233 " mlocked:%lukB" 6234 " bounce:%lukB" 6235 " free_pcp:%lukB" 6236 " local_pcp:%ukB" 6237 " free_cma:%lukB" 6238 "\n", 6239 zone->name, 6240 K(zone_page_state(zone, NR_FREE_PAGES)), 6241 K(zone->watermark_boost), 6242 K(min_wmark_pages(zone)), 6243 K(low_wmark_pages(zone)), 6244 K(high_wmark_pages(zone)), 6245 K(zone->nr_reserved_highatomic), 6246 K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)), 6247 K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)), 6248 K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)), 6249 K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)), 6250 K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)), 6251 K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)), 6252 K(zone->present_pages), 6253 K(zone_managed_pages(zone)), 6254 K(zone_page_state(zone, NR_MLOCK)), 6255 K(zone_page_state(zone, NR_BOUNCE)), 6256 K(free_pcp), 6257 K(this_cpu_read(zone->per_cpu_pageset->count)), 6258 K(zone_page_state(zone, NR_FREE_CMA_PAGES))); 6259 printk("lowmem_reserve[]:"); 6260 for (i = 0; i < MAX_NR_ZONES; i++) 6261 printk(KERN_CONT " %ld", zone->lowmem_reserve[i]); 6262 printk(KERN_CONT "\n"); 6263 } 6264 6265 for_each_populated_zone(zone) { 6266 unsigned int order; 6267 unsigned long nr[MAX_ORDER], flags, total = 0; 6268 unsigned char types[MAX_ORDER]; 6269 6270 if (zone_idx(zone) > max_zone_idx) 6271 continue; 6272 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask)) 6273 continue; 6274 show_node(zone); 6275 printk(KERN_CONT "%s: ", zone->name); 6276 6277 spin_lock_irqsave(&zone->lock, flags); 6278 for (order = 0; order < MAX_ORDER; order++) { 6279 struct free_area *area = &zone->free_area[order]; 6280 int type; 6281 6282 nr[order] = area->nr_free; 6283 total += nr[order] << order; 6284 6285 types[order] = 0; 6286 for (type = 0; type < MIGRATE_TYPES; type++) { 6287 if (!free_area_empty(area, type)) 6288 types[order] |= 1 << type; 6289 } 6290 } 6291 spin_unlock_irqrestore(&zone->lock, flags); 6292 for (order = 0; order < MAX_ORDER; order++) { 6293 printk(KERN_CONT "%lu*%lukB ", 6294 nr[order], K(1UL) << order); 6295 if (nr[order]) 6296 show_migration_types(types[order]); 6297 } 6298 printk(KERN_CONT "= %lukB\n", K(total)); 6299 } 6300 6301 for_each_online_node(nid) { 6302 if (show_mem_node_skip(filter, nid, nodemask)) 6303 continue; 6304 hugetlb_show_meminfo_node(nid); 6305 } 6306 6307 printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES)); 6308 6309 show_swap_cache_info(); 6310 } 6311 6312 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref) 6313 { 6314 zoneref->zone = zone; 6315 zoneref->zone_idx = zone_idx(zone); 6316 } 6317 6318 /* 6319 * Builds allocation fallback zone lists. 6320 * 6321 * Add all populated zones of a node to the zonelist. 6322 */ 6323 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs) 6324 { 6325 struct zone *zone; 6326 enum zone_type zone_type = MAX_NR_ZONES; 6327 int nr_zones = 0; 6328 6329 do { 6330 zone_type--; 6331 zone = pgdat->node_zones + zone_type; 6332 if (populated_zone(zone)) { 6333 zoneref_set_zone(zone, &zonerefs[nr_zones++]); 6334 check_highest_zone(zone_type); 6335 } 6336 } while (zone_type); 6337 6338 return nr_zones; 6339 } 6340 6341 #ifdef CONFIG_NUMA 6342 6343 static int __parse_numa_zonelist_order(char *s) 6344 { 6345 /* 6346 * We used to support different zonelists modes but they turned 6347 * out to be just not useful. Let's keep the warning in place 6348 * if somebody still use the cmd line parameter so that we do 6349 * not fail it silently 6350 */ 6351 if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) { 6352 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s); 6353 return -EINVAL; 6354 } 6355 return 0; 6356 } 6357 6358 char numa_zonelist_order[] = "Node"; 6359 6360 /* 6361 * sysctl handler for numa_zonelist_order 6362 */ 6363 int numa_zonelist_order_handler(struct ctl_table *table, int write, 6364 void *buffer, size_t *length, loff_t *ppos) 6365 { 6366 if (write) 6367 return __parse_numa_zonelist_order(buffer); 6368 return proc_dostring(table, write, buffer, length, ppos); 6369 } 6370 6371 6372 static int node_load[MAX_NUMNODES]; 6373 6374 /** 6375 * find_next_best_node - find the next node that should appear in a given node's fallback list 6376 * @node: node whose fallback list we're appending 6377 * @used_node_mask: nodemask_t of already used nodes 6378 * 6379 * We use a number of factors to determine which is the next node that should 6380 * appear on a given node's fallback list. The node should not have appeared 6381 * already in @node's fallback list, and it should be the next closest node 6382 * according to the distance array (which contains arbitrary distance values 6383 * from each node to each node in the system), and should also prefer nodes 6384 * with no CPUs, since presumably they'll have very little allocation pressure 6385 * on them otherwise. 6386 * 6387 * Return: node id of the found node or %NUMA_NO_NODE if no node is found. 6388 */ 6389 int find_next_best_node(int node, nodemask_t *used_node_mask) 6390 { 6391 int n, val; 6392 int min_val = INT_MAX; 6393 int best_node = NUMA_NO_NODE; 6394 6395 /* Use the local node if we haven't already */ 6396 if (!node_isset(node, *used_node_mask)) { 6397 node_set(node, *used_node_mask); 6398 return node; 6399 } 6400 6401 for_each_node_state(n, N_MEMORY) { 6402 6403 /* Don't want a node to appear more than once */ 6404 if (node_isset(n, *used_node_mask)) 6405 continue; 6406 6407 /* Use the distance array to find the distance */ 6408 val = node_distance(node, n); 6409 6410 /* Penalize nodes under us ("prefer the next node") */ 6411 val += (n < node); 6412 6413 /* Give preference to headless and unused nodes */ 6414 if (!cpumask_empty(cpumask_of_node(n))) 6415 val += PENALTY_FOR_NODE_WITH_CPUS; 6416 6417 /* Slight preference for less loaded node */ 6418 val *= MAX_NUMNODES; 6419 val += node_load[n]; 6420 6421 if (val < min_val) { 6422 min_val = val; 6423 best_node = n; 6424 } 6425 } 6426 6427 if (best_node >= 0) 6428 node_set(best_node, *used_node_mask); 6429 6430 return best_node; 6431 } 6432 6433 6434 /* 6435 * Build zonelists ordered by node and zones within node. 6436 * This results in maximum locality--normal zone overflows into local 6437 * DMA zone, if any--but risks exhausting DMA zone. 6438 */ 6439 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order, 6440 unsigned nr_nodes) 6441 { 6442 struct zoneref *zonerefs; 6443 int i; 6444 6445 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs; 6446 6447 for (i = 0; i < nr_nodes; i++) { 6448 int nr_zones; 6449 6450 pg_data_t *node = NODE_DATA(node_order[i]); 6451 6452 nr_zones = build_zonerefs_node(node, zonerefs); 6453 zonerefs += nr_zones; 6454 } 6455 zonerefs->zone = NULL; 6456 zonerefs->zone_idx = 0; 6457 } 6458 6459 /* 6460 * Build gfp_thisnode zonelists 6461 */ 6462 static void build_thisnode_zonelists(pg_data_t *pgdat) 6463 { 6464 struct zoneref *zonerefs; 6465 int nr_zones; 6466 6467 zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs; 6468 nr_zones = build_zonerefs_node(pgdat, zonerefs); 6469 zonerefs += nr_zones; 6470 zonerefs->zone = NULL; 6471 zonerefs->zone_idx = 0; 6472 } 6473 6474 /* 6475 * Build zonelists ordered by zone and nodes within zones. 6476 * This results in conserving DMA zone[s] until all Normal memory is 6477 * exhausted, but results in overflowing to remote node while memory 6478 * may still exist in local DMA zone. 6479 */ 6480 6481 static void build_zonelists(pg_data_t *pgdat) 6482 { 6483 static int node_order[MAX_NUMNODES]; 6484 int node, nr_nodes = 0; 6485 nodemask_t used_mask = NODE_MASK_NONE; 6486 int local_node, prev_node; 6487 6488 /* NUMA-aware ordering of nodes */ 6489 local_node = pgdat->node_id; 6490 prev_node = local_node; 6491 6492 memset(node_order, 0, sizeof(node_order)); 6493 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) { 6494 /* 6495 * We don't want to pressure a particular node. 6496 * So adding penalty to the first node in same 6497 * distance group to make it round-robin. 6498 */ 6499 if (node_distance(local_node, node) != 6500 node_distance(local_node, prev_node)) 6501 node_load[node] += 1; 6502 6503 node_order[nr_nodes++] = node; 6504 prev_node = node; 6505 } 6506 6507 build_zonelists_in_node_order(pgdat, node_order, nr_nodes); 6508 build_thisnode_zonelists(pgdat); 6509 pr_info("Fallback order for Node %d: ", local_node); 6510 for (node = 0; node < nr_nodes; node++) 6511 pr_cont("%d ", node_order[node]); 6512 pr_cont("\n"); 6513 } 6514 6515 #ifdef CONFIG_HAVE_MEMORYLESS_NODES 6516 /* 6517 * Return node id of node used for "local" allocations. 6518 * I.e., first node id of first zone in arg node's generic zonelist. 6519 * Used for initializing percpu 'numa_mem', which is used primarily 6520 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist. 6521 */ 6522 int local_memory_node(int node) 6523 { 6524 struct zoneref *z; 6525 6526 z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL), 6527 gfp_zone(GFP_KERNEL), 6528 NULL); 6529 return zone_to_nid(z->zone); 6530 } 6531 #endif 6532 6533 static void setup_min_unmapped_ratio(void); 6534 static void setup_min_slab_ratio(void); 6535 #else /* CONFIG_NUMA */ 6536 6537 static void build_zonelists(pg_data_t *pgdat) 6538 { 6539 int node, local_node; 6540 struct zoneref *zonerefs; 6541 int nr_zones; 6542 6543 local_node = pgdat->node_id; 6544 6545 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs; 6546 nr_zones = build_zonerefs_node(pgdat, zonerefs); 6547 zonerefs += nr_zones; 6548 6549 /* 6550 * Now we build the zonelist so that it contains the zones 6551 * of all the other nodes. 6552 * We don't want to pressure a particular node, so when 6553 * building the zones for node N, we make sure that the 6554 * zones coming right after the local ones are those from 6555 * node N+1 (modulo N) 6556 */ 6557 for (node = local_node + 1; node < MAX_NUMNODES; node++) { 6558 if (!node_online(node)) 6559 continue; 6560 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs); 6561 zonerefs += nr_zones; 6562 } 6563 for (node = 0; node < local_node; node++) { 6564 if (!node_online(node)) 6565 continue; 6566 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs); 6567 zonerefs += nr_zones; 6568 } 6569 6570 zonerefs->zone = NULL; 6571 zonerefs->zone_idx = 0; 6572 } 6573 6574 #endif /* CONFIG_NUMA */ 6575 6576 /* 6577 * Boot pageset table. One per cpu which is going to be used for all 6578 * zones and all nodes. The parameters will be set in such a way 6579 * that an item put on a list will immediately be handed over to 6580 * the buddy list. This is safe since pageset manipulation is done 6581 * with interrupts disabled. 6582 * 6583 * The boot_pagesets must be kept even after bootup is complete for 6584 * unused processors and/or zones. They do play a role for bootstrapping 6585 * hotplugged processors. 6586 * 6587 * zoneinfo_show() and maybe other functions do 6588 * not check if the processor is online before following the pageset pointer. 6589 * Other parts of the kernel may not check if the zone is available. 6590 */ 6591 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats); 6592 /* These effectively disable the pcplists in the boot pageset completely */ 6593 #define BOOT_PAGESET_HIGH 0 6594 #define BOOT_PAGESET_BATCH 1 6595 static DEFINE_PER_CPU(struct per_cpu_pages, boot_pageset); 6596 static DEFINE_PER_CPU(struct per_cpu_zonestat, boot_zonestats); 6597 static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats); 6598 6599 static void __build_all_zonelists(void *data) 6600 { 6601 int nid; 6602 int __maybe_unused cpu; 6603 pg_data_t *self = data; 6604 6605 write_seqlock(&zonelist_update_seq); 6606 6607 #ifdef CONFIG_NUMA 6608 memset(node_load, 0, sizeof(node_load)); 6609 #endif 6610 6611 /* 6612 * This node is hotadded and no memory is yet present. So just 6613 * building zonelists is fine - no need to touch other nodes. 6614 */ 6615 if (self && !node_online(self->node_id)) { 6616 build_zonelists(self); 6617 } else { 6618 /* 6619 * All possible nodes have pgdat preallocated 6620 * in free_area_init 6621 */ 6622 for_each_node(nid) { 6623 pg_data_t *pgdat = NODE_DATA(nid); 6624 6625 build_zonelists(pgdat); 6626 } 6627 6628 #ifdef CONFIG_HAVE_MEMORYLESS_NODES 6629 /* 6630 * We now know the "local memory node" for each node-- 6631 * i.e., the node of the first zone in the generic zonelist. 6632 * Set up numa_mem percpu variable for on-line cpus. During 6633 * boot, only the boot cpu should be on-line; we'll init the 6634 * secondary cpus' numa_mem as they come on-line. During 6635 * node/memory hotplug, we'll fixup all on-line cpus. 6636 */ 6637 for_each_online_cpu(cpu) 6638 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu))); 6639 #endif 6640 } 6641 6642 write_sequnlock(&zonelist_update_seq); 6643 } 6644 6645 static noinline void __init 6646 build_all_zonelists_init(void) 6647 { 6648 int cpu; 6649 6650 __build_all_zonelists(NULL); 6651 6652 /* 6653 * Initialize the boot_pagesets that are going to be used 6654 * for bootstrapping processors. The real pagesets for 6655 * each zone will be allocated later when the per cpu 6656 * allocator is available. 6657 * 6658 * boot_pagesets are used also for bootstrapping offline 6659 * cpus if the system is already booted because the pagesets 6660 * are needed to initialize allocators on a specific cpu too. 6661 * F.e. the percpu allocator needs the page allocator which 6662 * needs the percpu allocator in order to allocate its pagesets 6663 * (a chicken-egg dilemma). 6664 */ 6665 for_each_possible_cpu(cpu) 6666 per_cpu_pages_init(&per_cpu(boot_pageset, cpu), &per_cpu(boot_zonestats, cpu)); 6667 6668 mminit_verify_zonelist(); 6669 cpuset_init_current_mems_allowed(); 6670 } 6671 6672 /* 6673 * unless system_state == SYSTEM_BOOTING. 6674 * 6675 * __ref due to call of __init annotated helper build_all_zonelists_init 6676 * [protected by SYSTEM_BOOTING]. 6677 */ 6678 void __ref build_all_zonelists(pg_data_t *pgdat) 6679 { 6680 unsigned long vm_total_pages; 6681 6682 if (system_state == SYSTEM_BOOTING) { 6683 build_all_zonelists_init(); 6684 } else { 6685 __build_all_zonelists(pgdat); 6686 /* cpuset refresh routine should be here */ 6687 } 6688 /* Get the number of free pages beyond high watermark in all zones. */ 6689 vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE)); 6690 /* 6691 * Disable grouping by mobility if the number of pages in the 6692 * system is too low to allow the mechanism to work. It would be 6693 * more accurate, but expensive to check per-zone. This check is 6694 * made on memory-hotadd so a system can start with mobility 6695 * disabled and enable it later 6696 */ 6697 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES)) 6698 page_group_by_mobility_disabled = 1; 6699 else 6700 page_group_by_mobility_disabled = 0; 6701 6702 pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n", 6703 nr_online_nodes, 6704 page_group_by_mobility_disabled ? "off" : "on", 6705 vm_total_pages); 6706 #ifdef CONFIG_NUMA 6707 pr_info("Policy zone: %s\n", zone_names[policy_zone]); 6708 #endif 6709 } 6710 6711 /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */ 6712 static bool __meminit 6713 overlap_memmap_init(unsigned long zone, unsigned long *pfn) 6714 { 6715 static struct memblock_region *r; 6716 6717 if (mirrored_kernelcore && zone == ZONE_MOVABLE) { 6718 if (!r || *pfn >= memblock_region_memory_end_pfn(r)) { 6719 for_each_mem_region(r) { 6720 if (*pfn < memblock_region_memory_end_pfn(r)) 6721 break; 6722 } 6723 } 6724 if (*pfn >= memblock_region_memory_base_pfn(r) && 6725 memblock_is_mirror(r)) { 6726 *pfn = memblock_region_memory_end_pfn(r); 6727 return true; 6728 } 6729 } 6730 return false; 6731 } 6732 6733 /* 6734 * Initially all pages are reserved - free ones are freed 6735 * up by memblock_free_all() once the early boot process is 6736 * done. Non-atomic initialization, single-pass. 6737 * 6738 * All aligned pageblocks are initialized to the specified migratetype 6739 * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related 6740 * zone stats (e.g., nr_isolate_pageblock) are touched. 6741 */ 6742 void __meminit memmap_init_range(unsigned long size, int nid, unsigned long zone, 6743 unsigned long start_pfn, unsigned long zone_end_pfn, 6744 enum meminit_context context, 6745 struct vmem_altmap *altmap, int migratetype) 6746 { 6747 unsigned long pfn, end_pfn = start_pfn + size; 6748 struct page *page; 6749 6750 if (highest_memmap_pfn < end_pfn - 1) 6751 highest_memmap_pfn = end_pfn - 1; 6752 6753 #ifdef CONFIG_ZONE_DEVICE 6754 /* 6755 * Honor reservation requested by the driver for this ZONE_DEVICE 6756 * memory. We limit the total number of pages to initialize to just 6757 * those that might contain the memory mapping. We will defer the 6758 * ZONE_DEVICE page initialization until after we have released 6759 * the hotplug lock. 6760 */ 6761 if (zone == ZONE_DEVICE) { 6762 if (!altmap) 6763 return; 6764 6765 if (start_pfn == altmap->base_pfn) 6766 start_pfn += altmap->reserve; 6767 end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap); 6768 } 6769 #endif 6770 6771 for (pfn = start_pfn; pfn < end_pfn; ) { 6772 /* 6773 * There can be holes in boot-time mem_map[]s handed to this 6774 * function. They do not exist on hotplugged memory. 6775 */ 6776 if (context == MEMINIT_EARLY) { 6777 if (overlap_memmap_init(zone, &pfn)) 6778 continue; 6779 if (defer_init(nid, pfn, zone_end_pfn)) 6780 break; 6781 } 6782 6783 page = pfn_to_page(pfn); 6784 __init_single_page(page, pfn, zone, nid); 6785 if (context == MEMINIT_HOTPLUG) 6786 __SetPageReserved(page); 6787 6788 /* 6789 * Usually, we want to mark the pageblock MIGRATE_MOVABLE, 6790 * such that unmovable allocations won't be scattered all 6791 * over the place during system boot. 6792 */ 6793 if (pageblock_aligned(pfn)) { 6794 set_pageblock_migratetype(page, migratetype); 6795 cond_resched(); 6796 } 6797 pfn++; 6798 } 6799 } 6800 6801 #ifdef CONFIG_ZONE_DEVICE 6802 static void __ref __init_zone_device_page(struct page *page, unsigned long pfn, 6803 unsigned long zone_idx, int nid, 6804 struct dev_pagemap *pgmap) 6805 { 6806 6807 __init_single_page(page, pfn, zone_idx, nid); 6808 6809 /* 6810 * Mark page reserved as it will need to wait for onlining 6811 * phase for it to be fully associated with a zone. 6812 * 6813 * We can use the non-atomic __set_bit operation for setting 6814 * the flag as we are still initializing the pages. 6815 */ 6816 __SetPageReserved(page); 6817 6818 /* 6819 * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer 6820 * and zone_device_data. It is a bug if a ZONE_DEVICE page is 6821 * ever freed or placed on a driver-private list. 6822 */ 6823 page->pgmap = pgmap; 6824 page->zone_device_data = NULL; 6825 6826 /* 6827 * Mark the block movable so that blocks are reserved for 6828 * movable at startup. This will force kernel allocations 6829 * to reserve their blocks rather than leaking throughout 6830 * the address space during boot when many long-lived 6831 * kernel allocations are made. 6832 * 6833 * Please note that MEMINIT_HOTPLUG path doesn't clear memmap 6834 * because this is done early in section_activate() 6835 */ 6836 if (pageblock_aligned(pfn)) { 6837 set_pageblock_migratetype(page, MIGRATE_MOVABLE); 6838 cond_resched(); 6839 } 6840 6841 /* 6842 * ZONE_DEVICE pages are released directly to the driver page allocator 6843 * which will set the page count to 1 when allocating the page. 6844 */ 6845 if (pgmap->type == MEMORY_DEVICE_PRIVATE || 6846 pgmap->type == MEMORY_DEVICE_COHERENT) 6847 set_page_count(page, 0); 6848 } 6849 6850 /* 6851 * With compound page geometry and when struct pages are stored in ram most 6852 * tail pages are reused. Consequently, the amount of unique struct pages to 6853 * initialize is a lot smaller that the total amount of struct pages being 6854 * mapped. This is a paired / mild layering violation with explicit knowledge 6855 * of how the sparse_vmemmap internals handle compound pages in the lack 6856 * of an altmap. See vmemmap_populate_compound_pages(). 6857 */ 6858 static inline unsigned long compound_nr_pages(struct vmem_altmap *altmap, 6859 unsigned long nr_pages) 6860 { 6861 return is_power_of_2(sizeof(struct page)) && 6862 !altmap ? 2 * (PAGE_SIZE / sizeof(struct page)) : nr_pages; 6863 } 6864 6865 static void __ref memmap_init_compound(struct page *head, 6866 unsigned long head_pfn, 6867 unsigned long zone_idx, int nid, 6868 struct dev_pagemap *pgmap, 6869 unsigned long nr_pages) 6870 { 6871 unsigned long pfn, end_pfn = head_pfn + nr_pages; 6872 unsigned int order = pgmap->vmemmap_shift; 6873 6874 __SetPageHead(head); 6875 for (pfn = head_pfn + 1; pfn < end_pfn; pfn++) { 6876 struct page *page = pfn_to_page(pfn); 6877 6878 __init_zone_device_page(page, pfn, zone_idx, nid, pgmap); 6879 prep_compound_tail(head, pfn - head_pfn); 6880 set_page_count(page, 0); 6881 6882 /* 6883 * The first tail page stores important compound page info. 6884 * Call prep_compound_head() after the first tail page has 6885 * been initialized, to not have the data overwritten. 6886 */ 6887 if (pfn == head_pfn + 1) 6888 prep_compound_head(head, order); 6889 } 6890 } 6891 6892 void __ref memmap_init_zone_device(struct zone *zone, 6893 unsigned long start_pfn, 6894 unsigned long nr_pages, 6895 struct dev_pagemap *pgmap) 6896 { 6897 unsigned long pfn, end_pfn = start_pfn + nr_pages; 6898 struct pglist_data *pgdat = zone->zone_pgdat; 6899 struct vmem_altmap *altmap = pgmap_altmap(pgmap); 6900 unsigned int pfns_per_compound = pgmap_vmemmap_nr(pgmap); 6901 unsigned long zone_idx = zone_idx(zone); 6902 unsigned long start = jiffies; 6903 int nid = pgdat->node_id; 6904 6905 if (WARN_ON_ONCE(!pgmap || zone_idx != ZONE_DEVICE)) 6906 return; 6907 6908 /* 6909 * The call to memmap_init should have already taken care 6910 * of the pages reserved for the memmap, so we can just jump to 6911 * the end of that region and start processing the device pages. 6912 */ 6913 if (altmap) { 6914 start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap); 6915 nr_pages = end_pfn - start_pfn; 6916 } 6917 6918 for (pfn = start_pfn; pfn < end_pfn; pfn += pfns_per_compound) { 6919 struct page *page = pfn_to_page(pfn); 6920 6921 __init_zone_device_page(page, pfn, zone_idx, nid, pgmap); 6922 6923 if (pfns_per_compound == 1) 6924 continue; 6925 6926 memmap_init_compound(page, pfn, zone_idx, nid, pgmap, 6927 compound_nr_pages(altmap, pfns_per_compound)); 6928 } 6929 6930 pr_info("%s initialised %lu pages in %ums\n", __func__, 6931 nr_pages, jiffies_to_msecs(jiffies - start)); 6932 } 6933 6934 #endif 6935 static void __meminit zone_init_free_lists(struct zone *zone) 6936 { 6937 unsigned int order, t; 6938 for_each_migratetype_order(order, t) { 6939 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]); 6940 zone->free_area[order].nr_free = 0; 6941 } 6942 } 6943 6944 /* 6945 * Only struct pages that correspond to ranges defined by memblock.memory 6946 * are zeroed and initialized by going through __init_single_page() during 6947 * memmap_init_zone_range(). 6948 * 6949 * But, there could be struct pages that correspond to holes in 6950 * memblock.memory. This can happen because of the following reasons: 6951 * - physical memory bank size is not necessarily the exact multiple of the 6952 * arbitrary section size 6953 * - early reserved memory may not be listed in memblock.memory 6954 * - memory layouts defined with memmap= kernel parameter may not align 6955 * nicely with memmap sections 6956 * 6957 * Explicitly initialize those struct pages so that: 6958 * - PG_Reserved is set 6959 * - zone and node links point to zone and node that span the page if the 6960 * hole is in the middle of a zone 6961 * - zone and node links point to adjacent zone/node if the hole falls on 6962 * the zone boundary; the pages in such holes will be prepended to the 6963 * zone/node above the hole except for the trailing pages in the last 6964 * section that will be appended to the zone/node below. 6965 */ 6966 static void __init init_unavailable_range(unsigned long spfn, 6967 unsigned long epfn, 6968 int zone, int node) 6969 { 6970 unsigned long pfn; 6971 u64 pgcnt = 0; 6972 6973 for (pfn = spfn; pfn < epfn; pfn++) { 6974 if (!pfn_valid(pageblock_start_pfn(pfn))) { 6975 pfn = pageblock_end_pfn(pfn) - 1; 6976 continue; 6977 } 6978 __init_single_page(pfn_to_page(pfn), pfn, zone, node); 6979 __SetPageReserved(pfn_to_page(pfn)); 6980 pgcnt++; 6981 } 6982 6983 if (pgcnt) 6984 pr_info("On node %d, zone %s: %lld pages in unavailable ranges", 6985 node, zone_names[zone], pgcnt); 6986 } 6987 6988 static void __init memmap_init_zone_range(struct zone *zone, 6989 unsigned long start_pfn, 6990 unsigned long end_pfn, 6991 unsigned long *hole_pfn) 6992 { 6993 unsigned long zone_start_pfn = zone->zone_start_pfn; 6994 unsigned long zone_end_pfn = zone_start_pfn + zone->spanned_pages; 6995 int nid = zone_to_nid(zone), zone_id = zone_idx(zone); 6996 6997 start_pfn = clamp(start_pfn, zone_start_pfn, zone_end_pfn); 6998 end_pfn = clamp(end_pfn, zone_start_pfn, zone_end_pfn); 6999 7000 if (start_pfn >= end_pfn) 7001 return; 7002 7003 memmap_init_range(end_pfn - start_pfn, nid, zone_id, start_pfn, 7004 zone_end_pfn, MEMINIT_EARLY, NULL, MIGRATE_MOVABLE); 7005 7006 if (*hole_pfn < start_pfn) 7007 init_unavailable_range(*hole_pfn, start_pfn, zone_id, nid); 7008 7009 *hole_pfn = end_pfn; 7010 } 7011 7012 static void __init memmap_init(void) 7013 { 7014 unsigned long start_pfn, end_pfn; 7015 unsigned long hole_pfn = 0; 7016 int i, j, zone_id = 0, nid; 7017 7018 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) { 7019 struct pglist_data *node = NODE_DATA(nid); 7020 7021 for (j = 0; j < MAX_NR_ZONES; j++) { 7022 struct zone *zone = node->node_zones + j; 7023 7024 if (!populated_zone(zone)) 7025 continue; 7026 7027 memmap_init_zone_range(zone, start_pfn, end_pfn, 7028 &hole_pfn); 7029 zone_id = j; 7030 } 7031 } 7032 7033 #ifdef CONFIG_SPARSEMEM 7034 /* 7035 * Initialize the memory map for hole in the range [memory_end, 7036 * section_end]. 7037 * Append the pages in this hole to the highest zone in the last 7038 * node. 7039 * The call to init_unavailable_range() is outside the ifdef to 7040 * silence the compiler warining about zone_id set but not used; 7041 * for FLATMEM it is a nop anyway 7042 */ 7043 end_pfn = round_up(end_pfn, PAGES_PER_SECTION); 7044 if (hole_pfn < end_pfn) 7045 #endif 7046 init_unavailable_range(hole_pfn, end_pfn, zone_id, nid); 7047 } 7048 7049 void __init *memmap_alloc(phys_addr_t size, phys_addr_t align, 7050 phys_addr_t min_addr, int nid, bool exact_nid) 7051 { 7052 void *ptr; 7053 7054 if (exact_nid) 7055 ptr = memblock_alloc_exact_nid_raw(size, align, min_addr, 7056 MEMBLOCK_ALLOC_ACCESSIBLE, 7057 nid); 7058 else 7059 ptr = memblock_alloc_try_nid_raw(size, align, min_addr, 7060 MEMBLOCK_ALLOC_ACCESSIBLE, 7061 nid); 7062 7063 if (ptr && size > 0) 7064 page_init_poison(ptr, size); 7065 7066 return ptr; 7067 } 7068 7069 static int zone_batchsize(struct zone *zone) 7070 { 7071 #ifdef CONFIG_MMU 7072 int batch; 7073 7074 /* 7075 * The number of pages to batch allocate is either ~0.1% 7076 * of the zone or 1MB, whichever is smaller. The batch 7077 * size is striking a balance between allocation latency 7078 * and zone lock contention. 7079 */ 7080 batch = min(zone_managed_pages(zone) >> 10, SZ_1M / PAGE_SIZE); 7081 batch /= 4; /* We effectively *= 4 below */ 7082 if (batch < 1) 7083 batch = 1; 7084 7085 /* 7086 * Clamp the batch to a 2^n - 1 value. Having a power 7087 * of 2 value was found to be more likely to have 7088 * suboptimal cache aliasing properties in some cases. 7089 * 7090 * For example if 2 tasks are alternately allocating 7091 * batches of pages, one task can end up with a lot 7092 * of pages of one half of the possible page colors 7093 * and the other with pages of the other colors. 7094 */ 7095 batch = rounddown_pow_of_two(batch + batch/2) - 1; 7096 7097 return batch; 7098 7099 #else 7100 /* The deferral and batching of frees should be suppressed under NOMMU 7101 * conditions. 7102 * 7103 * The problem is that NOMMU needs to be able to allocate large chunks 7104 * of contiguous memory as there's no hardware page translation to 7105 * assemble apparent contiguous memory from discontiguous pages. 7106 * 7107 * Queueing large contiguous runs of pages for batching, however, 7108 * causes the pages to actually be freed in smaller chunks. As there 7109 * can be a significant delay between the individual batches being 7110 * recycled, this leads to the once large chunks of space being 7111 * fragmented and becoming unavailable for high-order allocations. 7112 */ 7113 return 0; 7114 #endif 7115 } 7116 7117 static int zone_highsize(struct zone *zone, int batch, int cpu_online) 7118 { 7119 #ifdef CONFIG_MMU 7120 int high; 7121 int nr_split_cpus; 7122 unsigned long total_pages; 7123 7124 if (!percpu_pagelist_high_fraction) { 7125 /* 7126 * By default, the high value of the pcp is based on the zone 7127 * low watermark so that if they are full then background 7128 * reclaim will not be started prematurely. 7129 */ 7130 total_pages = low_wmark_pages(zone); 7131 } else { 7132 /* 7133 * If percpu_pagelist_high_fraction is configured, the high 7134 * value is based on a fraction of the managed pages in the 7135 * zone. 7136 */ 7137 total_pages = zone_managed_pages(zone) / percpu_pagelist_high_fraction; 7138 } 7139 7140 /* 7141 * Split the high value across all online CPUs local to the zone. Note 7142 * that early in boot that CPUs may not be online yet and that during 7143 * CPU hotplug that the cpumask is not yet updated when a CPU is being 7144 * onlined. For memory nodes that have no CPUs, split pcp->high across 7145 * all online CPUs to mitigate the risk that reclaim is triggered 7146 * prematurely due to pages stored on pcp lists. 7147 */ 7148 nr_split_cpus = cpumask_weight(cpumask_of_node(zone_to_nid(zone))) + cpu_online; 7149 if (!nr_split_cpus) 7150 nr_split_cpus = num_online_cpus(); 7151 high = total_pages / nr_split_cpus; 7152 7153 /* 7154 * Ensure high is at least batch*4. The multiple is based on the 7155 * historical relationship between high and batch. 7156 */ 7157 high = max(high, batch << 2); 7158 7159 return high; 7160 #else 7161 return 0; 7162 #endif 7163 } 7164 7165 /* 7166 * pcp->high and pcp->batch values are related and generally batch is lower 7167 * than high. They are also related to pcp->count such that count is lower 7168 * than high, and as soon as it reaches high, the pcplist is flushed. 7169 * 7170 * However, guaranteeing these relations at all times would require e.g. write 7171 * barriers here but also careful usage of read barriers at the read side, and 7172 * thus be prone to error and bad for performance. Thus the update only prevents 7173 * store tearing. Any new users of pcp->batch and pcp->high should ensure they 7174 * can cope with those fields changing asynchronously, and fully trust only the 7175 * pcp->count field on the local CPU with interrupts disabled. 7176 * 7177 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function 7178 * outside of boot time (or some other assurance that no concurrent updaters 7179 * exist). 7180 */ 7181 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high, 7182 unsigned long batch) 7183 { 7184 WRITE_ONCE(pcp->batch, batch); 7185 WRITE_ONCE(pcp->high, high); 7186 } 7187 7188 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats) 7189 { 7190 int pindex; 7191 7192 memset(pcp, 0, sizeof(*pcp)); 7193 memset(pzstats, 0, sizeof(*pzstats)); 7194 7195 spin_lock_init(&pcp->lock); 7196 for (pindex = 0; pindex < NR_PCP_LISTS; pindex++) 7197 INIT_LIST_HEAD(&pcp->lists[pindex]); 7198 7199 /* 7200 * Set batch and high values safe for a boot pageset. A true percpu 7201 * pageset's initialization will update them subsequently. Here we don't 7202 * need to be as careful as pageset_update() as nobody can access the 7203 * pageset yet. 7204 */ 7205 pcp->high = BOOT_PAGESET_HIGH; 7206 pcp->batch = BOOT_PAGESET_BATCH; 7207 pcp->free_factor = 0; 7208 } 7209 7210 static void __zone_set_pageset_high_and_batch(struct zone *zone, unsigned long high, 7211 unsigned long batch) 7212 { 7213 struct per_cpu_pages *pcp; 7214 int cpu; 7215 7216 for_each_possible_cpu(cpu) { 7217 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 7218 pageset_update(pcp, high, batch); 7219 } 7220 } 7221 7222 /* 7223 * Calculate and set new high and batch values for all per-cpu pagesets of a 7224 * zone based on the zone's size. 7225 */ 7226 static void zone_set_pageset_high_and_batch(struct zone *zone, int cpu_online) 7227 { 7228 int new_high, new_batch; 7229 7230 new_batch = max(1, zone_batchsize(zone)); 7231 new_high = zone_highsize(zone, new_batch, cpu_online); 7232 7233 if (zone->pageset_high == new_high && 7234 zone->pageset_batch == new_batch) 7235 return; 7236 7237 zone->pageset_high = new_high; 7238 zone->pageset_batch = new_batch; 7239 7240 __zone_set_pageset_high_and_batch(zone, new_high, new_batch); 7241 } 7242 7243 void __meminit setup_zone_pageset(struct zone *zone) 7244 { 7245 int cpu; 7246 7247 /* Size may be 0 on !SMP && !NUMA */ 7248 if (sizeof(struct per_cpu_zonestat) > 0) 7249 zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat); 7250 7251 zone->per_cpu_pageset = alloc_percpu(struct per_cpu_pages); 7252 for_each_possible_cpu(cpu) { 7253 struct per_cpu_pages *pcp; 7254 struct per_cpu_zonestat *pzstats; 7255 7256 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 7257 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu); 7258 per_cpu_pages_init(pcp, pzstats); 7259 } 7260 7261 zone_set_pageset_high_and_batch(zone, 0); 7262 } 7263 7264 /* 7265 * The zone indicated has a new number of managed_pages; batch sizes and percpu 7266 * page high values need to be recalculated. 7267 */ 7268 static void zone_pcp_update(struct zone *zone, int cpu_online) 7269 { 7270 mutex_lock(&pcp_batch_high_lock); 7271 zone_set_pageset_high_and_batch(zone, cpu_online); 7272 mutex_unlock(&pcp_batch_high_lock); 7273 } 7274 7275 /* 7276 * Allocate per cpu pagesets and initialize them. 7277 * Before this call only boot pagesets were available. 7278 */ 7279 void __init setup_per_cpu_pageset(void) 7280 { 7281 struct pglist_data *pgdat; 7282 struct zone *zone; 7283 int __maybe_unused cpu; 7284 7285 for_each_populated_zone(zone) 7286 setup_zone_pageset(zone); 7287 7288 #ifdef CONFIG_NUMA 7289 /* 7290 * Unpopulated zones continue using the boot pagesets. 7291 * The numa stats for these pagesets need to be reset. 7292 * Otherwise, they will end up skewing the stats of 7293 * the nodes these zones are associated with. 7294 */ 7295 for_each_possible_cpu(cpu) { 7296 struct per_cpu_zonestat *pzstats = &per_cpu(boot_zonestats, cpu); 7297 memset(pzstats->vm_numa_event, 0, 7298 sizeof(pzstats->vm_numa_event)); 7299 } 7300 #endif 7301 7302 for_each_online_pgdat(pgdat) 7303 pgdat->per_cpu_nodestats = 7304 alloc_percpu(struct per_cpu_nodestat); 7305 } 7306 7307 static __meminit void zone_pcp_init(struct zone *zone) 7308 { 7309 /* 7310 * per cpu subsystem is not up at this point. The following code 7311 * relies on the ability of the linker to provide the 7312 * offset of a (static) per cpu variable into the per cpu area. 7313 */ 7314 zone->per_cpu_pageset = &boot_pageset; 7315 zone->per_cpu_zonestats = &boot_zonestats; 7316 zone->pageset_high = BOOT_PAGESET_HIGH; 7317 zone->pageset_batch = BOOT_PAGESET_BATCH; 7318 7319 if (populated_zone(zone)) 7320 pr_debug(" %s zone: %lu pages, LIFO batch:%u\n", zone->name, 7321 zone->present_pages, zone_batchsize(zone)); 7322 } 7323 7324 void __meminit init_currently_empty_zone(struct zone *zone, 7325 unsigned long zone_start_pfn, 7326 unsigned long size) 7327 { 7328 struct pglist_data *pgdat = zone->zone_pgdat; 7329 int zone_idx = zone_idx(zone) + 1; 7330 7331 if (zone_idx > pgdat->nr_zones) 7332 pgdat->nr_zones = zone_idx; 7333 7334 zone->zone_start_pfn = zone_start_pfn; 7335 7336 mminit_dprintk(MMINIT_TRACE, "memmap_init", 7337 "Initialising map node %d zone %lu pfns %lu -> %lu\n", 7338 pgdat->node_id, 7339 (unsigned long)zone_idx(zone), 7340 zone_start_pfn, (zone_start_pfn + size)); 7341 7342 zone_init_free_lists(zone); 7343 zone->initialized = 1; 7344 } 7345 7346 /** 7347 * get_pfn_range_for_nid - Return the start and end page frames for a node 7348 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned. 7349 * @start_pfn: Passed by reference. On return, it will have the node start_pfn. 7350 * @end_pfn: Passed by reference. On return, it will have the node end_pfn. 7351 * 7352 * It returns the start and end page frame of a node based on information 7353 * provided by memblock_set_node(). If called for a node 7354 * with no available memory, a warning is printed and the start and end 7355 * PFNs will be 0. 7356 */ 7357 void __init get_pfn_range_for_nid(unsigned int nid, 7358 unsigned long *start_pfn, unsigned long *end_pfn) 7359 { 7360 unsigned long this_start_pfn, this_end_pfn; 7361 int i; 7362 7363 *start_pfn = -1UL; 7364 *end_pfn = 0; 7365 7366 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) { 7367 *start_pfn = min(*start_pfn, this_start_pfn); 7368 *end_pfn = max(*end_pfn, this_end_pfn); 7369 } 7370 7371 if (*start_pfn == -1UL) 7372 *start_pfn = 0; 7373 } 7374 7375 /* 7376 * This finds a zone that can be used for ZONE_MOVABLE pages. The 7377 * assumption is made that zones within a node are ordered in monotonic 7378 * increasing memory addresses so that the "highest" populated zone is used 7379 */ 7380 static void __init find_usable_zone_for_movable(void) 7381 { 7382 int zone_index; 7383 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) { 7384 if (zone_index == ZONE_MOVABLE) 7385 continue; 7386 7387 if (arch_zone_highest_possible_pfn[zone_index] > 7388 arch_zone_lowest_possible_pfn[zone_index]) 7389 break; 7390 } 7391 7392 VM_BUG_ON(zone_index == -1); 7393 movable_zone = zone_index; 7394 } 7395 7396 /* 7397 * The zone ranges provided by the architecture do not include ZONE_MOVABLE 7398 * because it is sized independent of architecture. Unlike the other zones, 7399 * the starting point for ZONE_MOVABLE is not fixed. It may be different 7400 * in each node depending on the size of each node and how evenly kernelcore 7401 * is distributed. This helper function adjusts the zone ranges 7402 * provided by the architecture for a given node by using the end of the 7403 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that 7404 * zones within a node are in order of monotonic increases memory addresses 7405 */ 7406 static void __init adjust_zone_range_for_zone_movable(int nid, 7407 unsigned long zone_type, 7408 unsigned long node_start_pfn, 7409 unsigned long node_end_pfn, 7410 unsigned long *zone_start_pfn, 7411 unsigned long *zone_end_pfn) 7412 { 7413 /* Only adjust if ZONE_MOVABLE is on this node */ 7414 if (zone_movable_pfn[nid]) { 7415 /* Size ZONE_MOVABLE */ 7416 if (zone_type == ZONE_MOVABLE) { 7417 *zone_start_pfn = zone_movable_pfn[nid]; 7418 *zone_end_pfn = min(node_end_pfn, 7419 arch_zone_highest_possible_pfn[movable_zone]); 7420 7421 /* Adjust for ZONE_MOVABLE starting within this range */ 7422 } else if (!mirrored_kernelcore && 7423 *zone_start_pfn < zone_movable_pfn[nid] && 7424 *zone_end_pfn > zone_movable_pfn[nid]) { 7425 *zone_end_pfn = zone_movable_pfn[nid]; 7426 7427 /* Check if this whole range is within ZONE_MOVABLE */ 7428 } else if (*zone_start_pfn >= zone_movable_pfn[nid]) 7429 *zone_start_pfn = *zone_end_pfn; 7430 } 7431 } 7432 7433 /* 7434 * Return the number of pages a zone spans in a node, including holes 7435 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node() 7436 */ 7437 static unsigned long __init zone_spanned_pages_in_node(int nid, 7438 unsigned long zone_type, 7439 unsigned long node_start_pfn, 7440 unsigned long node_end_pfn, 7441 unsigned long *zone_start_pfn, 7442 unsigned long *zone_end_pfn) 7443 { 7444 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type]; 7445 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type]; 7446 /* When hotadd a new node from cpu_up(), the node should be empty */ 7447 if (!node_start_pfn && !node_end_pfn) 7448 return 0; 7449 7450 /* Get the start and end of the zone */ 7451 *zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high); 7452 *zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high); 7453 adjust_zone_range_for_zone_movable(nid, zone_type, 7454 node_start_pfn, node_end_pfn, 7455 zone_start_pfn, zone_end_pfn); 7456 7457 /* Check that this node has pages within the zone's required range */ 7458 if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn) 7459 return 0; 7460 7461 /* Move the zone boundaries inside the node if necessary */ 7462 *zone_end_pfn = min(*zone_end_pfn, node_end_pfn); 7463 *zone_start_pfn = max(*zone_start_pfn, node_start_pfn); 7464 7465 /* Return the spanned pages */ 7466 return *zone_end_pfn - *zone_start_pfn; 7467 } 7468 7469 /* 7470 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES, 7471 * then all holes in the requested range will be accounted for. 7472 */ 7473 unsigned long __init __absent_pages_in_range(int nid, 7474 unsigned long range_start_pfn, 7475 unsigned long range_end_pfn) 7476 { 7477 unsigned long nr_absent = range_end_pfn - range_start_pfn; 7478 unsigned long start_pfn, end_pfn; 7479 int i; 7480 7481 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) { 7482 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn); 7483 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn); 7484 nr_absent -= end_pfn - start_pfn; 7485 } 7486 return nr_absent; 7487 } 7488 7489 /** 7490 * absent_pages_in_range - Return number of page frames in holes within a range 7491 * @start_pfn: The start PFN to start searching for holes 7492 * @end_pfn: The end PFN to stop searching for holes 7493 * 7494 * Return: the number of pages frames in memory holes within a range. 7495 */ 7496 unsigned long __init absent_pages_in_range(unsigned long start_pfn, 7497 unsigned long end_pfn) 7498 { 7499 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn); 7500 } 7501 7502 /* Return the number of page frames in holes in a zone on a node */ 7503 static unsigned long __init zone_absent_pages_in_node(int nid, 7504 unsigned long zone_type, 7505 unsigned long node_start_pfn, 7506 unsigned long node_end_pfn) 7507 { 7508 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type]; 7509 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type]; 7510 unsigned long zone_start_pfn, zone_end_pfn; 7511 unsigned long nr_absent; 7512 7513 /* When hotadd a new node from cpu_up(), the node should be empty */ 7514 if (!node_start_pfn && !node_end_pfn) 7515 return 0; 7516 7517 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high); 7518 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high); 7519 7520 adjust_zone_range_for_zone_movable(nid, zone_type, 7521 node_start_pfn, node_end_pfn, 7522 &zone_start_pfn, &zone_end_pfn); 7523 nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn); 7524 7525 /* 7526 * ZONE_MOVABLE handling. 7527 * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages 7528 * and vice versa. 7529 */ 7530 if (mirrored_kernelcore && zone_movable_pfn[nid]) { 7531 unsigned long start_pfn, end_pfn; 7532 struct memblock_region *r; 7533 7534 for_each_mem_region(r) { 7535 start_pfn = clamp(memblock_region_memory_base_pfn(r), 7536 zone_start_pfn, zone_end_pfn); 7537 end_pfn = clamp(memblock_region_memory_end_pfn(r), 7538 zone_start_pfn, zone_end_pfn); 7539 7540 if (zone_type == ZONE_MOVABLE && 7541 memblock_is_mirror(r)) 7542 nr_absent += end_pfn - start_pfn; 7543 7544 if (zone_type == ZONE_NORMAL && 7545 !memblock_is_mirror(r)) 7546 nr_absent += end_pfn - start_pfn; 7547 } 7548 } 7549 7550 return nr_absent; 7551 } 7552 7553 static void __init calculate_node_totalpages(struct pglist_data *pgdat, 7554 unsigned long node_start_pfn, 7555 unsigned long node_end_pfn) 7556 { 7557 unsigned long realtotalpages = 0, totalpages = 0; 7558 enum zone_type i; 7559 7560 for (i = 0; i < MAX_NR_ZONES; i++) { 7561 struct zone *zone = pgdat->node_zones + i; 7562 unsigned long zone_start_pfn, zone_end_pfn; 7563 unsigned long spanned, absent; 7564 unsigned long size, real_size; 7565 7566 spanned = zone_spanned_pages_in_node(pgdat->node_id, i, 7567 node_start_pfn, 7568 node_end_pfn, 7569 &zone_start_pfn, 7570 &zone_end_pfn); 7571 absent = zone_absent_pages_in_node(pgdat->node_id, i, 7572 node_start_pfn, 7573 node_end_pfn); 7574 7575 size = spanned; 7576 real_size = size - absent; 7577 7578 if (size) 7579 zone->zone_start_pfn = zone_start_pfn; 7580 else 7581 zone->zone_start_pfn = 0; 7582 zone->spanned_pages = size; 7583 zone->present_pages = real_size; 7584 #if defined(CONFIG_MEMORY_HOTPLUG) 7585 zone->present_early_pages = real_size; 7586 #endif 7587 7588 totalpages += size; 7589 realtotalpages += real_size; 7590 } 7591 7592 pgdat->node_spanned_pages = totalpages; 7593 pgdat->node_present_pages = realtotalpages; 7594 pr_debug("On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages); 7595 } 7596 7597 #ifndef CONFIG_SPARSEMEM 7598 /* 7599 * Calculate the size of the zone->blockflags rounded to an unsigned long 7600 * Start by making sure zonesize is a multiple of pageblock_order by rounding 7601 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally 7602 * round what is now in bits to nearest long in bits, then return it in 7603 * bytes. 7604 */ 7605 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize) 7606 { 7607 unsigned long usemapsize; 7608 7609 zonesize += zone_start_pfn & (pageblock_nr_pages-1); 7610 usemapsize = roundup(zonesize, pageblock_nr_pages); 7611 usemapsize = usemapsize >> pageblock_order; 7612 usemapsize *= NR_PAGEBLOCK_BITS; 7613 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long)); 7614 7615 return usemapsize / 8; 7616 } 7617 7618 static void __ref setup_usemap(struct zone *zone) 7619 { 7620 unsigned long usemapsize = usemap_size(zone->zone_start_pfn, 7621 zone->spanned_pages); 7622 zone->pageblock_flags = NULL; 7623 if (usemapsize) { 7624 zone->pageblock_flags = 7625 memblock_alloc_node(usemapsize, SMP_CACHE_BYTES, 7626 zone_to_nid(zone)); 7627 if (!zone->pageblock_flags) 7628 panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n", 7629 usemapsize, zone->name, zone_to_nid(zone)); 7630 } 7631 } 7632 #else 7633 static inline void setup_usemap(struct zone *zone) {} 7634 #endif /* CONFIG_SPARSEMEM */ 7635 7636 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE 7637 7638 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */ 7639 void __init set_pageblock_order(void) 7640 { 7641 unsigned int order = MAX_ORDER - 1; 7642 7643 /* Check that pageblock_nr_pages has not already been setup */ 7644 if (pageblock_order) 7645 return; 7646 7647 /* Don't let pageblocks exceed the maximum allocation granularity. */ 7648 if (HPAGE_SHIFT > PAGE_SHIFT && HUGETLB_PAGE_ORDER < order) 7649 order = HUGETLB_PAGE_ORDER; 7650 7651 /* 7652 * Assume the largest contiguous order of interest is a huge page. 7653 * This value may be variable depending on boot parameters on IA64 and 7654 * powerpc. 7655 */ 7656 pageblock_order = order; 7657 } 7658 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */ 7659 7660 /* 7661 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order() 7662 * is unused as pageblock_order is set at compile-time. See 7663 * include/linux/pageblock-flags.h for the values of pageblock_order based on 7664 * the kernel config 7665 */ 7666 void __init set_pageblock_order(void) 7667 { 7668 } 7669 7670 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */ 7671 7672 static unsigned long __init calc_memmap_size(unsigned long spanned_pages, 7673 unsigned long present_pages) 7674 { 7675 unsigned long pages = spanned_pages; 7676 7677 /* 7678 * Provide a more accurate estimation if there are holes within 7679 * the zone and SPARSEMEM is in use. If there are holes within the 7680 * zone, each populated memory region may cost us one or two extra 7681 * memmap pages due to alignment because memmap pages for each 7682 * populated regions may not be naturally aligned on page boundary. 7683 * So the (present_pages >> 4) heuristic is a tradeoff for that. 7684 */ 7685 if (spanned_pages > present_pages + (present_pages >> 4) && 7686 IS_ENABLED(CONFIG_SPARSEMEM)) 7687 pages = present_pages; 7688 7689 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT; 7690 } 7691 7692 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 7693 static void pgdat_init_split_queue(struct pglist_data *pgdat) 7694 { 7695 struct deferred_split *ds_queue = &pgdat->deferred_split_queue; 7696 7697 spin_lock_init(&ds_queue->split_queue_lock); 7698 INIT_LIST_HEAD(&ds_queue->split_queue); 7699 ds_queue->split_queue_len = 0; 7700 } 7701 #else 7702 static void pgdat_init_split_queue(struct pglist_data *pgdat) {} 7703 #endif 7704 7705 #ifdef CONFIG_COMPACTION 7706 static void pgdat_init_kcompactd(struct pglist_data *pgdat) 7707 { 7708 init_waitqueue_head(&pgdat->kcompactd_wait); 7709 } 7710 #else 7711 static void pgdat_init_kcompactd(struct pglist_data *pgdat) {} 7712 #endif 7713 7714 static void __meminit pgdat_init_internals(struct pglist_data *pgdat) 7715 { 7716 int i; 7717 7718 pgdat_resize_init(pgdat); 7719 pgdat_kswapd_lock_init(pgdat); 7720 7721 pgdat_init_split_queue(pgdat); 7722 pgdat_init_kcompactd(pgdat); 7723 7724 init_waitqueue_head(&pgdat->kswapd_wait); 7725 init_waitqueue_head(&pgdat->pfmemalloc_wait); 7726 7727 for (i = 0; i < NR_VMSCAN_THROTTLE; i++) 7728 init_waitqueue_head(&pgdat->reclaim_wait[i]); 7729 7730 pgdat_page_ext_init(pgdat); 7731 lruvec_init(&pgdat->__lruvec); 7732 } 7733 7734 static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid, 7735 unsigned long remaining_pages) 7736 { 7737 atomic_long_set(&zone->managed_pages, remaining_pages); 7738 zone_set_nid(zone, nid); 7739 zone->name = zone_names[idx]; 7740 zone->zone_pgdat = NODE_DATA(nid); 7741 spin_lock_init(&zone->lock); 7742 zone_seqlock_init(zone); 7743 zone_pcp_init(zone); 7744 } 7745 7746 /* 7747 * Set up the zone data structures 7748 * - init pgdat internals 7749 * - init all zones belonging to this node 7750 * 7751 * NOTE: this function is only called during memory hotplug 7752 */ 7753 #ifdef CONFIG_MEMORY_HOTPLUG 7754 void __ref free_area_init_core_hotplug(struct pglist_data *pgdat) 7755 { 7756 int nid = pgdat->node_id; 7757 enum zone_type z; 7758 int cpu; 7759 7760 pgdat_init_internals(pgdat); 7761 7762 if (pgdat->per_cpu_nodestats == &boot_nodestats) 7763 pgdat->per_cpu_nodestats = alloc_percpu(struct per_cpu_nodestat); 7764 7765 /* 7766 * Reset the nr_zones, order and highest_zoneidx before reuse. 7767 * Note that kswapd will init kswapd_highest_zoneidx properly 7768 * when it starts in the near future. 7769 */ 7770 pgdat->nr_zones = 0; 7771 pgdat->kswapd_order = 0; 7772 pgdat->kswapd_highest_zoneidx = 0; 7773 pgdat->node_start_pfn = 0; 7774 for_each_online_cpu(cpu) { 7775 struct per_cpu_nodestat *p; 7776 7777 p = per_cpu_ptr(pgdat->per_cpu_nodestats, cpu); 7778 memset(p, 0, sizeof(*p)); 7779 } 7780 7781 for (z = 0; z < MAX_NR_ZONES; z++) 7782 zone_init_internals(&pgdat->node_zones[z], z, nid, 0); 7783 } 7784 #endif 7785 7786 /* 7787 * Set up the zone data structures: 7788 * - mark all pages reserved 7789 * - mark all memory queues empty 7790 * - clear the memory bitmaps 7791 * 7792 * NOTE: pgdat should get zeroed by caller. 7793 * NOTE: this function is only called during early init. 7794 */ 7795 static void __init free_area_init_core(struct pglist_data *pgdat) 7796 { 7797 enum zone_type j; 7798 int nid = pgdat->node_id; 7799 7800 pgdat_init_internals(pgdat); 7801 pgdat->per_cpu_nodestats = &boot_nodestats; 7802 7803 for (j = 0; j < MAX_NR_ZONES; j++) { 7804 struct zone *zone = pgdat->node_zones + j; 7805 unsigned long size, freesize, memmap_pages; 7806 7807 size = zone->spanned_pages; 7808 freesize = zone->present_pages; 7809 7810 /* 7811 * Adjust freesize so that it accounts for how much memory 7812 * is used by this zone for memmap. This affects the watermark 7813 * and per-cpu initialisations 7814 */ 7815 memmap_pages = calc_memmap_size(size, freesize); 7816 if (!is_highmem_idx(j)) { 7817 if (freesize >= memmap_pages) { 7818 freesize -= memmap_pages; 7819 if (memmap_pages) 7820 pr_debug(" %s zone: %lu pages used for memmap\n", 7821 zone_names[j], memmap_pages); 7822 } else 7823 pr_warn(" %s zone: %lu memmap pages exceeds freesize %lu\n", 7824 zone_names[j], memmap_pages, freesize); 7825 } 7826 7827 /* Account for reserved pages */ 7828 if (j == 0 && freesize > dma_reserve) { 7829 freesize -= dma_reserve; 7830 pr_debug(" %s zone: %lu pages reserved\n", zone_names[0], dma_reserve); 7831 } 7832 7833 if (!is_highmem_idx(j)) 7834 nr_kernel_pages += freesize; 7835 /* Charge for highmem memmap if there are enough kernel pages */ 7836 else if (nr_kernel_pages > memmap_pages * 2) 7837 nr_kernel_pages -= memmap_pages; 7838 nr_all_pages += freesize; 7839 7840 /* 7841 * Set an approximate value for lowmem here, it will be adjusted 7842 * when the bootmem allocator frees pages into the buddy system. 7843 * And all highmem pages will be managed by the buddy system. 7844 */ 7845 zone_init_internals(zone, j, nid, freesize); 7846 7847 if (!size) 7848 continue; 7849 7850 set_pageblock_order(); 7851 setup_usemap(zone); 7852 init_currently_empty_zone(zone, zone->zone_start_pfn, size); 7853 } 7854 } 7855 7856 #ifdef CONFIG_FLATMEM 7857 static void __init alloc_node_mem_map(struct pglist_data *pgdat) 7858 { 7859 unsigned long __maybe_unused start = 0; 7860 unsigned long __maybe_unused offset = 0; 7861 7862 /* Skip empty nodes */ 7863 if (!pgdat->node_spanned_pages) 7864 return; 7865 7866 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1); 7867 offset = pgdat->node_start_pfn - start; 7868 /* ia64 gets its own node_mem_map, before this, without bootmem */ 7869 if (!pgdat->node_mem_map) { 7870 unsigned long size, end; 7871 struct page *map; 7872 7873 /* 7874 * The zone's endpoints aren't required to be MAX_ORDER 7875 * aligned but the node_mem_map endpoints must be in order 7876 * for the buddy allocator to function correctly. 7877 */ 7878 end = pgdat_end_pfn(pgdat); 7879 end = ALIGN(end, MAX_ORDER_NR_PAGES); 7880 size = (end - start) * sizeof(struct page); 7881 map = memmap_alloc(size, SMP_CACHE_BYTES, MEMBLOCK_LOW_LIMIT, 7882 pgdat->node_id, false); 7883 if (!map) 7884 panic("Failed to allocate %ld bytes for node %d memory map\n", 7885 size, pgdat->node_id); 7886 pgdat->node_mem_map = map + offset; 7887 } 7888 pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n", 7889 __func__, pgdat->node_id, (unsigned long)pgdat, 7890 (unsigned long)pgdat->node_mem_map); 7891 #ifndef CONFIG_NUMA 7892 /* 7893 * With no DISCONTIG, the global mem_map is just set as node 0's 7894 */ 7895 if (pgdat == NODE_DATA(0)) { 7896 mem_map = NODE_DATA(0)->node_mem_map; 7897 if (page_to_pfn(mem_map) != pgdat->node_start_pfn) 7898 mem_map -= offset; 7899 } 7900 #endif 7901 } 7902 #else 7903 static inline void alloc_node_mem_map(struct pglist_data *pgdat) { } 7904 #endif /* CONFIG_FLATMEM */ 7905 7906 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 7907 static inline void pgdat_set_deferred_range(pg_data_t *pgdat) 7908 { 7909 pgdat->first_deferred_pfn = ULONG_MAX; 7910 } 7911 #else 7912 static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {} 7913 #endif 7914 7915 static void __init free_area_init_node(int nid) 7916 { 7917 pg_data_t *pgdat = NODE_DATA(nid); 7918 unsigned long start_pfn = 0; 7919 unsigned long end_pfn = 0; 7920 7921 /* pg_data_t should be reset to zero when it's allocated */ 7922 WARN_ON(pgdat->nr_zones || pgdat->kswapd_highest_zoneidx); 7923 7924 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn); 7925 7926 pgdat->node_id = nid; 7927 pgdat->node_start_pfn = start_pfn; 7928 pgdat->per_cpu_nodestats = NULL; 7929 7930 if (start_pfn != end_pfn) { 7931 pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid, 7932 (u64)start_pfn << PAGE_SHIFT, 7933 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0); 7934 } else { 7935 pr_info("Initmem setup node %d as memoryless\n", nid); 7936 } 7937 7938 calculate_node_totalpages(pgdat, start_pfn, end_pfn); 7939 7940 alloc_node_mem_map(pgdat); 7941 pgdat_set_deferred_range(pgdat); 7942 7943 free_area_init_core(pgdat); 7944 lru_gen_init_pgdat(pgdat); 7945 } 7946 7947 static void __init free_area_init_memoryless_node(int nid) 7948 { 7949 free_area_init_node(nid); 7950 } 7951 7952 #if MAX_NUMNODES > 1 7953 /* 7954 * Figure out the number of possible node ids. 7955 */ 7956 void __init setup_nr_node_ids(void) 7957 { 7958 unsigned int highest; 7959 7960 highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES); 7961 nr_node_ids = highest + 1; 7962 } 7963 #endif 7964 7965 /** 7966 * node_map_pfn_alignment - determine the maximum internode alignment 7967 * 7968 * This function should be called after node map is populated and sorted. 7969 * It calculates the maximum power of two alignment which can distinguish 7970 * all the nodes. 7971 * 7972 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value 7973 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the 7974 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is 7975 * shifted, 1GiB is enough and this function will indicate so. 7976 * 7977 * This is used to test whether pfn -> nid mapping of the chosen memory 7978 * model has fine enough granularity to avoid incorrect mapping for the 7979 * populated node map. 7980 * 7981 * Return: the determined alignment in pfn's. 0 if there is no alignment 7982 * requirement (single node). 7983 */ 7984 unsigned long __init node_map_pfn_alignment(void) 7985 { 7986 unsigned long accl_mask = 0, last_end = 0; 7987 unsigned long start, end, mask; 7988 int last_nid = NUMA_NO_NODE; 7989 int i, nid; 7990 7991 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) { 7992 if (!start || last_nid < 0 || last_nid == nid) { 7993 last_nid = nid; 7994 last_end = end; 7995 continue; 7996 } 7997 7998 /* 7999 * Start with a mask granular enough to pin-point to the 8000 * start pfn and tick off bits one-by-one until it becomes 8001 * too coarse to separate the current node from the last. 8002 */ 8003 mask = ~((1 << __ffs(start)) - 1); 8004 while (mask && last_end <= (start & (mask << 1))) 8005 mask <<= 1; 8006 8007 /* accumulate all internode masks */ 8008 accl_mask |= mask; 8009 } 8010 8011 /* convert mask to number of pages */ 8012 return ~accl_mask + 1; 8013 } 8014 8015 /* 8016 * early_calculate_totalpages() 8017 * Sum pages in active regions for movable zone. 8018 * Populate N_MEMORY for calculating usable_nodes. 8019 */ 8020 static unsigned long __init early_calculate_totalpages(void) 8021 { 8022 unsigned long totalpages = 0; 8023 unsigned long start_pfn, end_pfn; 8024 int i, nid; 8025 8026 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) { 8027 unsigned long pages = end_pfn - start_pfn; 8028 8029 totalpages += pages; 8030 if (pages) 8031 node_set_state(nid, N_MEMORY); 8032 } 8033 return totalpages; 8034 } 8035 8036 /* 8037 * Find the PFN the Movable zone begins in each node. Kernel memory 8038 * is spread evenly between nodes as long as the nodes have enough 8039 * memory. When they don't, some nodes will have more kernelcore than 8040 * others 8041 */ 8042 static void __init find_zone_movable_pfns_for_nodes(void) 8043 { 8044 int i, nid; 8045 unsigned long usable_startpfn; 8046 unsigned long kernelcore_node, kernelcore_remaining; 8047 /* save the state before borrow the nodemask */ 8048 nodemask_t saved_node_state = node_states[N_MEMORY]; 8049 unsigned long totalpages = early_calculate_totalpages(); 8050 int usable_nodes = nodes_weight(node_states[N_MEMORY]); 8051 struct memblock_region *r; 8052 8053 /* Need to find movable_zone earlier when movable_node is specified. */ 8054 find_usable_zone_for_movable(); 8055 8056 /* 8057 * If movable_node is specified, ignore kernelcore and movablecore 8058 * options. 8059 */ 8060 if (movable_node_is_enabled()) { 8061 for_each_mem_region(r) { 8062 if (!memblock_is_hotpluggable(r)) 8063 continue; 8064 8065 nid = memblock_get_region_node(r); 8066 8067 usable_startpfn = PFN_DOWN(r->base); 8068 zone_movable_pfn[nid] = zone_movable_pfn[nid] ? 8069 min(usable_startpfn, zone_movable_pfn[nid]) : 8070 usable_startpfn; 8071 } 8072 8073 goto out2; 8074 } 8075 8076 /* 8077 * If kernelcore=mirror is specified, ignore movablecore option 8078 */ 8079 if (mirrored_kernelcore) { 8080 bool mem_below_4gb_not_mirrored = false; 8081 8082 for_each_mem_region(r) { 8083 if (memblock_is_mirror(r)) 8084 continue; 8085 8086 nid = memblock_get_region_node(r); 8087 8088 usable_startpfn = memblock_region_memory_base_pfn(r); 8089 8090 if (usable_startpfn < PHYS_PFN(SZ_4G)) { 8091 mem_below_4gb_not_mirrored = true; 8092 continue; 8093 } 8094 8095 zone_movable_pfn[nid] = zone_movable_pfn[nid] ? 8096 min(usable_startpfn, zone_movable_pfn[nid]) : 8097 usable_startpfn; 8098 } 8099 8100 if (mem_below_4gb_not_mirrored) 8101 pr_warn("This configuration results in unmirrored kernel memory.\n"); 8102 8103 goto out2; 8104 } 8105 8106 /* 8107 * If kernelcore=nn% or movablecore=nn% was specified, calculate the 8108 * amount of necessary memory. 8109 */ 8110 if (required_kernelcore_percent) 8111 required_kernelcore = (totalpages * 100 * required_kernelcore_percent) / 8112 10000UL; 8113 if (required_movablecore_percent) 8114 required_movablecore = (totalpages * 100 * required_movablecore_percent) / 8115 10000UL; 8116 8117 /* 8118 * If movablecore= was specified, calculate what size of 8119 * kernelcore that corresponds so that memory usable for 8120 * any allocation type is evenly spread. If both kernelcore 8121 * and movablecore are specified, then the value of kernelcore 8122 * will be used for required_kernelcore if it's greater than 8123 * what movablecore would have allowed. 8124 */ 8125 if (required_movablecore) { 8126 unsigned long corepages; 8127 8128 /* 8129 * Round-up so that ZONE_MOVABLE is at least as large as what 8130 * was requested by the user 8131 */ 8132 required_movablecore = 8133 roundup(required_movablecore, MAX_ORDER_NR_PAGES); 8134 required_movablecore = min(totalpages, required_movablecore); 8135 corepages = totalpages - required_movablecore; 8136 8137 required_kernelcore = max(required_kernelcore, corepages); 8138 } 8139 8140 /* 8141 * If kernelcore was not specified or kernelcore size is larger 8142 * than totalpages, there is no ZONE_MOVABLE. 8143 */ 8144 if (!required_kernelcore || required_kernelcore >= totalpages) 8145 goto out; 8146 8147 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */ 8148 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone]; 8149 8150 restart: 8151 /* Spread kernelcore memory as evenly as possible throughout nodes */ 8152 kernelcore_node = required_kernelcore / usable_nodes; 8153 for_each_node_state(nid, N_MEMORY) { 8154 unsigned long start_pfn, end_pfn; 8155 8156 /* 8157 * Recalculate kernelcore_node if the division per node 8158 * now exceeds what is necessary to satisfy the requested 8159 * amount of memory for the kernel 8160 */ 8161 if (required_kernelcore < kernelcore_node) 8162 kernelcore_node = required_kernelcore / usable_nodes; 8163 8164 /* 8165 * As the map is walked, we track how much memory is usable 8166 * by the kernel using kernelcore_remaining. When it is 8167 * 0, the rest of the node is usable by ZONE_MOVABLE 8168 */ 8169 kernelcore_remaining = kernelcore_node; 8170 8171 /* Go through each range of PFNs within this node */ 8172 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) { 8173 unsigned long size_pages; 8174 8175 start_pfn = max(start_pfn, zone_movable_pfn[nid]); 8176 if (start_pfn >= end_pfn) 8177 continue; 8178 8179 /* Account for what is only usable for kernelcore */ 8180 if (start_pfn < usable_startpfn) { 8181 unsigned long kernel_pages; 8182 kernel_pages = min(end_pfn, usable_startpfn) 8183 - start_pfn; 8184 8185 kernelcore_remaining -= min(kernel_pages, 8186 kernelcore_remaining); 8187 required_kernelcore -= min(kernel_pages, 8188 required_kernelcore); 8189 8190 /* Continue if range is now fully accounted */ 8191 if (end_pfn <= usable_startpfn) { 8192 8193 /* 8194 * Push zone_movable_pfn to the end so 8195 * that if we have to rebalance 8196 * kernelcore across nodes, we will 8197 * not double account here 8198 */ 8199 zone_movable_pfn[nid] = end_pfn; 8200 continue; 8201 } 8202 start_pfn = usable_startpfn; 8203 } 8204 8205 /* 8206 * The usable PFN range for ZONE_MOVABLE is from 8207 * start_pfn->end_pfn. Calculate size_pages as the 8208 * number of pages used as kernelcore 8209 */ 8210 size_pages = end_pfn - start_pfn; 8211 if (size_pages > kernelcore_remaining) 8212 size_pages = kernelcore_remaining; 8213 zone_movable_pfn[nid] = start_pfn + size_pages; 8214 8215 /* 8216 * Some kernelcore has been met, update counts and 8217 * break if the kernelcore for this node has been 8218 * satisfied 8219 */ 8220 required_kernelcore -= min(required_kernelcore, 8221 size_pages); 8222 kernelcore_remaining -= size_pages; 8223 if (!kernelcore_remaining) 8224 break; 8225 } 8226 } 8227 8228 /* 8229 * If there is still required_kernelcore, we do another pass with one 8230 * less node in the count. This will push zone_movable_pfn[nid] further 8231 * along on the nodes that still have memory until kernelcore is 8232 * satisfied 8233 */ 8234 usable_nodes--; 8235 if (usable_nodes && required_kernelcore > usable_nodes) 8236 goto restart; 8237 8238 out2: 8239 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */ 8240 for (nid = 0; nid < MAX_NUMNODES; nid++) { 8241 unsigned long start_pfn, end_pfn; 8242 8243 zone_movable_pfn[nid] = 8244 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES); 8245 8246 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn); 8247 if (zone_movable_pfn[nid] >= end_pfn) 8248 zone_movable_pfn[nid] = 0; 8249 } 8250 8251 out: 8252 /* restore the node_state */ 8253 node_states[N_MEMORY] = saved_node_state; 8254 } 8255 8256 /* Any regular or high memory on that node ? */ 8257 static void check_for_memory(pg_data_t *pgdat, int nid) 8258 { 8259 enum zone_type zone_type; 8260 8261 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) { 8262 struct zone *zone = &pgdat->node_zones[zone_type]; 8263 if (populated_zone(zone)) { 8264 if (IS_ENABLED(CONFIG_HIGHMEM)) 8265 node_set_state(nid, N_HIGH_MEMORY); 8266 if (zone_type <= ZONE_NORMAL) 8267 node_set_state(nid, N_NORMAL_MEMORY); 8268 break; 8269 } 8270 } 8271 } 8272 8273 /* 8274 * Some architectures, e.g. ARC may have ZONE_HIGHMEM below ZONE_NORMAL. For 8275 * such cases we allow max_zone_pfn sorted in the descending order 8276 */ 8277 bool __weak arch_has_descending_max_zone_pfns(void) 8278 { 8279 return false; 8280 } 8281 8282 /** 8283 * free_area_init - Initialise all pg_data_t and zone data 8284 * @max_zone_pfn: an array of max PFNs for each zone 8285 * 8286 * This will call free_area_init_node() for each active node in the system. 8287 * Using the page ranges provided by memblock_set_node(), the size of each 8288 * zone in each node and their holes is calculated. If the maximum PFN 8289 * between two adjacent zones match, it is assumed that the zone is empty. 8290 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed 8291 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone 8292 * starts where the previous one ended. For example, ZONE_DMA32 starts 8293 * at arch_max_dma_pfn. 8294 */ 8295 void __init free_area_init(unsigned long *max_zone_pfn) 8296 { 8297 unsigned long start_pfn, end_pfn; 8298 int i, nid, zone; 8299 bool descending; 8300 8301 /* Record where the zone boundaries are */ 8302 memset(arch_zone_lowest_possible_pfn, 0, 8303 sizeof(arch_zone_lowest_possible_pfn)); 8304 memset(arch_zone_highest_possible_pfn, 0, 8305 sizeof(arch_zone_highest_possible_pfn)); 8306 8307 start_pfn = PHYS_PFN(memblock_start_of_DRAM()); 8308 descending = arch_has_descending_max_zone_pfns(); 8309 8310 for (i = 0; i < MAX_NR_ZONES; i++) { 8311 if (descending) 8312 zone = MAX_NR_ZONES - i - 1; 8313 else 8314 zone = i; 8315 8316 if (zone == ZONE_MOVABLE) 8317 continue; 8318 8319 end_pfn = max(max_zone_pfn[zone], start_pfn); 8320 arch_zone_lowest_possible_pfn[zone] = start_pfn; 8321 arch_zone_highest_possible_pfn[zone] = end_pfn; 8322 8323 start_pfn = end_pfn; 8324 } 8325 8326 /* Find the PFNs that ZONE_MOVABLE begins at in each node */ 8327 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn)); 8328 find_zone_movable_pfns_for_nodes(); 8329 8330 /* Print out the zone ranges */ 8331 pr_info("Zone ranges:\n"); 8332 for (i = 0; i < MAX_NR_ZONES; i++) { 8333 if (i == ZONE_MOVABLE) 8334 continue; 8335 pr_info(" %-8s ", zone_names[i]); 8336 if (arch_zone_lowest_possible_pfn[i] == 8337 arch_zone_highest_possible_pfn[i]) 8338 pr_cont("empty\n"); 8339 else 8340 pr_cont("[mem %#018Lx-%#018Lx]\n", 8341 (u64)arch_zone_lowest_possible_pfn[i] 8342 << PAGE_SHIFT, 8343 ((u64)arch_zone_highest_possible_pfn[i] 8344 << PAGE_SHIFT) - 1); 8345 } 8346 8347 /* Print out the PFNs ZONE_MOVABLE begins at in each node */ 8348 pr_info("Movable zone start for each node\n"); 8349 for (i = 0; i < MAX_NUMNODES; i++) { 8350 if (zone_movable_pfn[i]) 8351 pr_info(" Node %d: %#018Lx\n", i, 8352 (u64)zone_movable_pfn[i] << PAGE_SHIFT); 8353 } 8354 8355 /* 8356 * Print out the early node map, and initialize the 8357 * subsection-map relative to active online memory ranges to 8358 * enable future "sub-section" extensions of the memory map. 8359 */ 8360 pr_info("Early memory node ranges\n"); 8361 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) { 8362 pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid, 8363 (u64)start_pfn << PAGE_SHIFT, 8364 ((u64)end_pfn << PAGE_SHIFT) - 1); 8365 subsection_map_init(start_pfn, end_pfn - start_pfn); 8366 } 8367 8368 /* Initialise every node */ 8369 mminit_verify_pageflags_layout(); 8370 setup_nr_node_ids(); 8371 for_each_node(nid) { 8372 pg_data_t *pgdat; 8373 8374 if (!node_online(nid)) { 8375 pr_info("Initializing node %d as memoryless\n", nid); 8376 8377 /* Allocator not initialized yet */ 8378 pgdat = arch_alloc_nodedata(nid); 8379 if (!pgdat) { 8380 pr_err("Cannot allocate %zuB for node %d.\n", 8381 sizeof(*pgdat), nid); 8382 continue; 8383 } 8384 arch_refresh_nodedata(nid, pgdat); 8385 free_area_init_memoryless_node(nid); 8386 8387 /* 8388 * We do not want to confuse userspace by sysfs 8389 * files/directories for node without any memory 8390 * attached to it, so this node is not marked as 8391 * N_MEMORY and not marked online so that no sysfs 8392 * hierarchy will be created via register_one_node for 8393 * it. The pgdat will get fully initialized by 8394 * hotadd_init_pgdat() when memory is hotplugged into 8395 * this node. 8396 */ 8397 continue; 8398 } 8399 8400 pgdat = NODE_DATA(nid); 8401 free_area_init_node(nid); 8402 8403 /* Any memory on that node */ 8404 if (pgdat->node_present_pages) 8405 node_set_state(nid, N_MEMORY); 8406 check_for_memory(pgdat, nid); 8407 } 8408 8409 memmap_init(); 8410 } 8411 8412 static int __init cmdline_parse_core(char *p, unsigned long *core, 8413 unsigned long *percent) 8414 { 8415 unsigned long long coremem; 8416 char *endptr; 8417 8418 if (!p) 8419 return -EINVAL; 8420 8421 /* Value may be a percentage of total memory, otherwise bytes */ 8422 coremem = simple_strtoull(p, &endptr, 0); 8423 if (*endptr == '%') { 8424 /* Paranoid check for percent values greater than 100 */ 8425 WARN_ON(coremem > 100); 8426 8427 *percent = coremem; 8428 } else { 8429 coremem = memparse(p, &p); 8430 /* Paranoid check that UL is enough for the coremem value */ 8431 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX); 8432 8433 *core = coremem >> PAGE_SHIFT; 8434 *percent = 0UL; 8435 } 8436 return 0; 8437 } 8438 8439 /* 8440 * kernelcore=size sets the amount of memory for use for allocations that 8441 * cannot be reclaimed or migrated. 8442 */ 8443 static int __init cmdline_parse_kernelcore(char *p) 8444 { 8445 /* parse kernelcore=mirror */ 8446 if (parse_option_str(p, "mirror")) { 8447 mirrored_kernelcore = true; 8448 return 0; 8449 } 8450 8451 return cmdline_parse_core(p, &required_kernelcore, 8452 &required_kernelcore_percent); 8453 } 8454 8455 /* 8456 * movablecore=size sets the amount of memory for use for allocations that 8457 * can be reclaimed or migrated. 8458 */ 8459 static int __init cmdline_parse_movablecore(char *p) 8460 { 8461 return cmdline_parse_core(p, &required_movablecore, 8462 &required_movablecore_percent); 8463 } 8464 8465 early_param("kernelcore", cmdline_parse_kernelcore); 8466 early_param("movablecore", cmdline_parse_movablecore); 8467 8468 void adjust_managed_page_count(struct page *page, long count) 8469 { 8470 atomic_long_add(count, &page_zone(page)->managed_pages); 8471 totalram_pages_add(count); 8472 #ifdef CONFIG_HIGHMEM 8473 if (PageHighMem(page)) 8474 totalhigh_pages_add(count); 8475 #endif 8476 } 8477 EXPORT_SYMBOL(adjust_managed_page_count); 8478 8479 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s) 8480 { 8481 void *pos; 8482 unsigned long pages = 0; 8483 8484 start = (void *)PAGE_ALIGN((unsigned long)start); 8485 end = (void *)((unsigned long)end & PAGE_MASK); 8486 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) { 8487 struct page *page = virt_to_page(pos); 8488 void *direct_map_addr; 8489 8490 /* 8491 * 'direct_map_addr' might be different from 'pos' 8492 * because some architectures' virt_to_page() 8493 * work with aliases. Getting the direct map 8494 * address ensures that we get a _writeable_ 8495 * alias for the memset(). 8496 */ 8497 direct_map_addr = page_address(page); 8498 /* 8499 * Perform a kasan-unchecked memset() since this memory 8500 * has not been initialized. 8501 */ 8502 direct_map_addr = kasan_reset_tag(direct_map_addr); 8503 if ((unsigned int)poison <= 0xFF) 8504 memset(direct_map_addr, poison, PAGE_SIZE); 8505 8506 free_reserved_page(page); 8507 } 8508 8509 if (pages && s) 8510 pr_info("Freeing %s memory: %ldK\n", s, K(pages)); 8511 8512 return pages; 8513 } 8514 8515 void __init mem_init_print_info(void) 8516 { 8517 unsigned long physpages, codesize, datasize, rosize, bss_size; 8518 unsigned long init_code_size, init_data_size; 8519 8520 physpages = get_num_physpages(); 8521 codesize = _etext - _stext; 8522 datasize = _edata - _sdata; 8523 rosize = __end_rodata - __start_rodata; 8524 bss_size = __bss_stop - __bss_start; 8525 init_data_size = __init_end - __init_begin; 8526 init_code_size = _einittext - _sinittext; 8527 8528 /* 8529 * Detect special cases and adjust section sizes accordingly: 8530 * 1) .init.* may be embedded into .data sections 8531 * 2) .init.text.* may be out of [__init_begin, __init_end], 8532 * please refer to arch/tile/kernel/vmlinux.lds.S. 8533 * 3) .rodata.* may be embedded into .text or .data sections. 8534 */ 8535 #define adj_init_size(start, end, size, pos, adj) \ 8536 do { \ 8537 if (&start[0] <= &pos[0] && &pos[0] < &end[0] && size > adj) \ 8538 size -= adj; \ 8539 } while (0) 8540 8541 adj_init_size(__init_begin, __init_end, init_data_size, 8542 _sinittext, init_code_size); 8543 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size); 8544 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size); 8545 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize); 8546 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize); 8547 8548 #undef adj_init_size 8549 8550 pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved" 8551 #ifdef CONFIG_HIGHMEM 8552 ", %luK highmem" 8553 #endif 8554 ")\n", 8555 K(nr_free_pages()), K(physpages), 8556 codesize / SZ_1K, datasize / SZ_1K, rosize / SZ_1K, 8557 (init_data_size + init_code_size) / SZ_1K, bss_size / SZ_1K, 8558 K(physpages - totalram_pages() - totalcma_pages), 8559 K(totalcma_pages) 8560 #ifdef CONFIG_HIGHMEM 8561 , K(totalhigh_pages()) 8562 #endif 8563 ); 8564 } 8565 8566 /** 8567 * set_dma_reserve - set the specified number of pages reserved in the first zone 8568 * @new_dma_reserve: The number of pages to mark reserved 8569 * 8570 * The per-cpu batchsize and zone watermarks are determined by managed_pages. 8571 * In the DMA zone, a significant percentage may be consumed by kernel image 8572 * and other unfreeable allocations which can skew the watermarks badly. This 8573 * function may optionally be used to account for unfreeable pages in the 8574 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and 8575 * smaller per-cpu batchsize. 8576 */ 8577 void __init set_dma_reserve(unsigned long new_dma_reserve) 8578 { 8579 dma_reserve = new_dma_reserve; 8580 } 8581 8582 static int page_alloc_cpu_dead(unsigned int cpu) 8583 { 8584 struct zone *zone; 8585 8586 lru_add_drain_cpu(cpu); 8587 mlock_page_drain_remote(cpu); 8588 drain_pages(cpu); 8589 8590 /* 8591 * Spill the event counters of the dead processor 8592 * into the current processors event counters. 8593 * This artificially elevates the count of the current 8594 * processor. 8595 */ 8596 vm_events_fold_cpu(cpu); 8597 8598 /* 8599 * Zero the differential counters of the dead processor 8600 * so that the vm statistics are consistent. 8601 * 8602 * This is only okay since the processor is dead and cannot 8603 * race with what we are doing. 8604 */ 8605 cpu_vm_stats_fold(cpu); 8606 8607 for_each_populated_zone(zone) 8608 zone_pcp_update(zone, 0); 8609 8610 return 0; 8611 } 8612 8613 static int page_alloc_cpu_online(unsigned int cpu) 8614 { 8615 struct zone *zone; 8616 8617 for_each_populated_zone(zone) 8618 zone_pcp_update(zone, 1); 8619 return 0; 8620 } 8621 8622 #ifdef CONFIG_NUMA 8623 int hashdist = HASHDIST_DEFAULT; 8624 8625 static int __init set_hashdist(char *str) 8626 { 8627 if (!str) 8628 return 0; 8629 hashdist = simple_strtoul(str, &str, 0); 8630 return 1; 8631 } 8632 __setup("hashdist=", set_hashdist); 8633 #endif 8634 8635 void __init page_alloc_init(void) 8636 { 8637 int ret; 8638 8639 #ifdef CONFIG_NUMA 8640 if (num_node_state(N_MEMORY) == 1) 8641 hashdist = 0; 8642 #endif 8643 8644 ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC, 8645 "mm/page_alloc:pcp", 8646 page_alloc_cpu_online, 8647 page_alloc_cpu_dead); 8648 WARN_ON(ret < 0); 8649 } 8650 8651 /* 8652 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio 8653 * or min_free_kbytes changes. 8654 */ 8655 static void calculate_totalreserve_pages(void) 8656 { 8657 struct pglist_data *pgdat; 8658 unsigned long reserve_pages = 0; 8659 enum zone_type i, j; 8660 8661 for_each_online_pgdat(pgdat) { 8662 8663 pgdat->totalreserve_pages = 0; 8664 8665 for (i = 0; i < MAX_NR_ZONES; i++) { 8666 struct zone *zone = pgdat->node_zones + i; 8667 long max = 0; 8668 unsigned long managed_pages = zone_managed_pages(zone); 8669 8670 /* Find valid and maximum lowmem_reserve in the zone */ 8671 for (j = i; j < MAX_NR_ZONES; j++) { 8672 if (zone->lowmem_reserve[j] > max) 8673 max = zone->lowmem_reserve[j]; 8674 } 8675 8676 /* we treat the high watermark as reserved pages. */ 8677 max += high_wmark_pages(zone); 8678 8679 if (max > managed_pages) 8680 max = managed_pages; 8681 8682 pgdat->totalreserve_pages += max; 8683 8684 reserve_pages += max; 8685 } 8686 } 8687 totalreserve_pages = reserve_pages; 8688 } 8689 8690 /* 8691 * setup_per_zone_lowmem_reserve - called whenever 8692 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone 8693 * has a correct pages reserved value, so an adequate number of 8694 * pages are left in the zone after a successful __alloc_pages(). 8695 */ 8696 static void setup_per_zone_lowmem_reserve(void) 8697 { 8698 struct pglist_data *pgdat; 8699 enum zone_type i, j; 8700 8701 for_each_online_pgdat(pgdat) { 8702 for (i = 0; i < MAX_NR_ZONES - 1; i++) { 8703 struct zone *zone = &pgdat->node_zones[i]; 8704 int ratio = sysctl_lowmem_reserve_ratio[i]; 8705 bool clear = !ratio || !zone_managed_pages(zone); 8706 unsigned long managed_pages = 0; 8707 8708 for (j = i + 1; j < MAX_NR_ZONES; j++) { 8709 struct zone *upper_zone = &pgdat->node_zones[j]; 8710 8711 managed_pages += zone_managed_pages(upper_zone); 8712 8713 if (clear) 8714 zone->lowmem_reserve[j] = 0; 8715 else 8716 zone->lowmem_reserve[j] = managed_pages / ratio; 8717 } 8718 } 8719 } 8720 8721 /* update totalreserve_pages */ 8722 calculate_totalreserve_pages(); 8723 } 8724 8725 static void __setup_per_zone_wmarks(void) 8726 { 8727 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10); 8728 unsigned long lowmem_pages = 0; 8729 struct zone *zone; 8730 unsigned long flags; 8731 8732 /* Calculate total number of !ZONE_HIGHMEM pages */ 8733 for_each_zone(zone) { 8734 if (!is_highmem(zone)) 8735 lowmem_pages += zone_managed_pages(zone); 8736 } 8737 8738 for_each_zone(zone) { 8739 u64 tmp; 8740 8741 spin_lock_irqsave(&zone->lock, flags); 8742 tmp = (u64)pages_min * zone_managed_pages(zone); 8743 do_div(tmp, lowmem_pages); 8744 if (is_highmem(zone)) { 8745 /* 8746 * __GFP_HIGH and PF_MEMALLOC allocations usually don't 8747 * need highmem pages, so cap pages_min to a small 8748 * value here. 8749 * 8750 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN) 8751 * deltas control async page reclaim, and so should 8752 * not be capped for highmem. 8753 */ 8754 unsigned long min_pages; 8755 8756 min_pages = zone_managed_pages(zone) / 1024; 8757 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL); 8758 zone->_watermark[WMARK_MIN] = min_pages; 8759 } else { 8760 /* 8761 * If it's a lowmem zone, reserve a number of pages 8762 * proportionate to the zone's size. 8763 */ 8764 zone->_watermark[WMARK_MIN] = tmp; 8765 } 8766 8767 /* 8768 * Set the kswapd watermarks distance according to the 8769 * scale factor in proportion to available memory, but 8770 * ensure a minimum size on small systems. 8771 */ 8772 tmp = max_t(u64, tmp >> 2, 8773 mult_frac(zone_managed_pages(zone), 8774 watermark_scale_factor, 10000)); 8775 8776 zone->watermark_boost = 0; 8777 zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp; 8778 zone->_watermark[WMARK_HIGH] = low_wmark_pages(zone) + tmp; 8779 zone->_watermark[WMARK_PROMO] = high_wmark_pages(zone) + tmp; 8780 8781 spin_unlock_irqrestore(&zone->lock, flags); 8782 } 8783 8784 /* update totalreserve_pages */ 8785 calculate_totalreserve_pages(); 8786 } 8787 8788 /** 8789 * setup_per_zone_wmarks - called when min_free_kbytes changes 8790 * or when memory is hot-{added|removed} 8791 * 8792 * Ensures that the watermark[min,low,high] values for each zone are set 8793 * correctly with respect to min_free_kbytes. 8794 */ 8795 void setup_per_zone_wmarks(void) 8796 { 8797 struct zone *zone; 8798 static DEFINE_SPINLOCK(lock); 8799 8800 spin_lock(&lock); 8801 __setup_per_zone_wmarks(); 8802 spin_unlock(&lock); 8803 8804 /* 8805 * The watermark size have changed so update the pcpu batch 8806 * and high limits or the limits may be inappropriate. 8807 */ 8808 for_each_zone(zone) 8809 zone_pcp_update(zone, 0); 8810 } 8811 8812 /* 8813 * Initialise min_free_kbytes. 8814 * 8815 * For small machines we want it small (128k min). For large machines 8816 * we want it large (256MB max). But it is not linear, because network 8817 * bandwidth does not increase linearly with machine size. We use 8818 * 8819 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy: 8820 * min_free_kbytes = sqrt(lowmem_kbytes * 16) 8821 * 8822 * which yields 8823 * 8824 * 16MB: 512k 8825 * 32MB: 724k 8826 * 64MB: 1024k 8827 * 128MB: 1448k 8828 * 256MB: 2048k 8829 * 512MB: 2896k 8830 * 1024MB: 4096k 8831 * 2048MB: 5792k 8832 * 4096MB: 8192k 8833 * 8192MB: 11584k 8834 * 16384MB: 16384k 8835 */ 8836 void calculate_min_free_kbytes(void) 8837 { 8838 unsigned long lowmem_kbytes; 8839 int new_min_free_kbytes; 8840 8841 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10); 8842 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16); 8843 8844 if (new_min_free_kbytes > user_min_free_kbytes) 8845 min_free_kbytes = clamp(new_min_free_kbytes, 128, 262144); 8846 else 8847 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n", 8848 new_min_free_kbytes, user_min_free_kbytes); 8849 8850 } 8851 8852 int __meminit init_per_zone_wmark_min(void) 8853 { 8854 calculate_min_free_kbytes(); 8855 setup_per_zone_wmarks(); 8856 refresh_zone_stat_thresholds(); 8857 setup_per_zone_lowmem_reserve(); 8858 8859 #ifdef CONFIG_NUMA 8860 setup_min_unmapped_ratio(); 8861 setup_min_slab_ratio(); 8862 #endif 8863 8864 khugepaged_min_free_kbytes_update(); 8865 8866 return 0; 8867 } 8868 postcore_initcall(init_per_zone_wmark_min) 8869 8870 /* 8871 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so 8872 * that we can call two helper functions whenever min_free_kbytes 8873 * changes. 8874 */ 8875 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write, 8876 void *buffer, size_t *length, loff_t *ppos) 8877 { 8878 int rc; 8879 8880 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 8881 if (rc) 8882 return rc; 8883 8884 if (write) { 8885 user_min_free_kbytes = min_free_kbytes; 8886 setup_per_zone_wmarks(); 8887 } 8888 return 0; 8889 } 8890 8891 int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write, 8892 void *buffer, size_t *length, loff_t *ppos) 8893 { 8894 int rc; 8895 8896 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 8897 if (rc) 8898 return rc; 8899 8900 if (write) 8901 setup_per_zone_wmarks(); 8902 8903 return 0; 8904 } 8905 8906 #ifdef CONFIG_NUMA 8907 static void setup_min_unmapped_ratio(void) 8908 { 8909 pg_data_t *pgdat; 8910 struct zone *zone; 8911 8912 for_each_online_pgdat(pgdat) 8913 pgdat->min_unmapped_pages = 0; 8914 8915 for_each_zone(zone) 8916 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) * 8917 sysctl_min_unmapped_ratio) / 100; 8918 } 8919 8920 8921 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write, 8922 void *buffer, size_t *length, loff_t *ppos) 8923 { 8924 int rc; 8925 8926 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 8927 if (rc) 8928 return rc; 8929 8930 setup_min_unmapped_ratio(); 8931 8932 return 0; 8933 } 8934 8935 static void setup_min_slab_ratio(void) 8936 { 8937 pg_data_t *pgdat; 8938 struct zone *zone; 8939 8940 for_each_online_pgdat(pgdat) 8941 pgdat->min_slab_pages = 0; 8942 8943 for_each_zone(zone) 8944 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) * 8945 sysctl_min_slab_ratio) / 100; 8946 } 8947 8948 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write, 8949 void *buffer, size_t *length, loff_t *ppos) 8950 { 8951 int rc; 8952 8953 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 8954 if (rc) 8955 return rc; 8956 8957 setup_min_slab_ratio(); 8958 8959 return 0; 8960 } 8961 #endif 8962 8963 /* 8964 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around 8965 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve() 8966 * whenever sysctl_lowmem_reserve_ratio changes. 8967 * 8968 * The reserve ratio obviously has absolutely no relation with the 8969 * minimum watermarks. The lowmem reserve ratio can only make sense 8970 * if in function of the boot time zone sizes. 8971 */ 8972 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write, 8973 void *buffer, size_t *length, loff_t *ppos) 8974 { 8975 int i; 8976 8977 proc_dointvec_minmax(table, write, buffer, length, ppos); 8978 8979 for (i = 0; i < MAX_NR_ZONES; i++) { 8980 if (sysctl_lowmem_reserve_ratio[i] < 1) 8981 sysctl_lowmem_reserve_ratio[i] = 0; 8982 } 8983 8984 setup_per_zone_lowmem_reserve(); 8985 return 0; 8986 } 8987 8988 /* 8989 * percpu_pagelist_high_fraction - changes the pcp->high for each zone on each 8990 * cpu. It is the fraction of total pages in each zone that a hot per cpu 8991 * pagelist can have before it gets flushed back to buddy allocator. 8992 */ 8993 int percpu_pagelist_high_fraction_sysctl_handler(struct ctl_table *table, 8994 int write, void *buffer, size_t *length, loff_t *ppos) 8995 { 8996 struct zone *zone; 8997 int old_percpu_pagelist_high_fraction; 8998 int ret; 8999 9000 mutex_lock(&pcp_batch_high_lock); 9001 old_percpu_pagelist_high_fraction = percpu_pagelist_high_fraction; 9002 9003 ret = proc_dointvec_minmax(table, write, buffer, length, ppos); 9004 if (!write || ret < 0) 9005 goto out; 9006 9007 /* Sanity checking to avoid pcp imbalance */ 9008 if (percpu_pagelist_high_fraction && 9009 percpu_pagelist_high_fraction < MIN_PERCPU_PAGELIST_HIGH_FRACTION) { 9010 percpu_pagelist_high_fraction = old_percpu_pagelist_high_fraction; 9011 ret = -EINVAL; 9012 goto out; 9013 } 9014 9015 /* No change? */ 9016 if (percpu_pagelist_high_fraction == old_percpu_pagelist_high_fraction) 9017 goto out; 9018 9019 for_each_populated_zone(zone) 9020 zone_set_pageset_high_and_batch(zone, 0); 9021 out: 9022 mutex_unlock(&pcp_batch_high_lock); 9023 return ret; 9024 } 9025 9026 #ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES 9027 /* 9028 * Returns the number of pages that arch has reserved but 9029 * is not known to alloc_large_system_hash(). 9030 */ 9031 static unsigned long __init arch_reserved_kernel_pages(void) 9032 { 9033 return 0; 9034 } 9035 #endif 9036 9037 /* 9038 * Adaptive scale is meant to reduce sizes of hash tables on large memory 9039 * machines. As memory size is increased the scale is also increased but at 9040 * slower pace. Starting from ADAPT_SCALE_BASE (64G), every time memory 9041 * quadruples the scale is increased by one, which means the size of hash table 9042 * only doubles, instead of quadrupling as well. 9043 * Because 32-bit systems cannot have large physical memory, where this scaling 9044 * makes sense, it is disabled on such platforms. 9045 */ 9046 #if __BITS_PER_LONG > 32 9047 #define ADAPT_SCALE_BASE (64ul << 30) 9048 #define ADAPT_SCALE_SHIFT 2 9049 #define ADAPT_SCALE_NPAGES (ADAPT_SCALE_BASE >> PAGE_SHIFT) 9050 #endif 9051 9052 /* 9053 * allocate a large system hash table from bootmem 9054 * - it is assumed that the hash table must contain an exact power-of-2 9055 * quantity of entries 9056 * - limit is the number of hash buckets, not the total allocation size 9057 */ 9058 void *__init alloc_large_system_hash(const char *tablename, 9059 unsigned long bucketsize, 9060 unsigned long numentries, 9061 int scale, 9062 int flags, 9063 unsigned int *_hash_shift, 9064 unsigned int *_hash_mask, 9065 unsigned long low_limit, 9066 unsigned long high_limit) 9067 { 9068 unsigned long long max = high_limit; 9069 unsigned long log2qty, size; 9070 void *table; 9071 gfp_t gfp_flags; 9072 bool virt; 9073 bool huge; 9074 9075 /* allow the kernel cmdline to have a say */ 9076 if (!numentries) { 9077 /* round applicable memory size up to nearest megabyte */ 9078 numentries = nr_kernel_pages; 9079 numentries -= arch_reserved_kernel_pages(); 9080 9081 /* It isn't necessary when PAGE_SIZE >= 1MB */ 9082 if (PAGE_SIZE < SZ_1M) 9083 numentries = round_up(numentries, SZ_1M / PAGE_SIZE); 9084 9085 #if __BITS_PER_LONG > 32 9086 if (!high_limit) { 9087 unsigned long adapt; 9088 9089 for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries; 9090 adapt <<= ADAPT_SCALE_SHIFT) 9091 scale++; 9092 } 9093 #endif 9094 9095 /* limit to 1 bucket per 2^scale bytes of low memory */ 9096 if (scale > PAGE_SHIFT) 9097 numentries >>= (scale - PAGE_SHIFT); 9098 else 9099 numentries <<= (PAGE_SHIFT - scale); 9100 9101 /* Make sure we've got at least a 0-order allocation.. */ 9102 if (unlikely(flags & HASH_SMALL)) { 9103 /* Makes no sense without HASH_EARLY */ 9104 WARN_ON(!(flags & HASH_EARLY)); 9105 if (!(numentries >> *_hash_shift)) { 9106 numentries = 1UL << *_hash_shift; 9107 BUG_ON(!numentries); 9108 } 9109 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE)) 9110 numentries = PAGE_SIZE / bucketsize; 9111 } 9112 numentries = roundup_pow_of_two(numentries); 9113 9114 /* limit allocation size to 1/16 total memory by default */ 9115 if (max == 0) { 9116 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4; 9117 do_div(max, bucketsize); 9118 } 9119 max = min(max, 0x80000000ULL); 9120 9121 if (numentries < low_limit) 9122 numentries = low_limit; 9123 if (numentries > max) 9124 numentries = max; 9125 9126 log2qty = ilog2(numentries); 9127 9128 gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC; 9129 do { 9130 virt = false; 9131 size = bucketsize << log2qty; 9132 if (flags & HASH_EARLY) { 9133 if (flags & HASH_ZERO) 9134 table = memblock_alloc(size, SMP_CACHE_BYTES); 9135 else 9136 table = memblock_alloc_raw(size, 9137 SMP_CACHE_BYTES); 9138 } else if (get_order(size) >= MAX_ORDER || hashdist) { 9139 table = vmalloc_huge(size, gfp_flags); 9140 virt = true; 9141 if (table) 9142 huge = is_vm_area_hugepages(table); 9143 } else { 9144 /* 9145 * If bucketsize is not a power-of-two, we may free 9146 * some pages at the end of hash table which 9147 * alloc_pages_exact() automatically does 9148 */ 9149 table = alloc_pages_exact(size, gfp_flags); 9150 kmemleak_alloc(table, size, 1, gfp_flags); 9151 } 9152 } while (!table && size > PAGE_SIZE && --log2qty); 9153 9154 if (!table) 9155 panic("Failed to allocate %s hash table\n", tablename); 9156 9157 pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n", 9158 tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size, 9159 virt ? (huge ? "vmalloc hugepage" : "vmalloc") : "linear"); 9160 9161 if (_hash_shift) 9162 *_hash_shift = log2qty; 9163 if (_hash_mask) 9164 *_hash_mask = (1 << log2qty) - 1; 9165 9166 return table; 9167 } 9168 9169 #ifdef CONFIG_CONTIG_ALLOC 9170 #if defined(CONFIG_DYNAMIC_DEBUG) || \ 9171 (defined(CONFIG_DYNAMIC_DEBUG_CORE) && defined(DYNAMIC_DEBUG_MODULE)) 9172 /* Usage: See admin-guide/dynamic-debug-howto.rst */ 9173 static void alloc_contig_dump_pages(struct list_head *page_list) 9174 { 9175 DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure"); 9176 9177 if (DYNAMIC_DEBUG_BRANCH(descriptor)) { 9178 struct page *page; 9179 9180 dump_stack(); 9181 list_for_each_entry(page, page_list, lru) 9182 dump_page(page, "migration failure"); 9183 } 9184 } 9185 #else 9186 static inline void alloc_contig_dump_pages(struct list_head *page_list) 9187 { 9188 } 9189 #endif 9190 9191 /* [start, end) must belong to a single zone. */ 9192 int __alloc_contig_migrate_range(struct compact_control *cc, 9193 unsigned long start, unsigned long end) 9194 { 9195 /* This function is based on compact_zone() from compaction.c. */ 9196 unsigned int nr_reclaimed; 9197 unsigned long pfn = start; 9198 unsigned int tries = 0; 9199 int ret = 0; 9200 struct migration_target_control mtc = { 9201 .nid = zone_to_nid(cc->zone), 9202 .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL, 9203 }; 9204 9205 lru_cache_disable(); 9206 9207 while (pfn < end || !list_empty(&cc->migratepages)) { 9208 if (fatal_signal_pending(current)) { 9209 ret = -EINTR; 9210 break; 9211 } 9212 9213 if (list_empty(&cc->migratepages)) { 9214 cc->nr_migratepages = 0; 9215 ret = isolate_migratepages_range(cc, pfn, end); 9216 if (ret && ret != -EAGAIN) 9217 break; 9218 pfn = cc->migrate_pfn; 9219 tries = 0; 9220 } else if (++tries == 5) { 9221 ret = -EBUSY; 9222 break; 9223 } 9224 9225 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone, 9226 &cc->migratepages); 9227 cc->nr_migratepages -= nr_reclaimed; 9228 9229 ret = migrate_pages(&cc->migratepages, alloc_migration_target, 9230 NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE, NULL); 9231 9232 /* 9233 * On -ENOMEM, migrate_pages() bails out right away. It is pointless 9234 * to retry again over this error, so do the same here. 9235 */ 9236 if (ret == -ENOMEM) 9237 break; 9238 } 9239 9240 lru_cache_enable(); 9241 if (ret < 0) { 9242 if (!(cc->gfp_mask & __GFP_NOWARN) && ret == -EBUSY) 9243 alloc_contig_dump_pages(&cc->migratepages); 9244 putback_movable_pages(&cc->migratepages); 9245 return ret; 9246 } 9247 return 0; 9248 } 9249 9250 /** 9251 * alloc_contig_range() -- tries to allocate given range of pages 9252 * @start: start PFN to allocate 9253 * @end: one-past-the-last PFN to allocate 9254 * @migratetype: migratetype of the underlying pageblocks (either 9255 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks 9256 * in range must have the same migratetype and it must 9257 * be either of the two. 9258 * @gfp_mask: GFP mask to use during compaction 9259 * 9260 * The PFN range does not have to be pageblock aligned. The PFN range must 9261 * belong to a single zone. 9262 * 9263 * The first thing this routine does is attempt to MIGRATE_ISOLATE all 9264 * pageblocks in the range. Once isolated, the pageblocks should not 9265 * be modified by others. 9266 * 9267 * Return: zero on success or negative error code. On success all 9268 * pages which PFN is in [start, end) are allocated for the caller and 9269 * need to be freed with free_contig_range(). 9270 */ 9271 int alloc_contig_range(unsigned long start, unsigned long end, 9272 unsigned migratetype, gfp_t gfp_mask) 9273 { 9274 unsigned long outer_start, outer_end; 9275 int order; 9276 int ret = 0; 9277 9278 struct compact_control cc = { 9279 .nr_migratepages = 0, 9280 .order = -1, 9281 .zone = page_zone(pfn_to_page(start)), 9282 .mode = MIGRATE_SYNC, 9283 .ignore_skip_hint = true, 9284 .no_set_skip_hint = true, 9285 .gfp_mask = current_gfp_context(gfp_mask), 9286 .alloc_contig = true, 9287 }; 9288 INIT_LIST_HEAD(&cc.migratepages); 9289 9290 /* 9291 * What we do here is we mark all pageblocks in range as 9292 * MIGRATE_ISOLATE. Because pageblock and max order pages may 9293 * have different sizes, and due to the way page allocator 9294 * work, start_isolate_page_range() has special handlings for this. 9295 * 9296 * Once the pageblocks are marked as MIGRATE_ISOLATE, we 9297 * migrate the pages from an unaligned range (ie. pages that 9298 * we are interested in). This will put all the pages in 9299 * range back to page allocator as MIGRATE_ISOLATE. 9300 * 9301 * When this is done, we take the pages in range from page 9302 * allocator removing them from the buddy system. This way 9303 * page allocator will never consider using them. 9304 * 9305 * This lets us mark the pageblocks back as 9306 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the 9307 * aligned range but not in the unaligned, original range are 9308 * put back to page allocator so that buddy can use them. 9309 */ 9310 9311 ret = start_isolate_page_range(start, end, migratetype, 0, gfp_mask); 9312 if (ret) 9313 goto done; 9314 9315 drain_all_pages(cc.zone); 9316 9317 /* 9318 * In case of -EBUSY, we'd like to know which page causes problem. 9319 * So, just fall through. test_pages_isolated() has a tracepoint 9320 * which will report the busy page. 9321 * 9322 * It is possible that busy pages could become available before 9323 * the call to test_pages_isolated, and the range will actually be 9324 * allocated. So, if we fall through be sure to clear ret so that 9325 * -EBUSY is not accidentally used or returned to caller. 9326 */ 9327 ret = __alloc_contig_migrate_range(&cc, start, end); 9328 if (ret && ret != -EBUSY) 9329 goto done; 9330 ret = 0; 9331 9332 /* 9333 * Pages from [start, end) are within a pageblock_nr_pages 9334 * aligned blocks that are marked as MIGRATE_ISOLATE. What's 9335 * more, all pages in [start, end) are free in page allocator. 9336 * What we are going to do is to allocate all pages from 9337 * [start, end) (that is remove them from page allocator). 9338 * 9339 * The only problem is that pages at the beginning and at the 9340 * end of interesting range may be not aligned with pages that 9341 * page allocator holds, ie. they can be part of higher order 9342 * pages. Because of this, we reserve the bigger range and 9343 * once this is done free the pages we are not interested in. 9344 * 9345 * We don't have to hold zone->lock here because the pages are 9346 * isolated thus they won't get removed from buddy. 9347 */ 9348 9349 order = 0; 9350 outer_start = start; 9351 while (!PageBuddy(pfn_to_page(outer_start))) { 9352 if (++order >= MAX_ORDER) { 9353 outer_start = start; 9354 break; 9355 } 9356 outer_start &= ~0UL << order; 9357 } 9358 9359 if (outer_start != start) { 9360 order = buddy_order(pfn_to_page(outer_start)); 9361 9362 /* 9363 * outer_start page could be small order buddy page and 9364 * it doesn't include start page. Adjust outer_start 9365 * in this case to report failed page properly 9366 * on tracepoint in test_pages_isolated() 9367 */ 9368 if (outer_start + (1UL << order) <= start) 9369 outer_start = start; 9370 } 9371 9372 /* Make sure the range is really isolated. */ 9373 if (test_pages_isolated(outer_start, end, 0)) { 9374 ret = -EBUSY; 9375 goto done; 9376 } 9377 9378 /* Grab isolated pages from freelists. */ 9379 outer_end = isolate_freepages_range(&cc, outer_start, end); 9380 if (!outer_end) { 9381 ret = -EBUSY; 9382 goto done; 9383 } 9384 9385 /* Free head and tail (if any) */ 9386 if (start != outer_start) 9387 free_contig_range(outer_start, start - outer_start); 9388 if (end != outer_end) 9389 free_contig_range(end, outer_end - end); 9390 9391 done: 9392 undo_isolate_page_range(start, end, migratetype); 9393 return ret; 9394 } 9395 EXPORT_SYMBOL(alloc_contig_range); 9396 9397 static int __alloc_contig_pages(unsigned long start_pfn, 9398 unsigned long nr_pages, gfp_t gfp_mask) 9399 { 9400 unsigned long end_pfn = start_pfn + nr_pages; 9401 9402 return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE, 9403 gfp_mask); 9404 } 9405 9406 static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn, 9407 unsigned long nr_pages) 9408 { 9409 unsigned long i, end_pfn = start_pfn + nr_pages; 9410 struct page *page; 9411 9412 for (i = start_pfn; i < end_pfn; i++) { 9413 page = pfn_to_online_page(i); 9414 if (!page) 9415 return false; 9416 9417 if (page_zone(page) != z) 9418 return false; 9419 9420 if (PageReserved(page)) 9421 return false; 9422 } 9423 return true; 9424 } 9425 9426 static bool zone_spans_last_pfn(const struct zone *zone, 9427 unsigned long start_pfn, unsigned long nr_pages) 9428 { 9429 unsigned long last_pfn = start_pfn + nr_pages - 1; 9430 9431 return zone_spans_pfn(zone, last_pfn); 9432 } 9433 9434 /** 9435 * alloc_contig_pages() -- tries to find and allocate contiguous range of pages 9436 * @nr_pages: Number of contiguous pages to allocate 9437 * @gfp_mask: GFP mask to limit search and used during compaction 9438 * @nid: Target node 9439 * @nodemask: Mask for other possible nodes 9440 * 9441 * This routine is a wrapper around alloc_contig_range(). It scans over zones 9442 * on an applicable zonelist to find a contiguous pfn range which can then be 9443 * tried for allocation with alloc_contig_range(). This routine is intended 9444 * for allocation requests which can not be fulfilled with the buddy allocator. 9445 * 9446 * The allocated memory is always aligned to a page boundary. If nr_pages is a 9447 * power of two, then allocated range is also guaranteed to be aligned to same 9448 * nr_pages (e.g. 1GB request would be aligned to 1GB). 9449 * 9450 * Allocated pages can be freed with free_contig_range() or by manually calling 9451 * __free_page() on each allocated page. 9452 * 9453 * Return: pointer to contiguous pages on success, or NULL if not successful. 9454 */ 9455 struct page *alloc_contig_pages(unsigned long nr_pages, gfp_t gfp_mask, 9456 int nid, nodemask_t *nodemask) 9457 { 9458 unsigned long ret, pfn, flags; 9459 struct zonelist *zonelist; 9460 struct zone *zone; 9461 struct zoneref *z; 9462 9463 zonelist = node_zonelist(nid, gfp_mask); 9464 for_each_zone_zonelist_nodemask(zone, z, zonelist, 9465 gfp_zone(gfp_mask), nodemask) { 9466 spin_lock_irqsave(&zone->lock, flags); 9467 9468 pfn = ALIGN(zone->zone_start_pfn, nr_pages); 9469 while (zone_spans_last_pfn(zone, pfn, nr_pages)) { 9470 if (pfn_range_valid_contig(zone, pfn, nr_pages)) { 9471 /* 9472 * We release the zone lock here because 9473 * alloc_contig_range() will also lock the zone 9474 * at some point. If there's an allocation 9475 * spinning on this lock, it may win the race 9476 * and cause alloc_contig_range() to fail... 9477 */ 9478 spin_unlock_irqrestore(&zone->lock, flags); 9479 ret = __alloc_contig_pages(pfn, nr_pages, 9480 gfp_mask); 9481 if (!ret) 9482 return pfn_to_page(pfn); 9483 spin_lock_irqsave(&zone->lock, flags); 9484 } 9485 pfn += nr_pages; 9486 } 9487 spin_unlock_irqrestore(&zone->lock, flags); 9488 } 9489 return NULL; 9490 } 9491 #endif /* CONFIG_CONTIG_ALLOC */ 9492 9493 void free_contig_range(unsigned long pfn, unsigned long nr_pages) 9494 { 9495 unsigned long count = 0; 9496 9497 for (; nr_pages--; pfn++) { 9498 struct page *page = pfn_to_page(pfn); 9499 9500 count += page_count(page) != 1; 9501 __free_page(page); 9502 } 9503 WARN(count != 0, "%lu pages are still in use!\n", count); 9504 } 9505 EXPORT_SYMBOL(free_contig_range); 9506 9507 /* 9508 * Effectively disable pcplists for the zone by setting the high limit to 0 9509 * and draining all cpus. A concurrent page freeing on another CPU that's about 9510 * to put the page on pcplist will either finish before the drain and the page 9511 * will be drained, or observe the new high limit and skip the pcplist. 9512 * 9513 * Must be paired with a call to zone_pcp_enable(). 9514 */ 9515 void zone_pcp_disable(struct zone *zone) 9516 { 9517 mutex_lock(&pcp_batch_high_lock); 9518 __zone_set_pageset_high_and_batch(zone, 0, 1); 9519 __drain_all_pages(zone, true); 9520 } 9521 9522 void zone_pcp_enable(struct zone *zone) 9523 { 9524 __zone_set_pageset_high_and_batch(zone, zone->pageset_high, zone->pageset_batch); 9525 mutex_unlock(&pcp_batch_high_lock); 9526 } 9527 9528 void zone_pcp_reset(struct zone *zone) 9529 { 9530 int cpu; 9531 struct per_cpu_zonestat *pzstats; 9532 9533 if (zone->per_cpu_pageset != &boot_pageset) { 9534 for_each_online_cpu(cpu) { 9535 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu); 9536 drain_zonestat(zone, pzstats); 9537 } 9538 free_percpu(zone->per_cpu_pageset); 9539 zone->per_cpu_pageset = &boot_pageset; 9540 if (zone->per_cpu_zonestats != &boot_zonestats) { 9541 free_percpu(zone->per_cpu_zonestats); 9542 zone->per_cpu_zonestats = &boot_zonestats; 9543 } 9544 } 9545 } 9546 9547 #ifdef CONFIG_MEMORY_HOTREMOVE 9548 /* 9549 * All pages in the range must be in a single zone, must not contain holes, 9550 * must span full sections, and must be isolated before calling this function. 9551 */ 9552 void __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn) 9553 { 9554 unsigned long pfn = start_pfn; 9555 struct page *page; 9556 struct zone *zone; 9557 unsigned int order; 9558 unsigned long flags; 9559 9560 offline_mem_sections(pfn, end_pfn); 9561 zone = page_zone(pfn_to_page(pfn)); 9562 spin_lock_irqsave(&zone->lock, flags); 9563 while (pfn < end_pfn) { 9564 page = pfn_to_page(pfn); 9565 /* 9566 * The HWPoisoned page may be not in buddy system, and 9567 * page_count() is not 0. 9568 */ 9569 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) { 9570 pfn++; 9571 continue; 9572 } 9573 /* 9574 * At this point all remaining PageOffline() pages have a 9575 * reference count of 0 and can simply be skipped. 9576 */ 9577 if (PageOffline(page)) { 9578 BUG_ON(page_count(page)); 9579 BUG_ON(PageBuddy(page)); 9580 pfn++; 9581 continue; 9582 } 9583 9584 BUG_ON(page_count(page)); 9585 BUG_ON(!PageBuddy(page)); 9586 order = buddy_order(page); 9587 del_page_from_free_list(page, zone, order); 9588 pfn += (1 << order); 9589 } 9590 spin_unlock_irqrestore(&zone->lock, flags); 9591 } 9592 #endif 9593 9594 /* 9595 * This function returns a stable result only if called under zone lock. 9596 */ 9597 bool is_free_buddy_page(struct page *page) 9598 { 9599 unsigned long pfn = page_to_pfn(page); 9600 unsigned int order; 9601 9602 for (order = 0; order < MAX_ORDER; order++) { 9603 struct page *page_head = page - (pfn & ((1 << order) - 1)); 9604 9605 if (PageBuddy(page_head) && 9606 buddy_order_unsafe(page_head) >= order) 9607 break; 9608 } 9609 9610 return order < MAX_ORDER; 9611 } 9612 EXPORT_SYMBOL(is_free_buddy_page); 9613 9614 #ifdef CONFIG_MEMORY_FAILURE 9615 /* 9616 * Break down a higher-order page in sub-pages, and keep our target out of 9617 * buddy allocator. 9618 */ 9619 static void break_down_buddy_pages(struct zone *zone, struct page *page, 9620 struct page *target, int low, int high, 9621 int migratetype) 9622 { 9623 unsigned long size = 1 << high; 9624 struct page *current_buddy, *next_page; 9625 9626 while (high > low) { 9627 high--; 9628 size >>= 1; 9629 9630 if (target >= &page[size]) { 9631 next_page = page + size; 9632 current_buddy = page; 9633 } else { 9634 next_page = page; 9635 current_buddy = page + size; 9636 } 9637 9638 if (set_page_guard(zone, current_buddy, high, migratetype)) 9639 continue; 9640 9641 if (current_buddy != target) { 9642 add_to_free_list(current_buddy, zone, high, migratetype); 9643 set_buddy_order(current_buddy, high); 9644 page = next_page; 9645 } 9646 } 9647 } 9648 9649 /* 9650 * Take a page that will be marked as poisoned off the buddy allocator. 9651 */ 9652 bool take_page_off_buddy(struct page *page) 9653 { 9654 struct zone *zone = page_zone(page); 9655 unsigned long pfn = page_to_pfn(page); 9656 unsigned long flags; 9657 unsigned int order; 9658 bool ret = false; 9659 9660 spin_lock_irqsave(&zone->lock, flags); 9661 for (order = 0; order < MAX_ORDER; order++) { 9662 struct page *page_head = page - (pfn & ((1 << order) - 1)); 9663 int page_order = buddy_order(page_head); 9664 9665 if (PageBuddy(page_head) && page_order >= order) { 9666 unsigned long pfn_head = page_to_pfn(page_head); 9667 int migratetype = get_pfnblock_migratetype(page_head, 9668 pfn_head); 9669 9670 del_page_from_free_list(page_head, zone, page_order); 9671 break_down_buddy_pages(zone, page_head, page, 0, 9672 page_order, migratetype); 9673 SetPageHWPoisonTakenOff(page); 9674 if (!is_migrate_isolate(migratetype)) 9675 __mod_zone_freepage_state(zone, -1, migratetype); 9676 ret = true; 9677 break; 9678 } 9679 if (page_count(page_head) > 0) 9680 break; 9681 } 9682 spin_unlock_irqrestore(&zone->lock, flags); 9683 return ret; 9684 } 9685 9686 /* 9687 * Cancel takeoff done by take_page_off_buddy(). 9688 */ 9689 bool put_page_back_buddy(struct page *page) 9690 { 9691 struct zone *zone = page_zone(page); 9692 unsigned long pfn = page_to_pfn(page); 9693 unsigned long flags; 9694 int migratetype = get_pfnblock_migratetype(page, pfn); 9695 bool ret = false; 9696 9697 spin_lock_irqsave(&zone->lock, flags); 9698 if (put_page_testzero(page)) { 9699 ClearPageHWPoisonTakenOff(page); 9700 __free_one_page(page, pfn, zone, 0, migratetype, FPI_NONE); 9701 if (TestClearPageHWPoison(page)) { 9702 ret = true; 9703 } 9704 } 9705 spin_unlock_irqrestore(&zone->lock, flags); 9706 9707 return ret; 9708 } 9709 #endif 9710 9711 #ifdef CONFIG_ZONE_DMA 9712 bool has_managed_dma(void) 9713 { 9714 struct pglist_data *pgdat; 9715 9716 for_each_online_pgdat(pgdat) { 9717 struct zone *zone = &pgdat->node_zones[ZONE_DMA]; 9718 9719 if (managed_zone(zone)) 9720 return true; 9721 } 9722 return false; 9723 } 9724 #endif /* CONFIG_ZONE_DMA */ 9725