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