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