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