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