Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

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