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