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