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 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */ 4562 if (alloc_flags & ALLOC_KSWAPD) 4563 wake_all_kswapds(order, gfp_mask, ac); 4564 4565 reserve_flags = __gfp_pfmemalloc_flags(gfp_mask); 4566 if (reserve_flags) 4567 alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, reserve_flags) | 4568 (alloc_flags & ALLOC_KSWAPD); 4569 4570 /* 4571 * Reset the nodemask and zonelist iterators if memory policies can be 4572 * ignored. These allocations are high priority and system rather than 4573 * user oriented. 4574 */ 4575 if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) { 4576 ac->nodemask = NULL; 4577 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist, 4578 ac->highest_zoneidx, ac->nodemask); 4579 } 4580 4581 /* Attempt with potentially adjusted zonelist and alloc_flags */ 4582 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 4583 if (page) 4584 goto got_pg; 4585 4586 /* Caller is not willing to reclaim, we can't balance anything */ 4587 if (!can_direct_reclaim) 4588 goto nopage; 4589 4590 /* Avoid recursion of direct reclaim */ 4591 if (current->flags & PF_MEMALLOC) 4592 goto nopage; 4593 4594 /* Try direct reclaim and then allocating */ 4595 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac, 4596 &did_some_progress); 4597 if (page) 4598 goto got_pg; 4599 4600 /* Try direct compaction and then allocating */ 4601 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac, 4602 compact_priority, &compact_result); 4603 if (page) 4604 goto got_pg; 4605 4606 /* Do not loop if specifically requested */ 4607 if (gfp_mask & __GFP_NORETRY) 4608 goto nopage; 4609 4610 /* 4611 * Do not retry costly high order allocations unless they are 4612 * __GFP_RETRY_MAYFAIL and we can compact 4613 */ 4614 if (costly_order && (!can_compact || 4615 !(gfp_mask & __GFP_RETRY_MAYFAIL))) 4616 goto nopage; 4617 4618 if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags, 4619 did_some_progress > 0, &no_progress_loops)) 4620 goto retry; 4621 4622 /* 4623 * It doesn't make any sense to retry for the compaction if the order-0 4624 * reclaim is not able to make any progress because the current 4625 * implementation of the compaction depends on the sufficient amount 4626 * of free memory (see __compaction_suitable) 4627 */ 4628 if (did_some_progress > 0 && can_compact && 4629 should_compact_retry(ac, order, alloc_flags, 4630 compact_result, &compact_priority, 4631 &compaction_retries)) 4632 goto retry; 4633 4634 /* Reclaim/compaction failed to prevent the fallback */ 4635 if (defrag_mode && (alloc_flags & ALLOC_NOFRAGMENT)) { 4636 alloc_flags &= ~ALLOC_NOFRAGMENT; 4637 goto retry; 4638 } 4639 4640 /* 4641 * Deal with possible cpuset update races or zonelist updates to avoid 4642 * a unnecessary OOM kill. 4643 */ 4644 if (check_retry_cpuset(cpuset_mems_cookie, ac) || 4645 check_retry_zonelist(zonelist_iter_cookie)) 4646 goto restart; 4647 4648 /* Reclaim has failed us, start killing things */ 4649 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress); 4650 if (page) 4651 goto got_pg; 4652 4653 /* Avoid allocations with no watermarks from looping endlessly */ 4654 if (tsk_is_oom_victim(current) && 4655 (alloc_flags & ALLOC_OOM || 4656 (gfp_mask & __GFP_NOMEMALLOC))) 4657 goto nopage; 4658 4659 /* Retry as long as the OOM killer is making progress */ 4660 if (did_some_progress) { 4661 no_progress_loops = 0; 4662 goto retry; 4663 } 4664 4665 nopage: 4666 /* 4667 * Deal with possible cpuset update races or zonelist updates to avoid 4668 * a unnecessary OOM kill. 4669 */ 4670 if (check_retry_cpuset(cpuset_mems_cookie, ac) || 4671 check_retry_zonelist(zonelist_iter_cookie)) 4672 goto restart; 4673 4674 /* 4675 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure 4676 * we always retry 4677 */ 4678 if (unlikely(nofail)) { 4679 /* 4680 * Lacking direct_reclaim we can't do anything to reclaim memory, 4681 * we disregard these unreasonable nofail requests and still 4682 * return NULL 4683 */ 4684 if (!can_direct_reclaim) 4685 goto fail; 4686 4687 /* 4688 * Help non-failing allocations by giving some access to memory 4689 * reserves normally used for high priority non-blocking 4690 * allocations but do not use ALLOC_NO_WATERMARKS because this 4691 * could deplete whole memory reserves which would just make 4692 * the situation worse. 4693 */ 4694 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_MIN_RESERVE, ac); 4695 if (page) 4696 goto got_pg; 4697 4698 cond_resched(); 4699 goto retry; 4700 } 4701 fail: 4702 warn_alloc(gfp_mask, ac->nodemask, 4703 "page allocation failure: order:%u", order); 4704 got_pg: 4705 return page; 4706 } 4707 4708 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order, 4709 int preferred_nid, nodemask_t *nodemask, 4710 struct alloc_context *ac, gfp_t *alloc_gfp, 4711 unsigned int *alloc_flags) 4712 { 4713 ac->highest_zoneidx = gfp_zone(gfp_mask); 4714 ac->zonelist = node_zonelist(preferred_nid, gfp_mask); 4715 ac->nodemask = nodemask; 4716 ac->migratetype = gfp_migratetype(gfp_mask); 4717 4718 if (cpusets_enabled()) { 4719 *alloc_gfp |= __GFP_HARDWALL; 4720 /* 4721 * When we are in the interrupt context, it is irrelevant 4722 * to the current task context. It means that any node ok. 4723 */ 4724 if (in_task() && !ac->nodemask) 4725 ac->nodemask = &cpuset_current_mems_allowed; 4726 else 4727 *alloc_flags |= ALLOC_CPUSET; 4728 } 4729 4730 might_alloc(gfp_mask); 4731 4732 /* 4733 * Don't invoke should_fail logic, since it may call 4734 * get_random_u32() and printk() which need to spin_lock. 4735 */ 4736 if (!(*alloc_flags & ALLOC_TRYLOCK) && 4737 should_fail_alloc_page(gfp_mask, order)) 4738 return false; 4739 4740 *alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, *alloc_flags); 4741 4742 /* Dirty zone balancing only done in the fast path */ 4743 ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE); 4744 4745 /* 4746 * The preferred zone is used for statistics but crucially it is 4747 * also used as the starting point for the zonelist iterator. It 4748 * may get reset for allocations that ignore memory policies. 4749 */ 4750 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist, 4751 ac->highest_zoneidx, ac->nodemask); 4752 4753 return true; 4754 } 4755 4756 /* 4757 * __alloc_pages_bulk - Allocate a number of order-0 pages to an array 4758 * @gfp: GFP flags for the allocation 4759 * @preferred_nid: The preferred NUMA node ID to allocate from 4760 * @nodemask: Set of nodes to allocate from, may be NULL 4761 * @nr_pages: The number of pages desired in the array 4762 * @page_array: Array to store the pages 4763 * 4764 * This is a batched version of the page allocator that attempts to 4765 * allocate nr_pages quickly. Pages are added to the page_array. 4766 * 4767 * Note that only NULL elements are populated with pages and nr_pages 4768 * is the maximum number of pages that will be stored in the array. 4769 * 4770 * Returns the number of pages in the array. 4771 */ 4772 unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, 4773 nodemask_t *nodemask, int nr_pages, 4774 struct page **page_array) 4775 { 4776 struct page *page; 4777 unsigned long __maybe_unused UP_flags; 4778 struct zone *zone; 4779 struct zoneref *z; 4780 struct per_cpu_pages *pcp; 4781 struct list_head *pcp_list; 4782 struct alloc_context ac; 4783 gfp_t alloc_gfp; 4784 unsigned int alloc_flags = ALLOC_WMARK_LOW; 4785 int nr_populated = 0, nr_account = 0; 4786 4787 /* 4788 * Skip populated array elements to determine if any pages need 4789 * to be allocated before disabling IRQs. 4790 */ 4791 while (nr_populated < nr_pages && page_array[nr_populated]) 4792 nr_populated++; 4793 4794 /* No pages requested? */ 4795 if (unlikely(nr_pages <= 0)) 4796 goto out; 4797 4798 /* Already populated array? */ 4799 if (unlikely(nr_pages - nr_populated == 0)) 4800 goto out; 4801 4802 /* Bulk allocator does not support memcg accounting. */ 4803 if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT)) 4804 goto failed; 4805 4806 /* Use the single page allocator for one page. */ 4807 if (nr_pages - nr_populated == 1) 4808 goto failed; 4809 4810 #ifdef CONFIG_PAGE_OWNER 4811 /* 4812 * PAGE_OWNER may recurse into the allocator to allocate space to 4813 * save the stack with pagesets.lock held. Releasing/reacquiring 4814 * removes much of the performance benefit of bulk allocation so 4815 * force the caller to allocate one page at a time as it'll have 4816 * similar performance to added complexity to the bulk allocator. 4817 */ 4818 if (static_branch_unlikely(&page_owner_inited)) 4819 goto failed; 4820 #endif 4821 4822 /* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */ 4823 gfp &= gfp_allowed_mask; 4824 alloc_gfp = gfp; 4825 if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &alloc_gfp, &alloc_flags)) 4826 goto out; 4827 gfp = alloc_gfp; 4828 4829 /* Find an allowed local zone that meets the low watermark. */ 4830 z = ac.preferred_zoneref; 4831 for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) { 4832 unsigned long mark; 4833 4834 if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) && 4835 !__cpuset_zone_allowed(zone, gfp)) { 4836 continue; 4837 } 4838 4839 if (nr_online_nodes > 1 && zone != zonelist_zone(ac.preferred_zoneref) && 4840 zone_to_nid(zone) != zonelist_node_idx(ac.preferred_zoneref)) { 4841 goto failed; 4842 } 4843 4844 cond_accept_memory(zone, 0, alloc_flags); 4845 retry_this_zone: 4846 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages; 4847 if (zone_watermark_fast(zone, 0, mark, 4848 zonelist_zone_idx(ac.preferred_zoneref), 4849 alloc_flags, gfp)) { 4850 break; 4851 } 4852 4853 if (cond_accept_memory(zone, 0, alloc_flags)) 4854 goto retry_this_zone; 4855 4856 /* Try again if zone has deferred pages */ 4857 if (deferred_pages_enabled()) { 4858 if (_deferred_grow_zone(zone, 0)) 4859 goto retry_this_zone; 4860 } 4861 } 4862 4863 /* 4864 * If there are no allowed local zones that meets the watermarks then 4865 * try to allocate a single page and reclaim if necessary. 4866 */ 4867 if (unlikely(!zone)) 4868 goto failed; 4869 4870 /* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */ 4871 pcp_trylock_prepare(UP_flags); 4872 pcp = pcp_spin_trylock(zone->per_cpu_pageset); 4873 if (!pcp) 4874 goto failed_irq; 4875 4876 /* Attempt the batch allocation */ 4877 pcp_list = &pcp->lists[order_to_pindex(ac.migratetype, 0)]; 4878 while (nr_populated < nr_pages) { 4879 4880 /* Skip existing pages */ 4881 if (page_array[nr_populated]) { 4882 nr_populated++; 4883 continue; 4884 } 4885 4886 page = __rmqueue_pcplist(zone, 0, ac.migratetype, alloc_flags, 4887 pcp, pcp_list); 4888 if (unlikely(!page)) { 4889 /* Try and allocate at least one page */ 4890 if (!nr_account) { 4891 pcp_spin_unlock(pcp); 4892 goto failed_irq; 4893 } 4894 break; 4895 } 4896 nr_account++; 4897 4898 prep_new_page(page, 0, gfp, 0); 4899 set_page_refcounted(page); 4900 page_array[nr_populated++] = page; 4901 } 4902 4903 pcp_spin_unlock(pcp); 4904 pcp_trylock_finish(UP_flags); 4905 4906 __count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account); 4907 zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account); 4908 4909 out: 4910 return nr_populated; 4911 4912 failed_irq: 4913 pcp_trylock_finish(UP_flags); 4914 4915 failed: 4916 page = __alloc_pages_noprof(gfp, 0, preferred_nid, nodemask); 4917 if (page) 4918 page_array[nr_populated++] = page; 4919 goto out; 4920 } 4921 EXPORT_SYMBOL_GPL(alloc_pages_bulk_noprof); 4922 4923 /* 4924 * This is the 'heart' of the zoned buddy allocator. 4925 */ 4926 struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order, 4927 int preferred_nid, nodemask_t *nodemask) 4928 { 4929 struct page *page; 4930 unsigned int alloc_flags = ALLOC_WMARK_LOW; 4931 gfp_t alloc_gfp; /* The gfp_t that was actually used for allocation */ 4932 struct alloc_context ac = { }; 4933 4934 /* 4935 * There are several places where we assume that the order value is sane 4936 * so bail out early if the request is out of bound. 4937 */ 4938 if (WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp)) 4939 return NULL; 4940 4941 gfp &= gfp_allowed_mask; 4942 /* 4943 * Apply scoped allocation constraints. This is mainly about GFP_NOFS 4944 * resp. GFP_NOIO which has to be inherited for all allocation requests 4945 * from a particular context which has been marked by 4946 * memalloc_no{fs,io}_{save,restore}. And PF_MEMALLOC_PIN which ensures 4947 * movable zones are not used during allocation. 4948 */ 4949 gfp = current_gfp_context(gfp); 4950 alloc_gfp = gfp; 4951 if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac, 4952 &alloc_gfp, &alloc_flags)) 4953 return NULL; 4954 4955 /* 4956 * Forbid the first pass from falling back to types that fragment 4957 * memory until all local zones are considered. 4958 */ 4959 alloc_flags |= alloc_flags_nofragment(zonelist_zone(ac.preferred_zoneref), gfp); 4960 4961 /* First allocation attempt */ 4962 page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac); 4963 if (likely(page)) 4964 goto out; 4965 4966 alloc_gfp = gfp; 4967 ac.spread_dirty_pages = false; 4968 4969 /* 4970 * Restore the original nodemask if it was potentially replaced with 4971 * &cpuset_current_mems_allowed to optimize the fast-path attempt. 4972 */ 4973 ac.nodemask = nodemask; 4974 4975 page = __alloc_pages_slowpath(alloc_gfp, order, &ac); 4976 4977 out: 4978 if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT) && page && 4979 unlikely(__memcg_kmem_charge_page(page, gfp, order) != 0)) { 4980 free_frozen_pages(page, order); 4981 page = NULL; 4982 } 4983 4984 trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype); 4985 kmsan_alloc_page(page, order, alloc_gfp); 4986 4987 return page; 4988 } 4989 EXPORT_SYMBOL(__alloc_frozen_pages_noprof); 4990 4991 struct page *__alloc_pages_noprof(gfp_t gfp, unsigned int order, 4992 int preferred_nid, nodemask_t *nodemask) 4993 { 4994 struct page *page; 4995 4996 page = __alloc_frozen_pages_noprof(gfp, order, preferred_nid, nodemask); 4997 if (page) 4998 set_page_refcounted(page); 4999 return page; 5000 } 5001 EXPORT_SYMBOL(__alloc_pages_noprof); 5002 5003 struct folio *__folio_alloc_noprof(gfp_t gfp, unsigned int order, int preferred_nid, 5004 nodemask_t *nodemask) 5005 { 5006 struct page *page = __alloc_pages_noprof(gfp | __GFP_COMP, order, 5007 preferred_nid, nodemask); 5008 return page_rmappable_folio(page); 5009 } 5010 EXPORT_SYMBOL(__folio_alloc_noprof); 5011 5012 /* 5013 * Common helper functions. Never use with __GFP_HIGHMEM because the returned 5014 * address cannot represent highmem pages. Use alloc_pages and then kmap if 5015 * you need to access high mem. 5016 */ 5017 unsigned long get_free_pages_noprof(gfp_t gfp_mask, unsigned int order) 5018 { 5019 struct page *page; 5020 5021 page = alloc_pages_noprof(gfp_mask & ~__GFP_HIGHMEM, order); 5022 if (!page) 5023 return 0; 5024 return (unsigned long) page_address(page); 5025 } 5026 EXPORT_SYMBOL(get_free_pages_noprof); 5027 5028 unsigned long get_zeroed_page_noprof(gfp_t gfp_mask) 5029 { 5030 return get_free_pages_noprof(gfp_mask | __GFP_ZERO, 0); 5031 } 5032 EXPORT_SYMBOL(get_zeroed_page_noprof); 5033 5034 /** 5035 * ___free_pages - Free pages allocated with alloc_pages(). 5036 * @page: The page pointer returned from alloc_pages(). 5037 * @order: The order of the allocation. 5038 * @fpi_flags: Free Page Internal flags. 5039 * 5040 * This function can free multi-page allocations that are not compound 5041 * pages. It does not check that the @order passed in matches that of 5042 * the allocation, so it is easy to leak memory. Freeing more memory 5043 * than was allocated will probably emit a warning. 5044 * 5045 * If the last reference to this page is speculative, it will be released 5046 * by put_page() which only frees the first page of a non-compound 5047 * allocation. To prevent the remaining pages from being leaked, we free 5048 * the subsequent pages here. If you want to use the page's reference 5049 * count to decide when to free the allocation, you should allocate a 5050 * compound page, and use put_page() instead of __free_pages(). 5051 * 5052 * Context: May be called in interrupt context or while holding a normal 5053 * spinlock, but not in NMI context or while holding a raw spinlock. 5054 */ 5055 static void ___free_pages(struct page *page, unsigned int order, 5056 fpi_t fpi_flags) 5057 { 5058 /* get PageHead before we drop reference */ 5059 int head = PageHead(page); 5060 /* get alloc tag in case the page is released by others */ 5061 struct alloc_tag *tag = pgalloc_tag_get(page); 5062 5063 if (put_page_testzero(page)) 5064 __free_frozen_pages(page, order, fpi_flags); 5065 else if (!head) { 5066 pgalloc_tag_sub_pages(tag, (1 << order) - 1); 5067 while (order-- > 0) 5068 __free_frozen_pages(page + (1 << order), order, 5069 fpi_flags); 5070 } 5071 } 5072 void __free_pages(struct page *page, unsigned int order) 5073 { 5074 ___free_pages(page, order, FPI_NONE); 5075 } 5076 EXPORT_SYMBOL(__free_pages); 5077 5078 /* 5079 * Can be called while holding raw_spin_lock or from IRQ and NMI for any 5080 * page type (not only those that came from try_alloc_pages) 5081 */ 5082 void free_pages_nolock(struct page *page, unsigned int order) 5083 { 5084 ___free_pages(page, order, FPI_TRYLOCK); 5085 } 5086 5087 void free_pages(unsigned long addr, unsigned int order) 5088 { 5089 if (addr != 0) { 5090 VM_BUG_ON(!virt_addr_valid((void *)addr)); 5091 __free_pages(virt_to_page((void *)addr), order); 5092 } 5093 } 5094 5095 EXPORT_SYMBOL(free_pages); 5096 5097 static void *make_alloc_exact(unsigned long addr, unsigned int order, 5098 size_t size) 5099 { 5100 if (addr) { 5101 unsigned long nr = DIV_ROUND_UP(size, PAGE_SIZE); 5102 struct page *page = virt_to_page((void *)addr); 5103 struct page *last = page + nr; 5104 5105 split_page_owner(page, order, 0); 5106 pgalloc_tag_split(page_folio(page), order, 0); 5107 split_page_memcg(page, order); 5108 while (page < --last) 5109 set_page_refcounted(last); 5110 5111 last = page + (1UL << order); 5112 for (page += nr; page < last; page++) 5113 __free_pages_ok(page, 0, FPI_TO_TAIL); 5114 } 5115 return (void *)addr; 5116 } 5117 5118 /** 5119 * alloc_pages_exact - allocate an exact number physically-contiguous pages. 5120 * @size: the number of bytes to allocate 5121 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP 5122 * 5123 * This function is similar to alloc_pages(), except that it allocates the 5124 * minimum number of pages to satisfy the request. alloc_pages() can only 5125 * allocate memory in power-of-two pages. 5126 * 5127 * This function is also limited by MAX_PAGE_ORDER. 5128 * 5129 * Memory allocated by this function must be released by free_pages_exact(). 5130 * 5131 * Return: pointer to the allocated area or %NULL in case of error. 5132 */ 5133 void *alloc_pages_exact_noprof(size_t size, gfp_t gfp_mask) 5134 { 5135 unsigned int order = get_order(size); 5136 unsigned long addr; 5137 5138 if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM))) 5139 gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM); 5140 5141 addr = get_free_pages_noprof(gfp_mask, order); 5142 return make_alloc_exact(addr, order, size); 5143 } 5144 EXPORT_SYMBOL(alloc_pages_exact_noprof); 5145 5146 /** 5147 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous 5148 * pages on a node. 5149 * @nid: the preferred node ID where memory should be allocated 5150 * @size: the number of bytes to allocate 5151 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP 5152 * 5153 * Like alloc_pages_exact(), but try to allocate on node nid first before falling 5154 * back. 5155 * 5156 * Return: pointer to the allocated area or %NULL in case of error. 5157 */ 5158 void * __meminit alloc_pages_exact_nid_noprof(int nid, size_t size, gfp_t gfp_mask) 5159 { 5160 unsigned int order = get_order(size); 5161 struct page *p; 5162 5163 if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM))) 5164 gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM); 5165 5166 p = alloc_pages_node_noprof(nid, gfp_mask, order); 5167 if (!p) 5168 return NULL; 5169 return make_alloc_exact((unsigned long)page_address(p), order, size); 5170 } 5171 5172 /** 5173 * free_pages_exact - release memory allocated via alloc_pages_exact() 5174 * @virt: the value returned by alloc_pages_exact. 5175 * @size: size of allocation, same value as passed to alloc_pages_exact(). 5176 * 5177 * Release the memory allocated by a previous call to alloc_pages_exact. 5178 */ 5179 void free_pages_exact(void *virt, size_t size) 5180 { 5181 unsigned long addr = (unsigned long)virt; 5182 unsigned long end = addr + PAGE_ALIGN(size); 5183 5184 while (addr < end) { 5185 free_page(addr); 5186 addr += PAGE_SIZE; 5187 } 5188 } 5189 EXPORT_SYMBOL(free_pages_exact); 5190 5191 /** 5192 * nr_free_zone_pages - count number of pages beyond high watermark 5193 * @offset: The zone index of the highest zone 5194 * 5195 * nr_free_zone_pages() counts the number of pages which are beyond the 5196 * high watermark within all zones at or below a given zone index. For each 5197 * zone, the number of pages is calculated as: 5198 * 5199 * nr_free_zone_pages = managed_pages - high_pages 5200 * 5201 * Return: number of pages beyond high watermark. 5202 */ 5203 static unsigned long nr_free_zone_pages(int offset) 5204 { 5205 struct zoneref *z; 5206 struct zone *zone; 5207 5208 /* Just pick one node, since fallback list is circular */ 5209 unsigned long sum = 0; 5210 5211 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL); 5212 5213 for_each_zone_zonelist(zone, z, zonelist, offset) { 5214 unsigned long size = zone_managed_pages(zone); 5215 unsigned long high = high_wmark_pages(zone); 5216 if (size > high) 5217 sum += size - high; 5218 } 5219 5220 return sum; 5221 } 5222 5223 /** 5224 * nr_free_buffer_pages - count number of pages beyond high watermark 5225 * 5226 * nr_free_buffer_pages() counts the number of pages which are beyond the high 5227 * watermark within ZONE_DMA and ZONE_NORMAL. 5228 * 5229 * Return: number of pages beyond high watermark within ZONE_DMA and 5230 * ZONE_NORMAL. 5231 */ 5232 unsigned long nr_free_buffer_pages(void) 5233 { 5234 return nr_free_zone_pages(gfp_zone(GFP_USER)); 5235 } 5236 EXPORT_SYMBOL_GPL(nr_free_buffer_pages); 5237 5238 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref) 5239 { 5240 zoneref->zone = zone; 5241 zoneref->zone_idx = zone_idx(zone); 5242 } 5243 5244 /* 5245 * Builds allocation fallback zone lists. 5246 * 5247 * Add all populated zones of a node to the zonelist. 5248 */ 5249 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs) 5250 { 5251 struct zone *zone; 5252 enum zone_type zone_type = MAX_NR_ZONES; 5253 int nr_zones = 0; 5254 5255 do { 5256 zone_type--; 5257 zone = pgdat->node_zones + zone_type; 5258 if (populated_zone(zone)) { 5259 zoneref_set_zone(zone, &zonerefs[nr_zones++]); 5260 check_highest_zone(zone_type); 5261 } 5262 } while (zone_type); 5263 5264 return nr_zones; 5265 } 5266 5267 #ifdef CONFIG_NUMA 5268 5269 static int __parse_numa_zonelist_order(char *s) 5270 { 5271 /* 5272 * We used to support different zonelists modes but they turned 5273 * out to be just not useful. Let's keep the warning in place 5274 * if somebody still use the cmd line parameter so that we do 5275 * not fail it silently 5276 */ 5277 if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) { 5278 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s); 5279 return -EINVAL; 5280 } 5281 return 0; 5282 } 5283 5284 static char numa_zonelist_order[] = "Node"; 5285 #define NUMA_ZONELIST_ORDER_LEN 16 5286 /* 5287 * sysctl handler for numa_zonelist_order 5288 */ 5289 static int numa_zonelist_order_handler(const struct ctl_table *table, int write, 5290 void *buffer, size_t *length, loff_t *ppos) 5291 { 5292 if (write) 5293 return __parse_numa_zonelist_order(buffer); 5294 return proc_dostring(table, write, buffer, length, ppos); 5295 } 5296 5297 static int node_load[MAX_NUMNODES]; 5298 5299 /** 5300 * find_next_best_node - find the next node that should appear in a given node's fallback list 5301 * @node: node whose fallback list we're appending 5302 * @used_node_mask: nodemask_t of already used nodes 5303 * 5304 * We use a number of factors to determine which is the next node that should 5305 * appear on a given node's fallback list. The node should not have appeared 5306 * already in @node's fallback list, and it should be the next closest node 5307 * according to the distance array (which contains arbitrary distance values 5308 * from each node to each node in the system), and should also prefer nodes 5309 * with no CPUs, since presumably they'll have very little allocation pressure 5310 * on them otherwise. 5311 * 5312 * Return: node id of the found node or %NUMA_NO_NODE if no node is found. 5313 */ 5314 int find_next_best_node(int node, nodemask_t *used_node_mask) 5315 { 5316 int n, val; 5317 int min_val = INT_MAX; 5318 int best_node = NUMA_NO_NODE; 5319 5320 /* 5321 * Use the local node if we haven't already, but for memoryless local 5322 * node, we should skip it and fall back to other nodes. 5323 */ 5324 if (!node_isset(node, *used_node_mask) && node_state(node, N_MEMORY)) { 5325 node_set(node, *used_node_mask); 5326 return node; 5327 } 5328 5329 for_each_node_state(n, N_MEMORY) { 5330 5331 /* Don't want a node to appear more than once */ 5332 if (node_isset(n, *used_node_mask)) 5333 continue; 5334 5335 /* Use the distance array to find the distance */ 5336 val = node_distance(node, n); 5337 5338 /* Penalize nodes under us ("prefer the next node") */ 5339 val += (n < node); 5340 5341 /* Give preference to headless and unused nodes */ 5342 if (!cpumask_empty(cpumask_of_node(n))) 5343 val += PENALTY_FOR_NODE_WITH_CPUS; 5344 5345 /* Slight preference for less loaded node */ 5346 val *= MAX_NUMNODES; 5347 val += node_load[n]; 5348 5349 if (val < min_val) { 5350 min_val = val; 5351 best_node = n; 5352 } 5353 } 5354 5355 if (best_node >= 0) 5356 node_set(best_node, *used_node_mask); 5357 5358 return best_node; 5359 } 5360 5361 5362 /* 5363 * Build zonelists ordered by node and zones within node. 5364 * This results in maximum locality--normal zone overflows into local 5365 * DMA zone, if any--but risks exhausting DMA zone. 5366 */ 5367 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order, 5368 unsigned nr_nodes) 5369 { 5370 struct zoneref *zonerefs; 5371 int i; 5372 5373 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs; 5374 5375 for (i = 0; i < nr_nodes; i++) { 5376 int nr_zones; 5377 5378 pg_data_t *node = NODE_DATA(node_order[i]); 5379 5380 nr_zones = build_zonerefs_node(node, zonerefs); 5381 zonerefs += nr_zones; 5382 } 5383 zonerefs->zone = NULL; 5384 zonerefs->zone_idx = 0; 5385 } 5386 5387 /* 5388 * Build __GFP_THISNODE zonelists 5389 */ 5390 static void build_thisnode_zonelists(pg_data_t *pgdat) 5391 { 5392 struct zoneref *zonerefs; 5393 int nr_zones; 5394 5395 zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs; 5396 nr_zones = build_zonerefs_node(pgdat, zonerefs); 5397 zonerefs += nr_zones; 5398 zonerefs->zone = NULL; 5399 zonerefs->zone_idx = 0; 5400 } 5401 5402 static void build_zonelists(pg_data_t *pgdat) 5403 { 5404 static int node_order[MAX_NUMNODES]; 5405 int node, nr_nodes = 0; 5406 nodemask_t used_mask = NODE_MASK_NONE; 5407 int local_node, prev_node; 5408 5409 /* NUMA-aware ordering of nodes */ 5410 local_node = pgdat->node_id; 5411 prev_node = local_node; 5412 5413 memset(node_order, 0, sizeof(node_order)); 5414 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) { 5415 /* 5416 * We don't want to pressure a particular node. 5417 * So adding penalty to the first node in same 5418 * distance group to make it round-robin. 5419 */ 5420 if (node_distance(local_node, node) != 5421 node_distance(local_node, prev_node)) 5422 node_load[node] += 1; 5423 5424 node_order[nr_nodes++] = node; 5425 prev_node = node; 5426 } 5427 5428 build_zonelists_in_node_order(pgdat, node_order, nr_nodes); 5429 build_thisnode_zonelists(pgdat); 5430 pr_info("Fallback order for Node %d: ", local_node); 5431 for (node = 0; node < nr_nodes; node++) 5432 pr_cont("%d ", node_order[node]); 5433 pr_cont("\n"); 5434 } 5435 5436 #ifdef CONFIG_HAVE_MEMORYLESS_NODES 5437 /* 5438 * Return node id of node used for "local" allocations. 5439 * I.e., first node id of first zone in arg node's generic zonelist. 5440 * Used for initializing percpu 'numa_mem', which is used primarily 5441 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist. 5442 */ 5443 int local_memory_node(int node) 5444 { 5445 struct zoneref *z; 5446 5447 z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL), 5448 gfp_zone(GFP_KERNEL), 5449 NULL); 5450 return zonelist_node_idx(z); 5451 } 5452 #endif 5453 5454 static void setup_min_unmapped_ratio(void); 5455 static void setup_min_slab_ratio(void); 5456 #else /* CONFIG_NUMA */ 5457 5458 static void build_zonelists(pg_data_t *pgdat) 5459 { 5460 struct zoneref *zonerefs; 5461 int nr_zones; 5462 5463 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs; 5464 nr_zones = build_zonerefs_node(pgdat, zonerefs); 5465 zonerefs += nr_zones; 5466 5467 zonerefs->zone = NULL; 5468 zonerefs->zone_idx = 0; 5469 } 5470 5471 #endif /* CONFIG_NUMA */ 5472 5473 /* 5474 * Boot pageset table. One per cpu which is going to be used for all 5475 * zones and all nodes. The parameters will be set in such a way 5476 * that an item put on a list will immediately be handed over to 5477 * the buddy list. This is safe since pageset manipulation is done 5478 * with interrupts disabled. 5479 * 5480 * The boot_pagesets must be kept even after bootup is complete for 5481 * unused processors and/or zones. They do play a role for bootstrapping 5482 * hotplugged processors. 5483 * 5484 * zoneinfo_show() and maybe other functions do 5485 * not check if the processor is online before following the pageset pointer. 5486 * Other parts of the kernel may not check if the zone is available. 5487 */ 5488 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats); 5489 /* These effectively disable the pcplists in the boot pageset completely */ 5490 #define BOOT_PAGESET_HIGH 0 5491 #define BOOT_PAGESET_BATCH 1 5492 static DEFINE_PER_CPU(struct per_cpu_pages, boot_pageset); 5493 static DEFINE_PER_CPU(struct per_cpu_zonestat, boot_zonestats); 5494 5495 static void __build_all_zonelists(void *data) 5496 { 5497 int nid; 5498 int __maybe_unused cpu; 5499 pg_data_t *self = data; 5500 unsigned long flags; 5501 5502 /* 5503 * The zonelist_update_seq must be acquired with irqsave because the 5504 * reader can be invoked from IRQ with GFP_ATOMIC. 5505 */ 5506 write_seqlock_irqsave(&zonelist_update_seq, flags); 5507 /* 5508 * Also disable synchronous printk() to prevent any printk() from 5509 * trying to hold port->lock, for 5510 * tty_insert_flip_string_and_push_buffer() on other CPU might be 5511 * calling kmalloc(GFP_ATOMIC | __GFP_NOWARN) with port->lock held. 5512 */ 5513 printk_deferred_enter(); 5514 5515 #ifdef CONFIG_NUMA 5516 memset(node_load, 0, sizeof(node_load)); 5517 #endif 5518 5519 /* 5520 * This node is hotadded and no memory is yet present. So just 5521 * building zonelists is fine - no need to touch other nodes. 5522 */ 5523 if (self && !node_online(self->node_id)) { 5524 build_zonelists(self); 5525 } else { 5526 /* 5527 * All possible nodes have pgdat preallocated 5528 * in free_area_init 5529 */ 5530 for_each_node(nid) { 5531 pg_data_t *pgdat = NODE_DATA(nid); 5532 5533 build_zonelists(pgdat); 5534 } 5535 5536 #ifdef CONFIG_HAVE_MEMORYLESS_NODES 5537 /* 5538 * We now know the "local memory node" for each node-- 5539 * i.e., the node of the first zone in the generic zonelist. 5540 * Set up numa_mem percpu variable for on-line cpus. During 5541 * boot, only the boot cpu should be on-line; we'll init the 5542 * secondary cpus' numa_mem as they come on-line. During 5543 * node/memory hotplug, we'll fixup all on-line cpus. 5544 */ 5545 for_each_online_cpu(cpu) 5546 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu))); 5547 #endif 5548 } 5549 5550 printk_deferred_exit(); 5551 write_sequnlock_irqrestore(&zonelist_update_seq, flags); 5552 } 5553 5554 static noinline void __init 5555 build_all_zonelists_init(void) 5556 { 5557 int cpu; 5558 5559 __build_all_zonelists(NULL); 5560 5561 /* 5562 * Initialize the boot_pagesets that are going to be used 5563 * for bootstrapping processors. The real pagesets for 5564 * each zone will be allocated later when the per cpu 5565 * allocator is available. 5566 * 5567 * boot_pagesets are used also for bootstrapping offline 5568 * cpus if the system is already booted because the pagesets 5569 * are needed to initialize allocators on a specific cpu too. 5570 * F.e. the percpu allocator needs the page allocator which 5571 * needs the percpu allocator in order to allocate its pagesets 5572 * (a chicken-egg dilemma). 5573 */ 5574 for_each_possible_cpu(cpu) 5575 per_cpu_pages_init(&per_cpu(boot_pageset, cpu), &per_cpu(boot_zonestats, cpu)); 5576 5577 mminit_verify_zonelist(); 5578 cpuset_init_current_mems_allowed(); 5579 } 5580 5581 /* 5582 * unless system_state == SYSTEM_BOOTING. 5583 * 5584 * __ref due to call of __init annotated helper build_all_zonelists_init 5585 * [protected by SYSTEM_BOOTING]. 5586 */ 5587 void __ref build_all_zonelists(pg_data_t *pgdat) 5588 { 5589 unsigned long vm_total_pages; 5590 5591 if (system_state == SYSTEM_BOOTING) { 5592 build_all_zonelists_init(); 5593 } else { 5594 __build_all_zonelists(pgdat); 5595 /* cpuset refresh routine should be here */ 5596 } 5597 /* Get the number of free pages beyond high watermark in all zones. */ 5598 vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE)); 5599 /* 5600 * Disable grouping by mobility if the number of pages in the 5601 * system is too low to allow the mechanism to work. It would be 5602 * more accurate, but expensive to check per-zone. This check is 5603 * made on memory-hotadd so a system can start with mobility 5604 * disabled and enable it later 5605 */ 5606 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES)) 5607 page_group_by_mobility_disabled = 1; 5608 else 5609 page_group_by_mobility_disabled = 0; 5610 5611 pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n", 5612 nr_online_nodes, 5613 str_off_on(page_group_by_mobility_disabled), 5614 vm_total_pages); 5615 #ifdef CONFIG_NUMA 5616 pr_info("Policy zone: %s\n", zone_names[policy_zone]); 5617 #endif 5618 } 5619 5620 static int zone_batchsize(struct zone *zone) 5621 { 5622 #ifdef CONFIG_MMU 5623 int batch; 5624 5625 /* 5626 * The number of pages to batch allocate is either ~0.1% 5627 * of the zone or 1MB, whichever is smaller. The batch 5628 * size is striking a balance between allocation latency 5629 * and zone lock contention. 5630 */ 5631 batch = min(zone_managed_pages(zone) >> 10, SZ_1M / PAGE_SIZE); 5632 batch /= 4; /* We effectively *= 4 below */ 5633 if (batch < 1) 5634 batch = 1; 5635 5636 /* 5637 * Clamp the batch to a 2^n - 1 value. Having a power 5638 * of 2 value was found to be more likely to have 5639 * suboptimal cache aliasing properties in some cases. 5640 * 5641 * For example if 2 tasks are alternately allocating 5642 * batches of pages, one task can end up with a lot 5643 * of pages of one half of the possible page colors 5644 * and the other with pages of the other colors. 5645 */ 5646 batch = rounddown_pow_of_two(batch + batch/2) - 1; 5647 5648 return batch; 5649 5650 #else 5651 /* The deferral and batching of frees should be suppressed under NOMMU 5652 * conditions. 5653 * 5654 * The problem is that NOMMU needs to be able to allocate large chunks 5655 * of contiguous memory as there's no hardware page translation to 5656 * assemble apparent contiguous memory from discontiguous pages. 5657 * 5658 * Queueing large contiguous runs of pages for batching, however, 5659 * causes the pages to actually be freed in smaller chunks. As there 5660 * can be a significant delay between the individual batches being 5661 * recycled, this leads to the once large chunks of space being 5662 * fragmented and becoming unavailable for high-order allocations. 5663 */ 5664 return 0; 5665 #endif 5666 } 5667 5668 static int percpu_pagelist_high_fraction; 5669 static int zone_highsize(struct zone *zone, int batch, int cpu_online, 5670 int high_fraction) 5671 { 5672 #ifdef CONFIG_MMU 5673 int high; 5674 int nr_split_cpus; 5675 unsigned long total_pages; 5676 5677 if (!high_fraction) { 5678 /* 5679 * By default, the high value of the pcp is based on the zone 5680 * low watermark so that if they are full then background 5681 * reclaim will not be started prematurely. 5682 */ 5683 total_pages = low_wmark_pages(zone); 5684 } else { 5685 /* 5686 * If percpu_pagelist_high_fraction is configured, the high 5687 * value is based on a fraction of the managed pages in the 5688 * zone. 5689 */ 5690 total_pages = zone_managed_pages(zone) / high_fraction; 5691 } 5692 5693 /* 5694 * Split the high value across all online CPUs local to the zone. Note 5695 * that early in boot that CPUs may not be online yet and that during 5696 * CPU hotplug that the cpumask is not yet updated when a CPU is being 5697 * onlined. For memory nodes that have no CPUs, split the high value 5698 * across all online CPUs to mitigate the risk that reclaim is triggered 5699 * prematurely due to pages stored on pcp lists. 5700 */ 5701 nr_split_cpus = cpumask_weight(cpumask_of_node(zone_to_nid(zone))) + cpu_online; 5702 if (!nr_split_cpus) 5703 nr_split_cpus = num_online_cpus(); 5704 high = total_pages / nr_split_cpus; 5705 5706 /* 5707 * Ensure high is at least batch*4. The multiple is based on the 5708 * historical relationship between high and batch. 5709 */ 5710 high = max(high, batch << 2); 5711 5712 return high; 5713 #else 5714 return 0; 5715 #endif 5716 } 5717 5718 /* 5719 * pcp->high and pcp->batch values are related and generally batch is lower 5720 * than high. They are also related to pcp->count such that count is lower 5721 * than high, and as soon as it reaches high, the pcplist is flushed. 5722 * 5723 * However, guaranteeing these relations at all times would require e.g. write 5724 * barriers here but also careful usage of read barriers at the read side, and 5725 * thus be prone to error and bad for performance. Thus the update only prevents 5726 * store tearing. Any new users of pcp->batch, pcp->high_min and pcp->high_max 5727 * should ensure they can cope with those fields changing asynchronously, and 5728 * fully trust only the pcp->count field on the local CPU with interrupts 5729 * disabled. 5730 * 5731 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function 5732 * outside of boot time (or some other assurance that no concurrent updaters 5733 * exist). 5734 */ 5735 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high_min, 5736 unsigned long high_max, unsigned long batch) 5737 { 5738 WRITE_ONCE(pcp->batch, batch); 5739 WRITE_ONCE(pcp->high_min, high_min); 5740 WRITE_ONCE(pcp->high_max, high_max); 5741 } 5742 5743 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats) 5744 { 5745 int pindex; 5746 5747 memset(pcp, 0, sizeof(*pcp)); 5748 memset(pzstats, 0, sizeof(*pzstats)); 5749 5750 spin_lock_init(&pcp->lock); 5751 for (pindex = 0; pindex < NR_PCP_LISTS; pindex++) 5752 INIT_LIST_HEAD(&pcp->lists[pindex]); 5753 5754 /* 5755 * Set batch and high values safe for a boot pageset. A true percpu 5756 * pageset's initialization will update them subsequently. Here we don't 5757 * need to be as careful as pageset_update() as nobody can access the 5758 * pageset yet. 5759 */ 5760 pcp->high_min = BOOT_PAGESET_HIGH; 5761 pcp->high_max = BOOT_PAGESET_HIGH; 5762 pcp->batch = BOOT_PAGESET_BATCH; 5763 pcp->free_count = 0; 5764 } 5765 5766 static void __zone_set_pageset_high_and_batch(struct zone *zone, unsigned long high_min, 5767 unsigned long high_max, unsigned long batch) 5768 { 5769 struct per_cpu_pages *pcp; 5770 int cpu; 5771 5772 for_each_possible_cpu(cpu) { 5773 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 5774 pageset_update(pcp, high_min, high_max, batch); 5775 } 5776 } 5777 5778 /* 5779 * Calculate and set new high and batch values for all per-cpu pagesets of a 5780 * zone based on the zone's size. 5781 */ 5782 static void zone_set_pageset_high_and_batch(struct zone *zone, int cpu_online) 5783 { 5784 int new_high_min, new_high_max, new_batch; 5785 5786 new_batch = max(1, zone_batchsize(zone)); 5787 if (percpu_pagelist_high_fraction) { 5788 new_high_min = zone_highsize(zone, new_batch, cpu_online, 5789 percpu_pagelist_high_fraction); 5790 /* 5791 * PCP high is tuned manually, disable auto-tuning via 5792 * setting high_min and high_max to the manual value. 5793 */ 5794 new_high_max = new_high_min; 5795 } else { 5796 new_high_min = zone_highsize(zone, new_batch, cpu_online, 0); 5797 new_high_max = zone_highsize(zone, new_batch, cpu_online, 5798 MIN_PERCPU_PAGELIST_HIGH_FRACTION); 5799 } 5800 5801 if (zone->pageset_high_min == new_high_min && 5802 zone->pageset_high_max == new_high_max && 5803 zone->pageset_batch == new_batch) 5804 return; 5805 5806 zone->pageset_high_min = new_high_min; 5807 zone->pageset_high_max = new_high_max; 5808 zone->pageset_batch = new_batch; 5809 5810 __zone_set_pageset_high_and_batch(zone, new_high_min, new_high_max, 5811 new_batch); 5812 } 5813 5814 void __meminit setup_zone_pageset(struct zone *zone) 5815 { 5816 int cpu; 5817 5818 /* Size may be 0 on !SMP && !NUMA */ 5819 if (sizeof(struct per_cpu_zonestat) > 0) 5820 zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat); 5821 5822 zone->per_cpu_pageset = alloc_percpu(struct per_cpu_pages); 5823 for_each_possible_cpu(cpu) { 5824 struct per_cpu_pages *pcp; 5825 struct per_cpu_zonestat *pzstats; 5826 5827 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 5828 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu); 5829 per_cpu_pages_init(pcp, pzstats); 5830 } 5831 5832 zone_set_pageset_high_and_batch(zone, 0); 5833 } 5834 5835 /* 5836 * The zone indicated has a new number of managed_pages; batch sizes and percpu 5837 * page high values need to be recalculated. 5838 */ 5839 static void zone_pcp_update(struct zone *zone, int cpu_online) 5840 { 5841 mutex_lock(&pcp_batch_high_lock); 5842 zone_set_pageset_high_and_batch(zone, cpu_online); 5843 mutex_unlock(&pcp_batch_high_lock); 5844 } 5845 5846 static void zone_pcp_update_cacheinfo(struct zone *zone, unsigned int cpu) 5847 { 5848 struct per_cpu_pages *pcp; 5849 struct cpu_cacheinfo *cci; 5850 5851 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu); 5852 cci = get_cpu_cacheinfo(cpu); 5853 /* 5854 * If data cache slice of CPU is large enough, "pcp->batch" 5855 * pages can be preserved in PCP before draining PCP for 5856 * consecutive high-order pages freeing without allocation. 5857 * This can reduce zone lock contention without hurting 5858 * cache-hot pages sharing. 5859 */ 5860 spin_lock(&pcp->lock); 5861 if ((cci->per_cpu_data_slice_size >> PAGE_SHIFT) > 3 * pcp->batch) 5862 pcp->flags |= PCPF_FREE_HIGH_BATCH; 5863 else 5864 pcp->flags &= ~PCPF_FREE_HIGH_BATCH; 5865 spin_unlock(&pcp->lock); 5866 } 5867 5868 void setup_pcp_cacheinfo(unsigned int cpu) 5869 { 5870 struct zone *zone; 5871 5872 for_each_populated_zone(zone) 5873 zone_pcp_update_cacheinfo(zone, cpu); 5874 } 5875 5876 /* 5877 * Allocate per cpu pagesets and initialize them. 5878 * Before this call only boot pagesets were available. 5879 */ 5880 void __init setup_per_cpu_pageset(void) 5881 { 5882 struct pglist_data *pgdat; 5883 struct zone *zone; 5884 int __maybe_unused cpu; 5885 5886 for_each_populated_zone(zone) 5887 setup_zone_pageset(zone); 5888 5889 #ifdef CONFIG_NUMA 5890 /* 5891 * Unpopulated zones continue using the boot pagesets. 5892 * The numa stats for these pagesets need to be reset. 5893 * Otherwise, they will end up skewing the stats of 5894 * the nodes these zones are associated with. 5895 */ 5896 for_each_possible_cpu(cpu) { 5897 struct per_cpu_zonestat *pzstats = &per_cpu(boot_zonestats, cpu); 5898 memset(pzstats->vm_numa_event, 0, 5899 sizeof(pzstats->vm_numa_event)); 5900 } 5901 #endif 5902 5903 for_each_online_pgdat(pgdat) 5904 pgdat->per_cpu_nodestats = 5905 alloc_percpu(struct per_cpu_nodestat); 5906 } 5907 5908 __meminit void zone_pcp_init(struct zone *zone) 5909 { 5910 /* 5911 * per cpu subsystem is not up at this point. The following code 5912 * relies on the ability of the linker to provide the 5913 * offset of a (static) per cpu variable into the per cpu area. 5914 */ 5915 zone->per_cpu_pageset = &boot_pageset; 5916 zone->per_cpu_zonestats = &boot_zonestats; 5917 zone->pageset_high_min = BOOT_PAGESET_HIGH; 5918 zone->pageset_high_max = BOOT_PAGESET_HIGH; 5919 zone->pageset_batch = BOOT_PAGESET_BATCH; 5920 5921 if (populated_zone(zone)) 5922 pr_debug(" %s zone: %lu pages, LIFO batch:%u\n", zone->name, 5923 zone->present_pages, zone_batchsize(zone)); 5924 } 5925 5926 static void setup_per_zone_lowmem_reserve(void); 5927 5928 void adjust_managed_page_count(struct page *page, long count) 5929 { 5930 atomic_long_add(count, &page_zone(page)->managed_pages); 5931 totalram_pages_add(count); 5932 setup_per_zone_lowmem_reserve(); 5933 } 5934 EXPORT_SYMBOL(adjust_managed_page_count); 5935 5936 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s) 5937 { 5938 void *pos; 5939 unsigned long pages = 0; 5940 5941 start = (void *)PAGE_ALIGN((unsigned long)start); 5942 end = (void *)((unsigned long)end & PAGE_MASK); 5943 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) { 5944 struct page *page = virt_to_page(pos); 5945 void *direct_map_addr; 5946 5947 /* 5948 * 'direct_map_addr' might be different from 'pos' 5949 * because some architectures' virt_to_page() 5950 * work with aliases. Getting the direct map 5951 * address ensures that we get a _writeable_ 5952 * alias for the memset(). 5953 */ 5954 direct_map_addr = page_address(page); 5955 /* 5956 * Perform a kasan-unchecked memset() since this memory 5957 * has not been initialized. 5958 */ 5959 direct_map_addr = kasan_reset_tag(direct_map_addr); 5960 if ((unsigned int)poison <= 0xFF) 5961 memset(direct_map_addr, poison, PAGE_SIZE); 5962 5963 free_reserved_page(page); 5964 } 5965 5966 if (pages && s) 5967 pr_info("Freeing %s memory: %ldK\n", s, K(pages)); 5968 5969 return pages; 5970 } 5971 5972 void free_reserved_page(struct page *page) 5973 { 5974 clear_page_tag_ref(page); 5975 ClearPageReserved(page); 5976 init_page_count(page); 5977 __free_page(page); 5978 adjust_managed_page_count(page, 1); 5979 } 5980 EXPORT_SYMBOL(free_reserved_page); 5981 5982 static int page_alloc_cpu_dead(unsigned int cpu) 5983 { 5984 struct zone *zone; 5985 5986 lru_add_drain_cpu(cpu); 5987 mlock_drain_remote(cpu); 5988 drain_pages(cpu); 5989 5990 /* 5991 * Spill the event counters of the dead processor 5992 * into the current processors event counters. 5993 * This artificially elevates the count of the current 5994 * processor. 5995 */ 5996 vm_events_fold_cpu(cpu); 5997 5998 /* 5999 * Zero the differential counters of the dead processor 6000 * so that the vm statistics are consistent. 6001 * 6002 * This is only okay since the processor is dead and cannot 6003 * race with what we are doing. 6004 */ 6005 cpu_vm_stats_fold(cpu); 6006 6007 for_each_populated_zone(zone) 6008 zone_pcp_update(zone, 0); 6009 6010 return 0; 6011 } 6012 6013 static int page_alloc_cpu_online(unsigned int cpu) 6014 { 6015 struct zone *zone; 6016 6017 for_each_populated_zone(zone) 6018 zone_pcp_update(zone, 1); 6019 return 0; 6020 } 6021 6022 void __init page_alloc_init_cpuhp(void) 6023 { 6024 int ret; 6025 6026 ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC, 6027 "mm/page_alloc:pcp", 6028 page_alloc_cpu_online, 6029 page_alloc_cpu_dead); 6030 WARN_ON(ret < 0); 6031 } 6032 6033 /* 6034 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio 6035 * or min_free_kbytes changes. 6036 */ 6037 static void calculate_totalreserve_pages(void) 6038 { 6039 struct pglist_data *pgdat; 6040 unsigned long reserve_pages = 0; 6041 enum zone_type i, j; 6042 6043 for_each_online_pgdat(pgdat) { 6044 6045 pgdat->totalreserve_pages = 0; 6046 6047 for (i = 0; i < MAX_NR_ZONES; i++) { 6048 struct zone *zone = pgdat->node_zones + i; 6049 long max = 0; 6050 unsigned long managed_pages = zone_managed_pages(zone); 6051 6052 /* Find valid and maximum lowmem_reserve in the zone */ 6053 for (j = i; j < MAX_NR_ZONES; j++) { 6054 if (zone->lowmem_reserve[j] > max) 6055 max = zone->lowmem_reserve[j]; 6056 } 6057 6058 /* we treat the high watermark as reserved pages. */ 6059 max += high_wmark_pages(zone); 6060 6061 if (max > managed_pages) 6062 max = managed_pages; 6063 6064 pgdat->totalreserve_pages += max; 6065 6066 reserve_pages += max; 6067 } 6068 } 6069 totalreserve_pages = reserve_pages; 6070 trace_mm_calculate_totalreserve_pages(totalreserve_pages); 6071 } 6072 6073 /* 6074 * setup_per_zone_lowmem_reserve - called whenever 6075 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone 6076 * has a correct pages reserved value, so an adequate number of 6077 * pages are left in the zone after a successful __alloc_pages(). 6078 */ 6079 static void setup_per_zone_lowmem_reserve(void) 6080 { 6081 struct pglist_data *pgdat; 6082 enum zone_type i, j; 6083 6084 for_each_online_pgdat(pgdat) { 6085 for (i = 0; i < MAX_NR_ZONES - 1; i++) { 6086 struct zone *zone = &pgdat->node_zones[i]; 6087 int ratio = sysctl_lowmem_reserve_ratio[i]; 6088 bool clear = !ratio || !zone_managed_pages(zone); 6089 unsigned long managed_pages = 0; 6090 6091 for (j = i + 1; j < MAX_NR_ZONES; j++) { 6092 struct zone *upper_zone = &pgdat->node_zones[j]; 6093 6094 managed_pages += zone_managed_pages(upper_zone); 6095 6096 if (clear) 6097 zone->lowmem_reserve[j] = 0; 6098 else 6099 zone->lowmem_reserve[j] = managed_pages / ratio; 6100 trace_mm_setup_per_zone_lowmem_reserve(zone, upper_zone, 6101 zone->lowmem_reserve[j]); 6102 } 6103 } 6104 } 6105 6106 /* update totalreserve_pages */ 6107 calculate_totalreserve_pages(); 6108 } 6109 6110 static void __setup_per_zone_wmarks(void) 6111 { 6112 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10); 6113 unsigned long lowmem_pages = 0; 6114 struct zone *zone; 6115 unsigned long flags; 6116 6117 /* Calculate total number of !ZONE_HIGHMEM and !ZONE_MOVABLE pages */ 6118 for_each_zone(zone) { 6119 if (!is_highmem(zone) && zone_idx(zone) != ZONE_MOVABLE) 6120 lowmem_pages += zone_managed_pages(zone); 6121 } 6122 6123 for_each_zone(zone) { 6124 u64 tmp; 6125 6126 spin_lock_irqsave(&zone->lock, flags); 6127 tmp = (u64)pages_min * zone_managed_pages(zone); 6128 tmp = div64_ul(tmp, lowmem_pages); 6129 if (is_highmem(zone) || zone_idx(zone) == ZONE_MOVABLE) { 6130 /* 6131 * __GFP_HIGH and PF_MEMALLOC allocations usually don't 6132 * need highmem and movable zones pages, so cap pages_min 6133 * to a small value here. 6134 * 6135 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN) 6136 * deltas control async page reclaim, and so should 6137 * not be capped for highmem and movable zones. 6138 */ 6139 unsigned long min_pages; 6140 6141 min_pages = zone_managed_pages(zone) / 1024; 6142 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL); 6143 zone->_watermark[WMARK_MIN] = min_pages; 6144 } else { 6145 /* 6146 * If it's a lowmem zone, reserve a number of pages 6147 * proportionate to the zone's size. 6148 */ 6149 zone->_watermark[WMARK_MIN] = tmp; 6150 } 6151 6152 /* 6153 * Set the kswapd watermarks distance according to the 6154 * scale factor in proportion to available memory, but 6155 * ensure a minimum size on small systems. 6156 */ 6157 tmp = max_t(u64, tmp >> 2, 6158 mult_frac(zone_managed_pages(zone), 6159 watermark_scale_factor, 10000)); 6160 6161 zone->watermark_boost = 0; 6162 zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp; 6163 zone->_watermark[WMARK_HIGH] = low_wmark_pages(zone) + tmp; 6164 zone->_watermark[WMARK_PROMO] = high_wmark_pages(zone) + tmp; 6165 trace_mm_setup_per_zone_wmarks(zone); 6166 6167 spin_unlock_irqrestore(&zone->lock, flags); 6168 } 6169 6170 /* update totalreserve_pages */ 6171 calculate_totalreserve_pages(); 6172 } 6173 6174 /** 6175 * setup_per_zone_wmarks - called when min_free_kbytes changes 6176 * or when memory is hot-{added|removed} 6177 * 6178 * Ensures that the watermark[min,low,high] values for each zone are set 6179 * correctly with respect to min_free_kbytes. 6180 */ 6181 void setup_per_zone_wmarks(void) 6182 { 6183 struct zone *zone; 6184 static DEFINE_SPINLOCK(lock); 6185 6186 spin_lock(&lock); 6187 __setup_per_zone_wmarks(); 6188 spin_unlock(&lock); 6189 6190 /* 6191 * The watermark size have changed so update the pcpu batch 6192 * and high limits or the limits may be inappropriate. 6193 */ 6194 for_each_zone(zone) 6195 zone_pcp_update(zone, 0); 6196 } 6197 6198 /* 6199 * Initialise min_free_kbytes. 6200 * 6201 * For small machines we want it small (128k min). For large machines 6202 * we want it large (256MB max). But it is not linear, because network 6203 * bandwidth does not increase linearly with machine size. We use 6204 * 6205 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy: 6206 * min_free_kbytes = sqrt(lowmem_kbytes * 16) 6207 * 6208 * which yields 6209 * 6210 * 16MB: 512k 6211 * 32MB: 724k 6212 * 64MB: 1024k 6213 * 128MB: 1448k 6214 * 256MB: 2048k 6215 * 512MB: 2896k 6216 * 1024MB: 4096k 6217 * 2048MB: 5792k 6218 * 4096MB: 8192k 6219 * 8192MB: 11584k 6220 * 16384MB: 16384k 6221 */ 6222 void calculate_min_free_kbytes(void) 6223 { 6224 unsigned long lowmem_kbytes; 6225 int new_min_free_kbytes; 6226 6227 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10); 6228 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16); 6229 6230 if (new_min_free_kbytes > user_min_free_kbytes) 6231 min_free_kbytes = clamp(new_min_free_kbytes, 128, 262144); 6232 else 6233 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n", 6234 new_min_free_kbytes, user_min_free_kbytes); 6235 6236 } 6237 6238 int __meminit init_per_zone_wmark_min(void) 6239 { 6240 calculate_min_free_kbytes(); 6241 setup_per_zone_wmarks(); 6242 refresh_zone_stat_thresholds(); 6243 setup_per_zone_lowmem_reserve(); 6244 6245 #ifdef CONFIG_NUMA 6246 setup_min_unmapped_ratio(); 6247 setup_min_slab_ratio(); 6248 #endif 6249 6250 khugepaged_min_free_kbytes_update(); 6251 6252 return 0; 6253 } 6254 postcore_initcall(init_per_zone_wmark_min) 6255 6256 /* 6257 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so 6258 * that we can call two helper functions whenever min_free_kbytes 6259 * changes. 6260 */ 6261 static int min_free_kbytes_sysctl_handler(const struct ctl_table *table, int write, 6262 void *buffer, size_t *length, loff_t *ppos) 6263 { 6264 int rc; 6265 6266 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 6267 if (rc) 6268 return rc; 6269 6270 if (write) { 6271 user_min_free_kbytes = min_free_kbytes; 6272 setup_per_zone_wmarks(); 6273 } 6274 return 0; 6275 } 6276 6277 static int watermark_scale_factor_sysctl_handler(const struct ctl_table *table, int write, 6278 void *buffer, size_t *length, loff_t *ppos) 6279 { 6280 int rc; 6281 6282 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 6283 if (rc) 6284 return rc; 6285 6286 if (write) 6287 setup_per_zone_wmarks(); 6288 6289 return 0; 6290 } 6291 6292 #ifdef CONFIG_NUMA 6293 static void setup_min_unmapped_ratio(void) 6294 { 6295 pg_data_t *pgdat; 6296 struct zone *zone; 6297 6298 for_each_online_pgdat(pgdat) 6299 pgdat->min_unmapped_pages = 0; 6300 6301 for_each_zone(zone) 6302 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) * 6303 sysctl_min_unmapped_ratio) / 100; 6304 } 6305 6306 6307 static int sysctl_min_unmapped_ratio_sysctl_handler(const struct ctl_table *table, int write, 6308 void *buffer, size_t *length, loff_t *ppos) 6309 { 6310 int rc; 6311 6312 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 6313 if (rc) 6314 return rc; 6315 6316 setup_min_unmapped_ratio(); 6317 6318 return 0; 6319 } 6320 6321 static void setup_min_slab_ratio(void) 6322 { 6323 pg_data_t *pgdat; 6324 struct zone *zone; 6325 6326 for_each_online_pgdat(pgdat) 6327 pgdat->min_slab_pages = 0; 6328 6329 for_each_zone(zone) 6330 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) * 6331 sysctl_min_slab_ratio) / 100; 6332 } 6333 6334 static int sysctl_min_slab_ratio_sysctl_handler(const struct ctl_table *table, int write, 6335 void *buffer, size_t *length, loff_t *ppos) 6336 { 6337 int rc; 6338 6339 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 6340 if (rc) 6341 return rc; 6342 6343 setup_min_slab_ratio(); 6344 6345 return 0; 6346 } 6347 #endif 6348 6349 /* 6350 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around 6351 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve() 6352 * whenever sysctl_lowmem_reserve_ratio changes. 6353 * 6354 * The reserve ratio obviously has absolutely no relation with the 6355 * minimum watermarks. The lowmem reserve ratio can only make sense 6356 * if in function of the boot time zone sizes. 6357 */ 6358 static int lowmem_reserve_ratio_sysctl_handler(const struct ctl_table *table, 6359 int write, void *buffer, size_t *length, loff_t *ppos) 6360 { 6361 int i; 6362 6363 proc_dointvec_minmax(table, write, buffer, length, ppos); 6364 6365 for (i = 0; i < MAX_NR_ZONES; i++) { 6366 if (sysctl_lowmem_reserve_ratio[i] < 1) 6367 sysctl_lowmem_reserve_ratio[i] = 0; 6368 } 6369 6370 setup_per_zone_lowmem_reserve(); 6371 return 0; 6372 } 6373 6374 /* 6375 * percpu_pagelist_high_fraction - changes the pcp->high for each zone on each 6376 * cpu. It is the fraction of total pages in each zone that a hot per cpu 6377 * pagelist can have before it gets flushed back to buddy allocator. 6378 */ 6379 static int percpu_pagelist_high_fraction_sysctl_handler(const struct ctl_table *table, 6380 int write, void *buffer, size_t *length, loff_t *ppos) 6381 { 6382 struct zone *zone; 6383 int old_percpu_pagelist_high_fraction; 6384 int ret; 6385 6386 mutex_lock(&pcp_batch_high_lock); 6387 old_percpu_pagelist_high_fraction = percpu_pagelist_high_fraction; 6388 6389 ret = proc_dointvec_minmax(table, write, buffer, length, ppos); 6390 if (!write || ret < 0) 6391 goto out; 6392 6393 /* Sanity checking to avoid pcp imbalance */ 6394 if (percpu_pagelist_high_fraction && 6395 percpu_pagelist_high_fraction < MIN_PERCPU_PAGELIST_HIGH_FRACTION) { 6396 percpu_pagelist_high_fraction = old_percpu_pagelist_high_fraction; 6397 ret = -EINVAL; 6398 goto out; 6399 } 6400 6401 /* No change? */ 6402 if (percpu_pagelist_high_fraction == old_percpu_pagelist_high_fraction) 6403 goto out; 6404 6405 for_each_populated_zone(zone) 6406 zone_set_pageset_high_and_batch(zone, 0); 6407 out: 6408 mutex_unlock(&pcp_batch_high_lock); 6409 return ret; 6410 } 6411 6412 static const struct ctl_table page_alloc_sysctl_table[] = { 6413 { 6414 .procname = "min_free_kbytes", 6415 .data = &min_free_kbytes, 6416 .maxlen = sizeof(min_free_kbytes), 6417 .mode = 0644, 6418 .proc_handler = min_free_kbytes_sysctl_handler, 6419 .extra1 = SYSCTL_ZERO, 6420 }, 6421 { 6422 .procname = "watermark_boost_factor", 6423 .data = &watermark_boost_factor, 6424 .maxlen = sizeof(watermark_boost_factor), 6425 .mode = 0644, 6426 .proc_handler = proc_dointvec_minmax, 6427 .extra1 = SYSCTL_ZERO, 6428 }, 6429 { 6430 .procname = "watermark_scale_factor", 6431 .data = &watermark_scale_factor, 6432 .maxlen = sizeof(watermark_scale_factor), 6433 .mode = 0644, 6434 .proc_handler = watermark_scale_factor_sysctl_handler, 6435 .extra1 = SYSCTL_ONE, 6436 .extra2 = SYSCTL_THREE_THOUSAND, 6437 }, 6438 { 6439 .procname = "defrag_mode", 6440 .data = &defrag_mode, 6441 .maxlen = sizeof(defrag_mode), 6442 .mode = 0644, 6443 .proc_handler = proc_dointvec_minmax, 6444 .extra1 = SYSCTL_ZERO, 6445 .extra2 = SYSCTL_ONE, 6446 }, 6447 { 6448 .procname = "percpu_pagelist_high_fraction", 6449 .data = &percpu_pagelist_high_fraction, 6450 .maxlen = sizeof(percpu_pagelist_high_fraction), 6451 .mode = 0644, 6452 .proc_handler = percpu_pagelist_high_fraction_sysctl_handler, 6453 .extra1 = SYSCTL_ZERO, 6454 }, 6455 { 6456 .procname = "lowmem_reserve_ratio", 6457 .data = &sysctl_lowmem_reserve_ratio, 6458 .maxlen = sizeof(sysctl_lowmem_reserve_ratio), 6459 .mode = 0644, 6460 .proc_handler = lowmem_reserve_ratio_sysctl_handler, 6461 }, 6462 #ifdef CONFIG_NUMA 6463 { 6464 .procname = "numa_zonelist_order", 6465 .data = &numa_zonelist_order, 6466 .maxlen = NUMA_ZONELIST_ORDER_LEN, 6467 .mode = 0644, 6468 .proc_handler = numa_zonelist_order_handler, 6469 }, 6470 { 6471 .procname = "min_unmapped_ratio", 6472 .data = &sysctl_min_unmapped_ratio, 6473 .maxlen = sizeof(sysctl_min_unmapped_ratio), 6474 .mode = 0644, 6475 .proc_handler = sysctl_min_unmapped_ratio_sysctl_handler, 6476 .extra1 = SYSCTL_ZERO, 6477 .extra2 = SYSCTL_ONE_HUNDRED, 6478 }, 6479 { 6480 .procname = "min_slab_ratio", 6481 .data = &sysctl_min_slab_ratio, 6482 .maxlen = sizeof(sysctl_min_slab_ratio), 6483 .mode = 0644, 6484 .proc_handler = sysctl_min_slab_ratio_sysctl_handler, 6485 .extra1 = SYSCTL_ZERO, 6486 .extra2 = SYSCTL_ONE_HUNDRED, 6487 }, 6488 #endif 6489 }; 6490 6491 void __init page_alloc_sysctl_init(void) 6492 { 6493 register_sysctl_init("vm", page_alloc_sysctl_table); 6494 } 6495 6496 #ifdef CONFIG_CONTIG_ALLOC 6497 /* Usage: See admin-guide/dynamic-debug-howto.rst */ 6498 static void alloc_contig_dump_pages(struct list_head *page_list) 6499 { 6500 DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure"); 6501 6502 if (DYNAMIC_DEBUG_BRANCH(descriptor)) { 6503 struct page *page; 6504 6505 dump_stack(); 6506 list_for_each_entry(page, page_list, lru) 6507 dump_page(page, "migration failure"); 6508 } 6509 } 6510 6511 /* 6512 * [start, end) must belong to a single zone. 6513 * @migratetype: using migratetype to filter the type of migration in 6514 * trace_mm_alloc_contig_migrate_range_info. 6515 */ 6516 static int __alloc_contig_migrate_range(struct compact_control *cc, 6517 unsigned long start, unsigned long end, int migratetype) 6518 { 6519 /* This function is based on compact_zone() from compaction.c. */ 6520 unsigned int nr_reclaimed; 6521 unsigned long pfn = start; 6522 unsigned int tries = 0; 6523 int ret = 0; 6524 struct migration_target_control mtc = { 6525 .nid = zone_to_nid(cc->zone), 6526 .gfp_mask = cc->gfp_mask, 6527 .reason = MR_CONTIG_RANGE, 6528 }; 6529 struct page *page; 6530 unsigned long total_mapped = 0; 6531 unsigned long total_migrated = 0; 6532 unsigned long total_reclaimed = 0; 6533 6534 lru_cache_disable(); 6535 6536 while (pfn < end || !list_empty(&cc->migratepages)) { 6537 if (fatal_signal_pending(current)) { 6538 ret = -EINTR; 6539 break; 6540 } 6541 6542 if (list_empty(&cc->migratepages)) { 6543 cc->nr_migratepages = 0; 6544 ret = isolate_migratepages_range(cc, pfn, end); 6545 if (ret && ret != -EAGAIN) 6546 break; 6547 pfn = cc->migrate_pfn; 6548 tries = 0; 6549 } else if (++tries == 5) { 6550 ret = -EBUSY; 6551 break; 6552 } 6553 6554 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone, 6555 &cc->migratepages); 6556 cc->nr_migratepages -= nr_reclaimed; 6557 6558 if (trace_mm_alloc_contig_migrate_range_info_enabled()) { 6559 total_reclaimed += nr_reclaimed; 6560 list_for_each_entry(page, &cc->migratepages, lru) { 6561 struct folio *folio = page_folio(page); 6562 6563 total_mapped += folio_mapped(folio) * 6564 folio_nr_pages(folio); 6565 } 6566 } 6567 6568 ret = migrate_pages(&cc->migratepages, alloc_migration_target, 6569 NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE, NULL); 6570 6571 if (trace_mm_alloc_contig_migrate_range_info_enabled() && !ret) 6572 total_migrated += cc->nr_migratepages; 6573 6574 /* 6575 * On -ENOMEM, migrate_pages() bails out right away. It is pointless 6576 * to retry again over this error, so do the same here. 6577 */ 6578 if (ret == -ENOMEM) 6579 break; 6580 } 6581 6582 lru_cache_enable(); 6583 if (ret < 0) { 6584 if (!(cc->gfp_mask & __GFP_NOWARN) && ret == -EBUSY) 6585 alloc_contig_dump_pages(&cc->migratepages); 6586 putback_movable_pages(&cc->migratepages); 6587 } 6588 6589 trace_mm_alloc_contig_migrate_range_info(start, end, migratetype, 6590 total_migrated, 6591 total_reclaimed, 6592 total_mapped); 6593 return (ret < 0) ? ret : 0; 6594 } 6595 6596 static void split_free_pages(struct list_head *list, gfp_t gfp_mask) 6597 { 6598 int order; 6599 6600 for (order = 0; order < NR_PAGE_ORDERS; order++) { 6601 struct page *page, *next; 6602 int nr_pages = 1 << order; 6603 6604 list_for_each_entry_safe(page, next, &list[order], lru) { 6605 int i; 6606 6607 post_alloc_hook(page, order, gfp_mask); 6608 set_page_refcounted(page); 6609 if (!order) 6610 continue; 6611 6612 split_page(page, order); 6613 6614 /* Add all subpages to the order-0 head, in sequence. */ 6615 list_del(&page->lru); 6616 for (i = 0; i < nr_pages; i++) 6617 list_add_tail(&page[i].lru, &list[0]); 6618 } 6619 } 6620 } 6621 6622 static int __alloc_contig_verify_gfp_mask(gfp_t gfp_mask, gfp_t *gfp_cc_mask) 6623 { 6624 const gfp_t reclaim_mask = __GFP_IO | __GFP_FS | __GFP_RECLAIM; 6625 const gfp_t action_mask = __GFP_COMP | __GFP_RETRY_MAYFAIL | __GFP_NOWARN | 6626 __GFP_ZERO | __GFP_ZEROTAGS | __GFP_SKIP_ZERO; 6627 const gfp_t cc_action_mask = __GFP_RETRY_MAYFAIL | __GFP_NOWARN; 6628 6629 /* 6630 * We are given the range to allocate; node, mobility and placement 6631 * hints are irrelevant at this point. We'll simply ignore them. 6632 */ 6633 gfp_mask &= ~(GFP_ZONEMASK | __GFP_RECLAIMABLE | __GFP_WRITE | 6634 __GFP_HARDWALL | __GFP_THISNODE | __GFP_MOVABLE); 6635 6636 /* 6637 * We only support most reclaim flags (but not NOFAIL/NORETRY), and 6638 * selected action flags. 6639 */ 6640 if (gfp_mask & ~(reclaim_mask | action_mask)) 6641 return -EINVAL; 6642 6643 /* 6644 * Flags to control page compaction/migration/reclaim, to free up our 6645 * page range. Migratable pages are movable, __GFP_MOVABLE is implied 6646 * for them. 6647 * 6648 * Traditionally we always had __GFP_RETRY_MAYFAIL set, keep doing that 6649 * to not degrade callers. 6650 */ 6651 *gfp_cc_mask = (gfp_mask & (reclaim_mask | cc_action_mask)) | 6652 __GFP_MOVABLE | __GFP_RETRY_MAYFAIL; 6653 return 0; 6654 } 6655 6656 /** 6657 * alloc_contig_range() -- tries to allocate given range of pages 6658 * @start: start PFN to allocate 6659 * @end: one-past-the-last PFN to allocate 6660 * @migratetype: migratetype of the underlying pageblocks (either 6661 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks 6662 * in range must have the same migratetype and it must 6663 * be either of the two. 6664 * @gfp_mask: GFP mask. Node/zone/placement hints are ignored; only some 6665 * action and reclaim modifiers are supported. Reclaim modifiers 6666 * control allocation behavior during compaction/migration/reclaim. 6667 * 6668 * The PFN range does not have to be pageblock aligned. The PFN range must 6669 * belong to a single zone. 6670 * 6671 * The first thing this routine does is attempt to MIGRATE_ISOLATE all 6672 * pageblocks in the range. Once isolated, the pageblocks should not 6673 * be modified by others. 6674 * 6675 * Return: zero on success or negative error code. On success all 6676 * pages which PFN is in [start, end) are allocated for the caller and 6677 * need to be freed with free_contig_range(). 6678 */ 6679 int alloc_contig_range_noprof(unsigned long start, unsigned long end, 6680 unsigned migratetype, gfp_t gfp_mask) 6681 { 6682 unsigned long outer_start, outer_end; 6683 int ret = 0; 6684 6685 struct compact_control cc = { 6686 .nr_migratepages = 0, 6687 .order = -1, 6688 .zone = page_zone(pfn_to_page(start)), 6689 .mode = MIGRATE_SYNC, 6690 .ignore_skip_hint = true, 6691 .no_set_skip_hint = true, 6692 .alloc_contig = true, 6693 }; 6694 INIT_LIST_HEAD(&cc.migratepages); 6695 6696 gfp_mask = current_gfp_context(gfp_mask); 6697 if (__alloc_contig_verify_gfp_mask(gfp_mask, (gfp_t *)&cc.gfp_mask)) 6698 return -EINVAL; 6699 6700 /* 6701 * What we do here is we mark all pageblocks in range as 6702 * MIGRATE_ISOLATE. Because pageblock and max order pages may 6703 * have different sizes, and due to the way page allocator 6704 * work, start_isolate_page_range() has special handlings for this. 6705 * 6706 * Once the pageblocks are marked as MIGRATE_ISOLATE, we 6707 * migrate the pages from an unaligned range (ie. pages that 6708 * we are interested in). This will put all the pages in 6709 * range back to page allocator as MIGRATE_ISOLATE. 6710 * 6711 * When this is done, we take the pages in range from page 6712 * allocator removing them from the buddy system. This way 6713 * page allocator will never consider using them. 6714 * 6715 * This lets us mark the pageblocks back as 6716 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the 6717 * aligned range but not in the unaligned, original range are 6718 * put back to page allocator so that buddy can use them. 6719 */ 6720 6721 ret = start_isolate_page_range(start, end, migratetype, 0); 6722 if (ret) 6723 goto done; 6724 6725 drain_all_pages(cc.zone); 6726 6727 /* 6728 * In case of -EBUSY, we'd like to know which page causes problem. 6729 * So, just fall through. test_pages_isolated() has a tracepoint 6730 * which will report the busy page. 6731 * 6732 * It is possible that busy pages could become available before 6733 * the call to test_pages_isolated, and the range will actually be 6734 * allocated. So, if we fall through be sure to clear ret so that 6735 * -EBUSY is not accidentally used or returned to caller. 6736 */ 6737 ret = __alloc_contig_migrate_range(&cc, start, end, migratetype); 6738 if (ret && ret != -EBUSY) 6739 goto done; 6740 6741 /* 6742 * When in-use hugetlb pages are migrated, they may simply be released 6743 * back into the free hugepage pool instead of being returned to the 6744 * buddy system. After the migration of in-use huge pages is completed, 6745 * we will invoke replace_free_hugepage_folios() to ensure that these 6746 * hugepages are properly released to the buddy system. 6747 */ 6748 ret = replace_free_hugepage_folios(start, end); 6749 if (ret) 6750 goto done; 6751 6752 /* 6753 * Pages from [start, end) are within a pageblock_nr_pages 6754 * aligned blocks that are marked as MIGRATE_ISOLATE. What's 6755 * more, all pages in [start, end) are free in page allocator. 6756 * What we are going to do is to allocate all pages from 6757 * [start, end) (that is remove them from page allocator). 6758 * 6759 * The only problem is that pages at the beginning and at the 6760 * end of interesting range may be not aligned with pages that 6761 * page allocator holds, ie. they can be part of higher order 6762 * pages. Because of this, we reserve the bigger range and 6763 * once this is done free the pages we are not interested in. 6764 * 6765 * We don't have to hold zone->lock here because the pages are 6766 * isolated thus they won't get removed from buddy. 6767 */ 6768 outer_start = find_large_buddy(start); 6769 6770 /* Make sure the range is really isolated. */ 6771 if (test_pages_isolated(outer_start, end, 0)) { 6772 ret = -EBUSY; 6773 goto done; 6774 } 6775 6776 /* Grab isolated pages from freelists. */ 6777 outer_end = isolate_freepages_range(&cc, outer_start, end); 6778 if (!outer_end) { 6779 ret = -EBUSY; 6780 goto done; 6781 } 6782 6783 if (!(gfp_mask & __GFP_COMP)) { 6784 split_free_pages(cc.freepages, gfp_mask); 6785 6786 /* Free head and tail (if any) */ 6787 if (start != outer_start) 6788 free_contig_range(outer_start, start - outer_start); 6789 if (end != outer_end) 6790 free_contig_range(end, outer_end - end); 6791 } else if (start == outer_start && end == outer_end && is_power_of_2(end - start)) { 6792 struct page *head = pfn_to_page(start); 6793 int order = ilog2(end - start); 6794 6795 check_new_pages(head, order); 6796 prep_new_page(head, order, gfp_mask, 0); 6797 set_page_refcounted(head); 6798 } else { 6799 ret = -EINVAL; 6800 WARN(true, "PFN range: requested [%lu, %lu), allocated [%lu, %lu)\n", 6801 start, end, outer_start, outer_end); 6802 } 6803 done: 6804 undo_isolate_page_range(start, end, migratetype); 6805 return ret; 6806 } 6807 EXPORT_SYMBOL(alloc_contig_range_noprof); 6808 6809 static int __alloc_contig_pages(unsigned long start_pfn, 6810 unsigned long nr_pages, gfp_t gfp_mask) 6811 { 6812 unsigned long end_pfn = start_pfn + nr_pages; 6813 6814 return alloc_contig_range_noprof(start_pfn, end_pfn, MIGRATE_MOVABLE, 6815 gfp_mask); 6816 } 6817 6818 static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn, 6819 unsigned long nr_pages) 6820 { 6821 unsigned long i, end_pfn = start_pfn + nr_pages; 6822 struct page *page; 6823 6824 for (i = start_pfn; i < end_pfn; i++) { 6825 page = pfn_to_online_page(i); 6826 if (!page) 6827 return false; 6828 6829 if (page_zone(page) != z) 6830 return false; 6831 6832 if (PageReserved(page)) 6833 return false; 6834 6835 if (PageHuge(page)) 6836 return false; 6837 } 6838 return true; 6839 } 6840 6841 static bool zone_spans_last_pfn(const struct zone *zone, 6842 unsigned long start_pfn, unsigned long nr_pages) 6843 { 6844 unsigned long last_pfn = start_pfn + nr_pages - 1; 6845 6846 return zone_spans_pfn(zone, last_pfn); 6847 } 6848 6849 /** 6850 * alloc_contig_pages() -- tries to find and allocate contiguous range of pages 6851 * @nr_pages: Number of contiguous pages to allocate 6852 * @gfp_mask: GFP mask. Node/zone/placement hints limit the search; only some 6853 * action and reclaim modifiers are supported. Reclaim modifiers 6854 * control allocation behavior during compaction/migration/reclaim. 6855 * @nid: Target node 6856 * @nodemask: Mask for other possible nodes 6857 * 6858 * This routine is a wrapper around alloc_contig_range(). It scans over zones 6859 * on an applicable zonelist to find a contiguous pfn range which can then be 6860 * tried for allocation with alloc_contig_range(). This routine is intended 6861 * for allocation requests which can not be fulfilled with the buddy allocator. 6862 * 6863 * The allocated memory is always aligned to a page boundary. If nr_pages is a 6864 * power of two, then allocated range is also guaranteed to be aligned to same 6865 * nr_pages (e.g. 1GB request would be aligned to 1GB). 6866 * 6867 * Allocated pages can be freed with free_contig_range() or by manually calling 6868 * __free_page() on each allocated page. 6869 * 6870 * Return: pointer to contiguous pages on success, or NULL if not successful. 6871 */ 6872 struct page *alloc_contig_pages_noprof(unsigned long nr_pages, gfp_t gfp_mask, 6873 int nid, nodemask_t *nodemask) 6874 { 6875 unsigned long ret, pfn, flags; 6876 struct zonelist *zonelist; 6877 struct zone *zone; 6878 struct zoneref *z; 6879 6880 zonelist = node_zonelist(nid, gfp_mask); 6881 for_each_zone_zonelist_nodemask(zone, z, zonelist, 6882 gfp_zone(gfp_mask), nodemask) { 6883 spin_lock_irqsave(&zone->lock, flags); 6884 6885 pfn = ALIGN(zone->zone_start_pfn, nr_pages); 6886 while (zone_spans_last_pfn(zone, pfn, nr_pages)) { 6887 if (pfn_range_valid_contig(zone, pfn, nr_pages)) { 6888 /* 6889 * We release the zone lock here because 6890 * alloc_contig_range() will also lock the zone 6891 * at some point. If there's an allocation 6892 * spinning on this lock, it may win the race 6893 * and cause alloc_contig_range() to fail... 6894 */ 6895 spin_unlock_irqrestore(&zone->lock, flags); 6896 ret = __alloc_contig_pages(pfn, nr_pages, 6897 gfp_mask); 6898 if (!ret) 6899 return pfn_to_page(pfn); 6900 spin_lock_irqsave(&zone->lock, flags); 6901 } 6902 pfn += nr_pages; 6903 } 6904 spin_unlock_irqrestore(&zone->lock, flags); 6905 } 6906 return NULL; 6907 } 6908 #endif /* CONFIG_CONTIG_ALLOC */ 6909 6910 void free_contig_range(unsigned long pfn, unsigned long nr_pages) 6911 { 6912 unsigned long count = 0; 6913 struct folio *folio = pfn_folio(pfn); 6914 6915 if (folio_test_large(folio)) { 6916 int expected = folio_nr_pages(folio); 6917 6918 if (nr_pages == expected) 6919 folio_put(folio); 6920 else 6921 WARN(true, "PFN %lu: nr_pages %lu != expected %d\n", 6922 pfn, nr_pages, expected); 6923 return; 6924 } 6925 6926 for (; nr_pages--; pfn++) { 6927 struct page *page = pfn_to_page(pfn); 6928 6929 count += page_count(page) != 1; 6930 __free_page(page); 6931 } 6932 WARN(count != 0, "%lu pages are still in use!\n", count); 6933 } 6934 EXPORT_SYMBOL(free_contig_range); 6935 6936 /* 6937 * Effectively disable pcplists for the zone by setting the high limit to 0 6938 * and draining all cpus. A concurrent page freeing on another CPU that's about 6939 * to put the page on pcplist will either finish before the drain and the page 6940 * will be drained, or observe the new high limit and skip the pcplist. 6941 * 6942 * Must be paired with a call to zone_pcp_enable(). 6943 */ 6944 void zone_pcp_disable(struct zone *zone) 6945 { 6946 mutex_lock(&pcp_batch_high_lock); 6947 __zone_set_pageset_high_and_batch(zone, 0, 0, 1); 6948 __drain_all_pages(zone, true); 6949 } 6950 6951 void zone_pcp_enable(struct zone *zone) 6952 { 6953 __zone_set_pageset_high_and_batch(zone, zone->pageset_high_min, 6954 zone->pageset_high_max, zone->pageset_batch); 6955 mutex_unlock(&pcp_batch_high_lock); 6956 } 6957 6958 void zone_pcp_reset(struct zone *zone) 6959 { 6960 int cpu; 6961 struct per_cpu_zonestat *pzstats; 6962 6963 if (zone->per_cpu_pageset != &boot_pageset) { 6964 for_each_online_cpu(cpu) { 6965 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu); 6966 drain_zonestat(zone, pzstats); 6967 } 6968 free_percpu(zone->per_cpu_pageset); 6969 zone->per_cpu_pageset = &boot_pageset; 6970 if (zone->per_cpu_zonestats != &boot_zonestats) { 6971 free_percpu(zone->per_cpu_zonestats); 6972 zone->per_cpu_zonestats = &boot_zonestats; 6973 } 6974 } 6975 } 6976 6977 #ifdef CONFIG_MEMORY_HOTREMOVE 6978 /* 6979 * All pages in the range must be in a single zone, must not contain holes, 6980 * must span full sections, and must be isolated before calling this function. 6981 * 6982 * Returns the number of managed (non-PageOffline()) pages in the range: the 6983 * number of pages for which memory offlining code must adjust managed page 6984 * counters using adjust_managed_page_count(). 6985 */ 6986 unsigned long __offline_isolated_pages(unsigned long start_pfn, 6987 unsigned long end_pfn) 6988 { 6989 unsigned long already_offline = 0, flags; 6990 unsigned long pfn = start_pfn; 6991 struct page *page; 6992 struct zone *zone; 6993 unsigned int order; 6994 6995 offline_mem_sections(pfn, end_pfn); 6996 zone = page_zone(pfn_to_page(pfn)); 6997 spin_lock_irqsave(&zone->lock, flags); 6998 while (pfn < end_pfn) { 6999 page = pfn_to_page(pfn); 7000 /* 7001 * The HWPoisoned page may be not in buddy system, and 7002 * page_count() is not 0. 7003 */ 7004 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) { 7005 pfn++; 7006 continue; 7007 } 7008 /* 7009 * At this point all remaining PageOffline() pages have a 7010 * reference count of 0 and can simply be skipped. 7011 */ 7012 if (PageOffline(page)) { 7013 BUG_ON(page_count(page)); 7014 BUG_ON(PageBuddy(page)); 7015 already_offline++; 7016 pfn++; 7017 continue; 7018 } 7019 7020 BUG_ON(page_count(page)); 7021 BUG_ON(!PageBuddy(page)); 7022 VM_WARN_ON(get_pageblock_migratetype(page) != MIGRATE_ISOLATE); 7023 order = buddy_order(page); 7024 del_page_from_free_list(page, zone, order, MIGRATE_ISOLATE); 7025 pfn += (1 << order); 7026 } 7027 spin_unlock_irqrestore(&zone->lock, flags); 7028 7029 return end_pfn - start_pfn - already_offline; 7030 } 7031 #endif 7032 7033 /* 7034 * This function returns a stable result only if called under zone lock. 7035 */ 7036 bool is_free_buddy_page(const struct page *page) 7037 { 7038 unsigned long pfn = page_to_pfn(page); 7039 unsigned int order; 7040 7041 for (order = 0; order < NR_PAGE_ORDERS; order++) { 7042 const struct page *head = page - (pfn & ((1 << order) - 1)); 7043 7044 if (PageBuddy(head) && 7045 buddy_order_unsafe(head) >= order) 7046 break; 7047 } 7048 7049 return order <= MAX_PAGE_ORDER; 7050 } 7051 EXPORT_SYMBOL(is_free_buddy_page); 7052 7053 #ifdef CONFIG_MEMORY_FAILURE 7054 static inline void add_to_free_list(struct page *page, struct zone *zone, 7055 unsigned int order, int migratetype, 7056 bool tail) 7057 { 7058 __add_to_free_list(page, zone, order, migratetype, tail); 7059 account_freepages(zone, 1 << order, migratetype); 7060 } 7061 7062 /* 7063 * Break down a higher-order page in sub-pages, and keep our target out of 7064 * buddy allocator. 7065 */ 7066 static void break_down_buddy_pages(struct zone *zone, struct page *page, 7067 struct page *target, int low, int high, 7068 int migratetype) 7069 { 7070 unsigned long size = 1 << high; 7071 struct page *current_buddy; 7072 7073 while (high > low) { 7074 high--; 7075 size >>= 1; 7076 7077 if (target >= &page[size]) { 7078 current_buddy = page; 7079 page = page + size; 7080 } else { 7081 current_buddy = page + size; 7082 } 7083 7084 if (set_page_guard(zone, current_buddy, high)) 7085 continue; 7086 7087 add_to_free_list(current_buddy, zone, high, migratetype, false); 7088 set_buddy_order(current_buddy, high); 7089 } 7090 } 7091 7092 /* 7093 * Take a page that will be marked as poisoned off the buddy allocator. 7094 */ 7095 bool take_page_off_buddy(struct page *page) 7096 { 7097 struct zone *zone = page_zone(page); 7098 unsigned long pfn = page_to_pfn(page); 7099 unsigned long flags; 7100 unsigned int order; 7101 bool ret = false; 7102 7103 spin_lock_irqsave(&zone->lock, flags); 7104 for (order = 0; order < NR_PAGE_ORDERS; order++) { 7105 struct page *page_head = page - (pfn & ((1 << order) - 1)); 7106 int page_order = buddy_order(page_head); 7107 7108 if (PageBuddy(page_head) && page_order >= order) { 7109 unsigned long pfn_head = page_to_pfn(page_head); 7110 int migratetype = get_pfnblock_migratetype(page_head, 7111 pfn_head); 7112 7113 del_page_from_free_list(page_head, zone, page_order, 7114 migratetype); 7115 break_down_buddy_pages(zone, page_head, page, 0, 7116 page_order, migratetype); 7117 SetPageHWPoisonTakenOff(page); 7118 ret = true; 7119 break; 7120 } 7121 if (page_count(page_head) > 0) 7122 break; 7123 } 7124 spin_unlock_irqrestore(&zone->lock, flags); 7125 return ret; 7126 } 7127 7128 /* 7129 * Cancel takeoff done by take_page_off_buddy(). 7130 */ 7131 bool put_page_back_buddy(struct page *page) 7132 { 7133 struct zone *zone = page_zone(page); 7134 unsigned long flags; 7135 bool ret = false; 7136 7137 spin_lock_irqsave(&zone->lock, flags); 7138 if (put_page_testzero(page)) { 7139 unsigned long pfn = page_to_pfn(page); 7140 int migratetype = get_pfnblock_migratetype(page, pfn); 7141 7142 ClearPageHWPoisonTakenOff(page); 7143 __free_one_page(page, pfn, zone, 0, migratetype, FPI_NONE); 7144 if (TestClearPageHWPoison(page)) { 7145 ret = true; 7146 } 7147 } 7148 spin_unlock_irqrestore(&zone->lock, flags); 7149 7150 return ret; 7151 } 7152 #endif 7153 7154 #ifdef CONFIG_ZONE_DMA 7155 bool has_managed_dma(void) 7156 { 7157 struct pglist_data *pgdat; 7158 7159 for_each_online_pgdat(pgdat) { 7160 struct zone *zone = &pgdat->node_zones[ZONE_DMA]; 7161 7162 if (managed_zone(zone)) 7163 return true; 7164 } 7165 return false; 7166 } 7167 #endif /* CONFIG_ZONE_DMA */ 7168 7169 #ifdef CONFIG_UNACCEPTED_MEMORY 7170 7171 static bool lazy_accept = true; 7172 7173 static int __init accept_memory_parse(char *p) 7174 { 7175 if (!strcmp(p, "lazy")) { 7176 lazy_accept = true; 7177 return 0; 7178 } else if (!strcmp(p, "eager")) { 7179 lazy_accept = false; 7180 return 0; 7181 } else { 7182 return -EINVAL; 7183 } 7184 } 7185 early_param("accept_memory", accept_memory_parse); 7186 7187 static bool page_contains_unaccepted(struct page *page, unsigned int order) 7188 { 7189 phys_addr_t start = page_to_phys(page); 7190 7191 return range_contains_unaccepted_memory(start, PAGE_SIZE << order); 7192 } 7193 7194 static void __accept_page(struct zone *zone, unsigned long *flags, 7195 struct page *page) 7196 { 7197 list_del(&page->lru); 7198 account_freepages(zone, -MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE); 7199 __mod_zone_page_state(zone, NR_UNACCEPTED, -MAX_ORDER_NR_PAGES); 7200 __ClearPageUnaccepted(page); 7201 spin_unlock_irqrestore(&zone->lock, *flags); 7202 7203 accept_memory(page_to_phys(page), PAGE_SIZE << MAX_PAGE_ORDER); 7204 7205 __free_pages_ok(page, MAX_PAGE_ORDER, FPI_TO_TAIL); 7206 } 7207 7208 void accept_page(struct page *page) 7209 { 7210 struct zone *zone = page_zone(page); 7211 unsigned long flags; 7212 7213 spin_lock_irqsave(&zone->lock, flags); 7214 if (!PageUnaccepted(page)) { 7215 spin_unlock_irqrestore(&zone->lock, flags); 7216 return; 7217 } 7218 7219 /* Unlocks zone->lock */ 7220 __accept_page(zone, &flags, page); 7221 } 7222 7223 static bool try_to_accept_memory_one(struct zone *zone) 7224 { 7225 unsigned long flags; 7226 struct page *page; 7227 7228 spin_lock_irqsave(&zone->lock, flags); 7229 page = list_first_entry_or_null(&zone->unaccepted_pages, 7230 struct page, lru); 7231 if (!page) { 7232 spin_unlock_irqrestore(&zone->lock, flags); 7233 return false; 7234 } 7235 7236 /* Unlocks zone->lock */ 7237 __accept_page(zone, &flags, page); 7238 7239 return true; 7240 } 7241 7242 static bool cond_accept_memory(struct zone *zone, unsigned int order, 7243 int alloc_flags) 7244 { 7245 long to_accept, wmark; 7246 bool ret = false; 7247 7248 if (list_empty(&zone->unaccepted_pages)) 7249 return false; 7250 7251 /* Bailout, since try_to_accept_memory_one() needs to take a lock */ 7252 if (alloc_flags & ALLOC_TRYLOCK) 7253 return false; 7254 7255 wmark = promo_wmark_pages(zone); 7256 7257 /* 7258 * Watermarks have not been initialized yet. 7259 * 7260 * Accepting one MAX_ORDER page to ensure progress. 7261 */ 7262 if (!wmark) 7263 return try_to_accept_memory_one(zone); 7264 7265 /* How much to accept to get to promo watermark? */ 7266 to_accept = wmark - 7267 (zone_page_state(zone, NR_FREE_PAGES) - 7268 __zone_watermark_unusable_free(zone, order, 0) - 7269 zone_page_state(zone, NR_UNACCEPTED)); 7270 7271 while (to_accept > 0) { 7272 if (!try_to_accept_memory_one(zone)) 7273 break; 7274 ret = true; 7275 to_accept -= MAX_ORDER_NR_PAGES; 7276 } 7277 7278 return ret; 7279 } 7280 7281 static bool __free_unaccepted(struct page *page) 7282 { 7283 struct zone *zone = page_zone(page); 7284 unsigned long flags; 7285 7286 if (!lazy_accept) 7287 return false; 7288 7289 spin_lock_irqsave(&zone->lock, flags); 7290 list_add_tail(&page->lru, &zone->unaccepted_pages); 7291 account_freepages(zone, MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE); 7292 __mod_zone_page_state(zone, NR_UNACCEPTED, MAX_ORDER_NR_PAGES); 7293 __SetPageUnaccepted(page); 7294 spin_unlock_irqrestore(&zone->lock, flags); 7295 7296 return true; 7297 } 7298 7299 #else 7300 7301 static bool page_contains_unaccepted(struct page *page, unsigned int order) 7302 { 7303 return false; 7304 } 7305 7306 static bool cond_accept_memory(struct zone *zone, unsigned int order, 7307 int alloc_flags) 7308 { 7309 return false; 7310 } 7311 7312 static bool __free_unaccepted(struct page *page) 7313 { 7314 BUILD_BUG(); 7315 return false; 7316 } 7317 7318 #endif /* CONFIG_UNACCEPTED_MEMORY */ 7319 7320 /** 7321 * try_alloc_pages - opportunistic reentrant allocation from any context 7322 * @nid: node to allocate from 7323 * @order: allocation order size 7324 * 7325 * Allocates pages of a given order from the given node. This is safe to 7326 * call from any context (from atomic, NMI, and also reentrant 7327 * allocator -> tracepoint -> try_alloc_pages_noprof). 7328 * Allocation is best effort and to be expected to fail easily so nobody should 7329 * rely on the success. Failures are not reported via warn_alloc(). 7330 * See always fail conditions below. 7331 * 7332 * Return: allocated page or NULL on failure. 7333 */ 7334 struct page *try_alloc_pages_noprof(int nid, unsigned int order) 7335 { 7336 /* 7337 * Do not specify __GFP_DIRECT_RECLAIM, since direct claim is not allowed. 7338 * Do not specify __GFP_KSWAPD_RECLAIM either, since wake up of kswapd 7339 * is not safe in arbitrary context. 7340 * 7341 * These two are the conditions for gfpflags_allow_spinning() being true. 7342 * 7343 * Specify __GFP_NOWARN since failing try_alloc_pages() is not a reason 7344 * to warn. Also warn would trigger printk() which is unsafe from 7345 * various contexts. We cannot use printk_deferred_enter() to mitigate, 7346 * since the running context is unknown. 7347 * 7348 * Specify __GFP_ZERO to make sure that call to kmsan_alloc_page() below 7349 * is safe in any context. Also zeroing the page is mandatory for 7350 * BPF use cases. 7351 * 7352 * Though __GFP_NOMEMALLOC is not checked in the code path below, 7353 * specify it here to highlight that try_alloc_pages() 7354 * doesn't want to deplete reserves. 7355 */ 7356 gfp_t alloc_gfp = __GFP_NOWARN | __GFP_ZERO | __GFP_NOMEMALLOC 7357 | __GFP_ACCOUNT; 7358 unsigned int alloc_flags = ALLOC_TRYLOCK; 7359 struct alloc_context ac = { }; 7360 struct page *page; 7361 7362 /* 7363 * In PREEMPT_RT spin_trylock() will call raw_spin_lock() which is 7364 * unsafe in NMI. If spin_trylock() is called from hard IRQ the current 7365 * task may be waiting for one rt_spin_lock, but rt_spin_trylock() will 7366 * mark the task as the owner of another rt_spin_lock which will 7367 * confuse PI logic, so return immediately if called form hard IRQ or 7368 * NMI. 7369 * 7370 * Note, irqs_disabled() case is ok. This function can be called 7371 * from raw_spin_lock_irqsave region. 7372 */ 7373 if (IS_ENABLED(CONFIG_PREEMPT_RT) && (in_nmi() || in_hardirq())) 7374 return NULL; 7375 if (!pcp_allowed_order(order)) 7376 return NULL; 7377 7378 /* Bailout, since _deferred_grow_zone() needs to take a lock */ 7379 if (deferred_pages_enabled()) 7380 return NULL; 7381 7382 if (nid == NUMA_NO_NODE) 7383 nid = numa_node_id(); 7384 7385 prepare_alloc_pages(alloc_gfp, order, nid, NULL, &ac, 7386 &alloc_gfp, &alloc_flags); 7387 7388 /* 7389 * Best effort allocation from percpu free list. 7390 * If it's empty attempt to spin_trylock zone->lock. 7391 */ 7392 page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac); 7393 7394 /* Unlike regular alloc_pages() there is no __alloc_pages_slowpath(). */ 7395 7396 if (page) 7397 set_page_refcounted(page); 7398 7399 if (memcg_kmem_online() && page && 7400 unlikely(__memcg_kmem_charge_page(page, alloc_gfp, order) != 0)) { 7401 free_pages_nolock(page, order); 7402 page = NULL; 7403 } 7404 trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype); 7405 kmsan_alloc_page(page, order, alloc_gfp); 7406 return page; 7407 } 7408