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