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