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