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