1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * 4 * Manages the free list, the system allocates free pages here. 5 * Note that kmalloc() lives in slab.c 6 * 7 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds 8 * Swap reorganised 29.12.95, Stephen Tweedie 9 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999 10 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999 11 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999 12 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000 13 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002 14 * (lots of bits borrowed from Ingo Molnar & Andrew Morton) 15 */ 16 17 #include <linux/stddef.h> 18 #include <linux/mm.h> 19 #include <linux/highmem.h> 20 #include <linux/interrupt.h> 21 #include <linux/jiffies.h> 22 #include <linux/compiler.h> 23 #include <linux/kernel.h> 24 #include <linux/kasan.h> 25 #include <linux/kmsan.h> 26 #include <linux/module.h> 27 #include <linux/suspend.h> 28 #include <linux/ratelimit.h> 29 #include <linux/oom.h> 30 #include <linux/topology.h> 31 #include <linux/sysctl.h> 32 #include <linux/cpu.h> 33 #include <linux/cpuset.h> 34 #include <linux/folio_batch.h> 35 #include <linux/memory_hotplug.h> 36 #include <linux/nodemask.h> 37 #include <linux/vmstat.h> 38 #include <linux/fault-inject.h> 39 #include <linux/compaction.h> 40 #include <trace/events/kmem.h> 41 #include <trace/events/oom.h> 42 #include <linux/prefetch.h> 43 #include <linux/mm_inline.h> 44 #include <linux/mmu_notifier.h> 45 #include <linux/migrate.h> 46 #include <linux/sched/mm.h> 47 #include <linux/page_owner.h> 48 #include <linux/page_table_check.h> 49 #include <linux/memcontrol.h> 50 #include <linux/ftrace.h> 51 #include <linux/lockdep.h> 52 #include <linux/psi.h> 53 #include <linux/khugepaged.h> 54 #include <linux/delayacct.h> 55 #include <linux/cacheinfo.h> 56 #include <linux/pgalloc_tag.h> 57 #include <asm/div64.h> 58 #include "internal.h" 59 #include "mm_init.h" 60 #include "page_alloc.h" 61 #include "shuffle.h" 62 #include "page_reporting.h" 63 64 /* Free Page Internal flags: for internal, non-pcp variants of free_pages(). */ 65 typedef int __bitwise fpi_t; 66 67 /* No special request */ 68 #define FPI_NONE ((__force fpi_t)0) 69 70 /* 71 * Skip free page reporting notification for the (possibly merged) page. 72 * This does not hinder free page reporting from grabbing the page, 73 * reporting it and marking it "reported" - it only skips notifying 74 * the free page reporting infrastructure about a newly freed page. For 75 * example, used when temporarily pulling a page from a freelist and 76 * putting it back unmodified. 77 */ 78 #define FPI_SKIP_REPORT_NOTIFY ((__force fpi_t)BIT(0)) 79 80 /* 81 * Place the (possibly merged) page to the tail of the freelist. Will ignore 82 * page shuffling (relevant code - e.g., memory onlining - is expected to 83 * shuffle the whole zone). 84 * 85 * Note: No code should rely on this flag for correctness - it's purely 86 * to allow for optimizations when handing back either fresh pages 87 * (memory onlining) or untouched pages (page isolation, free page 88 * reporting). 89 */ 90 #define FPI_TO_TAIL ((__force fpi_t)BIT(1)) 91 92 /* Free the page without taking locks. Rely on trylock only. */ 93 #define FPI_NOLOCK ((__force fpi_t)BIT(2)) 94 95 /* free_pages_prepare() has already been called for page(s) being freed. */ 96 #define FPI_PREPARED ((__force fpi_t)BIT(3)) 97 98 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */ 99 static DEFINE_MUTEX(pcp_batch_high_lock); 100 #define MIN_PERCPU_PAGELIST_HIGH_FRACTION (8) 101 102 /* 103 * Locking a pcp requires a PCP lookup followed by a spinlock. To avoid 104 * a migration causing the wrong PCP to be locked and remote memory being 105 * potentially allocated, pin the task to the CPU for the lookup+lock. 106 * preempt_disable is used on !RT because it is faster than migrate_disable. 107 * migrate_disable is used on RT because otherwise RT spinlock usage is 108 * interfered with and a high priority task cannot preempt the allocator. 109 */ 110 #ifndef CONFIG_PREEMPT_RT 111 #define pcpu_task_pin() preempt_disable() 112 #define pcpu_task_unpin() preempt_enable() 113 #else 114 #define pcpu_task_pin() migrate_disable() 115 #define pcpu_task_unpin() migrate_enable() 116 #endif 117 118 /* 119 * A helper to lookup and trylock pcp with embedded spinlock. 120 * The return value should be used with the unlock helper. 121 * NULL return value means the trylock failed. 122 */ 123 #ifdef CONFIG_SMP 124 #define pcp_spin_trylock(ptr) \ 125 ({ \ 126 struct per_cpu_pages *_ret; \ 127 pcpu_task_pin(); \ 128 _ret = this_cpu_ptr(ptr); \ 129 if (!spin_trylock(&_ret->lock)) { \ 130 pcpu_task_unpin(); \ 131 _ret = NULL; \ 132 } \ 133 _ret; \ 134 }) 135 136 #define pcp_spin_unlock(ptr) \ 137 ({ \ 138 spin_unlock(&ptr->lock); \ 139 pcpu_task_unpin(); \ 140 }) 141 142 /* 143 * On CONFIG_SMP=n the UP implementation of spin_trylock() never fails and thus 144 * is not compatible with our locking scheme. However we do not need pcp for 145 * scalability in the first place, so just make all the trylocks fail and take 146 * the slow path unconditionally. 147 */ 148 #else 149 #define pcp_spin_trylock(ptr) \ 150 NULL 151 152 #define pcp_spin_unlock(ptr) \ 153 BUG_ON(1) 154 #endif 155 156 /* 157 * In some cases we do not need to pin the task to the CPU because we are 158 * already given a specific cpu's pcp pointer. 159 */ 160 #define pcp_spin_lock_nopin(ptr) \ 161 spin_lock(&(ptr)->lock) 162 #define pcp_spin_unlock_nopin(ptr) \ 163 spin_unlock(&(ptr)->lock) 164 165 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID 166 DEFINE_PER_CPU(int, numa_node); 167 EXPORT_PER_CPU_SYMBOL(numa_node); 168 #endif 169 170 #ifdef CONFIG_NUMA 171 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key); 172 #endif 173 174 #ifdef CONFIG_HAVE_MEMORYLESS_NODES 175 /* 176 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly. 177 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined. 178 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem() 179 * defined in <linux/topology.h>. 180 */ 181 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */ 182 EXPORT_PER_CPU_SYMBOL(_numa_mem_); 183 #endif 184 185 static DEFINE_MUTEX(pcpu_drain_mutex); 186 187 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY 188 volatile unsigned long latent_entropy __latent_entropy; 189 EXPORT_SYMBOL(latent_entropy); 190 #endif 191 192 /* 193 * Array of node states. 194 */ 195 nodemask_t node_states[NR_NODE_STATES] __read_mostly = { 196 [N_POSSIBLE] = NODE_MASK_ALL, 197 [N_ONLINE] = { { [0] = 1UL } }, 198 #ifndef CONFIG_NUMA 199 [N_NORMAL_MEMORY] = { { [0] = 1UL } }, 200 #ifdef CONFIG_HIGHMEM 201 [N_HIGH_MEMORY] = { { [0] = 1UL } }, 202 #endif 203 [N_MEMORY] = { { [0] = 1UL } }, 204 [N_CPU] = { { [0] = 1UL } }, 205 #endif /* NUMA */ 206 }; 207 EXPORT_SYMBOL(node_states); 208 209 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK; 210 211 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE 212 unsigned int pageblock_order __read_mostly; 213 #endif 214 215 static void __free_pages_ok(struct page *page, unsigned int order, 216 fpi_t fpi_flags); 217 static void reserve_highatomic_pageblock(struct page *page, int order, 218 struct zone *zone); 219 220 /* 221 * results with 256, 32 in the lowmem_reserve sysctl: 222 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high) 223 * 1G machine -> (16M dma, 784M normal, 224M high) 224 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA 225 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL 226 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA 227 * 228 * TBD: should special case ZONE_DMA32 machines here - in those we normally 229 * don't need any ZONE_NORMAL reservation 230 */ 231 static int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = { 232 #ifdef CONFIG_ZONE_DMA 233 [ZONE_DMA] = 256, 234 #endif 235 #ifdef CONFIG_ZONE_DMA32 236 [ZONE_DMA32] = 256, 237 #endif 238 [ZONE_NORMAL] = 32, 239 #ifdef CONFIG_HIGHMEM 240 [ZONE_HIGHMEM] = 0, 241 #endif 242 [ZONE_MOVABLE] = 0, 243 }; 244 245 char * const zone_names[MAX_NR_ZONES] = { 246 #ifdef CONFIG_ZONE_DMA 247 "DMA", 248 #endif 249 #ifdef CONFIG_ZONE_DMA32 250 "DMA32", 251 #endif 252 "Normal", 253 #ifdef CONFIG_HIGHMEM 254 "HighMem", 255 #endif 256 "Movable", 257 #ifdef CONFIG_ZONE_DEVICE 258 "Device", 259 #endif 260 }; 261 262 const char * const migratetype_names[MIGRATE_TYPES] = { 263 "Unmovable", 264 "Movable", 265 "Reclaimable", 266 "HighAtomic", 267 #ifdef CONFIG_CMA 268 "CMA", 269 #endif 270 #ifdef CONFIG_MEMORY_ISOLATION 271 "Isolate", 272 #endif 273 }; 274 275 int min_free_kbytes = 1024; 276 int user_min_free_kbytes = -1; 277 static int watermark_boost_factor __read_mostly = 15000; 278 static int watermark_scale_factor = 10; 279 int defrag_mode; 280 281 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */ 282 int movable_zone; 283 EXPORT_SYMBOL(movable_zone); 284 285 #if MAX_NUMNODES > 1 286 unsigned int nr_node_ids __read_mostly = MAX_NUMNODES; 287 unsigned int nr_online_nodes __read_mostly = 1; 288 EXPORT_SYMBOL(nr_node_ids); 289 EXPORT_SYMBOL(nr_online_nodes); 290 #endif 291 292 /* 293 * When page allocations stall for longer than a threshold, 294 * ALLOC_STALL_WARN_MSECS, leave a warning in the kernel log. Only one warning 295 * will be printed during this duration for the entire system. 296 */ 297 #define ALLOC_STALL_WARN_MSECS (10 * 1000UL) 298 static unsigned long alloc_stall_warn_jiffies = INITIAL_JIFFIES; 299 300 static bool page_contains_unaccepted(struct page *page, unsigned int order); 301 static bool cond_accept_memory(struct zone *zone, unsigned int order, 302 int alloc_flags); 303 static bool __free_unaccepted(struct page *page); 304 305 int page_group_by_mobility_disabled __read_mostly; 306 307 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 308 /* 309 * During boot we initialize deferred pages on-demand, as needed, but once 310 * page_alloc_init_late() has finished, the deferred pages are all initialized, 311 * and we can permanently disable that path. 312 */ 313 DEFINE_STATIC_KEY_TRUE(deferred_pages); 314 315 /* 316 * deferred_grow_zone() is __init, but it is called from 317 * get_page_from_freelist() during early boot until deferred_pages permanently 318 * disables this call. This is why we have refdata wrapper to avoid warning, 319 * and to ensure that the function body gets unloaded. 320 */ 321 static bool __ref 322 _deferred_grow_zone(struct zone *zone, unsigned int order) 323 { 324 return deferred_grow_zone(zone, order); 325 } 326 #else 327 static inline bool _deferred_grow_zone(struct zone *zone, unsigned int order) 328 { 329 return false; 330 } 331 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */ 332 333 /* Return a pointer to the bitmap storing bits affecting a block of pages */ 334 static inline unsigned long *get_pageblock_bitmap(const struct page *page, 335 unsigned long pfn) 336 { 337 #ifdef CONFIG_SPARSEMEM 338 return section_to_usemap(__pfn_to_section(pfn)); 339 #else 340 return page_zone(page)->pageblock_flags; 341 #endif /* CONFIG_SPARSEMEM */ 342 } 343 344 static inline int pfn_to_bitidx(const struct page *page, unsigned long pfn) 345 { 346 #ifdef CONFIG_SPARSEMEM 347 pfn &= (PAGES_PER_SECTION-1); 348 #else 349 pfn = pfn - pageblock_start_pfn(page_zone(page)->zone_start_pfn); 350 #endif /* CONFIG_SPARSEMEM */ 351 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS; 352 } 353 354 static __always_inline bool is_standalone_pb_bit(enum pageblock_bits pb_bit) 355 { 356 return pb_bit >= PB_compact_skip && pb_bit < __NR_PAGEBLOCK_BITS; 357 } 358 359 static __always_inline void 360 get_pfnblock_bitmap_bitidx(const struct page *page, unsigned long pfn, 361 unsigned long **bitmap_word, unsigned long *bitidx) 362 { 363 unsigned long *bitmap; 364 unsigned long word_bitidx; 365 366 #ifdef CONFIG_MEMORY_ISOLATION 367 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 8); 368 #else 369 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4); 370 #endif 371 BUILD_BUG_ON(__MIGRATE_TYPE_END > PAGEBLOCK_MIGRATETYPE_MASK); 372 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page); 373 374 bitmap = get_pageblock_bitmap(page, pfn); 375 *bitidx = pfn_to_bitidx(page, pfn); 376 word_bitidx = *bitidx / BITS_PER_LONG; 377 *bitidx &= (BITS_PER_LONG - 1); 378 *bitmap_word = &bitmap[word_bitidx]; 379 } 380 381 382 /** 383 * __get_pfnblock_flags_mask - Return the requested group of flags for 384 * a pageblock_nr_pages block of pages 385 * @page: The page within the block of interest 386 * @pfn: The target page frame number 387 * @mask: mask of bits that the caller is interested in 388 * 389 * Return: pageblock_bits flags 390 */ 391 static unsigned long __get_pfnblock_flags_mask(const struct page *page, 392 unsigned long pfn, 393 unsigned long mask) 394 { 395 unsigned long *bitmap_word; 396 unsigned long bitidx; 397 unsigned long word; 398 399 get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx); 400 /* 401 * This races, without locks, with set_pfnblock_migratetype(). Ensure 402 * a consistent read of the memory array, so that results, even though 403 * racy, are not corrupted. 404 */ 405 word = READ_ONCE(*bitmap_word); 406 return (word >> bitidx) & mask; 407 } 408 409 /** 410 * get_pfnblock_bit - Check if a standalone bit of a pageblock is set 411 * @page: The page within the block of interest 412 * @pfn: The target page frame number 413 * @pb_bit: pageblock bit to check 414 * 415 * Return: true if the bit is set, otherwise false 416 */ 417 bool get_pfnblock_bit(const struct page *page, unsigned long pfn, 418 enum pageblock_bits pb_bit) 419 { 420 unsigned long *bitmap_word; 421 unsigned long bitidx; 422 423 if (WARN_ON_ONCE(!is_standalone_pb_bit(pb_bit))) 424 return false; 425 426 get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx); 427 428 return test_bit(bitidx + pb_bit, bitmap_word); 429 } 430 431 /** 432 * get_pfnblock_migratetype - Return the migratetype of a pageblock 433 * @page: The page within the block of interest 434 * @pfn: The target page frame number 435 * 436 * Return: The migratetype of the pageblock 437 * 438 * Use get_pfnblock_migratetype() if caller already has both @page and @pfn 439 * to save a call to page_to_pfn(). 440 */ 441 enum migratetype 442 get_pfnblock_migratetype(const struct page *page, unsigned long pfn) 443 { 444 unsigned long mask = PAGEBLOCK_MIGRATETYPE_MASK | PAGEBLOCK_ISO_MASK; 445 unsigned long flags; 446 447 flags = __get_pfnblock_flags_mask(page, pfn, mask); 448 449 #ifdef CONFIG_MEMORY_ISOLATION 450 if (flags & BIT(PB_migrate_isolate)) 451 return MIGRATE_ISOLATE; 452 #endif 453 return flags & PAGEBLOCK_MIGRATETYPE_MASK; 454 } 455 456 /** 457 * __set_pfnblock_flags_mask - Set the requested group of flags for 458 * a pageblock_nr_pages block of pages 459 * @page: The page within the block of interest 460 * @pfn: The target page frame number 461 * @flags: The flags to set 462 * @mask: mask of bits that the caller is interested in 463 */ 464 static void __set_pfnblock_flags_mask(struct page *page, unsigned long pfn, 465 unsigned long flags, unsigned long mask) 466 { 467 unsigned long *bitmap_word; 468 unsigned long bitidx; 469 unsigned long word; 470 471 get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx); 472 473 mask <<= bitidx; 474 flags <<= bitidx; 475 476 word = READ_ONCE(*bitmap_word); 477 do { 478 } while (!try_cmpxchg(bitmap_word, &word, (word & ~mask) | flags)); 479 } 480 481 /** 482 * set_pfnblock_bit - Set a standalone bit of a pageblock 483 * @page: The page within the block of interest 484 * @pfn: The target page frame number 485 * @pb_bit: pageblock bit to set 486 */ 487 void set_pfnblock_bit(const struct page *page, unsigned long pfn, 488 enum pageblock_bits pb_bit) 489 { 490 unsigned long *bitmap_word; 491 unsigned long bitidx; 492 493 if (WARN_ON_ONCE(!is_standalone_pb_bit(pb_bit))) 494 return; 495 496 get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx); 497 498 set_bit(bitidx + pb_bit, bitmap_word); 499 } 500 501 /** 502 * clear_pfnblock_bit - Clear a standalone bit of a pageblock 503 * @page: The page within the block of interest 504 * @pfn: The target page frame number 505 * @pb_bit: pageblock bit to clear 506 */ 507 void clear_pfnblock_bit(const struct page *page, unsigned long pfn, 508 enum pageblock_bits pb_bit) 509 { 510 unsigned long *bitmap_word; 511 unsigned long bitidx; 512 513 if (WARN_ON_ONCE(!is_standalone_pb_bit(pb_bit))) 514 return; 515 516 get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx); 517 518 clear_bit(bitidx + pb_bit, bitmap_word); 519 } 520 521 /** 522 * set_pageblock_migratetype - Set the migratetype of a pageblock 523 * @page: The page within the block of interest 524 * @migratetype: migratetype to set 525 */ 526 static void set_pageblock_migratetype(struct page *page, 527 enum migratetype migratetype) 528 { 529 if (unlikely(page_group_by_mobility_disabled && 530 migratetype < MIGRATE_PCPTYPES)) 531 migratetype = MIGRATE_UNMOVABLE; 532 533 #ifdef CONFIG_MEMORY_ISOLATION 534 if (migratetype == MIGRATE_ISOLATE) { 535 VM_WARN_ONCE(1, 536 "Use set_pageblock_isolate() for pageblock isolation"); 537 return; 538 } 539 VM_WARN_ONCE(get_pageblock_isolate(page), 540 "Use clear_pageblock_isolate() to unisolate pageblock"); 541 /* PAGEBLOCK_ISO_MASK clears PB_migrate_isolate if it is set */ 542 #endif 543 __set_pfnblock_flags_mask(page, page_to_pfn(page), 544 (unsigned long)migratetype, 545 PAGEBLOCK_MIGRATETYPE_MASK | PAGEBLOCK_ISO_MASK); 546 } 547 548 void __meminit init_pageblock_migratetype(struct page *page, 549 enum migratetype migratetype, 550 bool isolate) 551 { 552 unsigned long flags; 553 554 if (unlikely(page_group_by_mobility_disabled && 555 migratetype < MIGRATE_PCPTYPES)) 556 migratetype = MIGRATE_UNMOVABLE; 557 558 flags = migratetype; 559 560 #ifdef CONFIG_MEMORY_ISOLATION 561 if (migratetype == MIGRATE_ISOLATE) { 562 VM_WARN_ONCE( 563 1, 564 "Set isolate=true to isolate pageblock with a migratetype"); 565 return; 566 } 567 if (isolate) 568 flags |= BIT(PB_migrate_isolate); 569 #endif 570 __set_pfnblock_flags_mask(page, page_to_pfn(page), flags, 571 PAGEBLOCK_MIGRATETYPE_MASK | PAGEBLOCK_ISO_MASK); 572 } 573 574 #ifdef CONFIG_DEBUG_VM 575 static int page_outside_zone_boundaries(struct zone *zone, struct page *page) 576 { 577 int ret; 578 unsigned seq; 579 unsigned long pfn = page_to_pfn(page); 580 unsigned long sp, start_pfn; 581 582 do { 583 seq = zone_span_seqbegin(zone); 584 start_pfn = zone->zone_start_pfn; 585 sp = zone->spanned_pages; 586 ret = !zone_spans_pfn(zone, pfn); 587 } while (zone_span_seqretry(zone, seq)); 588 589 if (ret) 590 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n", 591 pfn, zone_to_nid(zone), zone->name, 592 start_pfn, start_pfn + sp); 593 594 return ret; 595 } 596 597 /* 598 * Temporary debugging check for pages not lying within a given zone. 599 */ 600 static bool __maybe_unused bad_range(struct zone *zone, struct page *page) 601 { 602 if (page_outside_zone_boundaries(zone, page)) 603 return true; 604 if (zone != page_zone(page)) 605 return true; 606 607 return false; 608 } 609 #else 610 static inline bool __maybe_unused bad_range(struct zone *zone, struct page *page) 611 { 612 return false; 613 } 614 #endif 615 616 static void bad_page(struct page *page, const char *reason) 617 { 618 static unsigned long resume; 619 static unsigned long nr_shown; 620 static unsigned long nr_unshown; 621 622 /* 623 * Allow a burst of 60 reports, then keep quiet for that minute; 624 * or allow a steady drip of one report per second. 625 */ 626 if (nr_shown == 60) { 627 if (time_before(jiffies, resume)) { 628 nr_unshown++; 629 goto out; 630 } 631 if (nr_unshown) { 632 pr_alert( 633 "BUG: Bad page state: %lu messages suppressed\n", 634 nr_unshown); 635 nr_unshown = 0; 636 } 637 nr_shown = 0; 638 } 639 if (nr_shown++ == 0) 640 resume = jiffies + 60 * HZ; 641 642 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n", 643 current->comm, page_to_pfn(page)); 644 dump_page(page, reason); 645 646 print_modules(); 647 dump_stack(); 648 out: 649 /* Leave bad fields for debug, except PageBuddy could make trouble */ 650 if (PageBuddy(page)) 651 __ClearPageBuddy(page); 652 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); 653 } 654 655 static inline unsigned int order_to_pindex(int migratetype, int order) 656 { 657 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) { 658 bool movable = migratetype == MIGRATE_MOVABLE; 659 660 if (order > PAGE_ALLOC_COSTLY_ORDER) 661 return NR_LOWORDER_PCP_LISTS + movable; 662 } 663 664 return (MIGRATE_PCPTYPES * order) + migratetype; 665 } 666 667 static inline int pindex_to_order(unsigned int pindex) 668 { 669 int order = pindex / MIGRATE_PCPTYPES; 670 671 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) { 672 if (pindex >= NR_LOWORDER_PCP_LISTS) 673 order = HPAGE_PMD_ORDER; 674 } 675 676 return order; 677 } 678 679 static inline bool pcp_allowed_order(unsigned int order) 680 { 681 if (order <= PAGE_ALLOC_COSTLY_ORDER) 682 return true; 683 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 684 if (is_pmd_order(order)) 685 return true; 686 #endif 687 return false; 688 } 689 690 /* 691 * Higher-order pages are called "compound pages". They are structured thusly: 692 * 693 * The first PAGE_SIZE page is called the "head page" and have PG_head set. 694 * 695 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded 696 * in bit 0 of page->compound_info. The rest of bits is pointer to head page. 697 * 698 * The first tail page's ->compound_order holds the order of allocation. 699 * This usage means that zero-order pages may not be compound. 700 */ 701 702 void prep_compound_page(struct page *page, unsigned int order) 703 { 704 int i; 705 int nr_pages = 1 << order; 706 707 __SetPageHead(page); 708 for (i = 1; i < nr_pages; i++) 709 prep_compound_tail(page + i, page, order); 710 711 prep_compound_head(page, order); 712 } 713 714 static inline void set_buddy_order(struct page *page, unsigned int order) 715 { 716 set_page_private(page, order); 717 __SetPageBuddy(page); 718 } 719 720 #ifdef CONFIG_COMPACTION 721 static inline struct capture_control *task_capc(struct zone *zone) 722 { 723 struct capture_control *capc = current->capture_control; 724 725 return unlikely(capc) && 726 !(current->flags & PF_KTHREAD) && 727 !capc->page && 728 capc->zone == zone ? capc : NULL; 729 } 730 731 static inline bool 732 compaction_capture(struct capture_control *capc, struct page *page, 733 int order, int migratetype) 734 { 735 if (!capc || order != capc->order) 736 return false; 737 738 /* Do not accidentally pollute CMA or isolated regions*/ 739 if (is_migrate_cma(migratetype) || 740 is_migrate_isolate(migratetype)) 741 return false; 742 743 /* 744 * Do not let lower order allocations pollute a movable pageblock 745 * unless compaction is also requesting movable pages. 746 * This might let an unmovable request use a reclaimable pageblock 747 * and vice-versa but no more than normal fallback logic which can 748 * have trouble finding a high-order free page. 749 */ 750 if (order < pageblock_order && migratetype == MIGRATE_MOVABLE && 751 capc->migratetype != MIGRATE_MOVABLE) 752 return false; 753 754 if (migratetype != capc->migratetype) 755 trace_mm_page_alloc_extfrag(page, capc->order, order, 756 capc->migratetype, migratetype); 757 758 capc->page = page; 759 return true; 760 } 761 762 #else 763 static inline struct capture_control *task_capc(struct zone *zone) 764 { 765 return NULL; 766 } 767 768 static inline bool 769 compaction_capture(struct capture_control *capc, struct page *page, 770 int order, int migratetype) 771 { 772 return false; 773 } 774 #endif /* CONFIG_COMPACTION */ 775 776 static inline void account_freepages(struct zone *zone, int nr_pages, 777 int migratetype) 778 { 779 lockdep_assert_held(&zone->lock); 780 781 if (is_migrate_isolate(migratetype)) 782 return; 783 784 __mod_zone_page_state(zone, NR_FREE_PAGES, nr_pages); 785 786 if (is_migrate_cma(migratetype)) 787 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES, nr_pages); 788 else if (migratetype == MIGRATE_HIGHATOMIC) 789 WRITE_ONCE(zone->nr_free_highatomic, 790 zone->nr_free_highatomic + nr_pages); 791 } 792 793 /* Used for pages not on another list */ 794 static inline void __add_to_free_list(struct page *page, struct zone *zone, 795 unsigned int order, int migratetype, 796 bool tail) 797 { 798 struct free_area *area = &zone->free_area[order]; 799 int nr_pages = 1 << order; 800 801 VM_WARN_ONCE(get_pageblock_migratetype(page) != migratetype, 802 "page type is %d, passed migratetype is %d (nr=%d)\n", 803 get_pageblock_migratetype(page), migratetype, nr_pages); 804 805 if (tail) 806 list_add_tail(&page->buddy_list, &area->free_list[migratetype]); 807 else 808 list_add(&page->buddy_list, &area->free_list[migratetype]); 809 area->nr_free++; 810 811 if (order >= pageblock_order && !is_migrate_isolate(migratetype)) 812 __mod_zone_page_state(zone, NR_FREE_PAGES_BLOCKS, nr_pages); 813 } 814 815 /* 816 * Used for pages which are on another list. Move the pages to the tail 817 * of the list - so the moved pages won't immediately be considered for 818 * allocation again (e.g., optimization for memory onlining). 819 */ 820 static inline void move_to_free_list(struct page *page, struct zone *zone, 821 unsigned int order, int old_mt, int new_mt) 822 { 823 struct free_area *area = &zone->free_area[order]; 824 int nr_pages = 1 << order; 825 826 /* Free page moving can fail, so it happens before the type update */ 827 VM_WARN_ONCE(get_pageblock_migratetype(page) != old_mt, 828 "page type is %d, passed migratetype is %d (nr=%d)\n", 829 get_pageblock_migratetype(page), old_mt, nr_pages); 830 831 list_move_tail(&page->buddy_list, &area->free_list[new_mt]); 832 833 account_freepages(zone, -nr_pages, old_mt); 834 account_freepages(zone, nr_pages, new_mt); 835 836 if (order >= pageblock_order && 837 is_migrate_isolate(old_mt) != is_migrate_isolate(new_mt)) { 838 if (!is_migrate_isolate(old_mt)) 839 nr_pages = -nr_pages; 840 __mod_zone_page_state(zone, NR_FREE_PAGES_BLOCKS, nr_pages); 841 } 842 } 843 844 static inline void __del_page_from_free_list(struct page *page, struct zone *zone, 845 unsigned int order, int migratetype) 846 { 847 int nr_pages = 1 << order; 848 849 VM_WARN_ONCE(get_pageblock_migratetype(page) != migratetype, 850 "page type is %d, passed migratetype is %d (nr=%d)\n", 851 get_pageblock_migratetype(page), migratetype, nr_pages); 852 853 /* clear reported state and update reported page count */ 854 if (page_reported(page)) 855 __ClearPageReported(page); 856 857 list_del(&page->buddy_list); 858 __ClearPageBuddy(page); 859 set_page_private(page, 0); 860 zone->free_area[order].nr_free--; 861 862 if (order >= pageblock_order && !is_migrate_isolate(migratetype)) 863 __mod_zone_page_state(zone, NR_FREE_PAGES_BLOCKS, -nr_pages); 864 } 865 866 static inline void del_page_from_free_list(struct page *page, struct zone *zone, 867 unsigned int order, int migratetype) 868 { 869 __del_page_from_free_list(page, zone, order, migratetype); 870 account_freepages(zone, -(1 << order), migratetype); 871 } 872 873 static inline struct page *get_page_from_free_area(struct free_area *area, 874 int migratetype) 875 { 876 return list_first_entry_or_null(&area->free_list[migratetype], 877 struct page, buddy_list); 878 } 879 880 /* 881 * If this is less than the 2nd largest possible page, check if the buddy 882 * of the next-higher order is free. If it is, it's possible 883 * that pages are being freed that will coalesce soon. In case, 884 * that is happening, add the free page to the tail of the list 885 * so it's less likely to be used soon and more likely to be merged 886 * as a 2-level higher order page 887 */ 888 static inline bool 889 buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn, 890 struct page *page, unsigned int order) 891 { 892 unsigned long higher_page_pfn; 893 struct page *higher_page; 894 895 if (order >= MAX_PAGE_ORDER - 1) 896 return false; 897 898 higher_page_pfn = buddy_pfn & pfn; 899 higher_page = page + (higher_page_pfn - pfn); 900 901 return find_buddy_page_pfn(higher_page, higher_page_pfn, order + 1, 902 NULL) != NULL; 903 } 904 905 static void change_pageblock_range(struct page *pageblock_page, 906 int start_order, int migratetype) 907 { 908 int nr_pageblocks = 1 << (start_order - pageblock_order); 909 910 while (nr_pageblocks--) { 911 set_pageblock_migratetype(pageblock_page, migratetype); 912 pageblock_page += pageblock_nr_pages; 913 } 914 } 915 916 /* 917 * Freeing function for a buddy system allocator. 918 * 919 * The concept of a buddy system is to maintain direct-mapped table 920 * (containing bit values) for memory blocks of various "orders". 921 * The bottom level table contains the map for the smallest allocatable 922 * units of memory (here, pages), and each level above it describes 923 * pairs of units from the levels below, hence, "buddies". 924 * At a high level, all that happens here is marking the table entry 925 * at the bottom level available, and propagating the changes upward 926 * as necessary, plus some accounting needed to play nicely with other 927 * parts of the VM system. 928 * At each level, we keep a list of pages, which are heads of continuous 929 * free pages of length of (1 << order) and marked with PageBuddy. 930 * Page's order is recorded in page_private(page) field. 931 * So when we are allocating or freeing one, we can derive the state of the 932 * other. That is, if we allocate a small block, and both were 933 * free, the remainder of the region must be split into blocks. 934 * If a block is freed, and its buddy is also free, then this 935 * triggers coalescing into a block of larger size. 936 * 937 * -- nyc 938 */ 939 940 static inline void __free_one_page(struct page *page, 941 unsigned long pfn, 942 struct zone *zone, unsigned int order, 943 int migratetype, fpi_t fpi_flags) 944 { 945 struct capture_control *capc = task_capc(zone); 946 unsigned long buddy_pfn = 0; 947 unsigned long combined_pfn; 948 struct page *buddy; 949 bool to_tail; 950 951 VM_BUG_ON(!zone_is_initialized(zone)); 952 VM_BUG_ON_PAGE(page->flags.f & PAGE_FLAGS_CHECK_AT_PREP, page); 953 954 VM_BUG_ON(migratetype == -1); 955 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page); 956 VM_BUG_ON_PAGE(bad_range(zone, page), page); 957 958 account_freepages(zone, 1 << order, migratetype); 959 960 while (order < MAX_PAGE_ORDER) { 961 int buddy_mt = migratetype; 962 963 if (compaction_capture(capc, page, order, migratetype)) { 964 account_freepages(zone, -(1 << order), migratetype); 965 return; 966 } 967 968 buddy = find_buddy_page_pfn(page, pfn, order, &buddy_pfn); 969 if (!buddy) 970 goto done_merging; 971 972 if (unlikely(order >= pageblock_order)) { 973 /* 974 * We want to prevent merge between freepages on pageblock 975 * without fallbacks and normal pageblock. Without this, 976 * pageblock isolation could cause incorrect freepage or CMA 977 * accounting or HIGHATOMIC accounting. 978 */ 979 buddy_mt = get_pfnblock_migratetype(buddy, buddy_pfn); 980 981 if (migratetype != buddy_mt && 982 (!migratetype_is_mergeable(migratetype) || 983 !migratetype_is_mergeable(buddy_mt))) 984 goto done_merging; 985 } 986 987 /* 988 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page, 989 * merge with it and move up one order. 990 */ 991 if (page_is_guard(buddy)) 992 clear_page_guard(zone, buddy, order); 993 else 994 __del_page_from_free_list(buddy, zone, order, buddy_mt); 995 996 if (unlikely(buddy_mt != migratetype)) { 997 /* 998 * Match buddy type. This ensures that an 999 * expand() down the line puts the sub-blocks 1000 * on the right freelists. 1001 */ 1002 change_pageblock_range(buddy, order, migratetype); 1003 } 1004 1005 combined_pfn = buddy_pfn & pfn; 1006 page = page + (combined_pfn - pfn); 1007 pfn = combined_pfn; 1008 order++; 1009 } 1010 1011 done_merging: 1012 set_buddy_order(page, order); 1013 1014 if (fpi_flags & FPI_TO_TAIL) 1015 to_tail = true; 1016 else if (is_shuffle_order(order)) 1017 to_tail = shuffle_pick_tail(); 1018 else 1019 to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order); 1020 1021 __add_to_free_list(page, zone, order, migratetype, to_tail); 1022 1023 /* Notify page reporting subsystem of freed page */ 1024 if (!(fpi_flags & FPI_SKIP_REPORT_NOTIFY)) 1025 page_reporting_notify_free(order); 1026 } 1027 1028 /* 1029 * A bad page could be due to a number of fields. Instead of multiple branches, 1030 * try and check multiple fields with one check. The caller must do a detailed 1031 * check if necessary. 1032 */ 1033 static inline bool page_expected_state(struct page *page, 1034 unsigned long check_flags) 1035 { 1036 if (unlikely(atomic_read(&page->_mapcount) != -1)) 1037 return false; 1038 1039 if (unlikely((unsigned long)page->mapping | 1040 page_ref_count(page) | 1041 #ifdef CONFIG_MEMCG 1042 page->memcg_data | 1043 #endif 1044 page_pool_page_is_pp(page) | 1045 (page->flags.f & check_flags))) 1046 return false; 1047 1048 return true; 1049 } 1050 1051 static const char *page_bad_reason(struct page *page, unsigned long flags) 1052 { 1053 const char *bad_reason = NULL; 1054 1055 if (unlikely(atomic_read(&page->_mapcount) != -1)) 1056 bad_reason = "nonzero mapcount"; 1057 if (unlikely(page->mapping != NULL)) 1058 bad_reason = "non-NULL mapping"; 1059 if (unlikely(page_ref_count(page) != 0)) 1060 bad_reason = "nonzero _refcount"; 1061 if (unlikely(page->flags.f & flags)) { 1062 if (flags == PAGE_FLAGS_CHECK_AT_PREP) 1063 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag(s) set"; 1064 else 1065 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set"; 1066 } 1067 #ifdef CONFIG_MEMCG 1068 if (unlikely(page->memcg_data)) 1069 bad_reason = "page still charged to cgroup"; 1070 #endif 1071 if (unlikely(page_pool_page_is_pp(page))) 1072 bad_reason = "page_pool leak"; 1073 return bad_reason; 1074 } 1075 1076 static inline bool free_page_is_bad(struct page *page) 1077 { 1078 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE))) 1079 return false; 1080 1081 /* Something has gone sideways, find it */ 1082 bad_page(page, page_bad_reason(page, PAGE_FLAGS_CHECK_AT_FREE)); 1083 return true; 1084 } 1085 1086 static inline bool is_check_pages_enabled(void) 1087 { 1088 return static_branch_unlikely(&check_pages_enabled); 1089 } 1090 1091 static int free_tail_page_prepare(struct page *head_page, struct page *page) 1092 { 1093 struct folio *folio = (struct folio *)head_page; 1094 int ret = 1; 1095 1096 /* 1097 * We rely page->lru.next never has bit 0 set, unless the page 1098 * is PageTail(). Let's make sure that's true even for poisoned ->lru. 1099 */ 1100 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1); 1101 1102 if (!is_check_pages_enabled()) { 1103 ret = 0; 1104 goto out; 1105 } 1106 switch (page - head_page) { 1107 case 1: 1108 /* the first tail page: these may be in place of ->mapping */ 1109 if (unlikely(folio_large_mapcount(folio))) { 1110 bad_page(page, "nonzero large_mapcount"); 1111 goto out; 1112 } 1113 if (IS_ENABLED(CONFIG_PAGE_MAPCOUNT) && 1114 unlikely(atomic_read(&folio->_nr_pages_mapped))) { 1115 bad_page(page, "nonzero nr_pages_mapped"); 1116 goto out; 1117 } 1118 if (IS_ENABLED(CONFIG_MM_ID)) { 1119 if (unlikely(folio->_mm_id_mapcount[0] != -1)) { 1120 bad_page(page, "nonzero mm mapcount 0"); 1121 goto out; 1122 } 1123 if (unlikely(folio->_mm_id_mapcount[1] != -1)) { 1124 bad_page(page, "nonzero mm mapcount 1"); 1125 goto out; 1126 } 1127 } 1128 if (IS_ENABLED(CONFIG_64BIT)) { 1129 if (unlikely(atomic_read(&folio->_entire_mapcount) + 1)) { 1130 bad_page(page, "nonzero entire_mapcount"); 1131 goto out; 1132 } 1133 if (unlikely(atomic_read(&folio->_pincount))) { 1134 bad_page(page, "nonzero pincount"); 1135 goto out; 1136 } 1137 } 1138 break; 1139 case 2: 1140 /* the second tail page: deferred_list overlaps ->mapping */ 1141 if (unlikely(!list_empty(&folio->_deferred_list))) { 1142 bad_page(page, "on deferred list"); 1143 goto out; 1144 } 1145 if (!IS_ENABLED(CONFIG_64BIT)) { 1146 if (unlikely(atomic_read(&folio->_entire_mapcount) + 1)) { 1147 bad_page(page, "nonzero entire_mapcount"); 1148 goto out; 1149 } 1150 if (unlikely(atomic_read(&folio->_pincount))) { 1151 bad_page(page, "nonzero pincount"); 1152 goto out; 1153 } 1154 } 1155 break; 1156 case 3: 1157 /* the third tail page: hugetlb specifics overlap ->mappings */ 1158 if (IS_ENABLED(CONFIG_HUGETLB_PAGE)) 1159 break; 1160 fallthrough; 1161 default: 1162 if (page->mapping != TAIL_MAPPING) { 1163 bad_page(page, "corrupted mapping in tail page"); 1164 goto out; 1165 } 1166 break; 1167 } 1168 if (unlikely(!PageTail(page))) { 1169 bad_page(page, "PageTail not set"); 1170 goto out; 1171 } 1172 if (unlikely(compound_head(page) != head_page)) { 1173 bad_page(page, "compound_head not consistent"); 1174 goto out; 1175 } 1176 ret = 0; 1177 out: 1178 page->mapping = NULL; 1179 clear_compound_head(page); 1180 return ret; 1181 } 1182 1183 /* 1184 * Skip KASAN memory poisoning when either: 1185 * 1186 * 1. For generic KASAN: deferred memory initialization has not yet completed. 1187 * Tag-based KASAN modes skip pages freed via deferred memory initialization 1188 * using page tags instead (see below). 1189 * 2. For tag-based KASAN modes: the page has a match-all KASAN tag, indicating 1190 * that error detection is disabled for accesses via the page address. 1191 * 1192 * Pages will have match-all tags in the following circumstances: 1193 * 1194 * 1. Pages are being initialized for the first time, including during deferred 1195 * memory init; see the call to page_kasan_tag_reset in __init_single_page. 1196 * 2. The allocation was not unpoisoned due to __GFP_SKIP_KASAN, with the 1197 * exception of pages unpoisoned by kasan_unpoison_vmalloc. 1198 * 3. The allocation was excluded from being checked due to sampling, 1199 * see the call to kasan_unpoison_pages. 1200 * 1201 * Poisoning pages during deferred memory init will greatly lengthen the 1202 * process and cause problem in large memory systems as the deferred pages 1203 * initialization is done with interrupt disabled. 1204 * 1205 * Assuming that there will be no reference to those newly initialized 1206 * pages before they are ever allocated, this should have no effect on 1207 * KASAN memory tracking as the poison will be properly inserted at page 1208 * allocation time. The only corner case is when pages are allocated by 1209 * on-demand allocation and then freed again before the deferred pages 1210 * initialization is done, but this is not likely to happen. 1211 */ 1212 static inline bool should_skip_kasan_poison(struct page *page) 1213 { 1214 if (IS_ENABLED(CONFIG_KASAN_GENERIC)) 1215 return deferred_pages_enabled(); 1216 1217 return page_kasan_tag(page) == KASAN_TAG_KERNEL; 1218 } 1219 1220 static void clear_highpages_kasan_tagged(struct page *page, int numpages) 1221 { 1222 /* s390's use of memset() could override KASAN redzones. */ 1223 kasan_disable_current(); 1224 if (!IS_ENABLED(CONFIG_HIGHMEM)) { 1225 clear_pages(kasan_reset_tag(page_address(page)), numpages); 1226 } else { 1227 int i; 1228 1229 for (i = 0; i < numpages; i++) 1230 clear_highpage_kasan_tagged(page + i); 1231 } 1232 kasan_enable_current(); 1233 } 1234 1235 #ifdef CONFIG_MEM_ALLOC_PROFILING 1236 1237 /* Should be called only if mem_alloc_profiling_enabled() */ 1238 void __clear_page_tag_ref(struct page *page) 1239 { 1240 union pgtag_ref_handle handle; 1241 union codetag_ref ref; 1242 1243 if (get_page_tag_ref(page, &ref, &handle)) { 1244 set_codetag_empty(&ref); 1245 update_page_tag_ref(handle, &ref); 1246 put_page_tag_ref(handle); 1247 } 1248 } 1249 1250 /* Should be called only if mem_alloc_profiling_enabled() */ 1251 static noinline 1252 void __pgalloc_tag_add(struct page *page, struct task_struct *task, 1253 unsigned int nr, unsigned int alloc_flags) 1254 { 1255 union pgtag_ref_handle handle; 1256 union codetag_ref ref; 1257 1258 if (likely(get_page_tag_ref(page, &ref, &handle))) { 1259 alloc_tag_add(&ref, task->alloc_tag, PAGE_SIZE * nr); 1260 update_page_tag_ref(handle, &ref); 1261 put_page_tag_ref(handle); 1262 } else { 1263 /* 1264 * page_ext is not available yet, record the pfn so we can 1265 * clear the tag ref later when page_ext is initialized. 1266 */ 1267 alloc_tag_add_early_pfn(page_to_pfn(page), alloc_flags); 1268 if (task->alloc_tag) 1269 alloc_tag_set_inaccurate(task->alloc_tag); 1270 } 1271 } 1272 1273 static inline void pgalloc_tag_add(struct page *page, struct task_struct *task, 1274 unsigned int nr, unsigned int alloc_flags) 1275 { 1276 if (mem_alloc_profiling_enabled()) 1277 __pgalloc_tag_add(page, task, nr, alloc_flags); 1278 } 1279 1280 /* Should be called only if mem_alloc_profiling_enabled() */ 1281 static noinline 1282 void __pgalloc_tag_sub(struct page *page, unsigned int nr) 1283 { 1284 union pgtag_ref_handle handle; 1285 union codetag_ref ref; 1286 1287 if (get_page_tag_ref(page, &ref, &handle)) { 1288 alloc_tag_sub(&ref, PAGE_SIZE * nr); 1289 update_page_tag_ref(handle, &ref); 1290 put_page_tag_ref(handle); 1291 } 1292 } 1293 1294 static inline void pgalloc_tag_sub(struct page *page, unsigned int nr) 1295 { 1296 if (mem_alloc_profiling_enabled()) 1297 __pgalloc_tag_sub(page, nr); 1298 } 1299 1300 /* When tag is not NULL, assuming mem_alloc_profiling_enabled */ 1301 static inline void pgalloc_tag_sub_pages(struct alloc_tag *tag, unsigned int nr) 1302 { 1303 if (tag) 1304 this_cpu_sub(tag->counters->bytes, PAGE_SIZE * nr); 1305 } 1306 1307 #else /* CONFIG_MEM_ALLOC_PROFILING */ 1308 1309 static inline void pgalloc_tag_add(struct page *page, struct task_struct *task, 1310 unsigned int nr, unsigned int alloc_flags) {} 1311 static inline void pgalloc_tag_sub(struct page *page, unsigned int nr) {} 1312 static inline void pgalloc_tag_sub_pages(struct alloc_tag *tag, unsigned int nr) {} 1313 1314 #endif /* CONFIG_MEM_ALLOC_PROFILING */ 1315 1316 static __always_inline bool __free_pages_prepare(struct page *page, 1317 unsigned int order, fpi_t fpi_flags) 1318 { 1319 int bad = 0; 1320 bool skip_kasan_poison = should_skip_kasan_poison(page); 1321 bool init = want_init_on_free(); 1322 bool compound = PageCompound(page); 1323 struct folio *folio = page_folio(page); 1324 1325 if (fpi_flags & FPI_PREPARED) 1326 return true; 1327 1328 VM_BUG_ON_PAGE(PageTail(page), page); 1329 1330 trace_mm_page_free(page, order); 1331 kmsan_free_page(page, order); 1332 1333 if (memcg_kmem_online() && PageMemcgKmem(page)) 1334 __memcg_kmem_uncharge_page(page, order); 1335 1336 /* 1337 * In rare cases, when truncation or holepunching raced with 1338 * munlock after VM_LOCKED was cleared, Mlocked may still be 1339 * found set here. This does not indicate a problem, unless 1340 * "unevictable_pgs_cleared" appears worryingly large. 1341 */ 1342 if (unlikely(folio_test_mlocked(folio))) { 1343 long nr_pages = folio_nr_pages(folio); 1344 1345 __folio_clear_mlocked(folio); 1346 zone_stat_mod_folio(folio, NR_MLOCK, -nr_pages); 1347 count_vm_events(UNEVICTABLE_PGCLEARED, nr_pages); 1348 } 1349 1350 if (unlikely(PageHWPoison(page)) && !order) { 1351 /* Do not let hwpoison pages hit pcplists/buddy */ 1352 reset_page_owner(page, order); 1353 page_table_check_free(page, order); 1354 pgalloc_tag_sub(page, 1 << order); 1355 1356 /* 1357 * The page is isolated and accounted for. 1358 * Mark the codetag as empty to avoid accounting error 1359 * when the page is freed by unpoison_memory(). 1360 */ 1361 clear_page_tag_ref(page); 1362 return false; 1363 } 1364 1365 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page); 1366 1367 /* 1368 * Check tail pages before head page information is cleared to 1369 * avoid checking PageCompound for order-0 pages. 1370 */ 1371 if (unlikely(order)) { 1372 int i; 1373 1374 if (compound) { 1375 page[1].flags.f &= ~PAGE_FLAGS_SECOND; 1376 #ifdef NR_PAGES_IN_LARGE_FOLIO 1377 folio->_nr_pages = 0; 1378 #endif 1379 } 1380 for (i = 1; i < (1 << order); i++) { 1381 struct page *tail_page = page + i; 1382 1383 if (compound) 1384 bad += free_tail_page_prepare(page, tail_page); 1385 if (is_check_pages_enabled()) { 1386 if (free_page_is_bad(tail_page)) { 1387 bad++; 1388 continue; 1389 } 1390 1391 if (tail_page->private) { 1392 bad_page(tail_page, "nonzero private"); 1393 bad++; 1394 continue; 1395 } 1396 } 1397 tail_page->flags.f &= ~PAGE_FLAGS_CHECK_AT_PREP; 1398 } 1399 } 1400 if (folio_test_anon(folio)) { 1401 mod_mthp_stat(order, MTHP_STAT_NR_ANON, -1); 1402 folio->mapping = NULL; 1403 } 1404 if (unlikely(page_has_type(page))) 1405 /* Reset the page_type (which overlays _mapcount) */ 1406 page->page_type = UINT_MAX; 1407 1408 if (is_check_pages_enabled()) { 1409 if (free_page_is_bad(page)) 1410 bad++; 1411 if (bad) 1412 return false; 1413 } 1414 1415 page_cpupid_reset_last(page); 1416 page->flags.f &= ~PAGE_FLAGS_CHECK_AT_PREP; 1417 page->private = 0; 1418 reset_page_owner(page, order); 1419 page_table_check_free(page, order); 1420 pgalloc_tag_sub(page, 1 << order); 1421 1422 if (!PageHighMem(page) && !(fpi_flags & FPI_NOLOCK)) { 1423 debug_check_no_locks_freed(page_address(page), 1424 PAGE_SIZE << order); 1425 debug_check_no_obj_freed(page_address(page), 1426 PAGE_SIZE << order); 1427 } 1428 1429 kernel_poison_pages(page, 1 << order); 1430 1431 /* 1432 * As memory initialization might be integrated into KASAN, 1433 * KASAN poisoning and memory initialization code must be 1434 * kept together to avoid discrepancies in behavior. 1435 * 1436 * With hardware tag-based KASAN, memory tags must be set before the 1437 * page becomes unavailable via debug_pagealloc or arch_free_page. 1438 */ 1439 if (!skip_kasan_poison) { 1440 kasan_poison_pages(page, order, init); 1441 1442 /* Memory is already initialized if KASAN did it internally. */ 1443 if (kasan_has_integrated_init()) 1444 init = false; 1445 } 1446 if (init) 1447 clear_highpages_kasan_tagged(page, 1 << order); 1448 1449 /* 1450 * arch_free_page() can make the page's contents inaccessible. s390 1451 * does this. So nothing which can access the page's contents should 1452 * happen after this. 1453 */ 1454 arch_free_page(page, order); 1455 1456 debug_pagealloc_unmap_pages(page, 1 << order); 1457 1458 return true; 1459 } 1460 1461 bool free_pages_prepare(struct page *page, unsigned int order) 1462 { 1463 return __free_pages_prepare(page, order, FPI_NONE); 1464 } 1465 1466 /* 1467 * Frees a number of pages from the PCP lists 1468 * Assumes all pages on list are in same zone. 1469 * count is the number of pages to free. 1470 */ 1471 static void free_pcppages_bulk(struct zone *zone, int count, 1472 struct per_cpu_pages *pcp, 1473 int pindex) 1474 { 1475 unsigned int order; 1476 struct page *page; 1477 1478 /* 1479 * Ensure proper count is passed which otherwise would stuck in the 1480 * below while (list_empty(list)) loop. 1481 */ 1482 count = min(pcp->count, count); 1483 1484 /* Ensure requested pindex is drained first. */ 1485 pindex = pindex - 1; 1486 1487 guard(spinlock_irqsave)(&zone->lock); 1488 1489 while (count > 0) { 1490 struct list_head *list; 1491 int nr_pages; 1492 1493 /* Remove pages from lists in a round-robin fashion. */ 1494 do { 1495 if (++pindex > NR_PCP_LISTS - 1) 1496 pindex = 0; 1497 list = &pcp->lists[pindex]; 1498 } while (list_empty(list)); 1499 1500 order = pindex_to_order(pindex); 1501 nr_pages = 1 << order; 1502 do { 1503 unsigned long pfn; 1504 int mt; 1505 1506 page = list_last_entry(list, struct page, pcp_list); 1507 pfn = page_to_pfn(page); 1508 mt = get_pfnblock_migratetype(page, pfn); 1509 1510 /* must delete to avoid corrupting pcp list */ 1511 list_del(&page->pcp_list); 1512 count -= nr_pages; 1513 pcp->count -= nr_pages; 1514 1515 __free_one_page(page, pfn, zone, order, mt, FPI_NONE); 1516 trace_mm_page_pcpu_drain(page, order, mt); 1517 } while (count > 0 && !list_empty(list)); 1518 } 1519 } 1520 1521 /* Split a multi-block free page into its individual pageblocks. */ 1522 static void split_large_buddy(struct zone *zone, struct page *page, 1523 unsigned long pfn, int order, fpi_t fpi) 1524 { 1525 unsigned long end = pfn + (1 << order); 1526 1527 VM_WARN_ON_ONCE(!IS_ALIGNED(pfn, 1 << order)); 1528 /* Caller removed page from freelist, buddy info cleared! */ 1529 VM_WARN_ON_ONCE(PageBuddy(page)); 1530 1531 if (order > pageblock_order) 1532 order = pageblock_order; 1533 1534 do { 1535 int mt = get_pfnblock_migratetype(page, pfn); 1536 1537 __free_one_page(page, pfn, zone, order, mt, fpi); 1538 pfn += 1 << order; 1539 if (pfn == end) 1540 break; 1541 page = pfn_to_page(pfn); 1542 } while (1); 1543 } 1544 1545 static void add_page_to_zone_llist(struct zone *zone, struct page *page, 1546 unsigned int order) 1547 { 1548 /* Remember the order */ 1549 page->private = order; 1550 /* Add the page to the free list */ 1551 llist_add(&page->pcp_llist, &zone->trylock_free_pages); 1552 } 1553 1554 static void free_one_page(struct zone *zone, struct page *page, 1555 unsigned long pfn, unsigned int order, 1556 fpi_t fpi_flags) 1557 { 1558 struct llist_head *llhead; 1559 unsigned long flags; 1560 1561 if (unlikely(fpi_flags & FPI_NOLOCK)) { 1562 if (!can_spin_trylock() || !spin_trylock_irqsave(&zone->lock, flags)) { 1563 add_page_to_zone_llist(zone, page, order); 1564 return; 1565 } 1566 } else { 1567 spin_lock_irqsave(&zone->lock, flags); 1568 } 1569 1570 /* The lock succeeded. Process deferred pages. */ 1571 llhead = &zone->trylock_free_pages; 1572 if (unlikely(!llist_empty(llhead) && !(fpi_flags & FPI_NOLOCK))) { 1573 struct llist_node *llnode; 1574 struct page *p, *tmp; 1575 1576 llnode = llist_del_all(llhead); 1577 llist_for_each_entry_safe(p, tmp, llnode, pcp_llist) { 1578 unsigned int p_order = p->private; 1579 1580 split_large_buddy(zone, p, page_to_pfn(p), p_order, fpi_flags); 1581 __count_vm_events(PGFREE, 1 << p_order); 1582 } 1583 } 1584 split_large_buddy(zone, page, pfn, order, fpi_flags); 1585 spin_unlock_irqrestore(&zone->lock, flags); 1586 1587 __count_vm_events(PGFREE, 1 << order); 1588 } 1589 1590 static void __free_pages_ok(struct page *page, unsigned int order, 1591 fpi_t fpi_flags) 1592 { 1593 unsigned long pfn = page_to_pfn(page); 1594 struct zone *zone = page_zone(page); 1595 1596 if (__free_pages_prepare(page, order, fpi_flags)) 1597 free_one_page(zone, page, pfn, order, fpi_flags); 1598 } 1599 1600 void __meminit __free_pages_core(struct page *page, unsigned int order, 1601 enum meminit_context context) 1602 { 1603 unsigned int nr_pages = 1 << order; 1604 struct page *p = page; 1605 unsigned int loop; 1606 1607 /* 1608 * When initializing the memmap, __init_single_page() sets the refcount 1609 * of all pages to 1 ("allocated"/"not free"). We have to set the 1610 * refcount of all involved pages to 0. 1611 * 1612 * Note that hotplugged memory pages are initialized to PageOffline(). 1613 * Pages freed from memblock might be marked as reserved. 1614 */ 1615 if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG) && 1616 unlikely(context == MEMINIT_HOTPLUG)) { 1617 for (loop = 0; loop < nr_pages; loop++, p++) { 1618 VM_WARN_ON_ONCE(PageReserved(p)); 1619 __ClearPageOffline(p); 1620 set_page_count(p, 0); 1621 } 1622 1623 adjust_managed_page_count(page, nr_pages); 1624 } else { 1625 for (loop = 0; loop < nr_pages; loop++, p++) { 1626 __ClearPageReserved(p); 1627 set_page_count(p, 0); 1628 } 1629 1630 /* memblock adjusts totalram_pages() manually. */ 1631 atomic_long_add(nr_pages, &page_zone(page)->managed_pages); 1632 } 1633 1634 if (page_contains_unaccepted(page, order)) { 1635 if (order == MAX_PAGE_ORDER && __free_unaccepted(page)) 1636 return; 1637 1638 accept_memory(page_to_phys(page), PAGE_SIZE << order); 1639 } 1640 1641 /* 1642 * Bypass PCP and place fresh pages right to the tail, primarily 1643 * relevant for memory onlining. 1644 */ 1645 __free_pages_ok(page, order, FPI_TO_TAIL); 1646 } 1647 1648 /* 1649 * Check that the whole (or subset of) a pageblock given by the interval of 1650 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it 1651 * with the migration of free compaction scanner. 1652 * 1653 * Return struct page pointer of start_pfn, or NULL if checks were not passed. 1654 * 1655 * It's possible on some configurations to have a setup like node0 node1 node0 1656 * i.e. it's possible that all pages within a zones range of pages do not 1657 * belong to a single zone. We assume that a border between node0 and node1 1658 * can occur within a single pageblock, but not a node0 node1 node0 1659 * interleaving within a single pageblock. It is therefore sufficient to check 1660 * the first and last page of a pageblock and avoid checking each individual 1661 * page in a pageblock. 1662 * 1663 * Note: the function may return non-NULL struct page even for a page block 1664 * which contains a memory hole (i.e. there is no physical memory for a subset 1665 * of the pfn range). For example, if the pageblock order is MAX_PAGE_ORDER, which 1666 * will fall into 2 sub-sections, and the end pfn of the pageblock may be hole 1667 * even though the start pfn is online and valid. This should be safe most of 1668 * the time because struct pages are still initialized via init_unavailable_range() 1669 * and pfn walkers shouldn't touch any physical memory range for which they do 1670 * not recognize any specific metadata in struct pages. 1671 */ 1672 struct page *__pageblock_pfn_to_page(unsigned long start_pfn, 1673 unsigned long end_pfn, struct zone *zone) 1674 { 1675 struct page *start_page; 1676 struct page *end_page; 1677 1678 /* end_pfn is one past the range we are checking */ 1679 end_pfn--; 1680 1681 if (!pfn_valid(end_pfn)) 1682 return NULL; 1683 1684 start_page = pfn_to_online_page(start_pfn); 1685 if (!start_page) 1686 return NULL; 1687 1688 if (page_zone(start_page) != zone) 1689 return NULL; 1690 1691 end_page = pfn_to_page(end_pfn); 1692 1693 /* This gives a shorter code than deriving page_zone(end_page) */ 1694 if (page_zone_id(start_page) != page_zone_id(end_page)) 1695 return NULL; 1696 1697 return start_page; 1698 } 1699 1700 /* 1701 * The order of subdivision here is critical for the IO subsystem. 1702 * Please do not alter this order without good reasons and regression 1703 * testing. Specifically, as large blocks of memory are subdivided, 1704 * the order in which smaller blocks are delivered depends on the order 1705 * they're subdivided in this function. This is the primary factor 1706 * influencing the order in which pages are delivered to the IO 1707 * subsystem according to empirical testing, and this is also justified 1708 * by considering the behavior of a buddy system containing a single 1709 * large block of memory acted on by a series of small allocations. 1710 * This behavior is a critical factor in sglist merging's success. 1711 * 1712 * -- nyc 1713 */ 1714 static inline unsigned int expand(struct zone *zone, struct page *page, int low, 1715 int high, int migratetype) 1716 { 1717 unsigned int size = 1 << high; 1718 unsigned int nr_added = 0; 1719 1720 while (high > low) { 1721 high--; 1722 size >>= 1; 1723 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]); 1724 1725 /* 1726 * Mark as guard pages (or page), that will allow to 1727 * merge back to allocator when buddy will be freed. 1728 * Corresponding page table entries will not be touched, 1729 * pages will stay not present in virtual address space 1730 */ 1731 if (set_page_guard(zone, &page[size], high)) 1732 continue; 1733 1734 __add_to_free_list(&page[size], zone, high, migratetype, false); 1735 set_buddy_order(&page[size], high); 1736 nr_added += size; 1737 } 1738 1739 return nr_added; 1740 } 1741 1742 static __always_inline void page_del_and_expand(struct zone *zone, 1743 struct page *page, int low, 1744 int high, int migratetype) 1745 { 1746 int nr_pages = 1 << high; 1747 1748 __del_page_from_free_list(page, zone, high, migratetype); 1749 nr_pages -= expand(zone, page, low, high, migratetype); 1750 account_freepages(zone, -nr_pages, migratetype); 1751 } 1752 1753 static void check_new_page_bad(struct page *page) 1754 { 1755 if (unlikely(PageHWPoison(page))) { 1756 /* Don't complain about hwpoisoned pages */ 1757 if (PageBuddy(page)) 1758 __ClearPageBuddy(page); 1759 return; 1760 } 1761 1762 bad_page(page, 1763 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_PREP)); 1764 } 1765 1766 /* 1767 * This page is about to be returned from the page allocator 1768 */ 1769 static bool check_new_page(struct page *page) 1770 { 1771 if (likely(page_expected_state(page, 1772 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON))) 1773 return false; 1774 1775 check_new_page_bad(page); 1776 return true; 1777 } 1778 1779 static inline bool check_new_pages(struct page *page, unsigned int order) 1780 { 1781 if (is_check_pages_enabled()) { 1782 for (int i = 0; i < (1 << order); i++) { 1783 struct page *p = page + i; 1784 1785 if (check_new_page(p)) 1786 return true; 1787 } 1788 } 1789 1790 return false; 1791 } 1792 1793 static inline bool should_skip_kasan_unpoison(gfp_t flags) 1794 { 1795 /* Don't skip if a software KASAN mode is enabled. */ 1796 if (IS_ENABLED(CONFIG_KASAN_GENERIC) || 1797 IS_ENABLED(CONFIG_KASAN_SW_TAGS)) 1798 return false; 1799 1800 /* Skip, if hardware tag-based KASAN is not enabled. */ 1801 if (!kasan_hw_tags_enabled()) 1802 return true; 1803 1804 /* 1805 * With hardware tag-based KASAN enabled, skip if this has been 1806 * requested via __GFP_SKIP_KASAN. 1807 */ 1808 return flags & __GFP_SKIP_KASAN; 1809 } 1810 1811 static inline bool should_skip_init(gfp_t flags) 1812 { 1813 /* Don't skip, if hardware tag-based KASAN is not enabled. */ 1814 if (!kasan_hw_tags_enabled()) 1815 return false; 1816 1817 /* For hardware tag-based KASAN, skip if requested. */ 1818 return (flags & __GFP_SKIP_ZERO); 1819 } 1820 1821 inline void post_alloc_hook(struct page *page, unsigned int order, 1822 gfp_t gfp_flags, unsigned int alloc_flags) 1823 { 1824 const bool zero_tags = gfp_flags & __GFP_ZEROTAGS; 1825 bool init = !want_init_on_free() && want_init_on_alloc(gfp_flags) && 1826 !should_skip_init(gfp_flags); 1827 int i; 1828 1829 set_page_private(page, 0); 1830 1831 arch_alloc_page(page, order); 1832 debug_pagealloc_map_pages(page, 1 << order); 1833 1834 /* 1835 * Page unpoisoning must happen before memory initialization. 1836 * Otherwise, the poison pattern will be overwritten for __GFP_ZERO 1837 * allocations and the page unpoisoning code will complain. 1838 */ 1839 kernel_unpoison_pages(page, 1 << order); 1840 1841 /* 1842 * As memory initialization might be integrated into KASAN, 1843 * KASAN unpoisoning and memory initialization code must be 1844 * kept together to avoid discrepancies in behavior. 1845 */ 1846 1847 /* 1848 * Clearing tags can efficiently clear the memory for us as well, if 1849 * required. 1850 */ 1851 if (zero_tags) 1852 init = tag_clear_highpages(page, 1 << order, /* clear_pages= */init); 1853 1854 if (!should_skip_kasan_unpoison(gfp_flags) && 1855 kasan_unpoison_pages(page, order, init)) { 1856 /* Take note that memory was initialized by KASAN. */ 1857 if (kasan_has_integrated_init()) 1858 init = false; 1859 } else { 1860 /* 1861 * If memory tags have not been set by KASAN, reset the page 1862 * tags to ensure page_address() dereferencing does not fault. 1863 */ 1864 for (i = 0; i != 1 << order; ++i) 1865 page_kasan_tag_reset(page + i); 1866 } 1867 /* If memory is still not initialized, initialize it now. */ 1868 if (init) 1869 clear_highpages_kasan_tagged(page, 1 << order); 1870 1871 set_page_owner(page, order, gfp_flags); 1872 page_table_check_alloc(page, order); 1873 pgalloc_tag_add(page, current, 1 << order, alloc_flags); 1874 } 1875 1876 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags, 1877 unsigned int alloc_flags) 1878 { 1879 post_alloc_hook(page, order, gfp_flags, alloc_flags); 1880 1881 if (order && (gfp_flags & __GFP_COMP)) 1882 prep_compound_page(page, order); 1883 1884 /* 1885 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to 1886 * allocate the page. The expectation is that the caller is taking 1887 * steps that will free more memory. The caller should avoid the page 1888 * being used for !PFMEMALLOC purposes. 1889 */ 1890 if (alloc_flags & ALLOC_NO_WATERMARKS) 1891 set_page_pfmemalloc(page); 1892 else 1893 clear_page_pfmemalloc(page); 1894 } 1895 1896 /* 1897 * Go through the free lists for the given migratetype and remove 1898 * the smallest available page from the freelists 1899 */ 1900 static __always_inline 1901 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order, 1902 int migratetype) 1903 { 1904 unsigned int current_order; 1905 struct free_area *area; 1906 struct page *page; 1907 1908 /* Find a page of the appropriate size in the preferred list */ 1909 for (current_order = order; current_order < NR_PAGE_ORDERS; ++current_order) { 1910 area = &(zone->free_area[current_order]); 1911 page = get_page_from_free_area(area, migratetype); 1912 if (!page) 1913 continue; 1914 1915 page_del_and_expand(zone, page, order, current_order, 1916 migratetype); 1917 trace_mm_page_alloc_zone_locked(page, order, migratetype, 1918 pcp_allowed_order(order) && 1919 migratetype < MIGRATE_PCPTYPES); 1920 return page; 1921 } 1922 1923 return NULL; 1924 } 1925 1926 1927 /* 1928 * This array describes the order lists are fallen back to when 1929 * the free lists for the desirable migrate type are depleted 1930 * 1931 * The other migratetypes do not have fallbacks. 1932 */ 1933 static int fallbacks[MIGRATE_PCPTYPES][MIGRATE_PCPTYPES - 1] = { 1934 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE }, 1935 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE }, 1936 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE }, 1937 }; 1938 1939 #ifdef CONFIG_CMA 1940 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone, 1941 unsigned int order) 1942 { 1943 return __rmqueue_smallest(zone, order, MIGRATE_CMA); 1944 } 1945 #else 1946 static inline struct page *__rmqueue_cma_fallback(struct zone *zone, 1947 unsigned int order) { return NULL; } 1948 #endif 1949 1950 /* 1951 * Move all free pages of a block to new type's freelist. Caller needs to 1952 * change the block type. 1953 */ 1954 static int __move_freepages_block(struct zone *zone, unsigned long start_pfn, 1955 int old_mt, int new_mt) 1956 { 1957 struct page *page; 1958 unsigned long pfn, end_pfn; 1959 unsigned int order; 1960 int pages_moved = 0; 1961 1962 VM_WARN_ON(start_pfn & (pageblock_nr_pages - 1)); 1963 end_pfn = pageblock_end_pfn(start_pfn); 1964 1965 for (pfn = start_pfn; pfn < end_pfn;) { 1966 page = pfn_to_page(pfn); 1967 if (!PageBuddy(page)) { 1968 pfn++; 1969 continue; 1970 } 1971 1972 /* Make sure we are not inadvertently changing nodes */ 1973 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page); 1974 VM_BUG_ON_PAGE(page_zone(page) != zone, page); 1975 1976 order = buddy_order(page); 1977 1978 move_to_free_list(page, zone, order, old_mt, new_mt); 1979 1980 pfn += 1 << order; 1981 pages_moved += 1 << order; 1982 } 1983 1984 return pages_moved; 1985 } 1986 1987 static bool prep_move_freepages_block(struct zone *zone, struct page *page, 1988 unsigned long *start_pfn, 1989 int *num_free, int *num_movable) 1990 { 1991 unsigned long pfn, start, end; 1992 1993 pfn = page_to_pfn(page); 1994 start = pageblock_start_pfn(pfn); 1995 end = pageblock_end_pfn(pfn); 1996 1997 /* 1998 * The caller only has the lock for @zone, don't touch ranges 1999 * that straddle into other zones. While we could move part of 2000 * the range that's inside the zone, this call is usually 2001 * accompanied by other operations such as migratetype updates 2002 * which also should be locked. 2003 */ 2004 if (!zone_spans_pfn(zone, start)) 2005 return false; 2006 if (!zone_spans_pfn(zone, end - 1)) 2007 return false; 2008 2009 *start_pfn = start; 2010 2011 if (num_free) { 2012 *num_free = 0; 2013 *num_movable = 0; 2014 for (pfn = start; pfn < end;) { 2015 page = pfn_to_page(pfn); 2016 if (PageBuddy(page)) { 2017 int nr = 1 << buddy_order(page); 2018 2019 *num_free += nr; 2020 pfn += nr; 2021 continue; 2022 } 2023 /* 2024 * We assume that pages that could be isolated for 2025 * migration are movable. But we don't actually try 2026 * isolating, as that would be expensive. 2027 */ 2028 if (PageLRU(page) || page_has_movable_ops(page)) 2029 (*num_movable)++; 2030 pfn++; 2031 } 2032 } 2033 2034 return true; 2035 } 2036 2037 static int move_freepages_block(struct zone *zone, struct page *page, 2038 int old_mt, int new_mt) 2039 { 2040 unsigned long start_pfn; 2041 int res; 2042 2043 if (!prep_move_freepages_block(zone, page, &start_pfn, NULL, NULL)) 2044 return -1; 2045 2046 res = __move_freepages_block(zone, start_pfn, old_mt, new_mt); 2047 set_pageblock_migratetype(pfn_to_page(start_pfn), new_mt); 2048 2049 return res; 2050 2051 } 2052 2053 #ifdef CONFIG_MEMORY_ISOLATION 2054 /* Look for a buddy that straddles start_pfn */ 2055 static unsigned long find_large_buddy(unsigned long start_pfn) 2056 { 2057 /* 2058 * If start_pfn is not an order-0 PageBuddy, next PageBuddy containing 2059 * start_pfn has minimal order of __ffs(start_pfn) + 1. Start checking 2060 * the order with __ffs(start_pfn). If start_pfn is order-0 PageBuddy, 2061 * the starting order does not matter. 2062 */ 2063 int order = start_pfn ? __ffs(start_pfn) : MAX_PAGE_ORDER; 2064 struct page *page; 2065 unsigned long pfn = start_pfn; 2066 2067 while (!PageBuddy(page = pfn_to_page(pfn))) { 2068 /* Nothing found */ 2069 if (++order > MAX_PAGE_ORDER) 2070 return start_pfn; 2071 pfn &= ~0UL << order; 2072 } 2073 2074 /* 2075 * Found a preceding buddy, but does it straddle? 2076 */ 2077 if (pfn + (1 << buddy_order(page)) > start_pfn) 2078 return pfn; 2079 2080 /* Nothing found */ 2081 return start_pfn; 2082 } 2083 2084 static inline void toggle_pageblock_isolate(struct page *page, bool isolate) 2085 { 2086 if (isolate) 2087 set_pageblock_isolate(page); 2088 else 2089 clear_pageblock_isolate(page); 2090 } 2091 2092 /** 2093 * __move_freepages_block_isolate - move free pages in block for page isolation 2094 * @zone: the zone 2095 * @page: the pageblock page 2096 * @isolate: to isolate the given pageblock or unisolate it 2097 * 2098 * This is similar to move_freepages_block(), but handles the special 2099 * case encountered in page isolation, where the block of interest 2100 * might be part of a larger buddy spanning multiple pageblocks. 2101 * 2102 * Unlike the regular page allocator path, which moves pages while 2103 * stealing buddies off the freelist, page isolation is interested in 2104 * arbitrary pfn ranges that may have overlapping buddies on both ends. 2105 * 2106 * This function handles that. Straddling buddies are split into 2107 * individual pageblocks. Only the block of interest is moved. 2108 * 2109 * Returns %true if pages could be moved, %false otherwise. 2110 */ 2111 static bool __move_freepages_block_isolate(struct zone *zone, 2112 struct page *page, bool isolate) 2113 { 2114 unsigned long start_pfn, buddy_pfn; 2115 int from_mt; 2116 int to_mt; 2117 struct page *buddy; 2118 2119 if (isolate == get_pageblock_isolate(page)) { 2120 VM_WARN_ONCE(1, "%s a pageblock that is already in that state", 2121 isolate ? "Isolate" : "Unisolate"); 2122 return false; 2123 } 2124 2125 if (!prep_move_freepages_block(zone, page, &start_pfn, NULL, NULL)) 2126 return false; 2127 2128 /* No splits needed if buddies can't span multiple blocks */ 2129 if (pageblock_order == MAX_PAGE_ORDER) 2130 goto move; 2131 2132 buddy_pfn = find_large_buddy(start_pfn); 2133 buddy = pfn_to_page(buddy_pfn); 2134 /* We're a part of a larger buddy */ 2135 if (PageBuddy(buddy) && buddy_order(buddy) > pageblock_order) { 2136 int order = buddy_order(buddy); 2137 2138 del_page_from_free_list(buddy, zone, order, 2139 get_pfnblock_migratetype(buddy, buddy_pfn)); 2140 toggle_pageblock_isolate(page, isolate); 2141 split_large_buddy(zone, buddy, buddy_pfn, order, FPI_NONE); 2142 return true; 2143 } 2144 2145 move: 2146 /* Use PAGEBLOCK_MIGRATETYPE_MASK to get non-isolate migratetype */ 2147 if (isolate) { 2148 from_mt = __get_pfnblock_flags_mask(page, page_to_pfn(page), 2149 PAGEBLOCK_MIGRATETYPE_MASK); 2150 to_mt = MIGRATE_ISOLATE; 2151 } else { 2152 from_mt = MIGRATE_ISOLATE; 2153 to_mt = __get_pfnblock_flags_mask(page, page_to_pfn(page), 2154 PAGEBLOCK_MIGRATETYPE_MASK); 2155 } 2156 2157 __move_freepages_block(zone, start_pfn, from_mt, to_mt); 2158 toggle_pageblock_isolate(pfn_to_page(start_pfn), isolate); 2159 2160 return true; 2161 } 2162 2163 bool pageblock_isolate_and_move_free_pages(struct zone *zone, struct page *page) 2164 { 2165 return __move_freepages_block_isolate(zone, page, true); 2166 } 2167 2168 bool pageblock_unisolate_and_move_free_pages(struct zone *zone, struct page *page) 2169 { 2170 return __move_freepages_block_isolate(zone, page, false); 2171 } 2172 2173 #endif /* CONFIG_MEMORY_ISOLATION */ 2174 2175 static inline bool boost_watermark(struct zone *zone) 2176 { 2177 unsigned long max_boost; 2178 2179 if (!watermark_boost_factor) 2180 return false; 2181 /* 2182 * Don't bother in zones that are unlikely to produce results. 2183 * On small machines, including kdump capture kernels running 2184 * in a small area, boosting the watermark can cause an out of 2185 * memory situation immediately. 2186 */ 2187 if ((pageblock_nr_pages * 4) > zone_managed_pages(zone)) 2188 return false; 2189 2190 max_boost = mult_frac(zone->_watermark[WMARK_HIGH], 2191 watermark_boost_factor, 10000); 2192 2193 /* 2194 * high watermark may be uninitialised if fragmentation occurs 2195 * very early in boot so do not boost. We do not fall 2196 * through and boost by pageblock_nr_pages as failing 2197 * allocations that early means that reclaim is not going 2198 * to help and it may even be impossible to reclaim the 2199 * boosted watermark resulting in a hang. 2200 */ 2201 if (!max_boost) 2202 return false; 2203 2204 max_boost = max(pageblock_nr_pages, max_boost); 2205 2206 zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages, 2207 max_boost); 2208 2209 return true; 2210 } 2211 2212 /* 2213 * When we are falling back to another migratetype during allocation, should we 2214 * try to claim an entire block to satisfy further allocations, instead of 2215 * polluting multiple pageblocks? 2216 */ 2217 static bool should_try_claim_block(unsigned int order, int start_mt) 2218 { 2219 /* 2220 * Leaving this order check is intended, although there is 2221 * relaxed order check in next check. The reason is that 2222 * we can actually claim the whole pageblock if this condition met, 2223 * but, below check doesn't guarantee it and that is just heuristic 2224 * so could be changed anytime. 2225 */ 2226 if (order >= pageblock_order) 2227 return true; 2228 2229 /* 2230 * Above a certain threshold, always try to claim, as it's likely there 2231 * will be more free pages in the pageblock. 2232 */ 2233 if (order >= pageblock_order / 2) 2234 return true; 2235 2236 /* 2237 * Unmovable/reclaimable allocations would cause permanent 2238 * fragmentations if they fell back to allocating from a movable block 2239 * (polluting it), so we try to claim the whole block regardless of the 2240 * allocation size. Later movable allocations can always steal from this 2241 * block, which is less problematic. 2242 */ 2243 if (start_mt == MIGRATE_RECLAIMABLE || start_mt == MIGRATE_UNMOVABLE) 2244 return true; 2245 2246 if (page_group_by_mobility_disabled) 2247 return true; 2248 2249 /* 2250 * Movable pages won't cause permanent fragmentation, so when you alloc 2251 * small pages, we just need to temporarily steal unmovable or 2252 * reclaimable pages that are closest to the request size. After a 2253 * while, memory compaction may occur to form large contiguous pages, 2254 * and the next movable allocation may not need to steal. 2255 */ 2256 return false; 2257 } 2258 2259 /* 2260 * Check whether there is a suitable fallback freepage with requested order. 2261 * If claimable is true, this function returns fallback_mt only if 2262 * we would do this whole-block claiming. This would help to reduce 2263 * fragmentation due to mixed migratetype pages in one pageblock. 2264 */ 2265 enum fallback_result 2266 find_suitable_fallback(struct free_area *area, unsigned int order, 2267 int migratetype, bool claimable, int *mt_out) 2268 { 2269 int i; 2270 2271 if (claimable && !should_try_claim_block(order, migratetype)) 2272 return FALLBACK_NOCLAIM; 2273 2274 if (area->nr_free == 0) 2275 return FALLBACK_EMPTY; 2276 2277 for (i = 0; i < MIGRATE_PCPTYPES - 1 ; i++) { 2278 int fallback_mt = fallbacks[migratetype][i]; 2279 2280 if (!free_area_empty(area, fallback_mt)) { 2281 if (mt_out) 2282 *mt_out = fallback_mt; 2283 return FALLBACK_FOUND; 2284 } 2285 } 2286 2287 return FALLBACK_EMPTY; 2288 } 2289 2290 /* 2291 * This function implements actual block claiming behaviour. If order is large 2292 * enough, we can claim the whole pageblock for the requested migratetype. If 2293 * not, we check the pageblock for constituent pages; if at least half of the 2294 * pages are free or compatible, we can still claim the whole block, so pages 2295 * freed in the future will be put on the correct free list. 2296 */ 2297 static struct page * 2298 try_to_claim_block(struct zone *zone, struct page *page, 2299 int current_order, int order, int start_type, 2300 int block_type, unsigned int alloc_flags) 2301 { 2302 int free_pages, movable_pages, alike_pages; 2303 unsigned long start_pfn; 2304 2305 /* Take ownership for orders >= pageblock_order */ 2306 if (current_order >= pageblock_order) { 2307 unsigned int nr_added; 2308 2309 del_page_from_free_list(page, zone, current_order, block_type); 2310 change_pageblock_range(page, current_order, start_type); 2311 nr_added = expand(zone, page, order, current_order, start_type); 2312 account_freepages(zone, nr_added, start_type); 2313 return page; 2314 } 2315 2316 /* 2317 * Boost watermarks to increase reclaim pressure to reduce the 2318 * likelihood of future fallbacks. Wake kswapd now as the node 2319 * may be balanced overall and kswapd will not wake naturally. 2320 */ 2321 if (boost_watermark(zone) && (alloc_flags & ALLOC_KSWAPD)) 2322 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags); 2323 2324 /* moving whole block can fail due to zone boundary conditions */ 2325 if (!prep_move_freepages_block(zone, page, &start_pfn, &free_pages, 2326 &movable_pages)) 2327 return NULL; 2328 2329 /* 2330 * Determine how many pages are compatible with our allocation. 2331 * For movable allocation, it's the number of movable pages which 2332 * we just obtained. For other types it's a bit more tricky. 2333 */ 2334 if (start_type == MIGRATE_MOVABLE) { 2335 alike_pages = movable_pages; 2336 } else { 2337 /* 2338 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation 2339 * to MOVABLE pageblock, consider all non-movable pages as 2340 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or 2341 * vice versa, be conservative since we can't distinguish the 2342 * exact migratetype of non-movable pages. 2343 */ 2344 if (block_type == MIGRATE_MOVABLE) 2345 alike_pages = pageblock_nr_pages 2346 - (free_pages + movable_pages); 2347 else 2348 alike_pages = 0; 2349 } 2350 /* 2351 * If a sufficient number of pages in the block are either free or of 2352 * compatible migratability as our allocation, claim the whole block. 2353 */ 2354 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) || 2355 page_group_by_mobility_disabled) { 2356 __move_freepages_block(zone, start_pfn, block_type, start_type); 2357 set_pageblock_migratetype(pfn_to_page(start_pfn), start_type); 2358 return __rmqueue_smallest(zone, order, start_type); 2359 } 2360 2361 return NULL; 2362 } 2363 2364 /* 2365 * Try to allocate from some fallback migratetype by claiming the entire block, 2366 * i.e. converting it to the allocation's start migratetype. 2367 * 2368 * The use of signed ints for order and current_order is a deliberate 2369 * deviation from the rest of this file, to make the for loop 2370 * condition simpler. 2371 */ 2372 static __always_inline struct page * 2373 __rmqueue_claim(struct zone *zone, int order, int start_migratetype, 2374 unsigned int alloc_flags) 2375 { 2376 struct free_area *area; 2377 int current_order; 2378 int min_order = order; 2379 struct page *page; 2380 int fallback_mt; 2381 2382 /* 2383 * Do not steal pages from freelists belonging to other pageblocks 2384 * i.e. orders < pageblock_order. If there are no local zones free, 2385 * the zonelists will be reiterated without ALLOC_NOFRAGMENT. 2386 */ 2387 if (order < pageblock_order && alloc_flags & ALLOC_NOFRAGMENT) 2388 min_order = pageblock_order; 2389 2390 /* 2391 * Find the largest available free page in the other list. This roughly 2392 * approximates finding the pageblock with the most free pages, which 2393 * would be too costly to do exactly. 2394 */ 2395 for (current_order = MAX_PAGE_ORDER; current_order >= min_order; 2396 --current_order) { 2397 enum fallback_result result; 2398 2399 area = &(zone->free_area[current_order]); 2400 result = find_suitable_fallback(area, current_order, 2401 start_migratetype, true, &fallback_mt); 2402 2403 if (result == FALLBACK_EMPTY) 2404 continue; 2405 2406 if (result == FALLBACK_NOCLAIM) 2407 break; 2408 2409 page = get_page_from_free_area(area, fallback_mt); 2410 page = try_to_claim_block(zone, page, current_order, order, 2411 start_migratetype, fallback_mt, 2412 alloc_flags); 2413 if (page) { 2414 trace_mm_page_alloc_extfrag(page, order, current_order, 2415 start_migratetype, fallback_mt); 2416 return page; 2417 } 2418 } 2419 2420 return NULL; 2421 } 2422 2423 /* 2424 * Try to steal a single page from some fallback migratetype. Leave the rest of 2425 * the block as its current migratetype, potentially causing fragmentation. 2426 */ 2427 static __always_inline struct page * 2428 __rmqueue_steal(struct zone *zone, int order, int start_migratetype) 2429 { 2430 struct free_area *area; 2431 int current_order; 2432 struct page *page; 2433 int fallback_mt; 2434 2435 for (current_order = order; current_order < NR_PAGE_ORDERS; current_order++) { 2436 enum fallback_result result; 2437 2438 area = &(zone->free_area[current_order]); 2439 result = find_suitable_fallback(area, current_order, start_migratetype, 2440 false, &fallback_mt); 2441 if (result == FALLBACK_EMPTY) 2442 continue; 2443 2444 page = get_page_from_free_area(area, fallback_mt); 2445 page_del_and_expand(zone, page, order, current_order, fallback_mt); 2446 trace_mm_page_alloc_extfrag(page, order, current_order, 2447 start_migratetype, fallback_mt); 2448 return page; 2449 } 2450 2451 return NULL; 2452 } 2453 2454 enum rmqueue_mode { 2455 RMQUEUE_NORMAL, 2456 RMQUEUE_CMA, 2457 RMQUEUE_CLAIM, 2458 RMQUEUE_STEAL, 2459 }; 2460 2461 /* 2462 * Do the hard work of removing an element from the buddy allocator. 2463 * Call me with the zone->lock already held. 2464 */ 2465 static __always_inline struct page * 2466 __rmqueue(struct zone *zone, unsigned int order, int migratetype, 2467 unsigned int alloc_flags, enum rmqueue_mode *mode) 2468 { 2469 struct page *page; 2470 2471 if (IS_ENABLED(CONFIG_CMA)) { 2472 /* 2473 * Balance movable allocations between regular and CMA areas by 2474 * allocating from CMA when over half of the zone's free memory 2475 * is in the CMA area. 2476 */ 2477 if (alloc_flags & ALLOC_CMA && 2478 zone_page_state(zone, NR_FREE_CMA_PAGES) > 2479 zone_page_state(zone, NR_FREE_PAGES) / 2) { 2480 page = __rmqueue_cma_fallback(zone, order); 2481 if (page) 2482 return page; 2483 } 2484 } 2485 2486 /* 2487 * First try the freelists of the requested migratetype, then try 2488 * fallbacks modes with increasing levels of fragmentation risk. 2489 * 2490 * The fallback logic is expensive and rmqueue_bulk() calls in 2491 * a loop with the zone->lock held, meaning the freelists are 2492 * not subject to any outside changes. Remember in *mode where 2493 * we found pay dirt, to save us the search on the next call. 2494 */ 2495 switch (*mode) { 2496 case RMQUEUE_NORMAL: 2497 page = __rmqueue_smallest(zone, order, migratetype); 2498 if (page) 2499 return page; 2500 fallthrough; 2501 case RMQUEUE_CMA: 2502 if (alloc_flags & ALLOC_CMA) { 2503 page = __rmqueue_cma_fallback(zone, order); 2504 if (page) { 2505 *mode = RMQUEUE_CMA; 2506 return page; 2507 } 2508 } 2509 fallthrough; 2510 case RMQUEUE_CLAIM: 2511 page = __rmqueue_claim(zone, order, migratetype, alloc_flags); 2512 if (page) { 2513 /* Replenished preferred freelist, back to normal mode. */ 2514 *mode = RMQUEUE_NORMAL; 2515 return page; 2516 } 2517 fallthrough; 2518 case RMQUEUE_STEAL: 2519 if (!(alloc_flags & ALLOC_NOFRAGMENT)) { 2520 page = __rmqueue_steal(zone, order, migratetype); 2521 if (page) { 2522 *mode = RMQUEUE_STEAL; 2523 return page; 2524 } 2525 } 2526 } 2527 return NULL; 2528 } 2529 2530 /* 2531 * Obtain a specified number of elements from the buddy allocator, all under 2532 * a single hold of the lock, for efficiency. Add them to the supplied list. 2533 * Returns the number of new pages which were placed at *list. 2534 */ 2535 static int rmqueue_bulk(struct zone *zone, unsigned int order, 2536 unsigned long count, struct list_head *list, 2537 int migratetype, unsigned int alloc_flags) 2538 { 2539 enum rmqueue_mode rmqm = RMQUEUE_NORMAL; 2540 unsigned long flags; 2541 int i; 2542 2543 if (unlikely(alloc_flags & ALLOC_NOLOCK)) { 2544 if (!spin_trylock_irqsave(&zone->lock, flags)) 2545 return 0; 2546 } else { 2547 spin_lock_irqsave(&zone->lock, flags); 2548 } 2549 for (i = 0; i < count; ++i) { 2550 struct page *page = __rmqueue(zone, order, migratetype, 2551 alloc_flags, &rmqm); 2552 if (unlikely(page == NULL)) 2553 break; 2554 2555 /* 2556 * Split buddy pages returned by expand() are received here in 2557 * physical page order. The page is added to the tail of 2558 * caller's list. From the callers perspective, the linked list 2559 * is ordered by page number under some conditions. This is 2560 * useful for IO devices that can forward direction from the 2561 * head, thus also in the physical page order. This is useful 2562 * for IO devices that can merge IO requests if the physical 2563 * pages are ordered properly. 2564 */ 2565 list_add_tail(&page->pcp_list, list); 2566 } 2567 spin_unlock_irqrestore(&zone->lock, flags); 2568 2569 return i; 2570 } 2571 2572 /* 2573 * Called from the vmstat counter updater to decay the PCP high. 2574 * Return whether there are addition works to do. 2575 */ 2576 bool decay_pcp_high(struct zone *zone, struct per_cpu_pages *pcp) 2577 { 2578 int high_min, to_drain, to_drain_batched, batch; 2579 bool todo = false; 2580 2581 high_min = READ_ONCE(pcp->high_min); 2582 batch = READ_ONCE(pcp->batch); 2583 /* 2584 * Decrease pcp->high periodically to try to free possible 2585 * idle PCP pages. And, avoid to free too many pages to 2586 * control latency. This caps pcp->high decrement too. 2587 */ 2588 if (pcp->high > high_min) { 2589 pcp->high = max3(pcp->count - (batch << CONFIG_PCP_BATCH_SCALE_MAX), 2590 pcp->high - (pcp->high >> 3), high_min); 2591 if (pcp->high > high_min) 2592 todo = true; 2593 } 2594 2595 to_drain = pcp->count - pcp->high; 2596 while (to_drain > 0) { 2597 to_drain_batched = min(to_drain, batch); 2598 pcp_spin_lock_nopin(pcp); 2599 free_pcppages_bulk(zone, to_drain_batched, pcp, 0); 2600 pcp_spin_unlock_nopin(pcp); 2601 todo = true; 2602 2603 to_drain -= to_drain_batched; 2604 } 2605 2606 return todo; 2607 } 2608 2609 #ifdef CONFIG_NUMA 2610 /* 2611 * Called from the vmstat counter updater to drain pagesets of this 2612 * currently executing processor on remote nodes after they have 2613 * expired. 2614 */ 2615 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp) 2616 { 2617 int to_drain, batch; 2618 2619 batch = READ_ONCE(pcp->batch); 2620 to_drain = min(pcp->count, batch); 2621 if (to_drain > 0) { 2622 pcp_spin_lock_nopin(pcp); 2623 free_pcppages_bulk(zone, to_drain, pcp, 0); 2624 pcp_spin_unlock_nopin(pcp); 2625 } 2626 } 2627 #endif 2628 2629 /* 2630 * Drain pcplists of the indicated processor and zone. 2631 */ 2632 static void drain_pages_zone(unsigned int cpu, struct zone *zone) 2633 { 2634 struct per_cpu_pages *pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 2635 int count; 2636 2637 do { 2638 pcp_spin_lock_nopin(pcp); 2639 count = pcp->count; 2640 if (count) { 2641 int to_drain = min(count, 2642 pcp->batch << CONFIG_PCP_BATCH_SCALE_MAX); 2643 2644 free_pcppages_bulk(zone, to_drain, pcp, 0); 2645 count -= to_drain; 2646 } 2647 pcp_spin_unlock_nopin(pcp); 2648 } while (count); 2649 } 2650 2651 /* 2652 * Drain pcplists of all zones on the indicated processor. 2653 */ 2654 static void drain_pages(unsigned int cpu) 2655 { 2656 struct zone *zone; 2657 2658 for_each_populated_zone(zone) { 2659 drain_pages_zone(cpu, zone); 2660 } 2661 } 2662 2663 /* 2664 * Spill all of this CPU's per-cpu pages back into the buddy allocator. 2665 */ 2666 void drain_local_pages(struct zone *zone) 2667 { 2668 int cpu = smp_processor_id(); 2669 2670 if (zone) 2671 drain_pages_zone(cpu, zone); 2672 else 2673 drain_pages(cpu); 2674 } 2675 2676 /* 2677 * The implementation of drain_all_pages(), exposing an extra parameter to 2678 * drain on all cpus. 2679 * 2680 * drain_all_pages() is optimized to only execute on cpus where pcplists are 2681 * not empty. The check for non-emptiness can however race with a free to 2682 * pcplist that has not yet increased the pcp->count from 0 to 1. Callers 2683 * that need the guarantee that every CPU has drained can disable the 2684 * optimizing racy check. 2685 */ 2686 static void __drain_all_pages(struct zone *zone, bool force_all_cpus) 2687 { 2688 int cpu; 2689 2690 /* 2691 * Allocate in the BSS so we won't require allocation in 2692 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y 2693 */ 2694 static cpumask_t cpus_with_pcps; 2695 2696 /* 2697 * Do not drain if one is already in progress unless it's specific to 2698 * a zone. Such callers are primarily CMA and memory hotplug and need 2699 * the drain to be complete when the call returns. 2700 */ 2701 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) { 2702 if (!zone) 2703 return; 2704 mutex_lock(&pcpu_drain_mutex); 2705 } 2706 2707 /* 2708 * We don't care about racing with CPU hotplug event 2709 * as offline notification will cause the notified 2710 * cpu to drain that CPU pcps and on_each_cpu_mask 2711 * disables preemption as part of its processing 2712 */ 2713 for_each_online_cpu(cpu) { 2714 struct per_cpu_pages *pcp; 2715 struct zone *z; 2716 bool has_pcps = false; 2717 2718 if (force_all_cpus) { 2719 /* 2720 * The pcp.count check is racy, some callers need a 2721 * guarantee that no cpu is missed. 2722 */ 2723 has_pcps = true; 2724 } else if (zone) { 2725 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 2726 if (pcp->count) 2727 has_pcps = true; 2728 } else { 2729 for_each_populated_zone(z) { 2730 pcp = per_cpu_ptr(z->per_cpu_pageset, cpu); 2731 if (pcp->count) { 2732 has_pcps = true; 2733 break; 2734 } 2735 } 2736 } 2737 2738 if (has_pcps) 2739 cpumask_set_cpu(cpu, &cpus_with_pcps); 2740 else 2741 cpumask_clear_cpu(cpu, &cpus_with_pcps); 2742 } 2743 2744 for_each_cpu(cpu, &cpus_with_pcps) { 2745 if (zone) 2746 drain_pages_zone(cpu, zone); 2747 else 2748 drain_pages(cpu); 2749 } 2750 2751 mutex_unlock(&pcpu_drain_mutex); 2752 } 2753 2754 /* 2755 * Spill all the per-cpu pages from all CPUs back into the buddy allocator. 2756 * 2757 * When zone parameter is non-NULL, spill just the single zone's pages. 2758 */ 2759 void drain_all_pages(struct zone *zone) 2760 { 2761 __drain_all_pages(zone, false); 2762 } 2763 2764 static int nr_pcp_free(struct per_cpu_pages *pcp, int batch, int high, bool free_high) 2765 { 2766 int min_nr_free, max_nr_free; 2767 2768 /* Free as much as possible if batch freeing high-order pages. */ 2769 if (unlikely(free_high)) 2770 return min(pcp->count, batch << CONFIG_PCP_BATCH_SCALE_MAX); 2771 2772 /* Check for PCP disabled or boot pageset */ 2773 if (unlikely(high < batch)) 2774 return 1; 2775 2776 /* Leave at least pcp->batch pages on the list */ 2777 min_nr_free = batch; 2778 max_nr_free = high - batch; 2779 2780 /* 2781 * Increase the batch number to the number of the consecutive 2782 * freed pages to reduce zone lock contention. 2783 */ 2784 batch = clamp_t(int, pcp->free_count, min_nr_free, max_nr_free); 2785 2786 return batch; 2787 } 2788 2789 static int nr_pcp_high(struct per_cpu_pages *pcp, struct zone *zone, 2790 int batch, bool free_high) 2791 { 2792 int high, high_min, high_max; 2793 2794 high_min = READ_ONCE(pcp->high_min); 2795 high_max = READ_ONCE(pcp->high_max); 2796 high = pcp->high = clamp(pcp->high, high_min, high_max); 2797 2798 if (unlikely(!high)) 2799 return 0; 2800 2801 if (unlikely(free_high)) { 2802 pcp->high = max(high - (batch << CONFIG_PCP_BATCH_SCALE_MAX), 2803 high_min); 2804 return 0; 2805 } 2806 2807 /* 2808 * If reclaim is active, limit the number of pages that can be 2809 * stored on pcp lists 2810 */ 2811 if (test_bit(ZONE_RECLAIM_ACTIVE, &zone->flags)) { 2812 int free_count = max_t(int, pcp->free_count, batch); 2813 2814 pcp->high = max(high - free_count, high_min); 2815 return min(batch << 2, pcp->high); 2816 } 2817 2818 if (high_min == high_max) 2819 return high; 2820 2821 if (test_bit(ZONE_BELOW_HIGH, &zone->flags)) { 2822 int free_count = max_t(int, pcp->free_count, batch); 2823 2824 pcp->high = max(high - free_count, high_min); 2825 high = max(pcp->count, high_min); 2826 } else if (pcp->count >= high) { 2827 int need_high = pcp->free_count + batch; 2828 2829 /* pcp->high should be large enough to hold batch freed pages */ 2830 if (pcp->high < need_high) 2831 pcp->high = clamp(need_high, high_min, high_max); 2832 } 2833 2834 return high; 2835 } 2836 2837 /* 2838 * Tune pcp alloc factor and adjust count & free_count. Free pages to bring the 2839 * pcp's watermarks below high. 2840 * 2841 * May return a freed pcp, if during page freeing the pcp spinlock cannot be 2842 * reacquired. Return true if pcp is locked, false otherwise. 2843 */ 2844 static bool free_frozen_page_commit(struct zone *zone, 2845 struct per_cpu_pages *pcp, struct page *page, int migratetype, 2846 unsigned int order, fpi_t fpi_flags) 2847 { 2848 int high, batch; 2849 int to_free, to_free_batched; 2850 int pindex; 2851 int cpu = smp_processor_id(); 2852 int ret = true; 2853 bool free_high = false; 2854 2855 /* 2856 * On freeing, reduce the number of pages that are batch allocated. 2857 * See nr_pcp_alloc() where alloc_factor is increased for subsequent 2858 * allocations. 2859 */ 2860 pcp->alloc_factor >>= 1; 2861 __count_vm_events(PGFREE, 1 << order); 2862 pindex = order_to_pindex(migratetype, order); 2863 list_add(&page->pcp_list, &pcp->lists[pindex]); 2864 pcp->count += 1 << order; 2865 2866 batch = READ_ONCE(pcp->batch); 2867 /* 2868 * As high-order pages other than THP's stored on PCP can contribute 2869 * to fragmentation, limit the number stored when PCP is heavily 2870 * freeing without allocation. The remainder after bulk freeing 2871 * stops will be drained from vmstat refresh context. 2872 */ 2873 if (order && order <= PAGE_ALLOC_COSTLY_ORDER) { 2874 free_high = (pcp->free_count >= (batch + pcp->high_min / 2) && 2875 (pcp->flags & PCPF_PREV_FREE_HIGH_ORDER) && 2876 (!(pcp->flags & PCPF_FREE_HIGH_BATCH) || 2877 pcp->count >= batch)); 2878 pcp->flags |= PCPF_PREV_FREE_HIGH_ORDER; 2879 } else if (pcp->flags & PCPF_PREV_FREE_HIGH_ORDER) { 2880 pcp->flags &= ~PCPF_PREV_FREE_HIGH_ORDER; 2881 } 2882 if (pcp->free_count < (batch << CONFIG_PCP_BATCH_SCALE_MAX)) 2883 pcp->free_count += (1 << order); 2884 2885 if (unlikely(fpi_flags & FPI_NOLOCK)) { 2886 /* 2887 * Do not attempt to take a zone lock. Let pcp->count get 2888 * over high mark temporarily. 2889 */ 2890 return true; 2891 } 2892 2893 high = nr_pcp_high(pcp, zone, batch, free_high); 2894 if (pcp->count < high) 2895 return true; 2896 2897 to_free = nr_pcp_free(pcp, batch, high, free_high); 2898 while (to_free > 0 && pcp->count > 0) { 2899 to_free_batched = min(to_free, batch); 2900 free_pcppages_bulk(zone, to_free_batched, pcp, pindex); 2901 to_free -= to_free_batched; 2902 2903 if (to_free == 0 || pcp->count == 0) 2904 break; 2905 2906 pcp_spin_unlock(pcp); 2907 2908 pcp = pcp_spin_trylock(zone->per_cpu_pageset); 2909 if (!pcp) { 2910 ret = false; 2911 break; 2912 } 2913 2914 /* 2915 * Check if this thread has been migrated to a different CPU. 2916 * If that is the case, give up and indicate that the pcp is 2917 * returned in an unlocked state. 2918 */ 2919 if (smp_processor_id() != cpu) { 2920 pcp_spin_unlock(pcp); 2921 ret = false; 2922 break; 2923 } 2924 } 2925 2926 if (test_bit(ZONE_BELOW_HIGH, &zone->flags) && 2927 zone_watermark_ok(zone, 0, high_wmark_pages(zone), 2928 ZONE_MOVABLE, 0)) { 2929 struct pglist_data *pgdat = zone->zone_pgdat; 2930 clear_bit(ZONE_BELOW_HIGH, &zone->flags); 2931 2932 /* 2933 * Assume that memory pressure on this node is gone and may be 2934 * in a reclaimable state. If a memory fallback node exists, 2935 * direct reclaim may not have been triggered, causing a 2936 * 'hopeless node' to stay in that state for a while. Let 2937 * kswapd work again by resetting kswapd_failures. 2938 */ 2939 if (kswapd_test_hopeless(pgdat) && 2940 next_memory_node(pgdat->node_id) < MAX_NUMNODES) 2941 kswapd_clear_hopeless(pgdat, KSWAPD_CLEAR_HOPELESS_PCP); 2942 } 2943 return ret; 2944 } 2945 2946 /* 2947 * Free a pcp page 2948 */ 2949 static void __free_frozen_pages(struct page *page, unsigned int order, 2950 fpi_t fpi_flags) 2951 { 2952 struct per_cpu_pages *pcp; 2953 struct zone *zone; 2954 unsigned long pfn = page_to_pfn(page); 2955 int migratetype; 2956 2957 if (!pcp_allowed_order(order)) { 2958 __free_pages_ok(page, order, fpi_flags); 2959 return; 2960 } 2961 2962 if (!__free_pages_prepare(page, order, fpi_flags)) 2963 return; 2964 2965 /* 2966 * We only track unmovable, reclaimable and movable on pcp lists. 2967 * Place ISOLATE pages on the isolated list because they are being 2968 * offlined but treat HIGHATOMIC and CMA as movable pages so we can 2969 * get those areas back if necessary. Otherwise, we may have to free 2970 * excessively into the page allocator 2971 */ 2972 zone = page_zone(page); 2973 migratetype = get_pfnblock_migratetype(page, pfn); 2974 if (unlikely(migratetype >= MIGRATE_PCPTYPES)) { 2975 if (unlikely(is_migrate_isolate(migratetype))) { 2976 free_one_page(zone, page, pfn, order, fpi_flags); 2977 return; 2978 } 2979 migratetype = MIGRATE_MOVABLE; 2980 } 2981 2982 if (unlikely((fpi_flags & FPI_NOLOCK) && !can_spin_trylock())) { 2983 add_page_to_zone_llist(zone, page, order); 2984 return; 2985 } 2986 pcp = pcp_spin_trylock(zone->per_cpu_pageset); 2987 if (pcp) { 2988 if (!free_frozen_page_commit(zone, pcp, page, migratetype, 2989 order, fpi_flags)) 2990 return; 2991 pcp_spin_unlock(pcp); 2992 } else { 2993 free_one_page(zone, page, pfn, order, fpi_flags); 2994 } 2995 } 2996 2997 void free_frozen_pages(struct page *page, unsigned int order) 2998 { 2999 __free_frozen_pages(page, order, FPI_NONE); 3000 } 3001 3002 void free_frozen_pages_nolock(struct page *page, unsigned int order) 3003 { 3004 __free_frozen_pages(page, order, FPI_NOLOCK); 3005 } 3006 3007 /* 3008 * Free a batch of folios 3009 */ 3010 void free_unref_folios(struct folio_batch *folios) 3011 { 3012 struct per_cpu_pages *pcp = NULL; 3013 struct zone *locked_zone = NULL; 3014 int i, j; 3015 3016 /* Prepare folios for freeing */ 3017 for (i = 0, j = 0; i < folios->nr; i++) { 3018 struct folio *folio = folios->folios[i]; 3019 unsigned long pfn = folio_pfn(folio); 3020 unsigned int order = folio_order(folio); 3021 3022 if (!__free_pages_prepare(&folio->page, order, FPI_NONE)) 3023 continue; 3024 /* 3025 * Free orders not handled on the PCP directly to the 3026 * allocator. 3027 */ 3028 if (!pcp_allowed_order(order)) { 3029 free_one_page(folio_zone(folio), &folio->page, 3030 pfn, order, FPI_NONE); 3031 continue; 3032 } 3033 folio->private = (void *)(unsigned long)order; 3034 if (j != i) 3035 folios->folios[j] = folio; 3036 j++; 3037 } 3038 folios->nr = j; 3039 3040 for (i = 0; i < folios->nr; i++) { 3041 struct folio *folio = folios->folios[i]; 3042 struct zone *zone = folio_zone(folio); 3043 unsigned long pfn = folio_pfn(folio); 3044 unsigned int order = (unsigned long)folio->private; 3045 int migratetype; 3046 3047 folio->private = NULL; 3048 migratetype = get_pfnblock_migratetype(&folio->page, pfn); 3049 3050 /* Different zone requires a different pcp lock */ 3051 if (zone != locked_zone || 3052 is_migrate_isolate(migratetype)) { 3053 if (pcp) { 3054 pcp_spin_unlock(pcp); 3055 locked_zone = NULL; 3056 pcp = NULL; 3057 } 3058 3059 /* 3060 * Free isolated pages directly to the 3061 * allocator, see comment in free_frozen_pages. 3062 */ 3063 if (is_migrate_isolate(migratetype)) { 3064 free_one_page(zone, &folio->page, pfn, 3065 order, FPI_NONE); 3066 continue; 3067 } 3068 3069 /* 3070 * trylock is necessary as folios may be getting freed 3071 * from IRQ or SoftIRQ context after an IO completion. 3072 */ 3073 pcp = pcp_spin_trylock(zone->per_cpu_pageset); 3074 if (unlikely(!pcp)) { 3075 free_one_page(zone, &folio->page, pfn, 3076 order, FPI_NONE); 3077 continue; 3078 } 3079 locked_zone = zone; 3080 } 3081 3082 /* 3083 * Non-isolated types over MIGRATE_PCPTYPES get added 3084 * to the MIGRATE_MOVABLE pcp list. 3085 */ 3086 if (unlikely(migratetype >= MIGRATE_PCPTYPES)) 3087 migratetype = MIGRATE_MOVABLE; 3088 3089 trace_mm_page_free_batched(&folio->page); 3090 if (!free_frozen_page_commit(zone, pcp, &folio->page, 3091 migratetype, order, FPI_NONE)) { 3092 pcp = NULL; 3093 locked_zone = NULL; 3094 } 3095 } 3096 3097 if (pcp) 3098 pcp_spin_unlock(pcp); 3099 folio_batch_reinit(folios); 3100 } 3101 3102 static void __split_page(struct page *page, unsigned int order) 3103 { 3104 VM_WARN_ON_PAGE(PageCompound(page), page); 3105 3106 split_page_owner(page, order, 0); 3107 pgalloc_tag_split(page_folio(page), order, 0); 3108 split_page_memcg(page, order); 3109 } 3110 3111 /* 3112 * split_page takes a non-compound higher-order page, and splits it into 3113 * n (1<<order) sub-pages: page[0..n] 3114 * Each sub-page must be freed individually. 3115 * 3116 * Note: this is probably too low level an operation for use in drivers. 3117 * Please consult with lkml before using this in your driver. 3118 */ 3119 void split_page(struct page *page, unsigned int order) 3120 { 3121 int i; 3122 3123 VM_WARN_ON_PAGE(!page_count(page), page); 3124 3125 for (i = 1; i < (1 << order); i++) 3126 set_page_refcounted(page + i); 3127 3128 __split_page(page, order); 3129 } 3130 EXPORT_SYMBOL_GPL(split_page); 3131 3132 int __isolate_free_page(struct page *page, unsigned int order) 3133 { 3134 struct zone *zone = page_zone(page); 3135 int mt = get_pageblock_migratetype(page); 3136 3137 if (!is_migrate_isolate(mt)) { 3138 unsigned long watermark; 3139 /* 3140 * Obey watermarks as if the page was being allocated. We can 3141 * emulate a high-order watermark check with a raised order-0 3142 * watermark, because we already know our high-order page 3143 * exists. 3144 */ 3145 watermark = zone->_watermark[WMARK_MIN] + (1UL << order); 3146 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA)) 3147 return 0; 3148 } 3149 3150 del_page_from_free_list(page, zone, order, mt); 3151 3152 /* 3153 * Set the pageblock if the isolated page is at least half of a 3154 * pageblock 3155 */ 3156 if (order >= pageblock_order - 1) { 3157 struct page *endpage = page + (1 << order) - 1; 3158 for (; page < endpage; page += pageblock_nr_pages) { 3159 int mt = get_pageblock_migratetype(page); 3160 /* 3161 * Only change normal pageblocks (i.e., they can merge 3162 * with others) 3163 */ 3164 if (migratetype_is_mergeable(mt)) 3165 move_freepages_block(zone, page, mt, 3166 MIGRATE_MOVABLE); 3167 } 3168 } 3169 3170 return 1UL << order; 3171 } 3172 3173 /** 3174 * __putback_isolated_page - Return a now-isolated page back where we got it 3175 * @page: Page that was isolated 3176 * @order: Order of the isolated page 3177 * @mt: The page's pageblock's migratetype 3178 * 3179 * This function is meant to return a page pulled from the free lists via 3180 * __isolate_free_page back to the free lists they were pulled from. 3181 */ 3182 void __putback_isolated_page(struct page *page, unsigned int order, int mt) 3183 { 3184 struct zone *zone = page_zone(page); 3185 3186 /* zone lock should be held when this function is called */ 3187 lockdep_assert_held(&zone->lock); 3188 3189 /* Return isolated page to tail of freelist. */ 3190 __free_one_page(page, page_to_pfn(page), zone, order, mt, 3191 FPI_SKIP_REPORT_NOTIFY | FPI_TO_TAIL); 3192 } 3193 3194 /* 3195 * Update NUMA hit/miss statistics 3196 */ 3197 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z, 3198 long nr_account) 3199 { 3200 #ifdef CONFIG_NUMA 3201 enum numa_stat_item local_stat = NUMA_LOCAL; 3202 3203 /* skip numa counters update if numa stats is disabled */ 3204 if (!static_branch_likely(&vm_numa_stat_key)) 3205 return; 3206 3207 if (zone_to_nid(z) != numa_node_id()) 3208 local_stat = NUMA_OTHER; 3209 3210 if (zone_to_nid(z) == zone_to_nid(preferred_zone)) 3211 __count_numa_events(z, NUMA_HIT, nr_account); 3212 else { 3213 __count_numa_events(z, NUMA_MISS, nr_account); 3214 __count_numa_events(preferred_zone, NUMA_FOREIGN, nr_account); 3215 } 3216 __count_numa_events(z, local_stat, nr_account); 3217 #endif 3218 } 3219 3220 static __always_inline 3221 struct page *rmqueue_buddy(struct zone *preferred_zone, struct zone *zone, 3222 unsigned int order, unsigned int alloc_flags, 3223 int migratetype) 3224 { 3225 struct page *page; 3226 unsigned long flags; 3227 3228 do { 3229 page = NULL; 3230 if (unlikely(alloc_flags & ALLOC_NOLOCK)) { 3231 if (!spin_trylock_irqsave(&zone->lock, flags)) 3232 return NULL; 3233 } else { 3234 spin_lock_irqsave(&zone->lock, flags); 3235 } 3236 if (alloc_flags & ALLOC_HIGHATOMIC) 3237 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC); 3238 if (!page) { 3239 enum rmqueue_mode rmqm = RMQUEUE_NORMAL; 3240 3241 page = __rmqueue(zone, order, migratetype, alloc_flags, &rmqm); 3242 3243 /* 3244 * If the allocation fails, allow OOM handling and 3245 * order-0 (atomic) allocs access to HIGHATOMIC 3246 * reserves as failing now is worse than failing a 3247 * high-order atomic allocation in the future. 3248 */ 3249 if (!page && (alloc_flags & (ALLOC_OOM|ALLOC_NON_BLOCK))) 3250 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC); 3251 3252 if (!page) { 3253 spin_unlock_irqrestore(&zone->lock, flags); 3254 return NULL; 3255 } 3256 } 3257 spin_unlock_irqrestore(&zone->lock, flags); 3258 } while (check_new_pages(page, order)); 3259 3260 /* 3261 * Slowpath (precarious) high-atomic allocations may reserve 3262 * a pageblock for future use. 3263 */ 3264 if (unlikely((alloc_flags & ALLOC_HIGHATOMIC) && 3265 ((alloc_flags & ALLOC_WMARK_MASK) == ALLOC_WMARK_MIN))) 3266 reserve_highatomic_pageblock(page, order, zone); 3267 3268 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order); 3269 zone_statistics(preferred_zone, zone, 1); 3270 3271 return page; 3272 } 3273 3274 static int nr_pcp_alloc(struct per_cpu_pages *pcp, struct zone *zone, int order) 3275 { 3276 int high, base_batch, batch, max_nr_alloc; 3277 int high_max, high_min; 3278 3279 base_batch = READ_ONCE(pcp->batch); 3280 high_min = READ_ONCE(pcp->high_min); 3281 high_max = READ_ONCE(pcp->high_max); 3282 high = pcp->high = clamp(pcp->high, high_min, high_max); 3283 3284 /* Check for PCP disabled or boot pageset */ 3285 if (unlikely(high < base_batch)) 3286 return 1; 3287 3288 if (order) 3289 batch = base_batch; 3290 else 3291 batch = (base_batch << pcp->alloc_factor); 3292 3293 /* 3294 * If we had larger pcp->high, we could avoid to allocate from 3295 * zone. 3296 */ 3297 if (high_min != high_max && !test_bit(ZONE_BELOW_HIGH, &zone->flags)) 3298 high = pcp->high = min(high + batch, high_max); 3299 3300 if (!order) { 3301 max_nr_alloc = max(high - pcp->count - base_batch, base_batch); 3302 /* 3303 * Double the number of pages allocated each time there is 3304 * subsequent allocation of order-0 pages without any freeing. 3305 */ 3306 if (batch <= max_nr_alloc && 3307 pcp->alloc_factor < CONFIG_PCP_BATCH_SCALE_MAX) 3308 pcp->alloc_factor++; 3309 batch = min(batch, max_nr_alloc); 3310 } 3311 3312 /* 3313 * Scale batch relative to order if batch implies free pages 3314 * can be stored on the PCP. Batch can be 1 for small zones or 3315 * for boot pagesets which should never store free pages as 3316 * the pages may belong to arbitrary zones. 3317 */ 3318 if (batch > 1) 3319 batch = max(batch >> order, 2); 3320 3321 return batch; 3322 } 3323 3324 /* Remove page from the per-cpu list, caller must protect the list */ 3325 static inline 3326 struct page *__rmqueue_pcplist(struct zone *zone, unsigned int order, 3327 int migratetype, 3328 unsigned int alloc_flags, 3329 struct per_cpu_pages *pcp, 3330 struct list_head *list) 3331 { 3332 struct page *page; 3333 3334 do { 3335 if (list_empty(list)) { 3336 int batch = nr_pcp_alloc(pcp, zone, order); 3337 int alloced; 3338 3339 /* 3340 * Don't refill the list for a higher order atomic 3341 * allocation under memory pressure, as this would 3342 * not build up any HIGHATOMIC reserves, which 3343 * might be needed soon. 3344 * 3345 * Instead, direct it towards the reserves by 3346 * returning NULL, which will make the caller fall 3347 * back to rmqueue_buddy. This will try to use the 3348 * reserves first and grow them if needed. 3349 */ 3350 if (alloc_flags & ALLOC_HIGHATOMIC) 3351 return NULL; 3352 3353 alloced = rmqueue_bulk(zone, order, 3354 batch, list, 3355 migratetype, alloc_flags); 3356 3357 pcp->count += alloced << order; 3358 if (unlikely(list_empty(list))) 3359 return NULL; 3360 } 3361 3362 page = list_first_entry(list, struct page, pcp_list); 3363 list_del(&page->pcp_list); 3364 pcp->count -= 1 << order; 3365 } while (check_new_pages(page, order)); 3366 3367 return page; 3368 } 3369 3370 /* Lock and remove page from the per-cpu list */ 3371 static struct page *rmqueue_pcplist(struct zone *preferred_zone, 3372 struct zone *zone, unsigned int order, 3373 int migratetype, unsigned int alloc_flags) 3374 { 3375 struct per_cpu_pages *pcp; 3376 struct list_head *list; 3377 struct page *page; 3378 3379 /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */ 3380 pcp = pcp_spin_trylock(zone->per_cpu_pageset); 3381 if (!pcp) 3382 return NULL; 3383 3384 /* 3385 * On allocation, reduce the number of pages that are batch freed. 3386 * See nr_pcp_free() where free_factor is increased for subsequent 3387 * frees. 3388 */ 3389 pcp->free_count >>= 1; 3390 list = &pcp->lists[order_to_pindex(migratetype, order)]; 3391 page = __rmqueue_pcplist(zone, order, migratetype, alloc_flags, pcp, list); 3392 pcp_spin_unlock(pcp); 3393 if (page) { 3394 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order); 3395 zone_statistics(preferred_zone, zone, 1); 3396 } 3397 return page; 3398 } 3399 3400 /* 3401 * Allocate a page from the given zone. 3402 * Use pcplists for THP or "cheap" high-order allocations. 3403 */ 3404 3405 /* 3406 * Do not instrument rmqueue() with KMSAN. This function may call 3407 * __msan_poison_alloca() through a call to set_pfnblock_migratetype(). 3408 * If __msan_poison_alloca() attempts to allocate pages for the stack depot, it 3409 * may call rmqueue() again, which will result in a deadlock. 3410 */ 3411 __no_sanitize_memory 3412 static inline 3413 struct page *rmqueue(struct zone *preferred_zone, 3414 struct zone *zone, unsigned int order, 3415 gfp_t gfp_flags, unsigned int alloc_flags, 3416 int migratetype) 3417 { 3418 struct page *page; 3419 3420 if (likely(pcp_allowed_order(order))) { 3421 page = rmqueue_pcplist(preferred_zone, zone, order, 3422 migratetype, alloc_flags); 3423 if (likely(page)) 3424 goto out; 3425 } 3426 3427 page = rmqueue_buddy(preferred_zone, zone, order, alloc_flags, 3428 migratetype); 3429 3430 out: 3431 /* Separate test+clear to avoid unnecessary atomics */ 3432 if ((alloc_flags & ALLOC_KSWAPD) && 3433 unlikely(test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags))) { 3434 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags); 3435 wakeup_kswapd(zone, 0, 0, zone_idx(zone)); 3436 } 3437 3438 VM_BUG_ON_PAGE(page && bad_range(zone, page), page); 3439 return page; 3440 } 3441 3442 /* 3443 * Reserve the pageblock(s) surrounding an allocation request for 3444 * exclusive use of high-order atomic allocations if there are no 3445 * empty page blocks that contain a page with a suitable order 3446 */ 3447 static void reserve_highatomic_pageblock(struct page *page, int order, 3448 struct zone *zone) 3449 { 3450 int mt; 3451 unsigned long max_managed; 3452 3453 /* 3454 * The number reserved as: minimum is 1 pageblock, maximum is 3455 * roughly 1% of a zone. But if 1% of a zone falls below a 3456 * pageblock size, then don't reserve any pageblocks. 3457 * Check is race-prone but harmless. 3458 */ 3459 if ((zone_managed_pages(zone) / 100) < pageblock_nr_pages) 3460 return; 3461 max_managed = ALIGN((zone_managed_pages(zone) / 100), pageblock_nr_pages); 3462 if (zone->nr_reserved_highatomic >= max_managed) 3463 return; 3464 3465 guard(spinlock_irqsave)(&zone->lock); 3466 3467 /* Recheck the nr_reserved_highatomic limit under the lock */ 3468 if (zone->nr_reserved_highatomic >= max_managed) 3469 return; 3470 3471 /* Yoink! */ 3472 mt = get_pageblock_migratetype(page); 3473 /* Only reserve normal pageblocks (i.e., they can merge with others) */ 3474 if (!migratetype_is_mergeable(mt)) 3475 return; 3476 3477 if (order < pageblock_order) { 3478 if (move_freepages_block(zone, page, mt, MIGRATE_HIGHATOMIC) == -1) 3479 return; 3480 zone->nr_reserved_highatomic += pageblock_nr_pages; 3481 } else { 3482 change_pageblock_range(page, order, MIGRATE_HIGHATOMIC); 3483 zone->nr_reserved_highatomic += 1 << order; 3484 } 3485 } 3486 3487 /* 3488 * Used when an allocation is about to fail under memory pressure. This 3489 * potentially hurts the reliability of high-order allocations when under 3490 * intense memory pressure but failed atomic allocations should be easier 3491 * to recover from than an OOM. 3492 * 3493 * If @force is true, try to unreserve pageblocks even though highatomic 3494 * pageblock is exhausted. 3495 */ 3496 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac, 3497 bool force) 3498 { 3499 struct zonelist *zonelist = ac->zonelist; 3500 struct zoneref *z; 3501 struct zone *zone; 3502 struct page *page; 3503 int order; 3504 int ret; 3505 3506 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->highest_zoneidx, 3507 ac->nodemask) { 3508 /* 3509 * Preserve at least one pageblock unless memory pressure 3510 * is really high. 3511 */ 3512 if (!force && zone->nr_reserved_highatomic <= 3513 pageblock_nr_pages) 3514 continue; 3515 3516 guard(spinlock_irqsave)(&zone->lock); 3517 for (order = 0; order < NR_PAGE_ORDERS; order++) { 3518 struct free_area *area = &(zone->free_area[order]); 3519 unsigned long size; 3520 3521 page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC); 3522 if (!page) 3523 continue; 3524 3525 size = max(pageblock_nr_pages, 1UL << order); 3526 /* 3527 * It should never happen but changes to 3528 * locking could inadvertently allow a per-cpu 3529 * drain to add pages to MIGRATE_HIGHATOMIC 3530 * while unreserving so be safe and watch for 3531 * underflows. 3532 */ 3533 if (WARN_ON_ONCE(size > zone->nr_reserved_highatomic)) 3534 size = zone->nr_reserved_highatomic; 3535 zone->nr_reserved_highatomic -= size; 3536 3537 /* 3538 * Convert to ac->migratetype and avoid the normal 3539 * pageblock stealing heuristics. Minimally, the caller 3540 * is doing the work and needs the pages. More 3541 * importantly, if the block was always converted to 3542 * MIGRATE_UNMOVABLE or another type then the number 3543 * of pageblocks that cannot be completely freed 3544 * may increase. 3545 */ 3546 if (order < pageblock_order) 3547 ret = move_freepages_block(zone, page, 3548 MIGRATE_HIGHATOMIC, 3549 ac->migratetype); 3550 else { 3551 move_to_free_list(page, zone, order, 3552 MIGRATE_HIGHATOMIC, 3553 ac->migratetype); 3554 change_pageblock_range(page, order, 3555 ac->migratetype); 3556 ret = 1; 3557 } 3558 /* 3559 * Reserving the block(s) already succeeded, 3560 * so this should not fail on zone boundaries. 3561 */ 3562 WARN_ON_ONCE(ret == -1); 3563 if (ret > 0) 3564 return ret; 3565 } 3566 } 3567 3568 return false; 3569 } 3570 3571 static inline long __zone_watermark_unusable_free(struct zone *z, 3572 unsigned int order, unsigned int alloc_flags) 3573 { 3574 long unusable_free = (1 << order) - 1; 3575 3576 /* 3577 * If the caller does not have rights to reserves below the min 3578 * watermark then subtract the free pages reserved for highatomic. 3579 */ 3580 if (likely(!(alloc_flags & ALLOC_RESERVES))) 3581 unusable_free += READ_ONCE(z->nr_free_highatomic); 3582 3583 #ifdef CONFIG_CMA 3584 /* If allocation can't use CMA areas don't use free CMA pages */ 3585 if (!(alloc_flags & ALLOC_CMA)) 3586 unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES); 3587 #endif 3588 3589 return unusable_free; 3590 } 3591 3592 /* 3593 * Return true if free base pages are above 'mark'. For high-order checks it 3594 * will return true of the order-0 watermark is reached and there is at least 3595 * one free page of a suitable size. Checking now avoids taking the zone lock 3596 * to check in the allocation paths if no pages are free. 3597 */ 3598 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark, 3599 int highest_zoneidx, unsigned int alloc_flags, 3600 long free_pages) 3601 { 3602 long min = mark; 3603 int o; 3604 3605 /* free_pages may go negative - that's OK */ 3606 free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags); 3607 3608 if (unlikely(alloc_flags & ALLOC_RESERVES)) { 3609 /* 3610 * __GFP_HIGH allows access to 50% of the min reserve as well 3611 * as OOM. 3612 */ 3613 if (alloc_flags & ALLOC_MIN_RESERVE) { 3614 min -= min / 2; 3615 3616 /* 3617 * Non-blocking allocations (e.g. GFP_ATOMIC) can 3618 * access more reserves than just __GFP_HIGH. Other 3619 * non-blocking allocations requests such as GFP_NOWAIT 3620 * or (GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) do not get 3621 * access to the min reserve. 3622 */ 3623 if (alloc_flags & ALLOC_NON_BLOCK) 3624 min -= min / 4; 3625 } 3626 3627 /* 3628 * OOM victims can try even harder than the normal reserve 3629 * users on the grounds that it's definitely going to be in 3630 * the exit path shortly and free memory. Any allocation it 3631 * makes during the free path will be small and short-lived. 3632 */ 3633 if (alloc_flags & ALLOC_OOM) 3634 min -= min / 2; 3635 } 3636 3637 /* 3638 * Check watermarks for an order-0 allocation request. If these 3639 * are not met, then a high-order request also cannot go ahead 3640 * even if a suitable page happened to be free. 3641 */ 3642 if (free_pages <= min + z->lowmem_reserve[highest_zoneidx]) 3643 return false; 3644 3645 /* If this is an order-0 request then the watermark is fine */ 3646 if (!order) 3647 return true; 3648 3649 /* For a high-order request, check at least one suitable page is free */ 3650 for (o = order; o < NR_PAGE_ORDERS; o++) { 3651 struct free_area *area = &z->free_area[o]; 3652 int mt; 3653 3654 if (!area->nr_free) 3655 continue; 3656 3657 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) { 3658 if (!free_area_empty(area, mt)) 3659 return true; 3660 } 3661 3662 #ifdef CONFIG_CMA 3663 if ((alloc_flags & ALLOC_CMA) && 3664 !free_area_empty(area, MIGRATE_CMA)) { 3665 return true; 3666 } 3667 #endif 3668 if ((alloc_flags & (ALLOC_HIGHATOMIC|ALLOC_OOM)) && 3669 !free_area_empty(area, MIGRATE_HIGHATOMIC)) { 3670 return true; 3671 } 3672 } 3673 return false; 3674 } 3675 3676 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark, 3677 int highest_zoneidx, unsigned int alloc_flags) 3678 { 3679 return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags, 3680 zone_page_state(z, NR_FREE_PAGES)); 3681 } 3682 3683 static inline bool zone_watermark_fast(struct zone *z, unsigned int order, 3684 unsigned long mark, int highest_zoneidx, 3685 unsigned int alloc_flags, gfp_t gfp_mask) 3686 { 3687 long free_pages; 3688 3689 free_pages = zone_page_state(z, NR_FREE_PAGES); 3690 3691 /* 3692 * Fast check for order-0 only. If this fails then the reserves 3693 * need to be calculated. 3694 */ 3695 if (!order) { 3696 long usable_free; 3697 long reserved; 3698 3699 usable_free = free_pages; 3700 reserved = __zone_watermark_unusable_free(z, 0, alloc_flags); 3701 3702 /* reserved may over estimate high-atomic reserves. */ 3703 usable_free -= min(usable_free, reserved); 3704 if (usable_free > mark + z->lowmem_reserve[highest_zoneidx]) 3705 return true; 3706 } 3707 3708 if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags, 3709 free_pages)) 3710 return true; 3711 3712 /* 3713 * Ignore watermark boosting for __GFP_HIGH order-0 allocations 3714 * when checking the min watermark. The min watermark is the 3715 * point where boosting is ignored so that kswapd is woken up 3716 * when below the low watermark. 3717 */ 3718 if (unlikely(!order && (alloc_flags & ALLOC_MIN_RESERVE) && z->watermark_boost 3719 && ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) { 3720 mark = z->_watermark[WMARK_MIN]; 3721 return __zone_watermark_ok(z, order, mark, highest_zoneidx, 3722 alloc_flags, free_pages); 3723 } 3724 3725 return false; 3726 } 3727 3728 #ifdef CONFIG_NUMA 3729 int __read_mostly node_reclaim_distance = RECLAIM_DISTANCE; 3730 3731 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone) 3732 { 3733 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <= 3734 node_reclaim_distance; 3735 } 3736 #else /* CONFIG_NUMA */ 3737 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone) 3738 { 3739 return true; 3740 } 3741 #endif /* CONFIG_NUMA */ 3742 3743 /* 3744 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid 3745 * fragmentation is subtle. If the preferred zone was HIGHMEM then 3746 * premature use of a lower zone may cause lowmem pressure problems that 3747 * are worse than fragmentation. If the next zone is ZONE_DMA then it is 3748 * probably too small. It only makes sense to spread allocations to avoid 3749 * fragmentation between the Normal and DMA32 zones. 3750 */ 3751 static inline unsigned int 3752 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask) 3753 { 3754 unsigned int alloc_flags = 0; 3755 3756 if (gfp_mask & __GFP_KSWAPD_RECLAIM) 3757 alloc_flags |= ALLOC_KSWAPD; 3758 3759 if (defrag_mode) { 3760 alloc_flags |= ALLOC_NOFRAGMENT; 3761 return alloc_flags; 3762 } 3763 3764 #ifdef CONFIG_ZONE_DMA32 3765 if (!zone) 3766 return alloc_flags; 3767 3768 if (zone_idx(zone) != ZONE_NORMAL) 3769 return alloc_flags; 3770 3771 /* 3772 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and 3773 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume 3774 * on UMA that if Normal is populated then so is DMA32. 3775 */ 3776 BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1); 3777 if (nr_online_nodes > 1 && !populated_zone(--zone)) 3778 return alloc_flags; 3779 3780 alloc_flags |= ALLOC_NOFRAGMENT; 3781 #endif /* CONFIG_ZONE_DMA32 */ 3782 return alloc_flags; 3783 } 3784 3785 /* Must be called after current_gfp_context() which can change gfp_mask */ 3786 static inline unsigned int alloc_flags_cma(gfp_t gfp_mask) 3787 { 3788 #ifdef CONFIG_CMA 3789 if (gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE) 3790 return ALLOC_CMA; 3791 #endif 3792 return ALLOC_DEFAULT; 3793 } 3794 3795 /* 3796 * get_page_from_freelist goes through the zonelist trying to allocate 3797 * a page. 3798 */ 3799 static struct page * 3800 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, 3801 const struct alloc_context *ac) 3802 { 3803 struct zoneref *z; 3804 struct zone *zone; 3805 struct pglist_data *last_pgdat = NULL; 3806 bool last_pgdat_dirty_ok = false; 3807 bool no_fallback; 3808 bool skip_kswapd_nodes = nr_online_nodes > 1; 3809 bool skipped_kswapd_nodes = false; 3810 3811 retry: 3812 /* 3813 * Scan zonelist, looking for a zone with enough free. 3814 * See also cpuset_current_node_allowed() comment in kernel/cgroup/cpuset.c. 3815 */ 3816 no_fallback = alloc_flags & ALLOC_NOFRAGMENT; 3817 z = ac->preferred_zoneref; 3818 for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx, 3819 ac->nodemask) { 3820 struct page *page; 3821 unsigned long mark; 3822 3823 if (cpusets_enabled() && 3824 (alloc_flags & ALLOC_CPUSET) && 3825 !__cpuset_zone_allowed(zone, gfp_mask)) 3826 continue; 3827 /* 3828 * When allocating a page cache page for writing, we 3829 * want to get it from a node that is within its dirty 3830 * limit, such that no single node holds more than its 3831 * proportional share of globally allowed dirty pages. 3832 * The dirty limits take into account the node's 3833 * lowmem reserves and high watermark so that kswapd 3834 * should be able to balance it without having to 3835 * write pages from its LRU list. 3836 * 3837 * XXX: For now, allow allocations to potentially 3838 * exceed the per-node dirty limit in the slowpath 3839 * (spread_dirty_pages unset) before going into reclaim, 3840 * which is important when on a NUMA setup the allowed 3841 * nodes are together not big enough to reach the 3842 * global limit. The proper fix for these situations 3843 * will require awareness of nodes in the 3844 * dirty-throttling and the flusher threads. 3845 */ 3846 if (ac->spread_dirty_pages) { 3847 if (last_pgdat != zone->zone_pgdat) { 3848 last_pgdat = zone->zone_pgdat; 3849 last_pgdat_dirty_ok = node_dirty_ok(zone->zone_pgdat); 3850 } 3851 3852 if (!last_pgdat_dirty_ok) 3853 continue; 3854 } 3855 3856 if (no_fallback && !defrag_mode && nr_online_nodes > 1 && 3857 zone != zonelist_zone(ac->preferred_zoneref)) { 3858 int local_nid; 3859 3860 /* 3861 * If moving to a remote node, retry but allow 3862 * fragmenting fallbacks. Locality is more important 3863 * than fragmentation avoidance. 3864 */ 3865 local_nid = zonelist_node_idx(ac->preferred_zoneref); 3866 if (zone_to_nid(zone) != local_nid) { 3867 alloc_flags &= ~ALLOC_NOFRAGMENT; 3868 goto retry; 3869 } 3870 } 3871 3872 /* 3873 * If kswapd is already active on a node, keep looking 3874 * for other nodes that might be idle. This can happen 3875 * if another process has NUMA bindings and is causing 3876 * kswapd wakeups on only some nodes. Avoid accidental 3877 * "node_reclaim_mode"-like behavior in this case. 3878 */ 3879 if (skip_kswapd_nodes && 3880 !waitqueue_active(&zone->zone_pgdat->kswapd_wait)) { 3881 skipped_kswapd_nodes = true; 3882 continue; 3883 } 3884 3885 cond_accept_memory(zone, order, alloc_flags); 3886 3887 /* 3888 * Detect whether the number of free pages is below high 3889 * watermark. If so, we will decrease pcp->high and free 3890 * PCP pages in free path to reduce the possibility of 3891 * premature page reclaiming. Detection is done here to 3892 * avoid to do that in hotter free path. 3893 */ 3894 if (test_bit(ZONE_BELOW_HIGH, &zone->flags)) 3895 goto check_alloc_wmark; 3896 3897 mark = high_wmark_pages(zone); 3898 if (zone_watermark_fast(zone, order, mark, 3899 ac->highest_zoneidx, alloc_flags, 3900 gfp_mask)) 3901 goto try_this_zone; 3902 else 3903 set_bit(ZONE_BELOW_HIGH, &zone->flags); 3904 3905 check_alloc_wmark: 3906 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK); 3907 if (!zone_watermark_fast(zone, order, mark, 3908 ac->highest_zoneidx, alloc_flags, 3909 gfp_mask)) { 3910 if (cond_accept_memory(zone, order, alloc_flags)) 3911 goto try_this_zone; 3912 3913 /* 3914 * Watermark failed for this zone, but see if we can 3915 * grow this zone if it contains deferred pages. 3916 */ 3917 if (deferred_pages_enabled()) { 3918 if (_deferred_grow_zone(zone, order)) 3919 goto try_this_zone; 3920 } 3921 /* Checked here to keep the fast path fast */ 3922 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK); 3923 if (alloc_flags & ALLOC_NO_WATERMARKS) 3924 goto try_this_zone; 3925 3926 if (!node_reclaim_enabled() || 3927 !zone_allows_reclaim(zonelist_zone(ac->preferred_zoneref), zone)) 3928 continue; 3929 3930 if (!node_reclaim(zone->zone_pgdat, gfp_mask, order)) 3931 continue; 3932 3933 /* did we reclaim enough */ 3934 if (!zone_watermark_ok(zone, order, mark, 3935 ac->highest_zoneidx, alloc_flags)) 3936 continue; 3937 } 3938 3939 try_this_zone: 3940 page = rmqueue(zonelist_zone(ac->preferred_zoneref), zone, order, 3941 gfp_mask, alloc_flags, ac->migratetype); 3942 if (page) { 3943 prep_new_page(page, order, gfp_mask, alloc_flags); 3944 3945 return page; 3946 } else { 3947 if (cond_accept_memory(zone, order, alloc_flags)) 3948 goto try_this_zone; 3949 3950 /* Try again if zone has deferred pages */ 3951 if (deferred_pages_enabled()) { 3952 if (_deferred_grow_zone(zone, order)) 3953 goto try_this_zone; 3954 } 3955 } 3956 } 3957 3958 /* 3959 * If we skipped over nodes with active kswapds and found no 3960 * idle nodes, retry and place anywhere the watermarks permit. 3961 */ 3962 if (skip_kswapd_nodes && skipped_kswapd_nodes) { 3963 skip_kswapd_nodes = false; 3964 goto retry; 3965 } 3966 3967 /* 3968 * It's possible on a UMA machine to get through all zones that are 3969 * fragmented. If avoiding fragmentation, reset and try again. 3970 */ 3971 if (no_fallback && !defrag_mode) { 3972 alloc_flags &= ~ALLOC_NOFRAGMENT; 3973 goto retry; 3974 } 3975 3976 return NULL; 3977 } 3978 3979 static void warn_alloc_show_mem(gfp_t gfp_mask, const nodemask_t *nodemask) 3980 { 3981 unsigned int filter = SHOW_MEM_FILTER_NODES; 3982 3983 /* 3984 * This documents exceptions given to allocations in certain 3985 * contexts that are allowed to allocate outside current's set 3986 * of allowed nodes. 3987 */ 3988 if (!(gfp_mask & __GFP_NOMEMALLOC)) 3989 if (tsk_is_oom_victim(current) || 3990 (current->flags & (PF_MEMALLOC | PF_EXITING))) 3991 filter &= ~SHOW_MEM_FILTER_NODES; 3992 if (!in_task() || !(gfp_mask & __GFP_DIRECT_RECLAIM)) 3993 filter &= ~SHOW_MEM_FILTER_NODES; 3994 3995 __show_mem(filter, nodemask, gfp_zone(gfp_mask)); 3996 mem_cgroup_show_protected_memory(NULL); 3997 } 3998 3999 void warn_alloc(gfp_t gfp_mask, const nodemask_t *nodemask, const char *fmt, ...) 4000 { 4001 struct va_format vaf; 4002 va_list args; 4003 static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1); 4004 4005 if ((gfp_mask & __GFP_NOWARN) || 4006 !__ratelimit(&nopage_rs) || 4007 ((gfp_mask & __GFP_DMA) && !has_managed_dma())) 4008 return; 4009 4010 va_start(args, fmt); 4011 vaf.fmt = fmt; 4012 vaf.va = &args; 4013 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl", 4014 current->comm, &vaf, gfp_mask, &gfp_mask, 4015 nodemask_pr_args(nodemask)); 4016 va_end(args); 4017 4018 cpuset_print_current_mems_allowed(); 4019 pr_cont("\n"); 4020 dump_stack(); 4021 warn_alloc_show_mem(gfp_mask, nodemask); 4022 } 4023 4024 static inline struct page * 4025 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order, 4026 unsigned int alloc_flags, 4027 const struct alloc_context *ac) 4028 { 4029 struct page *page; 4030 4031 page = get_page_from_freelist(gfp_mask, order, 4032 alloc_flags|ALLOC_CPUSET, ac); 4033 /* 4034 * fallback to ignore cpuset restriction if our nodes 4035 * are depleted 4036 */ 4037 if (!page) 4038 page = get_page_from_freelist(gfp_mask, order, 4039 alloc_flags, ac); 4040 return page; 4041 } 4042 4043 static inline struct page * 4044 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order, 4045 const struct alloc_context *ac, unsigned long *did_some_progress) 4046 { 4047 struct oom_control oc = { 4048 .zonelist = ac->zonelist, 4049 .nodemask = ac->nodemask, 4050 .memcg = NULL, 4051 .gfp_mask = gfp_mask, 4052 .order = order, 4053 }; 4054 struct page *page; 4055 4056 *did_some_progress = 0; 4057 4058 /* 4059 * Acquire the oom lock. If that fails, somebody else is 4060 * making progress for us. 4061 */ 4062 if (!mutex_trylock(&oom_lock)) { 4063 *did_some_progress = 1; 4064 schedule_timeout_uninterruptible(1); 4065 return NULL; 4066 } 4067 4068 /* 4069 * Go through the zonelist yet one more time, keep very high watermark 4070 * here, this is only to catch a parallel oom killing, we must fail if 4071 * we're still under heavy pressure. But make sure that this reclaim 4072 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY 4073 * allocation which will never fail due to oom_lock already held. 4074 */ 4075 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) & 4076 ~__GFP_DIRECT_RECLAIM, order, 4077 ac->alloc_flags|ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac); 4078 if (page) 4079 goto out; 4080 4081 /* Coredumps can quickly deplete all memory reserves */ 4082 if (current->flags & PF_DUMPCORE) 4083 goto out; 4084 /* The OOM killer will not help higher order allocs */ 4085 if (order > PAGE_ALLOC_COSTLY_ORDER) 4086 goto out; 4087 /* 4088 * We have already exhausted all our reclaim opportunities without any 4089 * success so it is time to admit defeat. We will skip the OOM killer 4090 * because it is very likely that the caller has a more reasonable 4091 * fallback than shooting a random task. 4092 * 4093 * The OOM killer may not free memory on a specific node. 4094 */ 4095 if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE)) 4096 goto out; 4097 /* The OOM killer does not needlessly kill tasks for lowmem */ 4098 if (ac->highest_zoneidx < ZONE_NORMAL) 4099 goto out; 4100 if (pm_suspended_storage()) 4101 goto out; 4102 /* 4103 * XXX: GFP_NOFS allocations should rather fail than rely on 4104 * other request to make a forward progress. 4105 * We are in an unfortunate situation where out_of_memory cannot 4106 * do much for this context but let's try it to at least get 4107 * access to memory reserved if the current task is killed (see 4108 * out_of_memory). Once filesystems are ready to handle allocation 4109 * failures more gracefully we should just bail out here. 4110 */ 4111 4112 /* Exhausted what can be done so it's blame time */ 4113 if (out_of_memory(&oc) || 4114 WARN_ON_ONCE_GFP(gfp_mask & __GFP_NOFAIL, gfp_mask)) { 4115 *did_some_progress = 1; 4116 4117 /* 4118 * Help non-failing allocations by giving them access to memory 4119 * reserves 4120 */ 4121 if (gfp_mask & __GFP_NOFAIL) 4122 page = __alloc_pages_cpuset_fallback(gfp_mask, order, 4123 ac->alloc_flags|ALLOC_NO_WATERMARKS, ac); 4124 } 4125 out: 4126 mutex_unlock(&oom_lock); 4127 return page; 4128 } 4129 4130 /* 4131 * Maximum number of compaction retries with a progress before OOM 4132 * killer is consider as the only way to move forward. 4133 */ 4134 #define MAX_COMPACT_RETRIES 16 4135 4136 #ifdef CONFIG_COMPACTION 4137 /* Try memory compaction for high-order allocations before reclaim */ 4138 static struct page * 4139 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order, 4140 unsigned int alloc_flags, const struct alloc_context *ac, 4141 enum compact_priority prio, enum compact_result *compact_result) 4142 { 4143 struct page *page = NULL; 4144 unsigned long pflags; 4145 unsigned int noreclaim_flag; 4146 struct capture_control capc = { 4147 .zone = NULL, 4148 .migratetype = ac->migratetype, 4149 .order = order, 4150 .page = NULL, 4151 }; 4152 int compact_order = order; 4153 4154 /* 4155 * If fallbacks are not permitted (defrag_mode), we either 4156 * need to reclaim space in a block of matching type, or clear 4157 * out an entire block to allow __rmqueue_claim() to convert. 4158 * 4159 * Reclaim by itself is primarily freeing space in movable 4160 * blocks, since that's where the LRU pages live. So this 4161 * works for movable requests, but not for others. 4162 * 4163 * For those, promote the order to help make blocks, instead 4164 * of spinning in reclaim alone unproductively. 4165 */ 4166 if ((alloc_flags & ALLOC_NOFRAGMENT) && ac->migratetype != MIGRATE_MOVABLE) 4167 compact_order = max(order, pageblock_order); 4168 4169 if (!compact_order) 4170 return NULL; 4171 4172 psi_memstall_enter(&pflags); 4173 delayacct_compact_start(); 4174 fs_reclaim_acquire(gfp_mask); 4175 noreclaim_flag = memalloc_noreclaim_save(); 4176 4177 /* 4178 * Make sure the structs are really initialized before we expose the 4179 * capture control, in case we are interrupted and the interrupt handler 4180 * frees a page. 4181 */ 4182 barrier(); 4183 WRITE_ONCE(current->capture_control, &capc); 4184 4185 *compact_result = try_to_compact_pages(gfp_mask, compact_order, 4186 alloc_flags, ac, prio, &capc); 4187 4188 /* 4189 * Make sure we hide capture control first before we read the captured 4190 * page pointer, otherwise an interrupt could free and capture a page 4191 * and we would leak it. 4192 */ 4193 WRITE_ONCE(current->capture_control, NULL); 4194 page = READ_ONCE(capc.page); 4195 4196 /* 4197 * Technically, it is also possible that compaction is skipped but 4198 * the page is still captured out of luck(IRQ came and freed the page). 4199 * Returning COMPACT_SUCCESS in such cases helps in properly accounting 4200 * the COMPACT[STALL|FAIL] when compaction is skipped. 4201 */ 4202 if (page) 4203 *compact_result = COMPACT_SUCCESS; 4204 4205 memalloc_noreclaim_restore(noreclaim_flag); 4206 fs_reclaim_release(gfp_mask); 4207 psi_memstall_leave(&pflags); 4208 delayacct_compact_end(); 4209 4210 if (*compact_result == COMPACT_SKIPPED || 4211 *compact_result == COMPACT_DEFERRED) 4212 return NULL; 4213 /* 4214 * At least in one zone compaction wasn't deferred or skipped, so let's 4215 * count a compaction stall 4216 */ 4217 count_vm_event(COMPACTSTALL); 4218 4219 /* Prep a captured page if available */ 4220 if (page) 4221 prep_new_page(page, order, gfp_mask, alloc_flags); 4222 4223 /* Try get a page from the freelist if available */ 4224 if (!page) 4225 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 4226 4227 if (page) { 4228 struct zone *zone = page_zone(page); 4229 4230 zone->compact_blockskip_flush = false; 4231 compaction_defer_reset(zone, compact_order, true); 4232 count_vm_event(COMPACTSUCCESS); 4233 return page; 4234 } 4235 4236 /* 4237 * It's bad if compaction run occurs and fails. The most likely reason 4238 * is that pages exist, but not enough to satisfy watermarks. 4239 */ 4240 count_vm_event(COMPACTFAIL); 4241 4242 cond_resched(); 4243 4244 return NULL; 4245 } 4246 4247 static inline bool 4248 should_compact_retry(gfp_t gfp_mask, struct alloc_context *ac, int order, 4249 int alloc_flags, 4250 enum compact_result compact_result, 4251 enum compact_priority *compact_priority, 4252 int *compaction_retries) 4253 { 4254 int max_retries = MAX_COMPACT_RETRIES; 4255 int min_priority; 4256 bool ret = false; 4257 int retries = *compaction_retries; 4258 enum compact_priority priority = *compact_priority; 4259 4260 if (!order) 4261 return false; 4262 4263 if (fatal_signal_pending(current)) 4264 return false; 4265 4266 /* 4267 * Compaction was skipped due to a lack of free order-0 4268 * migration targets. Continue if reclaim can help. 4269 */ 4270 if (compact_result == COMPACT_SKIPPED) { 4271 ret = compaction_zonelist_suitable(ac, order, alloc_flags, 4272 gfp_mask); 4273 goto out; 4274 } 4275 4276 /* 4277 * Compaction managed to coalesce some page blocks, but the 4278 * allocation failed presumably due to a race. Retry some. 4279 */ 4280 if (compact_result == COMPACT_SUCCESS) { 4281 /* 4282 * !costly requests are much more important than 4283 * __GFP_RETRY_MAYFAIL costly ones because they are de 4284 * facto nofail and invoke OOM killer to move on while 4285 * costly can fail and users are ready to cope with 4286 * that. 1/4 retries is rather arbitrary but we would 4287 * need much more detailed feedback from compaction to 4288 * make a better decision. 4289 */ 4290 if (order > PAGE_ALLOC_COSTLY_ORDER) 4291 max_retries /= 4; 4292 4293 if (++(*compaction_retries) <= max_retries) { 4294 ret = true; 4295 goto out; 4296 } 4297 } 4298 4299 /* 4300 * Compaction failed. Retry with increasing priority. 4301 */ 4302 min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ? 4303 MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY; 4304 4305 if (*compact_priority > min_priority) { 4306 (*compact_priority)--; 4307 *compaction_retries = 0; 4308 ret = true; 4309 } 4310 out: 4311 trace_compact_retry(order, priority, compact_result, retries, max_retries, ret); 4312 return ret; 4313 } 4314 #else 4315 static inline struct page * 4316 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order, 4317 unsigned int alloc_flags, const struct alloc_context *ac, 4318 enum compact_priority prio, enum compact_result *compact_result) 4319 { 4320 *compact_result = COMPACT_SKIPPED; 4321 return NULL; 4322 } 4323 4324 static inline bool 4325 should_compact_retry(gfp_t gfp_mask, struct alloc_context *ac, int order, 4326 int alloc_flags, 4327 enum compact_result compact_result, 4328 enum compact_priority *compact_priority, 4329 int *compaction_retries) 4330 { 4331 struct zone *zone; 4332 struct zoneref *z; 4333 4334 if (!order || order > PAGE_ALLOC_COSTLY_ORDER) 4335 return false; 4336 4337 /* 4338 * There are setups with compaction disabled which would prefer to loop 4339 * inside the allocator rather than hit the oom killer prematurely. 4340 * Let's give them a good hope and keep retrying while the order-0 4341 * watermarks are OK. 4342 */ 4343 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, 4344 ac->highest_zoneidx, ac->nodemask) { 4345 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone), 4346 ac->highest_zoneidx, alloc_flags)) 4347 return true; 4348 } 4349 return false; 4350 } 4351 #endif /* CONFIG_COMPACTION */ 4352 4353 #ifdef CONFIG_LOCKDEP 4354 static struct lockdep_map __fs_reclaim_map = 4355 STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map); 4356 4357 static bool __need_reclaim(gfp_t gfp_mask) 4358 { 4359 /* no reclaim without waiting on it */ 4360 if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) 4361 return false; 4362 4363 /* this guy won't enter reclaim */ 4364 if (current->flags & PF_MEMALLOC) 4365 return false; 4366 4367 if (gfp_mask & __GFP_NOLOCKDEP) 4368 return false; 4369 4370 return true; 4371 } 4372 4373 void __fs_reclaim_acquire(unsigned long ip) 4374 { 4375 lock_acquire_exclusive(&__fs_reclaim_map, 0, 0, NULL, ip); 4376 } 4377 4378 void __fs_reclaim_release(unsigned long ip) 4379 { 4380 lock_release(&__fs_reclaim_map, ip); 4381 } 4382 4383 void fs_reclaim_acquire(gfp_t gfp_mask) 4384 { 4385 gfp_mask = current_gfp_context(gfp_mask); 4386 4387 if (__need_reclaim(gfp_mask)) { 4388 if (gfp_mask & __GFP_FS) 4389 __fs_reclaim_acquire(_RET_IP_); 4390 4391 #ifdef CONFIG_MMU_NOTIFIER 4392 lock_map_acquire(&__mmu_notifier_invalidate_range_start_map); 4393 lock_map_release(&__mmu_notifier_invalidate_range_start_map); 4394 #endif 4395 4396 } 4397 } 4398 EXPORT_SYMBOL_GPL(fs_reclaim_acquire); 4399 4400 void fs_reclaim_release(gfp_t gfp_mask) 4401 { 4402 gfp_mask = current_gfp_context(gfp_mask); 4403 4404 if (__need_reclaim(gfp_mask)) { 4405 if (gfp_mask & __GFP_FS) 4406 __fs_reclaim_release(_RET_IP_); 4407 } 4408 } 4409 EXPORT_SYMBOL_GPL(fs_reclaim_release); 4410 #endif 4411 4412 /* 4413 * Zonelists may change due to hotplug during allocation. Detect when zonelists 4414 * have been rebuilt so allocation retries. Reader side does not lock and 4415 * retries the allocation if zonelist changes. Writer side is protected by the 4416 * embedded spin_lock. 4417 */ 4418 static DEFINE_SEQLOCK(zonelist_update_seq); 4419 4420 static unsigned int zonelist_iter_begin(void) 4421 { 4422 if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) 4423 return read_seqbegin(&zonelist_update_seq); 4424 4425 return 0; 4426 } 4427 4428 static unsigned int check_retry_zonelist(unsigned int seq) 4429 { 4430 if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) 4431 return read_seqretry(&zonelist_update_seq, seq); 4432 4433 return seq; 4434 } 4435 4436 /* Perform direct synchronous page reclaim */ 4437 static unsigned long 4438 __perform_reclaim(gfp_t gfp_mask, unsigned int order, 4439 const struct alloc_context *ac) 4440 { 4441 unsigned int noreclaim_flag; 4442 unsigned long progress; 4443 4444 cond_resched(); 4445 4446 /* We now go into synchronous reclaim */ 4447 cpuset_memory_pressure_bump(); 4448 fs_reclaim_acquire(gfp_mask); 4449 noreclaim_flag = memalloc_noreclaim_save(); 4450 4451 progress = try_to_free_pages(ac->zonelist, order, gfp_mask, 4452 ac->nodemask); 4453 4454 memalloc_noreclaim_restore(noreclaim_flag); 4455 fs_reclaim_release(gfp_mask); 4456 4457 cond_resched(); 4458 4459 return progress; 4460 } 4461 4462 /* The really slow allocator path where we enter direct reclaim */ 4463 static inline struct page * 4464 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order, 4465 unsigned int alloc_flags, const struct alloc_context *ac, 4466 unsigned long *did_some_progress) 4467 { 4468 struct page *page = NULL; 4469 unsigned long pflags; 4470 bool drained = false; 4471 int reclaim_order = order; 4472 4473 /* Match the slowpath compaction promotion in __alloc_pages_direct_compact */ 4474 if ((alloc_flags & ALLOC_NOFRAGMENT) && ac->migratetype != MIGRATE_MOVABLE) 4475 reclaim_order = max(order, pageblock_order); 4476 4477 psi_memstall_enter(&pflags); 4478 *did_some_progress = __perform_reclaim(gfp_mask, reclaim_order, ac); 4479 if (unlikely(!(*did_some_progress))) 4480 goto out; 4481 4482 retry: 4483 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 4484 4485 /* 4486 * If an allocation failed after direct reclaim, it could be because 4487 * pages are pinned on the per-cpu lists or in high alloc reserves. 4488 * Shrink them and try again 4489 */ 4490 if (!page && !drained) { 4491 unreserve_highatomic_pageblock(ac, false); 4492 drain_all_pages(NULL); 4493 drained = true; 4494 goto retry; 4495 } 4496 out: 4497 psi_memstall_leave(&pflags); 4498 4499 return page; 4500 } 4501 4502 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask, 4503 const struct alloc_context *ac) 4504 { 4505 struct zoneref *z; 4506 struct zone *zone; 4507 pg_data_t *last_pgdat = NULL; 4508 enum zone_type highest_zoneidx = ac->highest_zoneidx; 4509 unsigned int reclaim_order; 4510 4511 if (defrag_mode) 4512 reclaim_order = max(order, pageblock_order); 4513 else 4514 reclaim_order = order; 4515 4516 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx, 4517 ac->nodemask) { 4518 if (!managed_zone(zone)) 4519 continue; 4520 if (last_pgdat == zone->zone_pgdat) 4521 continue; 4522 wakeup_kswapd(zone, gfp_mask, reclaim_order, highest_zoneidx); 4523 last_pgdat = zone->zone_pgdat; 4524 } 4525 } 4526 4527 static inline unsigned int 4528 alloc_flags_nonblocking(gfp_t gfp_mask, unsigned int order) 4529 { 4530 unsigned int alloc_flags = 0; 4531 4532 if (gfp_mask & __GFP_DIRECT_RECLAIM) 4533 return 0; 4534 4535 /* 4536 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even 4537 * if it can't schedule. 4538 */ 4539 if (gfp_mask & __GFP_NOMEMALLOC) 4540 return 0; 4541 4542 alloc_flags |= ALLOC_NON_BLOCK; 4543 4544 if (order > 0 && (gfp_mask & __GFP_HIGH)) 4545 alloc_flags |= ALLOC_HIGHATOMIC; 4546 4547 return alloc_flags; 4548 } 4549 4550 static inline unsigned int 4551 alloc_flags_slowpath(gfp_t gfp_mask, unsigned int order) 4552 { 4553 unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET; 4554 4555 /* 4556 * The caller may dip into page reserves a bit more if the caller 4557 * cannot run direct reclaim, or if the caller has realtime scheduling 4558 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will 4559 * set both ALLOC_NON_BLOCK and ALLOC_MIN_RESERVE(__GFP_HIGH). 4560 */ 4561 if (gfp_mask & __GFP_HIGH) 4562 alloc_flags |= ALLOC_MIN_RESERVE; 4563 if (gfp_mask & __GFP_KSWAPD_RECLAIM) 4564 alloc_flags |= ALLOC_KSWAPD; 4565 4566 alloc_flags |= alloc_flags_nonblocking(gfp_mask, order); 4567 4568 if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) { 4569 /* 4570 * Ignore cpuset mems for non-blocking __GFP_HIGH (probably 4571 * GFP_ATOMIC) rather than fail, see the comment for 4572 * cpuset_current_node_allowed(). 4573 */ 4574 if (alloc_flags & ALLOC_MIN_RESERVE) 4575 alloc_flags &= ~ALLOC_CPUSET; 4576 } else if (unlikely(rt_or_dl_task(current)) && in_task()) 4577 alloc_flags |= ALLOC_MIN_RESERVE; 4578 4579 alloc_flags |= alloc_flags_cma(gfp_mask); 4580 4581 if (defrag_mode) 4582 alloc_flags |= ALLOC_NOFRAGMENT; 4583 4584 return alloc_flags; 4585 } 4586 4587 static bool oom_reserves_allowed(struct task_struct *tsk) 4588 { 4589 if (!tsk_is_oom_victim(tsk)) 4590 return false; 4591 4592 /* 4593 * !MMU doesn't have oom reaper so give access to memory reserves 4594 * only to the thread with TIF_MEMDIE set 4595 */ 4596 if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE)) 4597 return false; 4598 4599 return true; 4600 } 4601 4602 /* 4603 * Distinguish requests which really need access to full memory 4604 * reserves from oom victims which can live with a portion of it 4605 */ 4606 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask) 4607 { 4608 if (unlikely(gfp_mask & __GFP_NOMEMALLOC)) 4609 return 0; 4610 if (gfp_mask & __GFP_MEMALLOC) 4611 return ALLOC_NO_WATERMARKS; 4612 if (in_serving_softirq() && (current->flags & PF_MEMALLOC)) 4613 return ALLOC_NO_WATERMARKS; 4614 if (!in_interrupt()) { 4615 if (current->flags & PF_MEMALLOC) 4616 return ALLOC_NO_WATERMARKS; 4617 else if (oom_reserves_allowed(current)) 4618 return ALLOC_OOM; 4619 } 4620 4621 return 0; 4622 } 4623 4624 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask) 4625 { 4626 return !!__gfp_pfmemalloc_flags(gfp_mask); 4627 } 4628 4629 /* 4630 * Checks whether it makes sense to retry the reclaim to make a forward progress 4631 * for the given allocation request. 4632 * 4633 * We give up when we either have tried MAX_RECLAIM_RETRIES in a row 4634 * without success, or when we couldn't even meet the watermark if we 4635 * reclaimed all remaining pages on the LRU lists. 4636 * 4637 * Returns true if a retry is viable or false to enter the oom path. 4638 */ 4639 static inline bool 4640 should_reclaim_retry(gfp_t gfp_mask, unsigned order, 4641 struct alloc_context *ac, int alloc_flags, 4642 bool did_some_progress, int *no_progress_loops) 4643 { 4644 struct zone *zone; 4645 struct zoneref *z; 4646 bool ret = false; 4647 4648 /* 4649 * Costly allocations might have made a progress but this doesn't mean 4650 * their order will become available due to high fragmentation so 4651 * always increment the no progress counter for them 4652 */ 4653 if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER) 4654 *no_progress_loops = 0; 4655 else 4656 (*no_progress_loops)++; 4657 4658 if (*no_progress_loops > MAX_RECLAIM_RETRIES) 4659 goto out; 4660 4661 4662 /* 4663 * Keep reclaiming pages while there is a chance this will lead 4664 * somewhere. If none of the target zones can satisfy our allocation 4665 * request even if all reclaimable pages are considered then we are 4666 * screwed and have to go OOM. 4667 */ 4668 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, 4669 ac->highest_zoneidx, ac->nodemask) { 4670 unsigned long available; 4671 unsigned long reclaimable; 4672 unsigned long min_wmark = min_wmark_pages(zone); 4673 bool wmark; 4674 4675 if (cpusets_enabled() && 4676 (alloc_flags & ALLOC_CPUSET) && 4677 !__cpuset_zone_allowed(zone, gfp_mask)) 4678 continue; 4679 4680 available = reclaimable = zone_reclaimable_pages(zone); 4681 available += zone_page_state_snapshot(zone, NR_FREE_PAGES); 4682 4683 /* 4684 * Would the allocation succeed if we reclaimed all 4685 * reclaimable pages? 4686 */ 4687 wmark = __zone_watermark_ok(zone, order, min_wmark, 4688 ac->highest_zoneidx, alloc_flags, available); 4689 trace_reclaim_retry_zone(z, order, reclaimable, 4690 available, min_wmark, *no_progress_loops, wmark); 4691 if (wmark) { 4692 ret = true; 4693 break; 4694 } 4695 } 4696 4697 /* 4698 * Memory allocation/reclaim might be called from a WQ context and the 4699 * current implementation of the WQ concurrency control doesn't 4700 * recognize that a particular WQ is congested if the worker thread is 4701 * looping without ever sleeping. Therefore we have to do a short sleep 4702 * here rather than calling cond_resched(). 4703 */ 4704 if (current->flags & PF_WQ_WORKER) 4705 schedule_timeout_uninterruptible(1); 4706 else 4707 cond_resched(); 4708 out: 4709 /* Before OOM, exhaust highatomic_reserve */ 4710 if (!ret) 4711 return unreserve_highatomic_pageblock(ac, true); 4712 4713 return ret; 4714 } 4715 4716 static inline bool 4717 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac) 4718 { 4719 /* 4720 * It's possible that cpuset's mems_allowed and the nodemask from 4721 * mempolicy don't intersect. This should be normally dealt with by 4722 * policy_nodemask(), but it's possible to race with cpuset update in 4723 * such a way the check therein was true, and then it became false 4724 * before we got our cpuset_mems_cookie here. 4725 * This assumes that for all allocations, ac->nodemask can come only 4726 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored 4727 * when it does not intersect with the cpuset restrictions) or the 4728 * caller can deal with a violated nodemask. 4729 */ 4730 if (cpusets_enabled() && ac->nodemask && 4731 !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) { 4732 ac->nodemask = NULL; 4733 return true; 4734 } 4735 4736 /* 4737 * When updating a task's mems_allowed or mempolicy nodemask, it is 4738 * possible to race with parallel threads in such a way that our 4739 * allocation can fail while the mask is being updated. If we are about 4740 * to fail, check if the cpuset changed during allocation and if so, 4741 * retry. 4742 */ 4743 if (read_mems_allowed_retry(cpuset_mems_cookie)) 4744 return true; 4745 4746 return false; 4747 } 4748 4749 static void check_alloc_stall_warn(gfp_t gfp_mask, const nodemask_t *nodemask, 4750 unsigned int order, unsigned long alloc_start_time) 4751 { 4752 static DEFINE_SPINLOCK(alloc_stall_lock); 4753 unsigned long stall_msecs = jiffies_to_msecs(jiffies - alloc_start_time); 4754 4755 if (likely(stall_msecs < ALLOC_STALL_WARN_MSECS)) 4756 return; 4757 if (time_is_after_jiffies(READ_ONCE(alloc_stall_warn_jiffies))) 4758 return; 4759 if (gfp_mask & __GFP_NOWARN) 4760 return; 4761 4762 if (!spin_trylock(&alloc_stall_lock)) 4763 return; 4764 4765 /* Check again, this time under the lock */ 4766 if (time_is_after_jiffies(alloc_stall_warn_jiffies)) { 4767 spin_unlock(&alloc_stall_lock); 4768 return; 4769 } 4770 4771 WRITE_ONCE(alloc_stall_warn_jiffies, jiffies + msecs_to_jiffies(ALLOC_STALL_WARN_MSECS)); 4772 spin_unlock(&alloc_stall_lock); 4773 4774 pr_warn("%s: page allocation stall for %lu secs: order:%d, mode:%#x(%pGg) nodemask=%*pbl", 4775 current->comm, stall_msecs / MSEC_PER_SEC, order, gfp_mask, &gfp_mask, 4776 nodemask_pr_args(nodemask)); 4777 cpuset_print_current_mems_allowed(); 4778 pr_cont("\n"); 4779 dump_stack(); 4780 warn_alloc_show_mem(gfp_mask, nodemask); 4781 } 4782 4783 static inline struct page * 4784 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order, 4785 struct alloc_context *ac) 4786 { 4787 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM; 4788 bool can_compact = can_direct_reclaim && gfp_compaction_allowed(gfp_mask); 4789 bool nofail = gfp_mask & __GFP_NOFAIL; 4790 const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER; 4791 struct page *page = NULL; 4792 unsigned int alloc_flags; 4793 unsigned long did_some_progress; 4794 enum compact_priority compact_priority; 4795 enum compact_result compact_result; 4796 int compaction_retries; 4797 int no_progress_loops; 4798 unsigned int cpuset_mems_cookie; 4799 unsigned int zonelist_iter_cookie; 4800 int reserve_flags; 4801 bool compact_first = false; 4802 bool can_retry_reserves = true; 4803 unsigned long alloc_start_time = jiffies; 4804 4805 if (unlikely(nofail)) { 4806 /* 4807 * Also we don't support __GFP_NOFAIL without __GFP_DIRECT_RECLAIM, 4808 * otherwise, we may result in lockup. 4809 */ 4810 WARN_ON_ONCE(!can_direct_reclaim); 4811 /* 4812 * PF_MEMALLOC request from this context is rather bizarre 4813 * because we cannot reclaim anything and only can loop waiting 4814 * for somebody to do a work for us. 4815 */ 4816 WARN_ON_ONCE(current->flags & PF_MEMALLOC); 4817 } 4818 4819 restart: 4820 compaction_retries = 0; 4821 no_progress_loops = 0; 4822 compact_result = COMPACT_SKIPPED; 4823 compact_priority = DEF_COMPACT_PRIORITY; 4824 cpuset_mems_cookie = read_mems_allowed_begin(); 4825 zonelist_iter_cookie = zonelist_iter_begin(); 4826 4827 /* 4828 * For costly allocations, try direct compaction first, as it's likely 4829 * that we have enough base pages and don't need to reclaim. For non- 4830 * movable high-order allocations, do that as well, as compaction will 4831 * try prevent permanent fragmentation by migrating from blocks of the 4832 * same migratetype. 4833 */ 4834 if (can_compact && (costly_order || (order > 0 && 4835 ac->migratetype != MIGRATE_MOVABLE))) { 4836 compact_first = true; 4837 compact_priority = INIT_COMPACT_PRIORITY; 4838 } 4839 4840 /* 4841 * The fast path uses conservative alloc_flags to succeed only until 4842 * kswapd needs to be woken up, and to avoid the cost of setting up 4843 * alloc_flags precisely. So we do that now. 4844 * 4845 * Can't just or alloc_flags if it contains WMARK bits, but those flags 4846 * shouldn't be set in ac->alloc_flags. 4847 */ 4848 VM_WARN_ON(ac->alloc_flags & ALLOC_WMARK_MASK); 4849 alloc_flags = ac->alloc_flags | alloc_flags_slowpath(gfp_mask, order); 4850 4851 /* 4852 * We need to recalculate the starting point for the zonelist iterator 4853 * because we might have used different nodemask in the fast path, or 4854 * there was a cpuset modification and we are retrying - otherwise we 4855 * could end up iterating over non-eligible zones endlessly. 4856 */ 4857 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist, 4858 ac->highest_zoneidx, ac->nodemask); 4859 if (!zonelist_zone(ac->preferred_zoneref)) 4860 goto nopage; 4861 4862 /* 4863 * Check for insane configurations where the cpuset doesn't contain 4864 * any suitable zone to satisfy the request - e.g. non-movable 4865 * GFP_HIGHUSER allocations from MOVABLE nodes only. 4866 */ 4867 if (cpusets_insane_config() && (gfp_mask & __GFP_HARDWALL)) { 4868 struct zoneref *z = first_zones_zonelist(ac->zonelist, 4869 ac->highest_zoneidx, 4870 &cpuset_current_mems_allowed); 4871 if (!zonelist_zone(z)) 4872 goto nopage; 4873 } 4874 4875 retry: 4876 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */ 4877 if (alloc_flags & ALLOC_KSWAPD) 4878 wake_all_kswapds(order, gfp_mask, ac); 4879 4880 /* 4881 * The adjusted alloc_flags might result in immediate success, so try 4882 * that first 4883 */ 4884 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 4885 if (page) 4886 goto got_pg; 4887 4888 reserve_flags = __gfp_pfmemalloc_flags(gfp_mask); 4889 if (reserve_flags) 4890 alloc_flags = alloc_flags_cma(gfp_mask) | reserve_flags | 4891 ac->alloc_flags | (alloc_flags & ALLOC_KSWAPD); 4892 4893 /* 4894 * Reset the nodemask and zonelist iterators if memory policies can be 4895 * ignored. These allocations are high priority and system rather than 4896 * user oriented. 4897 */ 4898 if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) { 4899 ac->nodemask = NULL; 4900 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist, 4901 ac->highest_zoneidx, ac->nodemask); 4902 4903 /* 4904 * The first time we adjust anything due to being allowed to 4905 * ignore memory policies or watermarks, retry immediately. This 4906 * allows us to keep the first allocation attempt optimistic so 4907 * it can succeed in a zone that is still above watermarks. 4908 */ 4909 if (can_retry_reserves) { 4910 can_retry_reserves = false; 4911 goto retry; 4912 } 4913 } 4914 4915 /* Caller is not willing to reclaim, we can't balance anything */ 4916 if (!can_direct_reclaim) { 4917 /* 4918 * Reclaim/compaction cannot run, so defrag_mode's strategy 4919 * of enforcing ALLOC_NOFRAGMENT cannot be fulfilled. Allow 4920 * fallbacks rather than failing the allocation outright. 4921 */ 4922 if (defrag_mode && (alloc_flags & ALLOC_NOFRAGMENT) && 4923 (gfp_mask & __GFP_KSWAPD_RECLAIM)) { 4924 alloc_flags &= ~ALLOC_NOFRAGMENT; 4925 goto retry; 4926 } 4927 goto nopage; 4928 } 4929 4930 /* Avoid recursion of direct reclaim */ 4931 if (current->flags & PF_MEMALLOC) 4932 goto nopage; 4933 4934 /* If allocation has taken excessively long, warn about it */ 4935 check_alloc_stall_warn(gfp_mask, ac->nodemask, order, alloc_start_time); 4936 4937 /* Try direct reclaim and then allocating */ 4938 if (!compact_first) { 4939 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, 4940 ac, &did_some_progress); 4941 if (page) 4942 goto got_pg; 4943 } 4944 4945 /* Try direct compaction and then allocating */ 4946 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac, 4947 compact_priority, &compact_result); 4948 if (page) 4949 goto got_pg; 4950 4951 if (compact_first) { 4952 /* 4953 * THP page faults may attempt local node only first, but are 4954 * then allowed to only compact, not reclaim, see 4955 * alloc_pages_mpol(). 4956 * 4957 * Compaction has failed above and we don't want such THP 4958 * allocations to put reclaim pressure on a single node in a 4959 * situation where other nodes might have plenty of available 4960 * memory. 4961 */ 4962 if (gfp_has_flags(gfp_mask, __GFP_NORETRY | __GFP_THISNODE)) 4963 goto nopage; 4964 4965 /* 4966 * For the initial compaction attempt we have lowered its 4967 * priority. Restore it for further retries, if those are 4968 * allowed. With __GFP_NORETRY there will be a single round of 4969 * reclaim and compaction with the lowered priority. 4970 */ 4971 if (!(gfp_mask & __GFP_NORETRY)) 4972 compact_priority = DEF_COMPACT_PRIORITY; 4973 4974 compact_first = false; 4975 goto retry; 4976 } 4977 4978 /* Do not loop if specifically requested */ 4979 if (gfp_mask & __GFP_NORETRY) 4980 goto nopage; 4981 4982 /* 4983 * Do not retry costly high order allocations unless they are 4984 * __GFP_RETRY_MAYFAIL and we can compact 4985 */ 4986 if (costly_order && (!can_compact || 4987 !(gfp_mask & __GFP_RETRY_MAYFAIL))) 4988 goto nopage; 4989 4990 /* 4991 * Deal with possible cpuset update races or zonelist updates to avoid 4992 * infinite retries. No "goto retry;" can be placed above this check 4993 * unless it can execute just once. 4994 */ 4995 if (check_retry_cpuset(cpuset_mems_cookie, ac) || 4996 check_retry_zonelist(zonelist_iter_cookie)) 4997 goto restart; 4998 4999 if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags, 5000 did_some_progress > 0, &no_progress_loops)) 5001 goto retry; 5002 5003 /* 5004 * It doesn't make any sense to retry for the compaction if the order-0 5005 * reclaim is not able to make any progress because the current 5006 * implementation of the compaction depends on the sufficient amount 5007 * of free memory (see __compaction_suitable) 5008 */ 5009 if (did_some_progress > 0 && can_compact && 5010 should_compact_retry(gfp_mask, ac, order, alloc_flags, 5011 compact_result, &compact_priority, 5012 &compaction_retries)) 5013 goto retry; 5014 5015 /* Reclaim/compaction failed to prevent the fallback */ 5016 if (defrag_mode && (alloc_flags & ALLOC_NOFRAGMENT)) { 5017 alloc_flags &= ~ALLOC_NOFRAGMENT; 5018 goto retry; 5019 } 5020 5021 /* 5022 * Deal with possible cpuset update races or zonelist updates to avoid 5023 * a unnecessary OOM kill. 5024 */ 5025 if (check_retry_cpuset(cpuset_mems_cookie, ac) || 5026 check_retry_zonelist(zonelist_iter_cookie)) 5027 goto restart; 5028 5029 /* Reclaim has failed us, start killing things */ 5030 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress); 5031 if (page) 5032 goto got_pg; 5033 5034 /* Avoid allocations with no watermarks from looping endlessly */ 5035 if (tsk_is_oom_victim(current) && 5036 (alloc_flags & ALLOC_OOM || 5037 (gfp_mask & __GFP_NOMEMALLOC))) 5038 goto nopage; 5039 5040 /* Retry as long as the OOM killer is making progress */ 5041 if (did_some_progress) { 5042 no_progress_loops = 0; 5043 goto retry; 5044 } 5045 5046 nopage: 5047 /* 5048 * Deal with possible cpuset update races or zonelist updates to avoid 5049 * a unnecessary OOM kill. 5050 */ 5051 if (check_retry_cpuset(cpuset_mems_cookie, ac) || 5052 check_retry_zonelist(zonelist_iter_cookie)) 5053 goto restart; 5054 5055 /* 5056 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure 5057 * we always retry 5058 */ 5059 if (unlikely(nofail)) { 5060 unsigned int alloc_flags = ac->alloc_flags | ALLOC_MIN_RESERVE; 5061 5062 /* 5063 * Lacking direct_reclaim we can't do anything to reclaim memory, 5064 * we disregard these unreasonable nofail requests and still 5065 * return NULL 5066 */ 5067 if (!can_direct_reclaim) 5068 goto fail; 5069 5070 /* 5071 * Help non-failing allocations by giving some access to memory 5072 * reserves normally used for high priority non-blocking 5073 * allocations but do not use ALLOC_NO_WATERMARKS because this 5074 * could deplete whole memory reserves which would just make 5075 * the situation worse. 5076 */ 5077 page = __alloc_pages_cpuset_fallback(gfp_mask, order, alloc_flags, ac); 5078 if (page) 5079 goto got_pg; 5080 5081 cond_resched(); 5082 goto retry; 5083 } 5084 fail: 5085 warn_alloc(gfp_mask, ac->nodemask, 5086 "page allocation failure: order:%u", order); 5087 got_pg: 5088 return page; 5089 } 5090 5091 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order, 5092 int preferred_nid, nodemask_t *nodemask, 5093 struct alloc_context *ac, gfp_t *alloc_gfp, 5094 unsigned int *alloc_flags) 5095 { 5096 ac->highest_zoneidx = gfp_zone(gfp_mask); 5097 ac->zonelist = node_zonelist(preferred_nid, gfp_mask); 5098 ac->nodemask = nodemask; 5099 ac->migratetype = gfp_migratetype(gfp_mask); 5100 5101 if (cpusets_enabled()) { 5102 *alloc_gfp |= __GFP_HARDWALL; 5103 /* 5104 * When we are in the interrupt context, it is irrelevant 5105 * to the current task context. It means that any node ok. 5106 */ 5107 if (in_task() && !ac->nodemask) 5108 ac->nodemask = &cpuset_current_mems_allowed; 5109 else 5110 *alloc_flags |= ALLOC_CPUSET; 5111 } 5112 5113 might_alloc(gfp_mask); 5114 5115 /* 5116 * Don't invoke should_fail logic, since it may call 5117 * get_random_u32() and printk() which need to spin_lock. 5118 */ 5119 if (!(*alloc_flags & ALLOC_NOLOCK) && 5120 should_fail_alloc_page(gfp_mask, order)) 5121 return false; 5122 5123 *alloc_flags |= alloc_flags_cma(gfp_mask); 5124 5125 /* Dirty zone balancing only done in the fast path */ 5126 ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE); 5127 5128 /* 5129 * The preferred zone is used for statistics but crucially it is 5130 * also used as the starting point for the zonelist iterator. It 5131 * may get reset for allocations that ignore memory policies. 5132 */ 5133 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist, 5134 ac->highest_zoneidx, ac->nodemask); 5135 5136 return true; 5137 } 5138 5139 /* 5140 * __alloc_pages_bulk - Allocate a number of order-0 pages to an array 5141 * @gfp: GFP flags for the allocation 5142 * @preferred_nid: The preferred NUMA node ID to allocate from 5143 * @nodemask: Set of nodes to allocate from, may be NULL 5144 * @nr_pages: The number of pages desired in the array 5145 * @page_array: Array to store the pages 5146 * 5147 * This is a batched version of the page allocator that attempts to allocate 5148 * @nr_pages quickly. Pages are added to @page_array. 5149 * 5150 * Note that only the elements in @page_array that were cleared to %NULL on 5151 * entry are populated with newly allocated pages. @nr_pages is the maximum 5152 * number of pages that will be stored in the array. 5153 * 5154 * Returns the number of pages in @page_array, including ones already 5155 * allocated on entry. This can be less than the number requested in @nr_pages, 5156 * but all empty slots are filled from the beginning. I.e., if all slots in 5157 * @page_array were set to %NULL on entry, the slots from 0 to the return value 5158 * - 1 will be filled. 5159 */ 5160 unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, 5161 nodemask_t *nodemask, int nr_pages, 5162 struct page **page_array) 5163 { 5164 struct page *page; 5165 struct zone *zone; 5166 struct zoneref *z; 5167 struct per_cpu_pages *pcp; 5168 struct list_head *pcp_list; 5169 struct alloc_context ac; 5170 unsigned int alloc_flags = ALLOC_WMARK_LOW; 5171 int nr_populated = 0, nr_account = 0; 5172 5173 /* 5174 * Skip populated array elements to determine if any pages need 5175 * to be allocated before disabling IRQs. 5176 */ 5177 while (nr_populated < nr_pages && page_array[nr_populated]) 5178 nr_populated++; 5179 5180 /* No pages requested? */ 5181 if (unlikely(nr_pages <= 0)) 5182 goto out; 5183 5184 /* Already populated array? */ 5185 if (unlikely(nr_pages - nr_populated == 0)) 5186 goto out; 5187 5188 /* Bulk allocator does not support memcg accounting. */ 5189 if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT)) 5190 goto failed; 5191 5192 /* Use the single page allocator for one page. */ 5193 if (nr_pages - nr_populated == 1) 5194 goto failed; 5195 5196 #ifdef CONFIG_PAGE_OWNER 5197 /* 5198 * PAGE_OWNER may recurse into the allocator to allocate space to 5199 * save the stack with pagesets.lock held. Releasing/reacquiring 5200 * removes much of the performance benefit of bulk allocation so 5201 * force the caller to allocate one page at a time as it'll have 5202 * similar performance to added complexity to the bulk allocator. 5203 */ 5204 if (static_branch_unlikely(&page_owner_inited)) 5205 goto failed; 5206 #endif 5207 5208 /* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */ 5209 gfp &= gfp_allowed_mask; 5210 if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &gfp, &alloc_flags)) 5211 goto out; 5212 5213 /* Find an allowed local zone that meets the low watermark. */ 5214 z = ac.preferred_zoneref; 5215 for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) { 5216 unsigned long mark; 5217 5218 if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) && 5219 !__cpuset_zone_allowed(zone, gfp)) { 5220 continue; 5221 } 5222 5223 if (nr_online_nodes > 1 && zone != zonelist_zone(ac.preferred_zoneref) && 5224 zone_to_nid(zone) != zonelist_node_idx(ac.preferred_zoneref)) { 5225 goto failed; 5226 } 5227 5228 cond_accept_memory(zone, 0, alloc_flags); 5229 retry_this_zone: 5230 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages - nr_populated; 5231 if (zone_watermark_fast(zone, 0, mark, 5232 zonelist_zone_idx(ac.preferred_zoneref), 5233 alloc_flags, gfp)) { 5234 break; 5235 } 5236 5237 if (cond_accept_memory(zone, 0, alloc_flags)) 5238 goto retry_this_zone; 5239 5240 /* Try again if zone has deferred pages */ 5241 if (deferred_pages_enabled()) { 5242 if (_deferred_grow_zone(zone, 0)) 5243 goto retry_this_zone; 5244 } 5245 } 5246 5247 /* 5248 * If there are no allowed local zones that meets the watermarks then 5249 * try to allocate a single page and reclaim if necessary. 5250 */ 5251 if (unlikely(!zone)) 5252 goto failed; 5253 5254 /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */ 5255 pcp = pcp_spin_trylock(zone->per_cpu_pageset); 5256 if (!pcp) 5257 goto failed; 5258 5259 /* Attempt the batch allocation */ 5260 pcp_list = &pcp->lists[order_to_pindex(ac.migratetype, 0)]; 5261 while (nr_populated < nr_pages) { 5262 5263 /* Skip existing pages */ 5264 if (page_array[nr_populated]) { 5265 nr_populated++; 5266 continue; 5267 } 5268 5269 page = __rmqueue_pcplist(zone, 0, ac.migratetype, alloc_flags, 5270 pcp, pcp_list); 5271 if (unlikely(!page)) { 5272 /* Try and allocate at least one page */ 5273 if (!nr_account) { 5274 pcp_spin_unlock(pcp); 5275 goto failed; 5276 } 5277 break; 5278 } 5279 nr_account++; 5280 5281 prep_new_page(page, 0, gfp, ALLOC_DEFAULT); 5282 set_page_refcounted(page); 5283 page_array[nr_populated++] = page; 5284 } 5285 5286 pcp_spin_unlock(pcp); 5287 5288 __count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account); 5289 zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account); 5290 5291 out: 5292 return nr_populated; 5293 5294 failed: 5295 page = __alloc_pages_noprof(gfp, 0, preferred_nid, nodemask, ALLOC_DEFAULT); 5296 if (page) 5297 page_array[nr_populated++] = page; 5298 goto out; 5299 } 5300 EXPORT_SYMBOL_GPL(alloc_pages_bulk_noprof); 5301 5302 /* 5303 * free_pages_bulk - Free an array of order-0 pages 5304 * @page_array: Array of pages to free 5305 * @nr_pages: The number of pages in the array 5306 * 5307 * Free the order-0 pages. Adjacent entries whose PFNs form a contiguous 5308 * run are released with a single __free_contig_range() call. 5309 * 5310 * This assumes page_array is sorted in ascending PFN order. Without that, 5311 * the function still frees all pages, but contiguous runs may not be 5312 * detected and the freeing pattern can degrade to freeing one page at a 5313 * time. 5314 * 5315 * Context: Sleepable process context only; calls cond_resched() 5316 */ 5317 void free_pages_bulk(struct page **page_array, unsigned long nr_pages) 5318 { 5319 while (nr_pages) { 5320 unsigned long nr_contig = num_pages_contiguous(page_array, nr_pages); 5321 5322 __free_contig_range(page_to_pfn(*page_array), nr_contig); 5323 5324 nr_pages -= nr_contig; 5325 page_array += nr_contig; 5326 cond_resched(); 5327 } 5328 } 5329 5330 static inline bool alloc_order_allowed(gfp_t gfp, unsigned int order, 5331 unsigned int alloc_flags) 5332 { 5333 if (alloc_flags & ALLOC_NOLOCK) 5334 return pcp_allowed_order(order); 5335 5336 /* 5337 * There are several places where we assume that the order value is sane 5338 * so bail out early if the request is out of bound. 5339 */ 5340 return !(WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp)); 5341 } 5342 5343 static inline bool alloc_nolock_allowed(void) 5344 { 5345 if (!can_spin_trylock()) 5346 return false; 5347 5348 /* Bailout, since _deferred_grow_zone() needs to take a lock */ 5349 if (deferred_pages_enabled()) 5350 return false; 5351 5352 return true; 5353 } 5354 5355 /* 5356 * GFP flags to set for ALLOC_NOLOCK i.e. alloc_pages_nolock(). 5357 * 5358 * Do not specify __GFP_DIRECT_RECLAIM, since direct claim is not allowed. 5359 * Do not specify __GFP_KSWAPD_RECLAIM either, since wake up of kswapd 5360 * is not safe in arbitrary context. 5361 * 5362 * These two are the conditions for gfpflags_allow_spinning() being true. 5363 * 5364 * Specify __GFP_NOWARN since failing alloc_pages_nolock() is not a reason 5365 * to warn. Also warn would trigger printk() which is unsafe from 5366 * various contexts. We cannot use printk_deferred_enter() to mitigate, 5367 * since the running context is unknown. 5368 * 5369 * Specify __GFP_ZERO to make sure that call to kmsan_alloc_page() below 5370 * is safe in any context. Also zeroing the page is mandatory for 5371 * BPF use cases. 5372 * 5373 * Though __GFP_NOMEMALLOC is not checked in the code path below, 5374 * specify it here to highlight that alloc_pages_nolock() 5375 * doesn't want to deplete reserves. 5376 */ 5377 static const gfp_t gfp_nolock = __GFP_NOWARN | __GFP_ZERO | __GFP_NOMEMALLOC | 5378 __GFP_COMP; 5379 5380 /* 5381 * This is the 'heart' of the zoned buddy allocator. 5382 */ 5383 struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order, 5384 int preferred_nid, nodemask_t *nodemask, unsigned int alloc_flags) 5385 { 5386 struct page *page; 5387 gfp_t alloc_gfp; /* The gfp_t that was actually used for allocation */ 5388 struct alloc_context ac = { 5389 .alloc_flags = alloc_flags, 5390 }; 5391 unsigned int fastpath_alloc_flags = alloc_flags; 5392 5393 /* Other flags could be supported later if needed. */ 5394 if (WARN_ON(alloc_flags & ~(ALLOC_NOLOCK | ALLOC_NO_CODETAG))) 5395 return NULL; 5396 5397 if (!alloc_order_allowed(gfp, order, alloc_flags)) 5398 return NULL; 5399 5400 if (alloc_flags & ALLOC_NOLOCK) { 5401 /* Certain other flags could be supported later if needed. */ 5402 VM_WARN_ON_ONCE(gfp & ~(__GFP_ACCOUNT | gfp_nolock)); 5403 if (!alloc_nolock_allowed()) 5404 return NULL; 5405 gfp |= gfp_nolock; 5406 fastpath_alloc_flags |= ALLOC_WMARK_MIN; 5407 } else { 5408 fastpath_alloc_flags |= ALLOC_WMARK_LOW; 5409 } 5410 5411 gfp &= gfp_allowed_mask; 5412 /* 5413 * Apply scoped allocation constraints. This is mainly about GFP_NOFS 5414 * resp. GFP_NOIO which has to be inherited for all allocation requests 5415 * from a particular context which has been marked by 5416 * memalloc_no{fs,io}_{save,restore}. And PF_MEMALLOC_PIN which ensures 5417 * movable zones are not used during allocation. 5418 */ 5419 gfp = current_gfp_context(gfp); 5420 alloc_gfp = gfp; 5421 if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac, 5422 &alloc_gfp, &fastpath_alloc_flags)) 5423 return NULL; 5424 5425 if (!(alloc_flags & ALLOC_NOLOCK)) { 5426 /* 5427 * Forbid the first pass from falling back to types that 5428 * fragment memory until all local zones are considered. 5429 */ 5430 fastpath_alloc_flags |= alloc_flags_nofragment( 5431 zonelist_zone(ac.preferred_zoneref), gfp); 5432 } 5433 fastpath_alloc_flags |= alloc_flags_nonblocking(gfp, order) & ALLOC_HIGHATOMIC; 5434 5435 /* First allocation attempt (or, for nolock, only attempt) */ 5436 page = get_page_from_freelist(alloc_gfp, order, fastpath_alloc_flags, &ac); 5437 if (likely(page) || (alloc_flags & ALLOC_NOLOCK)) 5438 goto out; 5439 5440 alloc_gfp = gfp; 5441 ac.spread_dirty_pages = false; 5442 5443 /* 5444 * Restore the original nodemask if it was potentially replaced with 5445 * &cpuset_current_mems_allowed to optimize the fast-path attempt. 5446 */ 5447 ac.nodemask = nodemask; 5448 5449 page = __alloc_pages_slowpath(alloc_gfp, order, &ac); 5450 5451 out: 5452 if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT) && page && 5453 unlikely(__memcg_kmem_charge_page(page, gfp, order) != 0)) { 5454 __free_frozen_pages(page, order, 5455 alloc_flags & ALLOC_NOLOCK ? FPI_NOLOCK : 0); 5456 page = NULL; 5457 } 5458 5459 trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype); 5460 kmsan_alloc_page(page, order, alloc_gfp); 5461 5462 return page; 5463 } 5464 EXPORT_SYMBOL(__alloc_frozen_pages_noprof); 5465 5466 struct page *__alloc_pages_noprof(gfp_t gfp, unsigned int order, 5467 int preferred_nid, nodemask_t *nodemask, unsigned int alloc_flags) 5468 { 5469 struct page *page; 5470 5471 page = __alloc_frozen_pages_noprof(gfp, order, preferred_nid, nodemask, 5472 alloc_flags); 5473 if (page) 5474 set_page_refcounted(page); 5475 return page; 5476 } 5477 5478 struct page *alloc_pages_node_noprof(int nid, gfp_t gfp_mask, unsigned int order) 5479 { 5480 if (nid == NUMA_NO_NODE) 5481 nid = numa_mem_id(); 5482 5483 warn_if_node_offline(nid, gfp_mask); 5484 5485 return __alloc_pages_noprof(gfp_mask, order, nid, NULL, ALLOC_DEFAULT); 5486 } 5487 EXPORT_SYMBOL(alloc_pages_node_noprof); 5488 5489 struct folio *__folio_alloc_noprof(gfp_t gfp, unsigned int order, int preferred_nid, 5490 nodemask_t *nodemask) 5491 { 5492 struct page *page = __alloc_pages_noprof(gfp | __GFP_COMP, order, 5493 preferred_nid, nodemask, ALLOC_DEFAULT); 5494 return page_rmappable_folio(page); 5495 } 5496 EXPORT_SYMBOL(__folio_alloc_noprof); 5497 5498 /* 5499 * Common helper functions. Never use with __GFP_HIGHMEM because the returned 5500 * address cannot represent highmem pages. Use alloc_pages and then kmap if 5501 * you need to access high mem. 5502 */ 5503 unsigned long get_free_pages_noprof(gfp_t gfp_mask, unsigned int order) 5504 { 5505 struct page *page; 5506 5507 page = alloc_pages_noprof(gfp_mask & ~__GFP_HIGHMEM, order); 5508 if (!page) 5509 return 0; 5510 return (unsigned long) page_address(page); 5511 } 5512 EXPORT_SYMBOL(get_free_pages_noprof); 5513 5514 unsigned long get_zeroed_page_noprof(gfp_t gfp_mask) 5515 { 5516 return get_free_pages_noprof(gfp_mask | __GFP_ZERO, 0); 5517 } 5518 EXPORT_SYMBOL(get_zeroed_page_noprof); 5519 5520 static void ___free_pages(struct page *page, unsigned int order, 5521 fpi_t fpi_flags) 5522 { 5523 /* get PageHead before we drop reference */ 5524 int head = PageHead(page); 5525 /* get alloc tag in case the page is released by others */ 5526 struct alloc_tag *tag = pgalloc_tag_get(page); 5527 5528 if (put_page_testzero(page)) 5529 __free_frozen_pages(page, order, fpi_flags); 5530 else if (!head) { 5531 pgalloc_tag_sub_pages(tag, (1 << order) - 1); 5532 while (order-- > 0) { 5533 /* 5534 * The "tail" pages of this non-compound high-order 5535 * page will have no code tags, so to avoid warnings 5536 * mark them as empty. 5537 */ 5538 clear_page_tag_ref(page + (1 << order)); 5539 __free_frozen_pages(page + (1 << order), order, 5540 fpi_flags); 5541 } 5542 } 5543 } 5544 5545 /** 5546 * __free_pages - Free pages allocated with alloc_pages(). 5547 * @page: The page pointer returned from alloc_pages(). 5548 * @order: The order of the allocation. 5549 * 5550 * This function can free multi-page allocations that are not compound 5551 * pages. It does not check that the @order passed in matches that of 5552 * the allocation, so it is easy to leak memory. Freeing more memory 5553 * than was allocated will probably emit a warning. 5554 * 5555 * If the last reference to this page is speculative, it will be released 5556 * by put_page() which only frees the first page of a non-compound 5557 * allocation. To prevent the remaining pages from being leaked, we free 5558 * the subsequent pages here. If you want to use the page's reference 5559 * count to decide when to free the allocation, you should allocate a 5560 * compound page, and use put_page() instead of __free_pages(). 5561 * 5562 * Context: May be called in interrupt context or while holding a normal 5563 * spinlock, but not in NMI context or while holding a raw spinlock. 5564 */ 5565 void __free_pages(struct page *page, unsigned int order) 5566 { 5567 ___free_pages(page, order, FPI_NONE); 5568 } 5569 EXPORT_SYMBOL(__free_pages); 5570 5571 /* 5572 * Can be called while holding raw_spin_lock or from IRQ and NMI for any 5573 * page type (not only those that came from alloc_pages_nolock) 5574 */ 5575 void free_pages_nolock(struct page *page, unsigned int order) 5576 { 5577 ___free_pages(page, order, FPI_NOLOCK); 5578 } 5579 5580 /** 5581 * free_pages - Free pages allocated with __get_free_pages(). 5582 * @addr: The virtual address tied to a page returned from __get_free_pages(). 5583 * @order: The order of the allocation. 5584 * 5585 * This function behaves the same as __free_pages(). Use this function 5586 * to free pages when you only have a valid virtual address. If you have 5587 * the page, call __free_pages() instead. 5588 */ 5589 void free_pages(unsigned long addr, unsigned int order) 5590 { 5591 if (addr != 0) { 5592 VM_BUG_ON(!virt_addr_valid((void *)addr)); 5593 __free_pages(virt_to_page((void *)addr), order); 5594 } 5595 } 5596 5597 EXPORT_SYMBOL(free_pages); 5598 5599 static void *make_alloc_exact(unsigned long addr, unsigned int order, 5600 size_t size) 5601 { 5602 if (addr) { 5603 unsigned long nr = DIV_ROUND_UP(size, PAGE_SIZE); 5604 struct page *page = virt_to_page((void *)addr); 5605 struct page *last = page + nr; 5606 5607 __split_page(page, order); 5608 while (page < --last) 5609 set_page_refcounted(last); 5610 5611 last = page + (1UL << order); 5612 for (page += nr; page < last; page++) 5613 __free_pages_ok(page, 0, FPI_TO_TAIL); 5614 } 5615 return (void *)addr; 5616 } 5617 5618 /** 5619 * alloc_pages_exact - allocate an exact number physically-contiguous pages. 5620 * @size: the number of bytes to allocate 5621 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP 5622 * 5623 * This function is similar to alloc_pages(), except that it allocates the 5624 * minimum number of pages to satisfy the request. alloc_pages() can only 5625 * allocate memory in power-of-two pages. 5626 * 5627 * This function is also limited by MAX_PAGE_ORDER. 5628 * 5629 * Memory allocated by this function must be released by free_pages_exact(). 5630 * 5631 * Return: pointer to the allocated area or %NULL in case of error. 5632 */ 5633 void *alloc_pages_exact_noprof(size_t size, gfp_t gfp_mask) 5634 { 5635 unsigned int order = get_order(size); 5636 unsigned long addr; 5637 5638 if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM))) 5639 gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM); 5640 5641 addr = get_free_pages_noprof(gfp_mask, order); 5642 return make_alloc_exact(addr, order, size); 5643 } 5644 EXPORT_SYMBOL(alloc_pages_exact_noprof); 5645 5646 /** 5647 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous 5648 * pages on a node. 5649 * @nid: the preferred node ID where memory should be allocated 5650 * @size: the number of bytes to allocate 5651 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP 5652 * 5653 * Like alloc_pages_exact(), but try to allocate on node nid first before falling 5654 * back. 5655 * 5656 * Return: pointer to the allocated area or %NULL in case of error. 5657 */ 5658 void * __meminit alloc_pages_exact_nid_noprof(int nid, size_t size, gfp_t gfp_mask) 5659 { 5660 unsigned int order = get_order(size); 5661 struct page *p; 5662 5663 if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM))) 5664 gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM); 5665 5666 p = alloc_pages_node_noprof(nid, gfp_mask, order); 5667 if (!p) 5668 return NULL; 5669 return make_alloc_exact((unsigned long)page_address(p), order, size); 5670 } 5671 5672 /** 5673 * free_pages_exact - release memory allocated via alloc_pages_exact() 5674 * @virt: the value returned by alloc_pages_exact. 5675 * @size: size of allocation, same value as passed to alloc_pages_exact(). 5676 * 5677 * Release the memory allocated by a previous call to alloc_pages_exact. 5678 */ 5679 void free_pages_exact(void *virt, size_t size) 5680 { 5681 unsigned long addr = (unsigned long)virt; 5682 unsigned long end = addr + PAGE_ALIGN(size); 5683 5684 while (addr < end) { 5685 free_page(addr); 5686 addr += PAGE_SIZE; 5687 } 5688 } 5689 EXPORT_SYMBOL(free_pages_exact); 5690 5691 /** 5692 * nr_free_zone_pages - count number of pages beyond high watermark 5693 * @offset: The zone index of the highest zone 5694 * 5695 * nr_free_zone_pages() counts the number of pages which are beyond the 5696 * high watermark within all zones at or below a given zone index. For each 5697 * zone, the number of pages is calculated as: 5698 * 5699 * nr_free_zone_pages = managed_pages - high_pages 5700 * 5701 * Return: number of pages beyond high watermark. 5702 */ 5703 static unsigned long nr_free_zone_pages(int offset) 5704 { 5705 struct zoneref *z; 5706 struct zone *zone; 5707 5708 /* Just pick one node, since fallback list is circular */ 5709 unsigned long sum = 0; 5710 5711 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL); 5712 5713 for_each_zone_zonelist(zone, z, zonelist, offset) { 5714 unsigned long size = zone_managed_pages(zone); 5715 unsigned long high = high_wmark_pages(zone); 5716 if (size > high) 5717 sum += size - high; 5718 } 5719 5720 return sum; 5721 } 5722 5723 /** 5724 * nr_free_buffer_pages - count number of pages beyond high watermark 5725 * 5726 * nr_free_buffer_pages() counts the number of pages which are beyond the high 5727 * watermark within ZONE_DMA and ZONE_NORMAL. 5728 * 5729 * Return: number of pages beyond high watermark within ZONE_DMA and 5730 * ZONE_NORMAL. 5731 */ 5732 unsigned long nr_free_buffer_pages(void) 5733 { 5734 return nr_free_zone_pages(gfp_zone(GFP_USER)); 5735 } 5736 EXPORT_SYMBOL_GPL(nr_free_buffer_pages); 5737 5738 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref) 5739 { 5740 zoneref->zone = zone; 5741 zoneref->zone_idx = zone_idx(zone); 5742 } 5743 5744 /* 5745 * Builds allocation fallback zone lists. 5746 * 5747 * Add all populated zones of a node to the zonelist. 5748 */ 5749 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs) 5750 { 5751 struct zone *zone; 5752 enum zone_type zone_type = MAX_NR_ZONES; 5753 int nr_zones = 0; 5754 5755 do { 5756 zone_type--; 5757 zone = pgdat->node_zones + zone_type; 5758 if (populated_zone(zone)) { 5759 zoneref_set_zone(zone, &zonerefs[nr_zones++]); 5760 check_highest_zone(zone_type); 5761 } 5762 } while (zone_type); 5763 5764 return nr_zones; 5765 } 5766 5767 #ifdef CONFIG_NUMA 5768 5769 static int __parse_numa_zonelist_order(char *s) 5770 { 5771 /* 5772 * We used to support different zonelists modes but they turned 5773 * out to be just not useful. Let's keep the warning in place 5774 * if somebody still use the cmd line parameter so that we do 5775 * not fail it silently 5776 */ 5777 if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) { 5778 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s); 5779 return -EINVAL; 5780 } 5781 return 0; 5782 } 5783 5784 static char numa_zonelist_order[] = "Node"; 5785 #define NUMA_ZONELIST_ORDER_LEN 16 5786 /* 5787 * sysctl handler for numa_zonelist_order 5788 */ 5789 static int numa_zonelist_order_handler(const struct ctl_table *table, int write, 5790 void *buffer, size_t *length, loff_t *ppos) 5791 { 5792 if (write) 5793 return __parse_numa_zonelist_order(buffer); 5794 return proc_dostring(table, write, buffer, length, ppos); 5795 } 5796 5797 static int node_load[MAX_NUMNODES]; 5798 5799 /** 5800 * find_next_best_node - find the next node that should appear in a given node's fallback list 5801 * @node: node whose fallback list we're appending 5802 * @used_node_mask: nodemask_t of already used nodes 5803 * 5804 * We use a number of factors to determine which is the next node that should 5805 * appear on a given node's fallback list. The node should not have appeared 5806 * already in @node's fallback list, and it should be the next closest node 5807 * according to the distance array (which contains arbitrary distance values 5808 * from each node to each node in the system), and should also prefer nodes 5809 * with no CPUs, since presumably they'll have very little allocation pressure 5810 * on them otherwise. 5811 * 5812 * Return: node id of the found node or %NUMA_NO_NODE if no node is found. 5813 */ 5814 int find_next_best_node(int node, nodemask_t *used_node_mask) 5815 { 5816 int n, val; 5817 int min_val = INT_MAX; 5818 int best_node = NUMA_NO_NODE; 5819 5820 /* 5821 * Use the local node if we haven't already, but for memoryless local 5822 * node, we should skip it and fall back to other nodes. 5823 */ 5824 if (!node_isset(node, *used_node_mask) && node_state(node, N_MEMORY)) { 5825 node_set(node, *used_node_mask); 5826 return node; 5827 } 5828 5829 for_each_node_state(n, N_MEMORY) { 5830 5831 /* Don't want a node to appear more than once */ 5832 if (node_isset(n, *used_node_mask)) 5833 continue; 5834 5835 /* Use the distance array to find the distance */ 5836 val = node_distance(node, n); 5837 5838 /* Penalize nodes under us ("prefer the next node") */ 5839 val += (n < node); 5840 5841 /* Give preference to headless and unused nodes */ 5842 if (!cpumask_empty(cpumask_of_node(n))) 5843 val += PENALTY_FOR_NODE_WITH_CPUS; 5844 5845 /* Slight preference for less loaded node */ 5846 val *= MAX_NUMNODES; 5847 val += node_load[n]; 5848 5849 if (val < min_val) { 5850 min_val = val; 5851 best_node = n; 5852 } 5853 } 5854 5855 if (best_node >= 0) 5856 node_set(best_node, *used_node_mask); 5857 5858 return best_node; 5859 } 5860 5861 5862 /* 5863 * Build zonelists ordered by node and zones within node. 5864 * This results in maximum locality--normal zone overflows into local 5865 * DMA zone, if any--but risks exhausting DMA zone. 5866 */ 5867 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order, 5868 unsigned nr_nodes) 5869 { 5870 struct zoneref *zonerefs; 5871 int i; 5872 5873 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs; 5874 5875 for (i = 0; i < nr_nodes; i++) { 5876 int nr_zones; 5877 5878 pg_data_t *node = NODE_DATA(node_order[i]); 5879 5880 nr_zones = build_zonerefs_node(node, zonerefs); 5881 zonerefs += nr_zones; 5882 } 5883 zonerefs->zone = NULL; 5884 zonerefs->zone_idx = 0; 5885 } 5886 5887 /* 5888 * Build __GFP_THISNODE zonelists 5889 */ 5890 static void build_thisnode_zonelists(pg_data_t *pgdat) 5891 { 5892 struct zoneref *zonerefs; 5893 int nr_zones; 5894 5895 zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs; 5896 nr_zones = build_zonerefs_node(pgdat, zonerefs); 5897 zonerefs += nr_zones; 5898 zonerefs->zone = NULL; 5899 zonerefs->zone_idx = 0; 5900 } 5901 5902 static void build_zonelists(pg_data_t *pgdat) 5903 { 5904 static int node_order[MAX_NUMNODES]; 5905 int node, nr_nodes = 0; 5906 nodemask_t used_mask = NODE_MASK_NONE; 5907 int local_node, prev_node; 5908 5909 /* NUMA-aware ordering of nodes */ 5910 local_node = pgdat->node_id; 5911 prev_node = local_node; 5912 5913 memset(node_order, 0, sizeof(node_order)); 5914 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) { 5915 /* 5916 * We don't want to pressure a particular node. 5917 * So adding penalty to the first node in same 5918 * distance group to make it round-robin. 5919 */ 5920 if (node_distance(local_node, node) != 5921 node_distance(local_node, prev_node)) 5922 node_load[node] += 1; 5923 5924 node_order[nr_nodes++] = node; 5925 prev_node = node; 5926 } 5927 5928 build_zonelists_in_node_order(pgdat, node_order, nr_nodes); 5929 build_thisnode_zonelists(pgdat); 5930 pr_info("Fallback order for Node %d: ", local_node); 5931 for (node = 0; node < nr_nodes; node++) 5932 pr_cont("%d ", node_order[node]); 5933 pr_cont("\n"); 5934 } 5935 5936 #ifdef CONFIG_HAVE_MEMORYLESS_NODES 5937 /* 5938 * Return node id of node used for "local" allocations. 5939 * I.e., first node id of first zone in arg node's generic zonelist. 5940 * Used for initializing percpu 'numa_mem', which is used primarily 5941 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist. 5942 */ 5943 int local_memory_node(int node) 5944 { 5945 struct zoneref *z; 5946 5947 z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL), 5948 gfp_zone(GFP_KERNEL), 5949 NULL); 5950 return zonelist_node_idx(z); 5951 } 5952 #endif 5953 5954 static void setup_min_unmapped_ratio(void); 5955 static void setup_min_slab_ratio(void); 5956 #else /* CONFIG_NUMA */ 5957 5958 static void build_zonelists(pg_data_t *pgdat) 5959 { 5960 struct zoneref *zonerefs; 5961 int nr_zones; 5962 5963 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs; 5964 nr_zones = build_zonerefs_node(pgdat, zonerefs); 5965 zonerefs += nr_zones; 5966 5967 zonerefs->zone = NULL; 5968 zonerefs->zone_idx = 0; 5969 } 5970 5971 #endif /* CONFIG_NUMA */ 5972 5973 /* 5974 * Boot pageset table. One per cpu which is going to be used for all 5975 * zones and all nodes. The parameters will be set in such a way 5976 * that an item put on a list will immediately be handed over to 5977 * the buddy list. This is safe since pageset manipulation is done 5978 * with interrupts disabled. 5979 * 5980 * The boot_pagesets must be kept even after bootup is complete for 5981 * unused processors and/or zones. They do play a role for bootstrapping 5982 * hotplugged processors. 5983 * 5984 * zoneinfo_show() and maybe other functions do 5985 * not check if the processor is online before following the pageset pointer. 5986 * Other parts of the kernel may not check if the zone is available. 5987 */ 5988 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats); 5989 /* These effectively disable the pcplists in the boot pageset completely */ 5990 #define BOOT_PAGESET_HIGH 0 5991 #define BOOT_PAGESET_BATCH 1 5992 static DEFINE_PER_CPU(struct per_cpu_pages, boot_pageset); 5993 static DEFINE_PER_CPU(struct per_cpu_zonestat, boot_zonestats); 5994 5995 static void __build_all_zonelists(void *data) 5996 { 5997 int nid; 5998 int __maybe_unused cpu; 5999 pg_data_t *self = data; 6000 unsigned long flags; 6001 6002 /* 6003 * The zonelist_update_seq must be acquired with irqsave because the 6004 * reader can be invoked from IRQ with GFP_ATOMIC. 6005 */ 6006 write_seqlock_irqsave(&zonelist_update_seq, flags); 6007 /* 6008 * Also disable synchronous printk() to prevent any printk() from 6009 * trying to hold port->lock, for 6010 * tty_insert_flip_string_and_push_buffer() on other CPU might be 6011 * calling kmalloc(GFP_ATOMIC | __GFP_NOWARN) with port->lock held. 6012 */ 6013 printk_deferred_enter(); 6014 6015 #ifdef CONFIG_NUMA 6016 memset(node_load, 0, sizeof(node_load)); 6017 #endif 6018 6019 /* 6020 * This node is hotadded and no memory is yet present. So just 6021 * building zonelists is fine - no need to touch other nodes. 6022 */ 6023 if (self && !node_online(self->node_id)) { 6024 build_zonelists(self); 6025 } else { 6026 /* 6027 * All possible nodes have pgdat preallocated 6028 * in free_area_init 6029 */ 6030 for_each_node(nid) { 6031 pg_data_t *pgdat = NODE_DATA(nid); 6032 6033 build_zonelists(pgdat); 6034 } 6035 6036 #ifdef CONFIG_HAVE_MEMORYLESS_NODES 6037 /* 6038 * We now know the "local memory node" for each node-- 6039 * i.e., the node of the first zone in the generic zonelist. 6040 * Set up numa_mem percpu variable for on-line cpus. During 6041 * boot, only the boot cpu should be on-line; we'll init the 6042 * secondary cpus' numa_mem as they come on-line. During 6043 * node/memory hotplug, we'll fixup all on-line cpus. 6044 */ 6045 for_each_online_cpu(cpu) 6046 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu))); 6047 #endif 6048 } 6049 6050 printk_deferred_exit(); 6051 write_sequnlock_irqrestore(&zonelist_update_seq, flags); 6052 } 6053 6054 static noinline void __init 6055 build_all_zonelists_init(void) 6056 { 6057 int cpu; 6058 6059 __build_all_zonelists(NULL); 6060 6061 /* 6062 * Initialize the boot_pagesets that are going to be used 6063 * for bootstrapping processors. The real pagesets for 6064 * each zone will be allocated later when the per cpu 6065 * allocator is available. 6066 * 6067 * boot_pagesets are used also for bootstrapping offline 6068 * cpus if the system is already booted because the pagesets 6069 * are needed to initialize allocators on a specific cpu too. 6070 * F.e. the percpu allocator needs the page allocator which 6071 * needs the percpu allocator in order to allocate its pagesets 6072 * (a chicken-egg dilemma). 6073 */ 6074 for_each_possible_cpu(cpu) 6075 per_cpu_pages_init(&per_cpu(boot_pageset, cpu), &per_cpu(boot_zonestats, cpu)); 6076 6077 mminit_verify_zonelist(); 6078 cpuset_init_current_mems_allowed(); 6079 } 6080 6081 /* 6082 * unless system_state == SYSTEM_BOOTING. 6083 * 6084 * __ref due to call of __init annotated helper build_all_zonelists_init 6085 * [protected by SYSTEM_BOOTING]. 6086 */ 6087 void __ref build_all_zonelists(pg_data_t *pgdat) 6088 { 6089 unsigned long vm_total_pages; 6090 6091 if (system_state == SYSTEM_BOOTING) { 6092 build_all_zonelists_init(); 6093 } else { 6094 __build_all_zonelists(pgdat); 6095 /* cpuset refresh routine should be here */ 6096 } 6097 /* Get the number of free pages beyond high watermark in all zones. */ 6098 vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE)); 6099 /* 6100 * Disable grouping by mobility if the number of pages in the 6101 * system is too low to allow the mechanism to work. It would be 6102 * more accurate, but expensive to check per-zone. This check is 6103 * made on memory-hotadd so a system can start with mobility 6104 * disabled and enable it later 6105 */ 6106 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES)) 6107 page_group_by_mobility_disabled = 1; 6108 else 6109 page_group_by_mobility_disabled = 0; 6110 6111 pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n", 6112 nr_online_nodes, 6113 str_off_on(page_group_by_mobility_disabled), 6114 vm_total_pages); 6115 #ifdef CONFIG_NUMA 6116 pr_info("Policy zone: %s\n", zone_names[policy_zone]); 6117 #endif 6118 } 6119 6120 static int zone_batchsize(struct zone *zone) 6121 { 6122 #ifdef CONFIG_MMU 6123 int batch; 6124 6125 /* 6126 * The number of pages to batch allocate is either ~0.025% 6127 * of the zone or 256KB, whichever is smaller. The batch 6128 * size is striking a balance between allocation latency 6129 * and zone lock contention. 6130 */ 6131 batch = min(zone_managed_pages(zone) >> 12, SZ_256K / PAGE_SIZE); 6132 if (batch <= 1) 6133 return 1; 6134 6135 /* 6136 * Clamp the batch to a 2^n - 1 value. Having a power 6137 * of 2 value was found to be more likely to have 6138 * suboptimal cache aliasing properties in some cases. 6139 * 6140 * For example if 2 tasks are alternately allocating 6141 * batches of pages, one task can end up with a lot 6142 * of pages of one half of the possible page colors 6143 * and the other with pages of the other colors. 6144 */ 6145 batch = rounddown_pow_of_two(batch + batch/2) - 1; 6146 6147 return batch; 6148 6149 #else 6150 /* The deferral and batching of frees should be suppressed under NOMMU 6151 * conditions. 6152 * 6153 * The problem is that NOMMU needs to be able to allocate large chunks 6154 * of contiguous memory as there's no hardware page translation to 6155 * assemble apparent contiguous memory from discontiguous pages. 6156 * 6157 * Queueing large contiguous runs of pages for batching, however, 6158 * causes the pages to actually be freed in smaller chunks. As there 6159 * can be a significant delay between the individual batches being 6160 * recycled, this leads to the once large chunks of space being 6161 * fragmented and becoming unavailable for high-order allocations. 6162 */ 6163 return 1; 6164 #endif 6165 } 6166 6167 static int percpu_pagelist_high_fraction; 6168 static int zone_highsize(struct zone *zone, int batch, int cpu_online, 6169 int high_fraction) 6170 { 6171 #ifdef CONFIG_MMU 6172 int high; 6173 int nr_split_cpus; 6174 unsigned long total_pages; 6175 6176 if (!high_fraction) { 6177 /* 6178 * By default, the high value of the pcp is based on the zone 6179 * low watermark so that if they are full then background 6180 * reclaim will not be started prematurely. 6181 */ 6182 total_pages = low_wmark_pages(zone); 6183 } else { 6184 /* 6185 * If percpu_pagelist_high_fraction is configured, the high 6186 * value is based on a fraction of the managed pages in the 6187 * zone. 6188 */ 6189 total_pages = zone_managed_pages(zone) / high_fraction; 6190 } 6191 6192 /* 6193 * Split the high value across all online CPUs local to the zone. Note 6194 * that early in boot that CPUs may not be online yet and that during 6195 * CPU hotplug that the cpumask is not yet updated when a CPU is being 6196 * onlined. For memory nodes that have no CPUs, split the high value 6197 * across all online CPUs to mitigate the risk that reclaim is triggered 6198 * prematurely due to pages stored on pcp lists. 6199 */ 6200 nr_split_cpus = cpumask_weight(cpumask_of_node(zone_to_nid(zone))) + cpu_online; 6201 if (!nr_split_cpus) 6202 nr_split_cpus = num_online_cpus(); 6203 high = total_pages / nr_split_cpus; 6204 6205 /* 6206 * Ensure high is at least batch*4. The multiple is based on the 6207 * historical relationship between high and batch. 6208 */ 6209 high = max(high, batch << 2); 6210 6211 return high; 6212 #else 6213 return 0; 6214 #endif 6215 } 6216 6217 /* 6218 * pcp->high and pcp->batch values are related and generally batch is lower 6219 * than high. They are also related to pcp->count such that count is lower 6220 * than high, and as soon as it reaches high, the pcplist is flushed. 6221 * 6222 * However, guaranteeing these relations at all times would require e.g. write 6223 * barriers here but also careful usage of read barriers at the read side, and 6224 * thus be prone to error and bad for performance. Thus the update only prevents 6225 * store tearing. Any new users of pcp->batch, pcp->high_min and pcp->high_max 6226 * should ensure they can cope with those fields changing asynchronously, and 6227 * fully trust only the pcp->count field on the local CPU with interrupts 6228 * disabled. 6229 * 6230 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function 6231 * outside of boot time (or some other assurance that no concurrent updaters 6232 * exist). 6233 */ 6234 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high_min, 6235 unsigned long high_max, unsigned long batch) 6236 { 6237 WRITE_ONCE(pcp->batch, batch); 6238 WRITE_ONCE(pcp->high_min, high_min); 6239 WRITE_ONCE(pcp->high_max, high_max); 6240 } 6241 6242 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats) 6243 { 6244 int pindex; 6245 6246 memset(pcp, 0, sizeof(*pcp)); 6247 memset(pzstats, 0, sizeof(*pzstats)); 6248 6249 spin_lock_init(&pcp->lock); 6250 for (pindex = 0; pindex < NR_PCP_LISTS; pindex++) 6251 INIT_LIST_HEAD(&pcp->lists[pindex]); 6252 6253 /* 6254 * Set batch and high values safe for a boot pageset. A true percpu 6255 * pageset's initialization will update them subsequently. Here we don't 6256 * need to be as careful as pageset_update() as nobody can access the 6257 * pageset yet. 6258 */ 6259 pcp->high_min = BOOT_PAGESET_HIGH; 6260 pcp->high_max = BOOT_PAGESET_HIGH; 6261 pcp->batch = BOOT_PAGESET_BATCH; 6262 } 6263 6264 static void __zone_set_pageset_high_and_batch(struct zone *zone, unsigned long high_min, 6265 unsigned long high_max, unsigned long batch) 6266 { 6267 struct per_cpu_pages *pcp; 6268 int cpu; 6269 6270 for_each_possible_cpu(cpu) { 6271 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 6272 pageset_update(pcp, high_min, high_max, batch); 6273 } 6274 } 6275 6276 /* 6277 * Calculate and set new high and batch values for all per-cpu pagesets of a 6278 * zone based on the zone's size. 6279 */ 6280 static void zone_set_pageset_high_and_batch(struct zone *zone, int cpu_online) 6281 { 6282 int new_high_min, new_high_max, new_batch; 6283 6284 new_batch = zone_batchsize(zone); 6285 if (percpu_pagelist_high_fraction) { 6286 new_high_min = zone_highsize(zone, new_batch, cpu_online, 6287 percpu_pagelist_high_fraction); 6288 /* 6289 * PCP high is tuned manually, disable auto-tuning via 6290 * setting high_min and high_max to the manual value. 6291 */ 6292 new_high_max = new_high_min; 6293 } else { 6294 new_high_min = zone_highsize(zone, new_batch, cpu_online, 0); 6295 new_high_max = zone_highsize(zone, new_batch, cpu_online, 6296 MIN_PERCPU_PAGELIST_HIGH_FRACTION); 6297 } 6298 6299 if (zone->pageset_high_min == new_high_min && 6300 zone->pageset_high_max == new_high_max && 6301 zone->pageset_batch == new_batch) 6302 return; 6303 6304 zone->pageset_high_min = new_high_min; 6305 zone->pageset_high_max = new_high_max; 6306 zone->pageset_batch = new_batch; 6307 6308 __zone_set_pageset_high_and_batch(zone, new_high_min, new_high_max, 6309 new_batch); 6310 } 6311 6312 void __meminit setup_zone_pageset(struct zone *zone) 6313 { 6314 int cpu; 6315 6316 /* Size may be 0 on !SMP && !NUMA */ 6317 if (sizeof(struct per_cpu_zonestat) > 0) 6318 zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat); 6319 6320 zone->per_cpu_pageset = alloc_percpu(struct per_cpu_pages); 6321 for_each_possible_cpu(cpu) { 6322 struct per_cpu_pages *pcp; 6323 struct per_cpu_zonestat *pzstats; 6324 6325 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 6326 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu); 6327 per_cpu_pages_init(pcp, pzstats); 6328 } 6329 6330 zone_set_pageset_high_and_batch(zone, 0); 6331 } 6332 6333 /* 6334 * The zone indicated has a new number of managed_pages; batch sizes and percpu 6335 * page high values need to be recalculated. 6336 */ 6337 static void zone_pcp_update(struct zone *zone, int cpu_online) 6338 { 6339 mutex_lock(&pcp_batch_high_lock); 6340 zone_set_pageset_high_and_batch(zone, cpu_online); 6341 mutex_unlock(&pcp_batch_high_lock); 6342 } 6343 6344 static void zone_pcp_update_cacheinfo(struct zone *zone, unsigned int cpu) 6345 { 6346 struct per_cpu_pages *pcp; 6347 struct cpu_cacheinfo *cci; 6348 6349 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 6350 cci = get_cpu_cacheinfo(cpu); 6351 /* 6352 * If data cache slice of CPU is large enough, "pcp->batch" 6353 * pages can be preserved in PCP before draining PCP for 6354 * consecutive high-order pages freeing without allocation. 6355 * This can reduce zone lock contention without hurting 6356 * cache-hot pages sharing. 6357 */ 6358 pcp_spin_lock_nopin(pcp); 6359 if ((cci->per_cpu_data_slice_size >> PAGE_SHIFT) > 3 * pcp->batch) 6360 pcp->flags |= PCPF_FREE_HIGH_BATCH; 6361 else 6362 pcp->flags &= ~PCPF_FREE_HIGH_BATCH; 6363 pcp_spin_unlock_nopin(pcp); 6364 } 6365 6366 void setup_pcp_cacheinfo(unsigned int cpu) 6367 { 6368 struct zone *zone; 6369 6370 for_each_populated_zone(zone) 6371 zone_pcp_update_cacheinfo(zone, cpu); 6372 } 6373 6374 /* 6375 * Allocate per cpu pagesets and initialize them. 6376 * Before this call only boot pagesets were available. 6377 */ 6378 void __init setup_per_cpu_pageset(void) 6379 { 6380 struct pglist_data *pgdat; 6381 struct zone *zone; 6382 int __maybe_unused cpu; 6383 6384 for_each_populated_zone(zone) 6385 setup_zone_pageset(zone); 6386 6387 #ifdef CONFIG_NUMA 6388 /* 6389 * Unpopulated zones continue using the boot pagesets. 6390 * The numa stats for these pagesets need to be reset. 6391 * Otherwise, they will end up skewing the stats of 6392 * the nodes these zones are associated with. 6393 */ 6394 for_each_possible_cpu(cpu) { 6395 struct per_cpu_zonestat *pzstats = &per_cpu(boot_zonestats, cpu); 6396 memset(pzstats->vm_numa_event, 0, 6397 sizeof(pzstats->vm_numa_event)); 6398 } 6399 #endif 6400 6401 for_each_online_pgdat(pgdat) 6402 pgdat->per_cpu_nodestats = 6403 alloc_percpu(struct per_cpu_nodestat); 6404 } 6405 6406 __meminit void zone_pcp_init(struct zone *zone) 6407 { 6408 /* 6409 * per cpu subsystem is not up at this point. The following code 6410 * relies on the ability of the linker to provide the 6411 * offset of a (static) per cpu variable into the per cpu area. 6412 */ 6413 zone->per_cpu_pageset = &boot_pageset; 6414 zone->per_cpu_zonestats = &boot_zonestats; 6415 zone->pageset_high_min = BOOT_PAGESET_HIGH; 6416 zone->pageset_high_max = BOOT_PAGESET_HIGH; 6417 zone->pageset_batch = BOOT_PAGESET_BATCH; 6418 6419 if (populated_zone(zone)) 6420 pr_debug(" %s zone: %lu pages, LIFO batch:%u\n", zone->name, 6421 zone->present_pages, zone_batchsize(zone)); 6422 } 6423 6424 static void setup_per_zone_lowmem_reserve(void); 6425 6426 void adjust_managed_page_count(struct page *page, long count) 6427 { 6428 atomic_long_add(count, &page_zone(page)->managed_pages); 6429 totalram_pages_add(count); 6430 setup_per_zone_lowmem_reserve(); 6431 } 6432 EXPORT_SYMBOL(adjust_managed_page_count); 6433 6434 /** 6435 * free_reserved_pages - free reserved pages 6436 * @page: First page to free. 6437 * @order: The page order to free. 6438 * 6439 * Free pages allocated through memblock during boot, letting the buddy 6440 * manage them from now on. 6441 * 6442 * @page must be naturally aligned to the order and the order must not 6443 * exceed MAX_PAGE_ORDER. All pages must be reserved. 6444 */ 6445 void free_reserved_pages(struct page *page, unsigned int order) 6446 { 6447 const unsigned long nr_pages = 1UL << order; 6448 int i; 6449 6450 VM_WARN_ON_ONCE(!IS_ALIGNED(page_to_pfn(page), nr_pages)); 6451 VM_WARN_ON_ONCE(order > MAX_PAGE_ORDER); 6452 6453 for (i = 0; i < nr_pages; i++) { 6454 clear_page_tag_ref(page + i); 6455 set_page_count(page + i, 0); 6456 ClearPageReserved(page + i); 6457 } 6458 adjust_managed_page_count(page, nr_pages); 6459 __free_frozen_pages(page, order, FPI_NONE); 6460 } 6461 EXPORT_SYMBOL(free_reserved_pages); 6462 6463 static int page_alloc_cpu_dead(unsigned int cpu) 6464 { 6465 struct zone *zone; 6466 6467 lru_add_drain_cpu(cpu); 6468 mlock_drain_remote(cpu); 6469 drain_pages(cpu); 6470 6471 /* 6472 * Spill the event counters of the dead processor 6473 * into the current processors event counters. 6474 * This artificially elevates the count of the current 6475 * processor. 6476 */ 6477 vm_events_fold_cpu(cpu); 6478 6479 /* 6480 * Zero the differential counters of the dead processor 6481 * so that the vm statistics are consistent. 6482 * 6483 * This is only okay since the processor is dead and cannot 6484 * race with what we are doing. 6485 */ 6486 cpu_vm_stats_fold(cpu); 6487 6488 for_each_populated_zone(zone) 6489 zone_pcp_update(zone, 0); 6490 6491 return 0; 6492 } 6493 6494 static int page_alloc_cpu_online(unsigned int cpu) 6495 { 6496 struct zone *zone; 6497 6498 for_each_populated_zone(zone) 6499 zone_pcp_update(zone, 1); 6500 return 0; 6501 } 6502 6503 void __init page_alloc_init_cpuhp(void) 6504 { 6505 int ret; 6506 6507 ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC, 6508 "mm/page_alloc:pcp", 6509 page_alloc_cpu_online, 6510 page_alloc_cpu_dead); 6511 WARN_ON(ret < 0); 6512 } 6513 6514 /* 6515 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio 6516 * or min_free_kbytes changes. 6517 */ 6518 static void calculate_totalreserve_pages(void) 6519 { 6520 struct pglist_data *pgdat; 6521 unsigned long reserve_pages = 0; 6522 enum zone_type i, j; 6523 6524 for_each_online_pgdat(pgdat) { 6525 6526 pgdat->totalreserve_pages = 0; 6527 6528 for (i = 0; i < MAX_NR_ZONES; i++) { 6529 struct zone *zone = pgdat->node_zones + i; 6530 long max = 0; 6531 unsigned long managed_pages = zone_managed_pages(zone); 6532 6533 /* 6534 * lowmem_reserve[j] is monotonically non-decreasing 6535 * in j for a given zone (see 6536 * setup_per_zone_lowmem_reserve()). The maximum 6537 * valid reserve lives at the highest index with a 6538 * non-zero value, so scan backwards and stop at the 6539 * first hit. 6540 */ 6541 for (j = MAX_NR_ZONES - 1; j > i; j--) { 6542 if (!zone->lowmem_reserve[j]) 6543 continue; 6544 6545 max = zone->lowmem_reserve[j]; 6546 break; 6547 } 6548 /* we treat the high watermark as reserved pages. */ 6549 max += high_wmark_pages(zone); 6550 6551 max = min_t(unsigned long, max, managed_pages); 6552 6553 pgdat->totalreserve_pages += max; 6554 6555 reserve_pages += max; 6556 } 6557 } 6558 totalreserve_pages = reserve_pages; 6559 trace_mm_calculate_totalreserve_pages(totalreserve_pages); 6560 } 6561 6562 /* 6563 * setup_per_zone_lowmem_reserve - called whenever 6564 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone 6565 * has a correct pages reserved value, so an adequate number of 6566 * pages are left in the zone after a successful __alloc_pages(). 6567 */ 6568 static void setup_per_zone_lowmem_reserve(void) 6569 { 6570 struct pglist_data *pgdat; 6571 enum zone_type i, j; 6572 /* 6573 * For a given zone node_zones[i], lowmem_reserve[j] (j > i) 6574 * represents how many pages in zone i must effectively be kept 6575 * in reserve when deciding whether an allocation class that is 6576 * allowed to allocate from zones up to j may fall back into 6577 * zone i. 6578 * 6579 * As j increases, the allocation class can use a strictly larger 6580 * set of fallback zones and therefore must not be allowed to 6581 * deplete low zones more aggressively than a less flexible one. 6582 * As a result, lowmem_reserve[j] is required to be monotonically 6583 * non-decreasing in j for each zone i. Callers such as 6584 * calculate_totalreserve_pages() rely on this monotonicity when 6585 * selecting the maximum reserve entry. 6586 */ 6587 for_each_online_pgdat(pgdat) { 6588 for (i = 0; i < MAX_NR_ZONES - 1; i++) { 6589 struct zone *zone = &pgdat->node_zones[i]; 6590 int ratio = sysctl_lowmem_reserve_ratio[i]; 6591 bool clear = !ratio || !zone_managed_pages(zone); 6592 unsigned long managed_pages = 0; 6593 6594 for (j = i + 1; j < MAX_NR_ZONES; j++) { 6595 struct zone *upper_zone = &pgdat->node_zones[j]; 6596 6597 managed_pages += zone_managed_pages(upper_zone); 6598 6599 if (clear) 6600 zone->lowmem_reserve[j] = 0; 6601 else 6602 zone->lowmem_reserve[j] = managed_pages / ratio; 6603 trace_mm_setup_per_zone_lowmem_reserve(zone, upper_zone, 6604 zone->lowmem_reserve[j]); 6605 } 6606 } 6607 } 6608 6609 /* update totalreserve_pages */ 6610 calculate_totalreserve_pages(); 6611 } 6612 6613 static void __setup_per_zone_wmarks(void) 6614 { 6615 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10); 6616 unsigned long lowmem_pages = 0; 6617 struct zone *zone; 6618 unsigned long flags; 6619 6620 /* Calculate total number of !ZONE_HIGHMEM and !ZONE_MOVABLE pages */ 6621 for_each_zone(zone) { 6622 if (!is_highmem(zone) && zone_idx(zone) != ZONE_MOVABLE) 6623 lowmem_pages += zone_managed_pages(zone); 6624 } 6625 6626 for_each_zone(zone) { 6627 u64 tmp; 6628 6629 spin_lock_irqsave(&zone->lock, flags); 6630 tmp = (u64)pages_min * zone_managed_pages(zone); 6631 tmp = div64_ul(tmp, lowmem_pages); 6632 if (is_highmem(zone) || zone_idx(zone) == ZONE_MOVABLE) { 6633 /* 6634 * __GFP_HIGH and PF_MEMALLOC allocations usually don't 6635 * need highmem and movable zones pages, so cap pages_min 6636 * to a small value here. 6637 * 6638 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN) 6639 * deltas control async page reclaim, and so should 6640 * not be capped for highmem and movable zones. 6641 */ 6642 unsigned long min_pages; 6643 6644 min_pages = zone_managed_pages(zone) / 1024; 6645 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL); 6646 zone->_watermark[WMARK_MIN] = min_pages; 6647 } else { 6648 /* 6649 * If it's a lowmem zone, reserve a number of pages 6650 * proportionate to the zone's size. 6651 */ 6652 zone->_watermark[WMARK_MIN] = tmp; 6653 } 6654 6655 /* 6656 * Set the kswapd watermarks distance according to the 6657 * scale factor in proportion to available memory, but 6658 * ensure a minimum size on small systems. 6659 */ 6660 tmp = max_t(u64, tmp >> 2, 6661 mult_frac(zone_managed_pages(zone), 6662 watermark_scale_factor, 10000)); 6663 6664 zone->watermark_boost = 0; 6665 zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp; 6666 zone->_watermark[WMARK_HIGH] = low_wmark_pages(zone) + tmp; 6667 zone->_watermark[WMARK_PROMO] = high_wmark_pages(zone) + tmp; 6668 trace_mm_setup_per_zone_wmarks(zone); 6669 6670 spin_unlock_irqrestore(&zone->lock, flags); 6671 } 6672 6673 /* update totalreserve_pages */ 6674 calculate_totalreserve_pages(); 6675 } 6676 6677 /** 6678 * setup_per_zone_wmarks - called when min_free_kbytes changes 6679 * or when memory is hot-{added|removed} 6680 * 6681 * Ensures that the watermark[min,low,high] values for each zone are set 6682 * correctly with respect to min_free_kbytes. 6683 */ 6684 void setup_per_zone_wmarks(void) 6685 { 6686 struct zone *zone; 6687 static DEFINE_SPINLOCK(lock); 6688 6689 spin_lock(&lock); 6690 __setup_per_zone_wmarks(); 6691 spin_unlock(&lock); 6692 6693 /* 6694 * The watermark size have changed so update the pcpu batch 6695 * and high limits or the limits may be inappropriate. 6696 */ 6697 for_each_zone(zone) 6698 zone_pcp_update(zone, 0); 6699 } 6700 6701 /* 6702 * Initialise min_free_kbytes. 6703 * 6704 * For small machines we want it small (128k min). For large machines 6705 * we want it large (256MB max). But it is not linear, because network 6706 * bandwidth does not increase linearly with machine size. We use 6707 * 6708 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy: 6709 * min_free_kbytes = sqrt(lowmem_kbytes * 16) 6710 * 6711 * which yields 6712 * 6713 * 16MB: 512k 6714 * 32MB: 724k 6715 * 64MB: 1024k 6716 * 128MB: 1448k 6717 * 256MB: 2048k 6718 * 512MB: 2896k 6719 * 1024MB: 4096k 6720 * 2048MB: 5792k 6721 * 4096MB: 8192k 6722 * 8192MB: 11584k 6723 * 16384MB: 16384k 6724 */ 6725 void calculate_min_free_kbytes(void) 6726 { 6727 unsigned long lowmem_kbytes; 6728 int new_min_free_kbytes; 6729 6730 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10); 6731 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16); 6732 6733 if (new_min_free_kbytes > user_min_free_kbytes) 6734 min_free_kbytes = clamp(new_min_free_kbytes, 128, 262144); 6735 else 6736 pr_warn_ratelimited("min_free_kbytes is not updated to %d because user defined value %d is preferred\n", 6737 new_min_free_kbytes, user_min_free_kbytes); 6738 6739 } 6740 6741 int __meminit init_per_zone_wmark_min(void) 6742 { 6743 calculate_min_free_kbytes(); 6744 setup_per_zone_wmarks(); 6745 refresh_zone_stat_thresholds(); 6746 setup_per_zone_lowmem_reserve(); 6747 6748 #ifdef CONFIG_NUMA 6749 setup_min_unmapped_ratio(); 6750 setup_min_slab_ratio(); 6751 #endif 6752 6753 khugepaged_min_free_kbytes_update(); 6754 6755 return 0; 6756 } 6757 postcore_initcall(init_per_zone_wmark_min) 6758 6759 /* 6760 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so 6761 * that we can call two helper functions whenever min_free_kbytes 6762 * changes. 6763 */ 6764 static int min_free_kbytes_sysctl_handler(const struct ctl_table *table, int write, 6765 void *buffer, size_t *length, loff_t *ppos) 6766 { 6767 int rc; 6768 6769 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 6770 if (rc) 6771 return rc; 6772 6773 if (write) { 6774 user_min_free_kbytes = min_free_kbytes; 6775 setup_per_zone_wmarks(); 6776 } 6777 return 0; 6778 } 6779 6780 static int watermark_scale_factor_sysctl_handler(const struct ctl_table *table, int write, 6781 void *buffer, size_t *length, loff_t *ppos) 6782 { 6783 int rc; 6784 6785 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 6786 if (rc) 6787 return rc; 6788 6789 if (write) 6790 setup_per_zone_wmarks(); 6791 6792 return 0; 6793 } 6794 6795 #ifdef CONFIG_NUMA 6796 static void setup_min_unmapped_ratio(void) 6797 { 6798 pg_data_t *pgdat; 6799 struct zone *zone; 6800 6801 for_each_online_pgdat(pgdat) 6802 pgdat->min_unmapped_pages = 0; 6803 6804 for_each_zone(zone) 6805 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) * 6806 sysctl_min_unmapped_ratio) / 100; 6807 } 6808 6809 6810 static int sysctl_min_unmapped_ratio_sysctl_handler(const struct ctl_table *table, int write, 6811 void *buffer, size_t *length, loff_t *ppos) 6812 { 6813 int rc; 6814 6815 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 6816 if (rc) 6817 return rc; 6818 6819 if (write) 6820 setup_min_unmapped_ratio(); 6821 6822 return 0; 6823 } 6824 6825 static void setup_min_slab_ratio(void) 6826 { 6827 pg_data_t *pgdat; 6828 struct zone *zone; 6829 6830 for_each_online_pgdat(pgdat) 6831 pgdat->min_slab_pages = 0; 6832 6833 for_each_zone(zone) 6834 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) * 6835 sysctl_min_slab_ratio) / 100; 6836 } 6837 6838 static int sysctl_min_slab_ratio_sysctl_handler(const struct ctl_table *table, int write, 6839 void *buffer, size_t *length, loff_t *ppos) 6840 { 6841 int rc; 6842 6843 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 6844 if (rc) 6845 return rc; 6846 6847 if (write) 6848 setup_min_slab_ratio(); 6849 6850 return 0; 6851 } 6852 #endif 6853 6854 /* 6855 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around 6856 * proc_dointvec_minmax() so that we can call 6857 * setup_per_zone_lowmem_reserve() when the sysctl is written. 6858 * 6859 * The reserve ratio obviously has absolutely no relation with the 6860 * minimum watermarks. The lowmem reserve ratio can only make sense 6861 * if in function of the boot time zone sizes. 6862 */ 6863 static int lowmem_reserve_ratio_sysctl_handler(const struct ctl_table *table, 6864 int write, void *buffer, size_t *length, loff_t *ppos) 6865 { 6866 struct ctl_table tmp = *table; 6867 int ratio[ARRAY_SIZE(sysctl_lowmem_reserve_ratio)]; 6868 int rc; 6869 6870 if (!write) 6871 return proc_dointvec_minmax(table, write, buffer, length, ppos); 6872 6873 /* 6874 * proc_dointvec_max() works incrementally. Use a buffer and only set 6875 * the values if all of them parse cleanly. 6876 */ 6877 memcpy(ratio, sysctl_lowmem_reserve_ratio, sizeof(ratio)); 6878 tmp.data = ratio; 6879 6880 rc = proc_dointvec_minmax(&tmp, write, buffer, length, ppos); 6881 if (rc) 6882 return rc; 6883 6884 memcpy(sysctl_lowmem_reserve_ratio, ratio, sizeof(ratio)); 6885 setup_per_zone_lowmem_reserve(); 6886 6887 return 0; 6888 } 6889 6890 /* 6891 * percpu_pagelist_high_fraction - changes the pcp->high for each zone on each 6892 * cpu. It is the fraction of total pages in each zone that a hot per cpu 6893 * pagelist can have before it gets flushed back to buddy allocator. 6894 */ 6895 static int percpu_pagelist_high_fraction_sysctl_handler(const struct ctl_table *table, 6896 int write, void *buffer, size_t *length, loff_t *ppos) 6897 { 6898 struct zone *zone; 6899 int old_percpu_pagelist_high_fraction; 6900 int ret; 6901 6902 /* 6903 * Avoid using pcp_batch_high_lock for reads as the value is read 6904 * atomically and a race with offlining is harmless. 6905 */ 6906 6907 if (!write) 6908 return proc_dointvec_minmax(table, write, buffer, length, ppos); 6909 6910 mutex_lock(&pcp_batch_high_lock); 6911 old_percpu_pagelist_high_fraction = percpu_pagelist_high_fraction; 6912 6913 ret = proc_dointvec_minmax(table, write, buffer, length, ppos); 6914 if (ret < 0) 6915 goto out; 6916 6917 /* Sanity checking to avoid pcp imbalance */ 6918 if (percpu_pagelist_high_fraction && 6919 percpu_pagelist_high_fraction < MIN_PERCPU_PAGELIST_HIGH_FRACTION) { 6920 percpu_pagelist_high_fraction = old_percpu_pagelist_high_fraction; 6921 ret = -EINVAL; 6922 goto out; 6923 } 6924 6925 /* No change? */ 6926 if (percpu_pagelist_high_fraction == old_percpu_pagelist_high_fraction) 6927 goto out; 6928 6929 for_each_populated_zone(zone) 6930 zone_set_pageset_high_and_batch(zone, 0); 6931 out: 6932 mutex_unlock(&pcp_batch_high_lock); 6933 return ret; 6934 } 6935 6936 static const struct ctl_table page_alloc_sysctl_table[] = { 6937 { 6938 .procname = "min_free_kbytes", 6939 .data = &min_free_kbytes, 6940 .maxlen = sizeof(min_free_kbytes), 6941 .mode = 0644, 6942 .proc_handler = min_free_kbytes_sysctl_handler, 6943 .extra1 = SYSCTL_ZERO, 6944 }, 6945 { 6946 .procname = "watermark_boost_factor", 6947 .data = &watermark_boost_factor, 6948 .maxlen = sizeof(watermark_boost_factor), 6949 .mode = 0644, 6950 .proc_handler = proc_dointvec_minmax, 6951 .extra1 = SYSCTL_ZERO, 6952 }, 6953 { 6954 .procname = "watermark_scale_factor", 6955 .data = &watermark_scale_factor, 6956 .maxlen = sizeof(watermark_scale_factor), 6957 .mode = 0644, 6958 .proc_handler = watermark_scale_factor_sysctl_handler, 6959 .extra1 = SYSCTL_ONE, 6960 .extra2 = SYSCTL_THREE_THOUSAND, 6961 }, 6962 { 6963 .procname = "defrag_mode", 6964 .data = &defrag_mode, 6965 .maxlen = sizeof(defrag_mode), 6966 .mode = 0644, 6967 .proc_handler = proc_dointvec_minmax, 6968 .extra1 = SYSCTL_ZERO, 6969 .extra2 = SYSCTL_ONE, 6970 }, 6971 { 6972 .procname = "percpu_pagelist_high_fraction", 6973 .data = &percpu_pagelist_high_fraction, 6974 .maxlen = sizeof(percpu_pagelist_high_fraction), 6975 .mode = 0644, 6976 .proc_handler = percpu_pagelist_high_fraction_sysctl_handler, 6977 .extra1 = SYSCTL_ZERO, 6978 }, 6979 { 6980 .procname = "lowmem_reserve_ratio", 6981 .data = &sysctl_lowmem_reserve_ratio, 6982 .maxlen = sizeof(sysctl_lowmem_reserve_ratio), 6983 .mode = 0644, 6984 .proc_handler = lowmem_reserve_ratio_sysctl_handler, 6985 .extra1 = SYSCTL_ZERO, 6986 }, 6987 #ifdef CONFIG_NUMA 6988 { 6989 .procname = "numa_zonelist_order", 6990 .data = &numa_zonelist_order, 6991 .maxlen = NUMA_ZONELIST_ORDER_LEN, 6992 .mode = 0644, 6993 .proc_handler = numa_zonelist_order_handler, 6994 }, 6995 { 6996 .procname = "min_unmapped_ratio", 6997 .data = &sysctl_min_unmapped_ratio, 6998 .maxlen = sizeof(sysctl_min_unmapped_ratio), 6999 .mode = 0644, 7000 .proc_handler = sysctl_min_unmapped_ratio_sysctl_handler, 7001 .extra1 = SYSCTL_ZERO, 7002 .extra2 = SYSCTL_ONE_HUNDRED, 7003 }, 7004 { 7005 .procname = "min_slab_ratio", 7006 .data = &sysctl_min_slab_ratio, 7007 .maxlen = sizeof(sysctl_min_slab_ratio), 7008 .mode = 0644, 7009 .proc_handler = sysctl_min_slab_ratio_sysctl_handler, 7010 .extra1 = SYSCTL_ZERO, 7011 .extra2 = SYSCTL_ONE_HUNDRED, 7012 }, 7013 #endif 7014 }; 7015 7016 void __init page_alloc_sysctl_init(void) 7017 { 7018 register_sysctl_init("vm", page_alloc_sysctl_table); 7019 } 7020 7021 static void free_prepared_contig_range(struct page *page, 7022 unsigned long nr_pages) 7023 { 7024 unsigned long pfn = page_to_pfn(page); 7025 7026 while (nr_pages) { 7027 unsigned int order; 7028 7029 /* We are limited by the largest buddy order. */ 7030 order = pfn ? __ffs(pfn) : MAX_PAGE_ORDER; 7031 /* Don't exceed the number of pages to free. */ 7032 order = min_t(unsigned int, order, ilog2(nr_pages)); 7033 order = min_t(unsigned int, order, MAX_PAGE_ORDER); 7034 7035 /* 7036 * Free the chunk as a single block. Our caller has already 7037 * called free_pages_prepare() for each order-0 page. 7038 */ 7039 __free_frozen_pages(page, order, FPI_PREPARED); 7040 7041 pfn += 1UL << order; 7042 page += 1UL << order; 7043 nr_pages -= 1UL << order; 7044 } 7045 } 7046 7047 static void __free_contig_range_common(unsigned long pfn, unsigned long nr_pages, 7048 bool is_frozen) 7049 { 7050 struct page *page, *start = NULL; 7051 unsigned long nr_start = 0; 7052 unsigned long start_sec; 7053 unsigned long i; 7054 7055 for (i = 0; i < nr_pages; i++) { 7056 bool can_free = true; 7057 7058 /* 7059 * Contiguous PFNs might not have contiguous "struct pages" 7060 * in some kernel configs: page++ across a section boundary 7061 * is undefined. Use pfn_to_page() for each PFN. 7062 */ 7063 page = pfn_to_page(pfn + i); 7064 7065 VM_WARN_ON_ONCE(PageHead(page)); 7066 VM_WARN_ON_ONCE(PageTail(page)); 7067 7068 if (!is_frozen) 7069 can_free = put_page_testzero(page); 7070 7071 if (can_free) 7072 can_free = free_pages_prepare(page, 0); 7073 7074 if (!can_free) { 7075 if (start) { 7076 free_prepared_contig_range(start, i - nr_start); 7077 start = NULL; 7078 } 7079 continue; 7080 } 7081 7082 if (start && memdesc_section(&page->flags) != start_sec) { 7083 free_prepared_contig_range(start, i - nr_start); 7084 start = page; 7085 nr_start = i; 7086 start_sec = memdesc_section(&page->flags); 7087 } else if (!start) { 7088 start = page; 7089 nr_start = i; 7090 start_sec = memdesc_section(&page->flags); 7091 } 7092 } 7093 7094 if (start) 7095 free_prepared_contig_range(start, nr_pages - nr_start); 7096 } 7097 7098 /** 7099 * __free_contig_range - Free contiguous range of order-0 pages. 7100 * @pfn: Page frame number of the first page in the range. 7101 * @nr_pages: Number of pages to free. 7102 * 7103 * For each order-0 struct page in the physically contiguous range, put a 7104 * reference. Free any page who's reference count falls to zero. The 7105 * implementation is functionally equivalent to, but significantly faster than 7106 * calling __free_page() for each struct page in a loop. 7107 * 7108 * Memory allocated with alloc_pages(order>=1) then subsequently split to 7109 * order-0 with split_page() is an example of appropriate contiguous pages that 7110 * can be freed with this API. 7111 * 7112 * Context: May be called in interrupt context or while holding a normal 7113 * spinlock, but not in NMI context or while holding a raw spinlock. 7114 */ 7115 void __free_contig_range(unsigned long pfn, unsigned long nr_pages) 7116 { 7117 __free_contig_range_common(pfn, nr_pages, /* is_frozen= */ false); 7118 } 7119 7120 #ifdef CONFIG_CONTIG_ALLOC 7121 /* Usage: See admin-guide/dynamic-debug-howto.rst */ 7122 static void alloc_contig_dump_pages(struct list_head *page_list) 7123 { 7124 DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure"); 7125 7126 if (DYNAMIC_DEBUG_BRANCH(descriptor)) { 7127 struct page *page; 7128 7129 dump_stack(); 7130 list_for_each_entry(page, page_list, lru) 7131 dump_page(page, "migration failure"); 7132 } 7133 } 7134 7135 /* [start, end) must belong to a single zone. */ 7136 static int __alloc_contig_migrate_range(struct compact_control *cc, 7137 unsigned long start, unsigned long end) 7138 { 7139 /* This function is based on compact_zone() from compaction.c. */ 7140 unsigned int nr_reclaimed; 7141 unsigned long pfn = start; 7142 unsigned int tries = 0; 7143 int ret = 0; 7144 struct migration_target_control mtc = { 7145 .nid = zone_to_nid(cc->zone), 7146 .gfp_mask = cc->gfp_mask, 7147 .reason = MR_CONTIG_RANGE, 7148 }; 7149 7150 lru_cache_disable(); 7151 7152 while (pfn < end || !list_empty(&cc->migratepages)) { 7153 if (fatal_signal_pending(current)) { 7154 ret = -EINTR; 7155 break; 7156 } 7157 7158 if (list_empty(&cc->migratepages)) { 7159 cc->nr_migratepages = 0; 7160 ret = isolate_migratepages_range(cc, pfn, end); 7161 if (ret && ret != -EAGAIN) 7162 break; 7163 pfn = cc->migrate_pfn; 7164 tries = 0; 7165 } else if (++tries == 5) { 7166 ret = -EBUSY; 7167 break; 7168 } 7169 7170 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone, 7171 &cc->migratepages); 7172 cc->nr_migratepages -= nr_reclaimed; 7173 7174 ret = migrate_pages(&cc->migratepages, alloc_migration_target, 7175 NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE, NULL); 7176 7177 /* 7178 * On -ENOMEM, migrate_pages() bails out right away. It is pointless 7179 * to retry again over this error, so do the same here. 7180 */ 7181 if (ret == -ENOMEM) 7182 break; 7183 } 7184 7185 lru_cache_enable(); 7186 if (ret < 0) { 7187 if (!(cc->gfp_mask & __GFP_NOWARN) && ret == -EBUSY) 7188 alloc_contig_dump_pages(&cc->migratepages); 7189 putback_movable_pages(&cc->migratepages); 7190 } 7191 7192 return (ret < 0) ? ret : 0; 7193 } 7194 7195 static void split_free_frozen_pages(struct list_head *list, gfp_t gfp_mask) 7196 { 7197 int order; 7198 7199 for (order = 0; order < NR_PAGE_ORDERS; order++) { 7200 struct page *page, *next; 7201 int nr_pages = 1 << order; 7202 7203 list_for_each_entry_safe(page, next, &list[order], lru) { 7204 int i; 7205 7206 post_alloc_hook(page, order, gfp_mask, ALLOC_DEFAULT); 7207 if (!order) 7208 continue; 7209 7210 __split_page(page, order); 7211 7212 /* Add all subpages to the order-0 head, in sequence. */ 7213 list_del(&page->lru); 7214 for (i = 0; i < nr_pages; i++) 7215 list_add_tail(&page[i].lru, &list[0]); 7216 } 7217 } 7218 } 7219 7220 static int __alloc_contig_verify_gfp_mask(gfp_t gfp_mask, gfp_t *gfp_cc_mask) 7221 { 7222 const gfp_t reclaim_mask = __GFP_IO | __GFP_FS | __GFP_RECLAIM; 7223 const gfp_t action_mask = __GFP_COMP | __GFP_RETRY_MAYFAIL | __GFP_NOWARN | 7224 __GFP_ZERO | __GFP_ZEROTAGS | __GFP_SKIP_ZERO | 7225 __GFP_SKIP_KASAN; 7226 const gfp_t cc_action_mask = __GFP_RETRY_MAYFAIL | __GFP_NOWARN; 7227 7228 /* 7229 * We are given the range to allocate; node, mobility and placement 7230 * hints are irrelevant at this point. We'll simply ignore them. 7231 */ 7232 gfp_mask &= ~(GFP_ZONEMASK | __GFP_RECLAIMABLE | __GFP_WRITE | 7233 __GFP_HARDWALL | __GFP_THISNODE | __GFP_MOVABLE); 7234 7235 /* 7236 * We only support most reclaim flags (but not NOFAIL/NORETRY), and 7237 * selected action flags. 7238 */ 7239 if (gfp_mask & ~(reclaim_mask | action_mask)) 7240 return -EINVAL; 7241 7242 /* 7243 * Flags to control page compaction/migration/reclaim, to free up our 7244 * page range. Migratable pages are movable, __GFP_MOVABLE is implied 7245 * for them. 7246 * 7247 * Traditionally we always had __GFP_RETRY_MAYFAIL set, keep doing that 7248 * to not degrade callers. 7249 */ 7250 *gfp_cc_mask = (gfp_mask & (reclaim_mask | cc_action_mask)) | 7251 __GFP_MOVABLE | __GFP_RETRY_MAYFAIL; 7252 return 0; 7253 } 7254 7255 static void __free_contig_frozen_range(unsigned long pfn, unsigned long nr_pages) 7256 { 7257 __free_contig_range_common(pfn, nr_pages, /* is_frozen= */ true); 7258 } 7259 7260 /** 7261 * alloc_contig_frozen_range() -- tries to allocate given range of frozen pages 7262 * @start: start PFN to allocate 7263 * @end: one-past-the-last PFN to allocate 7264 * @alloc_flags: allocation information 7265 * @gfp_mask: GFP mask. Node/zone/placement hints are ignored; only some 7266 * action and reclaim modifiers are supported. Reclaim modifiers 7267 * control allocation behavior during compaction/migration/reclaim. 7268 * 7269 * The PFN range does not have to be pageblock aligned. The PFN range must 7270 * belong to a single zone. 7271 * 7272 * The first thing this routine does is attempt to MIGRATE_ISOLATE all 7273 * pageblocks in the range. Once isolated, the pageblocks should not 7274 * be modified by others. 7275 * 7276 * All frozen pages which PFN is in [start, end) are allocated for the 7277 * caller, and they could be freed with free_contig_frozen_range(), 7278 * free_frozen_pages() also could be used to free compound frozen pages 7279 * directly. 7280 * 7281 * Return: zero on success or negative error code. 7282 */ 7283 int alloc_contig_frozen_range_noprof(unsigned long start, unsigned long end, 7284 acr_flags_t alloc_flags, gfp_t gfp_mask) 7285 { 7286 const unsigned int order = ilog2(end - start); 7287 unsigned long outer_start, outer_end; 7288 int ret = 0; 7289 7290 struct compact_control cc = { 7291 .nr_migratepages = 0, 7292 .order = -1, 7293 .zone = page_zone(pfn_to_page(start)), 7294 .mode = MIGRATE_SYNC, 7295 .ignore_skip_hint = true, 7296 .no_set_skip_hint = true, 7297 .alloc_contig = true, 7298 }; 7299 INIT_LIST_HEAD(&cc.migratepages); 7300 enum pb_isolate_mode mode = (alloc_flags & ACR_FLAGS_CMA) ? 7301 PB_ISOLATE_MODE_CMA_ALLOC : 7302 PB_ISOLATE_MODE_OTHER; 7303 7304 /* 7305 * In contrast to the buddy, we allow for orders here that exceed 7306 * MAX_PAGE_ORDER, so we must manually make sure that we are not 7307 * exceeding the maximum folio order. 7308 */ 7309 if (WARN_ON_ONCE((gfp_mask & __GFP_COMP) && order > MAX_FOLIO_ORDER)) 7310 return -EINVAL; 7311 7312 gfp_mask = current_gfp_context(gfp_mask); 7313 if (__alloc_contig_verify_gfp_mask(gfp_mask, (gfp_t *)&cc.gfp_mask)) 7314 return -EINVAL; 7315 7316 /* 7317 * What we do here is we mark all pageblocks in range as 7318 * MIGRATE_ISOLATE. Because pageblock and max order pages may 7319 * have different sizes, and due to the way page allocator 7320 * work, start_isolate_page_range() has special handlings for this. 7321 * 7322 * Once the pageblocks are marked as MIGRATE_ISOLATE, we 7323 * migrate the pages from an unaligned range (ie. pages that 7324 * we are interested in). This will put all the pages in 7325 * range back to page allocator as MIGRATE_ISOLATE. 7326 * 7327 * When this is done, we take the pages in range from page 7328 * allocator removing them from the buddy system. This way 7329 * page allocator will never consider using them. 7330 * 7331 * This lets us mark the pageblocks back as 7332 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the 7333 * aligned range but not in the unaligned, original range are 7334 * put back to page allocator so that buddy can use them. 7335 */ 7336 7337 ret = start_isolate_page_range(start, end, mode); 7338 if (ret) 7339 goto done; 7340 7341 drain_all_pages(cc.zone); 7342 7343 /* 7344 * In case of -EBUSY, we'd like to know which page causes problem. 7345 * So, just fall through. test_pages_isolated() has a tracepoint 7346 * which will report the busy page. 7347 * 7348 * It is possible that busy pages could become available before 7349 * the call to test_pages_isolated, and the range will actually be 7350 * allocated. So, if we fall through be sure to clear ret so that 7351 * -EBUSY is not accidentally used or returned to caller. 7352 */ 7353 ret = __alloc_contig_migrate_range(&cc, start, end); 7354 if (ret && ret != -EBUSY) 7355 goto done; 7356 7357 /* 7358 * When in-use hugetlb pages are migrated, they may simply be released 7359 * back into the free hugepage pool instead of being returned to the 7360 * buddy system. After the migration of in-use huge pages is completed, 7361 * we will invoke replace_free_hugepage_folios() to ensure that these 7362 * hugepages are properly released to the buddy system. 7363 */ 7364 ret = replace_free_hugepage_folios(start, end); 7365 if (ret) 7366 goto done; 7367 7368 /* 7369 * Pages from [start, end) are within a pageblock_nr_pages 7370 * aligned blocks that are marked as MIGRATE_ISOLATE. What's 7371 * more, all pages in [start, end) are free in page allocator. 7372 * What we are going to do is to allocate all pages from 7373 * [start, end) (that is remove them from page allocator). 7374 * 7375 * The only problem is that pages at the beginning and at the 7376 * end of interesting range may be not aligned with pages that 7377 * page allocator holds, ie. they can be part of higher order 7378 * pages. Because of this, we reserve the bigger range and 7379 * once this is done free the pages we are not interested in. 7380 * 7381 * We don't have to hold zone->lock here because the pages are 7382 * isolated thus they won't get removed from buddy. 7383 */ 7384 outer_start = find_large_buddy(start); 7385 7386 /* Make sure the range is really isolated. */ 7387 if (test_pages_isolated(outer_start, end, mode)) { 7388 ret = -EBUSY; 7389 goto done; 7390 } 7391 7392 /* Grab isolated pages from freelists. */ 7393 outer_end = isolate_freepages_range(&cc, outer_start, end); 7394 if (!outer_end) { 7395 ret = -EBUSY; 7396 goto done; 7397 } 7398 7399 if (!(gfp_mask & __GFP_COMP)) { 7400 split_free_frozen_pages(cc.freepages, gfp_mask); 7401 7402 /* Free head and tail (if any) */ 7403 if (start != outer_start) 7404 __free_contig_frozen_range(outer_start, start - outer_start); 7405 if (end != outer_end) 7406 __free_contig_frozen_range(end, outer_end - end); 7407 } else if (start == outer_start && end == outer_end && is_power_of_2(end - start)) { 7408 struct page *head = pfn_to_page(start); 7409 7410 check_new_pages(head, order); 7411 prep_new_page(head, order, gfp_mask, ALLOC_DEFAULT); 7412 } else { 7413 ret = -EINVAL; 7414 WARN(true, "PFN range: requested [%lu, %lu), allocated [%lu, %lu)\n", 7415 start, end, outer_start, outer_end); 7416 } 7417 done: 7418 undo_isolate_page_range(start, end); 7419 return ret; 7420 } 7421 EXPORT_SYMBOL(alloc_contig_frozen_range_noprof); 7422 7423 /** 7424 * alloc_contig_range() -- tries to allocate given range of pages 7425 * @start: start PFN to allocate 7426 * @end: one-past-the-last PFN to allocate 7427 * @alloc_flags: allocation information 7428 * @gfp_mask: GFP mask. 7429 * 7430 * This routine is a wrapper around alloc_contig_frozen_range(), it can't 7431 * be used to allocate compound pages, the refcount of each allocated page 7432 * will be set to one. 7433 * 7434 * All pages which PFN is in [start, end) are allocated for the caller, 7435 * and should be freed with free_contig_range() or by manually calling 7436 * __free_page() on each allocated page. 7437 * 7438 * Return: zero on success or negative error code. 7439 */ 7440 int alloc_contig_range_noprof(unsigned long start, unsigned long end, 7441 acr_flags_t alloc_flags, gfp_t gfp_mask) 7442 { 7443 int ret; 7444 7445 if (WARN_ON(gfp_mask & __GFP_COMP)) 7446 return -EINVAL; 7447 7448 ret = alloc_contig_frozen_range_noprof(start, end, alloc_flags, gfp_mask); 7449 if (!ret) 7450 set_pages_refcounted(pfn_to_page(start), end - start); 7451 7452 return ret; 7453 } 7454 EXPORT_SYMBOL(alloc_contig_range_noprof); 7455 7456 static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn, 7457 unsigned long nr_pages, bool skip_hugetlb, 7458 bool *skipped_hugetlb) 7459 { 7460 unsigned long end_pfn = start_pfn + nr_pages; 7461 struct page *page; 7462 7463 while (start_pfn < end_pfn) { 7464 unsigned long step = 1; 7465 7466 page = pfn_to_online_page(start_pfn); 7467 if (!page) 7468 return false; 7469 7470 if (page_zone(page) != z) 7471 return false; 7472 7473 if (page_is_unmovable(z, page, PB_ISOLATE_MODE_OTHER, &step)) 7474 return false; 7475 7476 /* 7477 * Only consider ranges containing hugepages if those pages are 7478 * smaller than the requested contiguous region. e.g.: 7479 * Move 2MB pages to free up a 1GB range. 7480 * Don't move 1GB pages to free up a 2MB range. 7481 * 7482 * This makes contiguous allocation more reliable if multiple 7483 * hugepage sizes are used without causing needless movement. 7484 */ 7485 if (PageHuge(page)) { 7486 unsigned int order; 7487 7488 if (skip_hugetlb) { 7489 *skipped_hugetlb = true; 7490 return false; 7491 } 7492 7493 page = compound_head(page); 7494 order = compound_order(page); 7495 if ((order >= MAX_FOLIO_ORDER) || 7496 (nr_pages <= (1 << order))) 7497 return false; 7498 } 7499 7500 start_pfn += step; 7501 } 7502 return true; 7503 } 7504 7505 static bool zone_spans_last_pfn(const struct zone *zone, 7506 unsigned long start_pfn, unsigned long nr_pages) 7507 { 7508 unsigned long last_pfn = start_pfn + nr_pages - 1; 7509 7510 return zone_spans_pfn(zone, last_pfn); 7511 } 7512 7513 /** 7514 * alloc_contig_frozen_pages() -- tries to find and allocate contiguous range of frozen pages 7515 * @nr_pages: Number of contiguous pages to allocate 7516 * @gfp_mask: GFP mask. Node/zone/placement hints limit the search; only some 7517 * action and reclaim modifiers are supported. Reclaim modifiers 7518 * control allocation behavior during compaction/migration/reclaim. 7519 * @nid: Target node 7520 * @nodemask: Mask for other possible nodes 7521 * 7522 * This routine is a wrapper around alloc_contig_frozen_range(). It scans over 7523 * zones on an applicable zonelist to find a contiguous pfn range which can then 7524 * be tried for allocation with alloc_contig_frozen_range(). This routine is 7525 * intended for allocation requests which can not be fulfilled with the buddy 7526 * allocator. 7527 * 7528 * The allocated memory is always aligned to a page boundary. If nr_pages is a 7529 * power of two, then allocated range is also guaranteed to be aligned to same 7530 * nr_pages (e.g. 1GB request would be aligned to 1GB). 7531 * 7532 * Allocated frozen pages need be freed with free_contig_frozen_range(), 7533 * or by manually calling free_frozen_pages() on each allocated frozen 7534 * non-compound page, for compound frozen pages could be freed with 7535 * free_frozen_pages() directly. 7536 * 7537 * Return: pointer to contiguous frozen pages on success, or NULL if not successful. 7538 */ 7539 struct page *alloc_contig_frozen_pages_noprof(unsigned long nr_pages, 7540 gfp_t gfp_mask, int nid, nodemask_t *nodemask) 7541 { 7542 unsigned long ret, pfn, flags; 7543 struct zonelist *zonelist; 7544 struct zone *zone; 7545 struct zoneref *z; 7546 bool skip_hugetlb = true; 7547 bool skipped_hugetlb = false; 7548 7549 retry: 7550 zonelist = node_zonelist(nid, gfp_mask); 7551 for_each_zone_zonelist_nodemask(zone, z, zonelist, 7552 gfp_zone(gfp_mask), nodemask) { 7553 spin_lock_irqsave(&zone->lock, flags); 7554 7555 pfn = ALIGN(zone->zone_start_pfn, nr_pages); 7556 while (zone_spans_last_pfn(zone, pfn, nr_pages)) { 7557 if (pfn_range_valid_contig(zone, pfn, nr_pages, 7558 skip_hugetlb, 7559 &skipped_hugetlb)) { 7560 /* 7561 * We release the zone lock here because 7562 * alloc_contig_frozen_range() will also lock 7563 * the zone at some point. If there's an 7564 * allocation spinning on this lock, it may 7565 * win the race and cause allocation to fail. 7566 */ 7567 spin_unlock_irqrestore(&zone->lock, flags); 7568 ret = alloc_contig_frozen_range_noprof(pfn, 7569 pfn + nr_pages, 7570 ACR_FLAGS_NONE, 7571 gfp_mask); 7572 if (!ret) 7573 return pfn_to_page(pfn); 7574 spin_lock_irqsave(&zone->lock, flags); 7575 } 7576 pfn += nr_pages; 7577 } 7578 spin_unlock_irqrestore(&zone->lock, flags); 7579 } 7580 /* 7581 * If we failed, retry the search, but treat regions with HugeTLB pages 7582 * as valid targets. This retains fast-allocations on first pass 7583 * without trying to migrate HugeTLB pages (which may fail). On the 7584 * second pass, we will try moving HugeTLB pages when those pages are 7585 * smaller than the requested contiguous region size. 7586 */ 7587 if (skip_hugetlb && skipped_hugetlb) { 7588 skip_hugetlb = false; 7589 goto retry; 7590 } 7591 return NULL; 7592 } 7593 EXPORT_SYMBOL(alloc_contig_frozen_pages_noprof); 7594 7595 /** 7596 * alloc_contig_pages() -- tries to find and allocate contiguous range of pages 7597 * @nr_pages: Number of contiguous pages to allocate 7598 * @gfp_mask: GFP mask. 7599 * @nid: Target node 7600 * @nodemask: Mask for other possible nodes 7601 * 7602 * This routine is a wrapper around alloc_contig_frozen_pages(), it can't 7603 * be used to allocate compound pages, the refcount of each allocated page 7604 * will be set to one. 7605 * 7606 * Allocated pages can be freed with free_contig_range() or by manually 7607 * calling __free_page() on each allocated page. 7608 * 7609 * Return: pointer to contiguous pages on success, or NULL if not successful. 7610 */ 7611 struct page *alloc_contig_pages_noprof(unsigned long nr_pages, gfp_t gfp_mask, 7612 int nid, nodemask_t *nodemask) 7613 { 7614 struct page *page; 7615 7616 if (WARN_ON(gfp_mask & __GFP_COMP)) 7617 return NULL; 7618 7619 page = alloc_contig_frozen_pages_noprof(nr_pages, gfp_mask, nid, 7620 nodemask); 7621 if (page) 7622 set_pages_refcounted(page, nr_pages); 7623 7624 return page; 7625 } 7626 EXPORT_SYMBOL(alloc_contig_pages_noprof); 7627 7628 /** 7629 * free_contig_frozen_range() -- free the contiguous range of frozen pages 7630 * @pfn: start PFN to free 7631 * @nr_pages: Number of contiguous frozen pages to free 7632 * 7633 * This can be used to free the allocated compound/non-compound frozen pages. 7634 */ 7635 void free_contig_frozen_range(unsigned long pfn, unsigned long nr_pages) 7636 { 7637 struct page *first_page = pfn_to_page(pfn); 7638 const unsigned int order = ilog2(nr_pages); 7639 7640 if (WARN_ON_ONCE(first_page != compound_head(first_page))) 7641 return; 7642 7643 if (PageHead(first_page)) { 7644 WARN_ON_ONCE(order != compound_order(first_page)); 7645 free_frozen_pages(first_page, order); 7646 return; 7647 } 7648 7649 __free_contig_frozen_range(pfn, nr_pages); 7650 } 7651 EXPORT_SYMBOL(free_contig_frozen_range); 7652 7653 /** 7654 * free_contig_range() -- free the contiguous range of pages 7655 * @pfn: start PFN to free 7656 * @nr_pages: Number of contiguous pages to free 7657 * 7658 * This can be only used to free the allocated non-compound pages. 7659 */ 7660 void free_contig_range(unsigned long pfn, unsigned long nr_pages) 7661 { 7662 if (WARN_ON_ONCE(PageHead(pfn_to_page(pfn)))) 7663 return; 7664 7665 __free_contig_range(pfn, nr_pages); 7666 } 7667 EXPORT_SYMBOL(free_contig_range); 7668 #endif /* CONFIG_CONTIG_ALLOC */ 7669 7670 /* 7671 * Effectively disable pcplists for the zone by setting the high limit to 0 7672 * and draining all cpus. A concurrent page freeing on another CPU that's about 7673 * to put the page on pcplist will either finish before the drain and the page 7674 * will be drained, or observe the new high limit and skip the pcplist. 7675 * 7676 * Must be paired with a call to zone_pcp_enable(). 7677 */ 7678 void zone_pcp_disable(struct zone *zone) 7679 { 7680 mutex_lock(&pcp_batch_high_lock); 7681 __zone_set_pageset_high_and_batch(zone, 0, 0, 1); 7682 __drain_all_pages(zone, true); 7683 } 7684 7685 void zone_pcp_enable(struct zone *zone) 7686 { 7687 __zone_set_pageset_high_and_batch(zone, zone->pageset_high_min, 7688 zone->pageset_high_max, zone->pageset_batch); 7689 mutex_unlock(&pcp_batch_high_lock); 7690 } 7691 7692 void zone_pcp_reset(struct zone *zone) 7693 { 7694 int cpu; 7695 struct per_cpu_zonestat *pzstats; 7696 7697 if (zone->per_cpu_pageset != &boot_pageset) { 7698 for_each_online_cpu(cpu) { 7699 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu); 7700 drain_zonestat(zone, pzstats); 7701 } 7702 free_percpu(zone->per_cpu_pageset); 7703 zone->per_cpu_pageset = &boot_pageset; 7704 if (zone->per_cpu_zonestats != &boot_zonestats) { 7705 free_percpu(zone->per_cpu_zonestats); 7706 zone->per_cpu_zonestats = &boot_zonestats; 7707 } 7708 } 7709 } 7710 7711 #ifdef CONFIG_MEMORY_HOTREMOVE 7712 /* 7713 * All pages in the range must be in a single zone, must not contain holes, 7714 * must span full sections, and must be isolated before calling this function. 7715 * 7716 * Returns the number of managed (non-PageOffline()) pages in the range: the 7717 * number of pages for which memory offlining code must adjust managed page 7718 * counters using adjust_managed_page_count(). 7719 */ 7720 unsigned long __offline_isolated_pages(unsigned long start_pfn, 7721 unsigned long end_pfn) 7722 { 7723 unsigned long already_offline = 0; 7724 unsigned long pfn = start_pfn; 7725 struct page *page; 7726 struct zone *zone; 7727 unsigned int order; 7728 7729 offline_mem_sections(pfn, end_pfn); 7730 zone = page_zone(pfn_to_page(pfn)); 7731 guard(spinlock_irqsave)(&zone->lock); 7732 while (pfn < end_pfn) { 7733 page = pfn_to_page(pfn); 7734 /* 7735 * The HWPoisoned page may be not in buddy system, and 7736 * page_count() is not 0. 7737 */ 7738 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) { 7739 pfn++; 7740 continue; 7741 } 7742 /* 7743 * At this point all remaining PageOffline() pages have a 7744 * reference count of 0 and can simply be skipped. 7745 */ 7746 if (PageOffline(page)) { 7747 BUG_ON(page_count(page)); 7748 BUG_ON(PageBuddy(page)); 7749 already_offline++; 7750 pfn++; 7751 continue; 7752 } 7753 7754 BUG_ON(page_count(page)); 7755 BUG_ON(!PageBuddy(page)); 7756 VM_WARN_ON(get_pageblock_migratetype(page) != MIGRATE_ISOLATE); 7757 order = buddy_order(page); 7758 del_page_from_free_list(page, zone, order, MIGRATE_ISOLATE); 7759 pfn += (1 << order); 7760 } 7761 7762 return end_pfn - start_pfn - already_offline; 7763 } 7764 #endif 7765 7766 /* 7767 * This function returns a stable result only if called under zone lock. 7768 */ 7769 bool is_free_buddy_page(const struct page *page) 7770 { 7771 unsigned long pfn = page_to_pfn(page); 7772 unsigned int order; 7773 7774 for (order = 0; order < NR_PAGE_ORDERS; order++) { 7775 const struct page *head = page - (pfn & ((1 << order) - 1)); 7776 7777 if (PageBuddy(head) && 7778 buddy_order_unsafe(head) >= order) 7779 break; 7780 } 7781 7782 return order <= MAX_PAGE_ORDER; 7783 } 7784 EXPORT_SYMBOL(is_free_buddy_page); 7785 7786 #ifdef CONFIG_MEMORY_FAILURE 7787 static inline void add_to_free_list(struct page *page, struct zone *zone, 7788 unsigned int order, int migratetype, 7789 bool tail) 7790 { 7791 __add_to_free_list(page, zone, order, migratetype, tail); 7792 account_freepages(zone, 1 << order, migratetype); 7793 } 7794 7795 /* 7796 * Break down a higher-order page in sub-pages, and keep our target out of 7797 * buddy allocator. 7798 */ 7799 static void break_down_buddy_pages(struct zone *zone, struct page *page, 7800 struct page *target, int low, int high, 7801 int migratetype) 7802 { 7803 unsigned long size = 1 << high; 7804 struct page *current_buddy; 7805 7806 while (high > low) { 7807 high--; 7808 size >>= 1; 7809 7810 if (target >= &page[size]) { 7811 current_buddy = page; 7812 page = page + size; 7813 } else { 7814 current_buddy = page + size; 7815 } 7816 7817 if (set_page_guard(zone, current_buddy, high)) 7818 continue; 7819 7820 add_to_free_list(current_buddy, zone, high, migratetype, false); 7821 set_buddy_order(current_buddy, high); 7822 } 7823 } 7824 7825 /* 7826 * Take a page that will be marked as poisoned off the buddy allocator. 7827 */ 7828 bool take_page_off_buddy(struct page *page) 7829 { 7830 struct zone *zone = page_zone(page); 7831 unsigned long pfn = page_to_pfn(page); 7832 unsigned int order; 7833 7834 guard(spinlock_irqsave)(&zone->lock); 7835 for (order = 0; order < NR_PAGE_ORDERS; order++) { 7836 struct page *page_head = page - (pfn & ((1 << order) - 1)); 7837 int page_order = buddy_order(page_head); 7838 7839 if (PageBuddy(page_head) && page_order >= order) { 7840 unsigned long pfn_head = page_to_pfn(page_head); 7841 int migratetype = get_pfnblock_migratetype(page_head, 7842 pfn_head); 7843 7844 del_page_from_free_list(page_head, zone, page_order, 7845 migratetype); 7846 break_down_buddy_pages(zone, page_head, page, 0, 7847 page_order, migratetype); 7848 SetPageHWPoisonTakenOff(page); 7849 return true; 7850 } 7851 if (page_count(page_head) > 0) 7852 break; 7853 } 7854 return false; 7855 } 7856 7857 /* 7858 * Cancel takeoff done by take_page_off_buddy(). 7859 */ 7860 bool put_page_back_buddy(struct page *page) 7861 { 7862 struct zone *zone = page_zone(page); 7863 7864 guard(spinlock_irqsave)(&zone->lock); 7865 if (put_page_testzero(page)) { 7866 unsigned long pfn = page_to_pfn(page); 7867 int migratetype = get_pfnblock_migratetype(page, pfn); 7868 7869 ClearPageHWPoisonTakenOff(page); 7870 __free_one_page(page, pfn, zone, 0, migratetype, FPI_NONE); 7871 if (TestClearPageHWPoison(page)) 7872 return true; 7873 } 7874 7875 return false; 7876 } 7877 #endif 7878 7879 bool has_managed_zone(enum zone_type zone) 7880 { 7881 struct pglist_data *pgdat; 7882 7883 for_each_online_pgdat(pgdat) { 7884 if (managed_zone(&pgdat->node_zones[zone])) 7885 return true; 7886 } 7887 return false; 7888 } 7889 7890 #ifdef CONFIG_UNACCEPTED_MEMORY 7891 7892 static bool lazy_accept = true; 7893 7894 static int __init accept_memory_parse(char *p) 7895 { 7896 if (!strcmp(p, "lazy")) { 7897 lazy_accept = true; 7898 return 0; 7899 } else if (!strcmp(p, "eager")) { 7900 lazy_accept = false; 7901 return 0; 7902 } else { 7903 return -EINVAL; 7904 } 7905 } 7906 early_param("accept_memory", accept_memory_parse); 7907 7908 static bool page_contains_unaccepted(struct page *page, unsigned int order) 7909 { 7910 phys_addr_t start = page_to_phys(page); 7911 7912 return range_contains_unaccepted_memory(start, PAGE_SIZE << order); 7913 } 7914 7915 static void __accept_page(struct zone *zone, unsigned long *flags, 7916 struct page *page) 7917 { 7918 list_del(&page->lru); 7919 account_freepages(zone, -MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE); 7920 __mod_zone_page_state(zone, NR_UNACCEPTED, -MAX_ORDER_NR_PAGES); 7921 __ClearPageUnaccepted(page); 7922 spin_unlock_irqrestore(&zone->lock, *flags); 7923 7924 accept_memory(page_to_phys(page), PAGE_SIZE << MAX_PAGE_ORDER); 7925 7926 __free_pages_ok(page, MAX_PAGE_ORDER, FPI_TO_TAIL); 7927 } 7928 7929 void accept_page(struct page *page) 7930 { 7931 struct zone *zone = page_zone(page); 7932 unsigned long flags; 7933 7934 spin_lock_irqsave(&zone->lock, flags); 7935 if (!PageUnaccepted(page)) { 7936 spin_unlock_irqrestore(&zone->lock, flags); 7937 return; 7938 } 7939 7940 /* Unlocks zone->lock */ 7941 __accept_page(zone, &flags, page); 7942 } 7943 7944 static bool try_to_accept_memory_one(struct zone *zone) 7945 { 7946 unsigned long flags; 7947 struct page *page; 7948 7949 spin_lock_irqsave(&zone->lock, flags); 7950 page = list_first_entry_or_null(&zone->unaccepted_pages, 7951 struct page, lru); 7952 if (!page) { 7953 spin_unlock_irqrestore(&zone->lock, flags); 7954 return false; 7955 } 7956 7957 /* Unlocks zone->lock */ 7958 __accept_page(zone, &flags, page); 7959 7960 return true; 7961 } 7962 7963 static bool cond_accept_memory(struct zone *zone, unsigned int order, 7964 int alloc_flags) 7965 { 7966 long to_accept, wmark; 7967 bool ret = false; 7968 7969 if (list_empty(&zone->unaccepted_pages)) 7970 return false; 7971 7972 /* Bailout, since try_to_accept_memory_one() needs to take a lock */ 7973 if (alloc_flags & ALLOC_NOLOCK) 7974 return false; 7975 7976 wmark = promo_wmark_pages(zone); 7977 7978 /* 7979 * Watermarks have not been initialized yet. 7980 * 7981 * Accepting one MAX_ORDER page to ensure progress. 7982 */ 7983 if (!wmark) 7984 return try_to_accept_memory_one(zone); 7985 7986 /* How much to accept to get to promo watermark? */ 7987 to_accept = wmark - 7988 (zone_page_state(zone, NR_FREE_PAGES) - 7989 __zone_watermark_unusable_free(zone, order, 0) - 7990 zone_page_state(zone, NR_UNACCEPTED)); 7991 7992 while (to_accept > 0) { 7993 if (!try_to_accept_memory_one(zone)) 7994 break; 7995 ret = true; 7996 to_accept -= MAX_ORDER_NR_PAGES; 7997 } 7998 7999 return ret; 8000 } 8001 8002 static bool __free_unaccepted(struct page *page) 8003 { 8004 struct zone *zone = page_zone(page); 8005 unsigned long flags; 8006 8007 if (!lazy_accept) 8008 return false; 8009 8010 spin_lock_irqsave(&zone->lock, flags); 8011 list_add_tail(&page->lru, &zone->unaccepted_pages); 8012 account_freepages(zone, MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE); 8013 __mod_zone_page_state(zone, NR_UNACCEPTED, MAX_ORDER_NR_PAGES); 8014 __SetPageUnaccepted(page); 8015 spin_unlock_irqrestore(&zone->lock, flags); 8016 8017 return true; 8018 } 8019 8020 #else 8021 8022 static bool page_contains_unaccepted(struct page *page, unsigned int order) 8023 { 8024 return false; 8025 } 8026 8027 static bool cond_accept_memory(struct zone *zone, unsigned int order, 8028 int alloc_flags) 8029 { 8030 return false; 8031 } 8032 8033 static bool __free_unaccepted(struct page *page) 8034 { 8035 BUILD_BUG(); 8036 return false; 8037 } 8038 8039 #endif /* CONFIG_UNACCEPTED_MEMORY */ 8040 8041 struct page *alloc_frozen_pages_nolock_noprof(gfp_t gfp_flags, int nid, unsigned int order) 8042 { 8043 if (nid == NUMA_NO_NODE) 8044 nid = numa_node_id(); 8045 8046 return __alloc_frozen_pages_noprof(gfp_flags, order, nid, NULL, ALLOC_NOLOCK); 8047 } 8048 /** 8049 * alloc_pages_nolock - opportunistic reentrant allocation from any context 8050 * @gfp_flags: GFP flags. Only __GFP_ACCOUNT, plus some flags that get set 8051 * internally regardless (see %gfp_nolock) are allowed. 8052 * @nid: node to allocate from 8053 * @order: allocation order size 8054 * 8055 * Allocates pages of a given order from the given node. This is safe to 8056 * call from any context where RCU is watching (from atomic, NMI, and also 8057 * reentrant allocator -> tracepoint -> alloc_pages_nolock_noprof). 8058 * Allocation is best effort and to be expected to fail easily so nobody should 8059 * rely on the success. Failures are not reported via warn_alloc(). 8060 * See always fail conditions below. 8061 * 8062 * Return: allocated page or NULL on failure. NULL does not mean EBUSY or EAGAIN. 8063 * It means ENOMEM. There is no reason to call it again and expect !NULL. 8064 */ 8065 struct page *alloc_pages_nolock_noprof(gfp_t gfp_flags, int nid, unsigned int order) 8066 { 8067 struct page *page; 8068 8069 page = alloc_frozen_pages_nolock_noprof(gfp_flags, nid, order); 8070 if (page) 8071 set_page_refcounted(page); 8072 return page; 8073 } 8074 EXPORT_SYMBOL_GPL(alloc_pages_nolock_noprof); 8075