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/swap.h> 22#include <linux/interrupt.h> 23#include <linux/pagemap.h> 24#include <linux/jiffies.h> 25#include <linux/memblock.h> 26#include <linux/compiler.h> 27#include <linux/kernel.h> 28#include <linux/kasan.h> 29#include <linux/module.h> 30#include <linux/suspend.h> 31#include <linux/pagevec.h> 32#include <linux/blkdev.h> 33#include <linux/slab.h> 34#include <linux/ratelimit.h> 35#include <linux/oom.h> 36#include <linux/topology.h> 37#include <linux/sysctl.h> 38#include <linux/cpu.h> 39#include <linux/cpuset.h> 40#include <linux/memory_hotplug.h> 41#include <linux/nodemask.h> 42#include <linux/vmalloc.h> 43#include <linux/vmstat.h> 44#include <linux/mempolicy.h> 45#include <linux/memremap.h> 46#include <linux/stop_machine.h> 47#include <linux/random.h> 48#include <linux/sort.h> 49#include <linux/pfn.h> 50#include <linux/backing-dev.h> 51#include <linux/fault-inject.h> 52#include <linux/page-isolation.h> 53#include <linux/debugobjects.h> 54#include <linux/kmemleak.h> 55#include <linux/compaction.h> 56#include <trace/events/kmem.h> 57#include <trace/events/oom.h> 58#include <linux/prefetch.h> 59#include <linux/mm_inline.h> 60#include <linux/migrate.h> 61#include <linux/hugetlb.h> 62#include <linux/sched/rt.h> 63#include <linux/sched/mm.h> 64#include <linux/page_owner.h> 65#include <linux/kthread.h> 66#include <linux/memcontrol.h> 67#include <linux/ftrace.h> 68#include <linux/lockdep.h> 69#include <linux/nmi.h> 70#include <linux/psi.h> 71#include <linux/padata.h> 72#include <linux/khugepaged.h> 73#include <linux/zswapd.h> 74#ifdef CONFIG_RECLAIM_ACCT 75#include <linux/reclaim_acct.h> 76#endif 77 78#include <asm/sections.h> 79#include <asm/tlbflush.h> 80#include <asm/div64.h> 81#include "internal.h" 82#include "shuffle.h" 83#include "page_reporting.h" 84 85/* Free Page Internal flags: for internal, non-pcp variants of free_pages(). */ 86typedef int __bitwise fpi_t; 87 88/* No special request */ 89#define FPI_NONE ((__force fpi_t)0) 90 91/* 92 * Skip free page reporting notification for the (possibly merged) page. 93 * This does not hinder free page reporting from grabbing the page, 94 * reporting it and marking it "reported" - it only skips notifying 95 * the free page reporting infrastructure about a newly freed page. For 96 * example, used when temporarily pulling a page from a freelist and 97 * putting it back unmodified. 98 */ 99#define FPI_SKIP_REPORT_NOTIFY ((__force fpi_t)BIT(0)) 100 101/* 102 * Place the (possibly merged) page to the tail of the freelist. Will ignore 103 * page shuffling (relevant code - e.g., memory onlining - is expected to 104 * shuffle the whole zone). 105 * 106 * Note: No code should rely on this flag for correctness - it's purely 107 * to allow for optimizations when handing back either fresh pages 108 * (memory onlining) or untouched pages (page isolation, free page 109 * reporting). 110 */ 111#define FPI_TO_TAIL ((__force fpi_t)BIT(1)) 112 113/* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */ 114static DEFINE_MUTEX(pcp_batch_high_lock); 115#define MIN_PERCPU_PAGELIST_FRACTION (8) 116 117#ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID 118DEFINE_PER_CPU(int, numa_node); 119EXPORT_PER_CPU_SYMBOL(numa_node); 120#endif 121 122DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key); 123 124#ifdef CONFIG_HAVE_MEMORYLESS_NODES 125/* 126 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly. 127 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined. 128 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem() 129 * defined in <linux/topology.h>. 130 */ 131DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */ 132EXPORT_PER_CPU_SYMBOL(_numa_mem_); 133#endif 134 135/* work_structs for global per-cpu drains */ 136struct pcpu_drain { 137 struct zone *zone; 138 struct work_struct work; 139}; 140static DEFINE_MUTEX(pcpu_drain_mutex); 141static DEFINE_PER_CPU(struct pcpu_drain, pcpu_drain); 142 143#ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY 144volatile unsigned long latent_entropy __latent_entropy; 145EXPORT_SYMBOL(latent_entropy); 146#endif 147 148/* 149 * Array of node states. 150 */ 151nodemask_t node_states[NR_NODE_STATES] __read_mostly = { 152 [N_POSSIBLE] = NODE_MASK_ALL, 153 [N_ONLINE] = { { [0] = 1UL } }, 154#ifndef CONFIG_NUMA 155 [N_NORMAL_MEMORY] = { { [0] = 1UL } }, 156#ifdef CONFIG_HIGHMEM 157 [N_HIGH_MEMORY] = { { [0] = 1UL } }, 158#endif 159 [N_MEMORY] = { { [0] = 1UL } }, 160 [N_CPU] = { { [0] = 1UL } }, 161#endif /* NUMA */ 162}; 163EXPORT_SYMBOL(node_states); 164 165atomic_long_t _totalram_pages __read_mostly; 166EXPORT_SYMBOL(_totalram_pages); 167unsigned long totalreserve_pages __read_mostly; 168unsigned long totalcma_pages __read_mostly; 169 170int percpu_pagelist_fraction; 171gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK; 172#ifdef CONFIG_INIT_ON_ALLOC_DEFAULT_ON 173DEFINE_STATIC_KEY_TRUE(init_on_alloc); 174#else 175DEFINE_STATIC_KEY_FALSE(init_on_alloc); 176#endif 177EXPORT_SYMBOL(init_on_alloc); 178 179#ifdef CONFIG_INIT_ON_FREE_DEFAULT_ON 180DEFINE_STATIC_KEY_TRUE(init_on_free); 181#else 182DEFINE_STATIC_KEY_FALSE(init_on_free); 183#endif 184EXPORT_SYMBOL(init_on_free); 185 186static int __init early_init_on_alloc(char *buf) 187{ 188 int ret; 189 bool bool_result; 190 191 ret = kstrtobool(buf, &bool_result); 192 if (ret) 193 return ret; 194 if (bool_result && page_poisoning_enabled()) 195 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, will take precedence over init_on_alloc\n"); 196 if (bool_result) 197 static_branch_enable(&init_on_alloc); 198 else 199 static_branch_disable(&init_on_alloc); 200 return 0; 201} 202early_param("init_on_alloc", early_init_on_alloc); 203 204static int __init early_init_on_free(char *buf) 205{ 206 int ret; 207 bool bool_result; 208 209 ret = kstrtobool(buf, &bool_result); 210 if (ret) 211 return ret; 212 if (bool_result && page_poisoning_enabled()) 213 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, will take precedence over init_on_free\n"); 214 if (bool_result) 215 static_branch_enable(&init_on_free); 216 else 217 static_branch_disable(&init_on_free); 218 return 0; 219} 220early_param("init_on_free", early_init_on_free); 221 222/* 223 * A cached value of the page's pageblock's migratetype, used when the page is 224 * put on a pcplist. Used to avoid the pageblock migratetype lookup when 225 * freeing from pcplists in most cases, at the cost of possibly becoming stale. 226 * Also the migratetype set in the page does not necessarily match the pcplist 227 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any 228 * other index - this ensures that it will be put on the correct CMA freelist. 229 */ 230static inline int get_pcppage_migratetype(struct page *page) 231{ 232 return page->index; 233} 234 235static inline void set_pcppage_migratetype(struct page *page, int migratetype) 236{ 237 page->index = migratetype; 238} 239 240#ifdef CONFIG_PM_SLEEP 241/* 242 * The following functions are used by the suspend/hibernate code to temporarily 243 * change gfp_allowed_mask in order to avoid using I/O during memory allocations 244 * while devices are suspended. To avoid races with the suspend/hibernate code, 245 * they should always be called with system_transition_mutex held 246 * (gfp_allowed_mask also should only be modified with system_transition_mutex 247 * held, unless the suspend/hibernate code is guaranteed not to run in parallel 248 * with that modification). 249 */ 250 251static gfp_t saved_gfp_mask; 252 253void pm_restore_gfp_mask(void) 254{ 255 WARN_ON(!mutex_is_locked(&system_transition_mutex)); 256 if (saved_gfp_mask) { 257 gfp_allowed_mask = saved_gfp_mask; 258 saved_gfp_mask = 0; 259 } 260} 261 262void pm_restrict_gfp_mask(void) 263{ 264 WARN_ON(!mutex_is_locked(&system_transition_mutex)); 265 WARN_ON(saved_gfp_mask); 266 saved_gfp_mask = gfp_allowed_mask; 267 gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS); 268} 269 270bool pm_suspended_storage(void) 271{ 272 if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS)) 273 return false; 274 return true; 275} 276#endif /* CONFIG_PM_SLEEP */ 277 278#ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE 279unsigned int pageblock_order __read_mostly; 280#endif 281 282static void __free_pages_ok(struct page *page, unsigned int order, 283 fpi_t fpi_flags); 284 285/* 286 * results with 256, 32 in the lowmem_reserve sysctl: 287 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high) 288 * 1G machine -> (16M dma, 784M normal, 224M high) 289 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA 290 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL 291 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA 292 * 293 * TBD: should special case ZONE_DMA32 machines here - in those we normally 294 * don't need any ZONE_NORMAL reservation 295 */ 296int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = { 297#ifdef CONFIG_ZONE_DMA 298 [ZONE_DMA] = 256, 299#endif 300#ifdef CONFIG_ZONE_DMA32 301 [ZONE_DMA32] = 256, 302#endif 303 [ZONE_NORMAL] = 32, 304#ifdef CONFIG_HIGHMEM 305 [ZONE_HIGHMEM] = 0, 306#endif 307 [ZONE_MOVABLE] = 0, 308}; 309 310static char * const zone_names[MAX_NR_ZONES] = { 311#ifdef CONFIG_ZONE_DMA 312 "DMA", 313#endif 314#ifdef CONFIG_ZONE_DMA32 315 "DMA32", 316#endif 317 "Normal", 318#ifdef CONFIG_HIGHMEM 319 "HighMem", 320#endif 321 "Movable", 322#ifdef CONFIG_ZONE_DEVICE 323 "Device", 324#endif 325}; 326 327const char * const migratetype_names[MIGRATE_TYPES] = { 328 "Unmovable", 329 "Movable", 330 "Reclaimable", 331#ifdef CONFIG_CMA_REUSE 332 "CMA", 333#endif 334 "HighAtomic", 335#if defined(CONFIG_CMA) && !defined(CONFIG_CMA_REUSE) 336 "CMA", 337#endif 338#ifdef CONFIG_MEMORY_ISOLATION 339 "Isolate", 340#endif 341}; 342 343compound_page_dtor * const compound_page_dtors[NR_COMPOUND_DTORS] = { 344 [NULL_COMPOUND_DTOR] = NULL, 345 [COMPOUND_PAGE_DTOR] = free_compound_page, 346#ifdef CONFIG_HUGETLB_PAGE 347 [HUGETLB_PAGE_DTOR] = free_huge_page, 348#endif 349#ifdef CONFIG_TRANSPARENT_HUGEPAGE 350 [TRANSHUGE_PAGE_DTOR] = free_transhuge_page, 351#endif 352}; 353 354int min_free_kbytes = 1024; 355int user_min_free_kbytes = -1; 356#ifdef CONFIG_DISCONTIGMEM 357/* 358 * DiscontigMem defines memory ranges as separate pg_data_t even if the ranges 359 * are not on separate NUMA nodes. Functionally this works but with 360 * watermark_boost_factor, it can reclaim prematurely as the ranges can be 361 * quite small. By default, do not boost watermarks on discontigmem as in 362 * many cases very high-order allocations like THP are likely to be 363 * unsupported and the premature reclaim offsets the advantage of long-term 364 * fragmentation avoidance. 365 */ 366int watermark_boost_factor __read_mostly; 367#else 368int watermark_boost_factor __read_mostly = 15000; 369#endif 370int watermark_scale_factor = 10; 371 372static unsigned long nr_kernel_pages __initdata; 373static unsigned long nr_all_pages __initdata; 374static unsigned long dma_reserve __initdata; 375 376static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata; 377static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata; 378static unsigned long required_kernelcore __initdata; 379static unsigned long required_kernelcore_percent __initdata; 380static unsigned long required_movablecore __initdata; 381static unsigned long required_movablecore_percent __initdata; 382static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata; 383static bool mirrored_kernelcore __meminitdata; 384 385/* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */ 386int movable_zone; 387EXPORT_SYMBOL(movable_zone); 388 389#if MAX_NUMNODES > 1 390unsigned int nr_node_ids __read_mostly = MAX_NUMNODES; 391unsigned int nr_online_nodes __read_mostly = 1; 392EXPORT_SYMBOL(nr_node_ids); 393EXPORT_SYMBOL(nr_online_nodes); 394#endif 395 396int page_group_by_mobility_disabled __read_mostly; 397 398#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 399/* 400 * During boot we initialize deferred pages on-demand, as needed, but once 401 * page_alloc_init_late() has finished, the deferred pages are all initialized, 402 * and we can permanently disable that path. 403 */ 404static DEFINE_STATIC_KEY_TRUE(deferred_pages); 405 406/* 407 * Calling kasan_free_pages() only after deferred memory initialization 408 * has completed. Poisoning pages during deferred memory init will greatly 409 * lengthen the process and cause problem in large memory systems as the 410 * deferred pages initialization is done with interrupt disabled. 411 * 412 * Assuming that there will be no reference to those newly initialized 413 * pages before they are ever allocated, this should have no effect on 414 * KASAN memory tracking as the poison will be properly inserted at page 415 * allocation time. The only corner case is when pages are allocated by 416 * on-demand allocation and then freed again before the deferred pages 417 * initialization is done, but this is not likely to happen. 418 */ 419static inline void kasan_free_nondeferred_pages(struct page *page, int order) 420{ 421 if (!static_branch_unlikely(&deferred_pages)) 422 kasan_free_pages(page, order); 423} 424 425/* Returns true if the struct page for the pfn is uninitialised */ 426static inline bool __meminit early_page_uninitialised(unsigned long pfn) 427{ 428 int nid = early_pfn_to_nid(pfn); 429 430 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn) 431 return true; 432 433 return false; 434} 435 436/* 437 * Returns true when the remaining initialisation should be deferred until 438 * later in the boot cycle when it can be parallelised. 439 */ 440static bool __meminit 441defer_init(int nid, unsigned long pfn, unsigned long end_pfn) 442{ 443 static unsigned long prev_end_pfn, nr_initialised; 444 445 /* 446 * prev_end_pfn static that contains the end of previous zone 447 * No need to protect because called very early in boot before smp_init. 448 */ 449 if (prev_end_pfn != end_pfn) { 450 prev_end_pfn = end_pfn; 451 nr_initialised = 0; 452 } 453 454 /* Always populate low zones for address-constrained allocations */ 455 if (end_pfn < pgdat_end_pfn(NODE_DATA(nid))) 456 return false; 457 458 if (NODE_DATA(nid)->first_deferred_pfn != ULONG_MAX) 459 return true; 460 /* 461 * We start only with one section of pages, more pages are added as 462 * needed until the rest of deferred pages are initialized. 463 */ 464 nr_initialised++; 465 if ((nr_initialised > PAGES_PER_SECTION) && 466 (pfn & (PAGES_PER_SECTION - 1)) == 0) { 467 NODE_DATA(nid)->first_deferred_pfn = pfn; 468 return true; 469 } 470 return false; 471} 472#else 473#define kasan_free_nondeferred_pages(p, o) kasan_free_pages(p, o) 474 475static inline bool early_page_uninitialised(unsigned long pfn) 476{ 477 return false; 478} 479 480static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn) 481{ 482 return false; 483} 484#endif 485 486/* Return a pointer to the bitmap storing bits affecting a block of pages */ 487static inline unsigned long *get_pageblock_bitmap(struct page *page, 488 unsigned long pfn) 489{ 490#ifdef CONFIG_SPARSEMEM 491 return section_to_usemap(__pfn_to_section(pfn)); 492#else 493 return page_zone(page)->pageblock_flags; 494#endif /* CONFIG_SPARSEMEM */ 495} 496 497static inline int pfn_to_bitidx(struct page *page, unsigned long pfn) 498{ 499#ifdef CONFIG_SPARSEMEM 500 pfn &= (PAGES_PER_SECTION-1); 501#else 502 pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages); 503#endif /* CONFIG_SPARSEMEM */ 504 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS; 505} 506 507/** 508 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages 509 * @page: The page within the block of interest 510 * @pfn: The target page frame number 511 * @mask: mask of bits that the caller is interested in 512 * 513 * Return: pageblock_bits flags 514 */ 515static __always_inline 516unsigned long __get_pfnblock_flags_mask(struct page *page, 517 unsigned long pfn, 518 unsigned long mask) 519{ 520 unsigned long *bitmap; 521 unsigned long bitidx, word_bitidx; 522 unsigned long word; 523 524 bitmap = get_pageblock_bitmap(page, pfn); 525 bitidx = pfn_to_bitidx(page, pfn); 526 word_bitidx = bitidx / BITS_PER_LONG; 527 bitidx &= (BITS_PER_LONG-1); 528 529 word = bitmap[word_bitidx]; 530 return (word >> bitidx) & mask; 531} 532 533unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn, 534 unsigned long mask) 535{ 536 return __get_pfnblock_flags_mask(page, pfn, mask); 537} 538 539static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn) 540{ 541 return __get_pfnblock_flags_mask(page, pfn, MIGRATETYPE_MASK); 542} 543 544/** 545 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages 546 * @page: The page within the block of interest 547 * @flags: The flags to set 548 * @pfn: The target page frame number 549 * @mask: mask of bits that the caller is interested in 550 */ 551void set_pfnblock_flags_mask(struct page *page, unsigned long flags, 552 unsigned long pfn, 553 unsigned long mask) 554{ 555 unsigned long *bitmap; 556 unsigned long bitidx, word_bitidx; 557 unsigned long old_word, word; 558 559 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4); 560 BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits)); 561 562 bitmap = get_pageblock_bitmap(page, pfn); 563 bitidx = pfn_to_bitidx(page, pfn); 564 word_bitidx = bitidx / BITS_PER_LONG; 565 bitidx &= (BITS_PER_LONG-1); 566 567 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page); 568 569 mask <<= bitidx; 570 flags <<= bitidx; 571 572 word = READ_ONCE(bitmap[word_bitidx]); 573 for (;;) { 574 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags); 575 if (word == old_word) 576 break; 577 word = old_word; 578 } 579} 580 581void set_pageblock_migratetype(struct page *page, int migratetype) 582{ 583 if (unlikely(page_group_by_mobility_disabled && 584 migratetype < MIGRATE_PCPTYPES)) 585 migratetype = MIGRATE_UNMOVABLE; 586 587 set_pfnblock_flags_mask(page, (unsigned long)migratetype, 588 page_to_pfn(page), MIGRATETYPE_MASK); 589} 590 591#ifdef CONFIG_DEBUG_VM 592static int page_outside_zone_boundaries(struct zone *zone, struct page *page) 593{ 594 int ret = 0; 595 unsigned seq; 596 unsigned long pfn = page_to_pfn(page); 597 unsigned long sp, start_pfn; 598 599 do { 600 seq = zone_span_seqbegin(zone); 601 start_pfn = zone->zone_start_pfn; 602 sp = zone->spanned_pages; 603 if (!zone_spans_pfn(zone, pfn)) 604 ret = 1; 605 } while (zone_span_seqretry(zone, seq)); 606 607 if (ret) 608 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n", 609 pfn, zone_to_nid(zone), zone->name, 610 start_pfn, start_pfn + sp); 611 612 return ret; 613} 614 615static int page_is_consistent(struct zone *zone, struct page *page) 616{ 617 if (!pfn_valid_within(page_to_pfn(page))) 618 return 0; 619 if (zone != page_zone(page)) 620 return 0; 621 622 return 1; 623} 624/* 625 * Temporary debugging check for pages not lying within a given zone. 626 */ 627static int __maybe_unused bad_range(struct zone *zone, struct page *page) 628{ 629 if (page_outside_zone_boundaries(zone, page)) 630 return 1; 631 if (!page_is_consistent(zone, page)) 632 return 1; 633 634 return 0; 635} 636#else 637static inline int __maybe_unused bad_range(struct zone *zone, struct page *page) 638{ 639 return 0; 640} 641#endif 642 643static void bad_page(struct page *page, const char *reason) 644{ 645 static unsigned long resume; 646 static unsigned long nr_shown; 647 static unsigned long nr_unshown; 648 649 /* 650 * Allow a burst of 60 reports, then keep quiet for that minute; 651 * or allow a steady drip of one report per second. 652 */ 653 if (nr_shown == 60) { 654 if (time_before(jiffies, resume)) { 655 nr_unshown++; 656 goto out; 657 } 658 if (nr_unshown) { 659 pr_alert( 660 "BUG: Bad page state: %lu messages suppressed\n", 661 nr_unshown); 662 nr_unshown = 0; 663 } 664 nr_shown = 0; 665 } 666 if (nr_shown++ == 0) 667 resume = jiffies + 60 * HZ; 668 669 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n", 670 current->comm, page_to_pfn(page)); 671 __dump_page(page, reason); 672 dump_page_owner(page); 673 674 print_modules(); 675 dump_stack(); 676out: 677 /* Leave bad fields for debug, except PageBuddy could make trouble */ 678 page_mapcount_reset(page); /* remove PageBuddy */ 679 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); 680} 681 682/* 683 * Higher-order pages are called "compound pages". They are structured thusly: 684 * 685 * The first PAGE_SIZE page is called the "head page" and have PG_head set. 686 * 687 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded 688 * in bit 0 of page->compound_head. The rest of bits is pointer to head page. 689 * 690 * The first tail page's ->compound_dtor holds the offset in array of compound 691 * page destructors. See compound_page_dtors. 692 * 693 * The first tail page's ->compound_order holds the order of allocation. 694 * This usage means that zero-order pages may not be compound. 695 */ 696 697void free_compound_page(struct page *page) 698{ 699 mem_cgroup_uncharge(page); 700 __free_pages_ok(page, compound_order(page), FPI_NONE); 701} 702 703void prep_compound_page(struct page *page, unsigned int order) 704{ 705 int i; 706 int nr_pages = 1 << order; 707 708 __SetPageHead(page); 709 for (i = 1; i < nr_pages; i++) { 710 struct page *p = page + i; 711 set_page_count(p, 0); 712 p->mapping = TAIL_MAPPING; 713 set_compound_head(p, page); 714 } 715 716 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR); 717 set_compound_order(page, order); 718 atomic_set(compound_mapcount_ptr(page), -1); 719 if (hpage_pincount_available(page)) 720 atomic_set(compound_pincount_ptr(page), 0); 721} 722 723#ifdef CONFIG_DEBUG_PAGEALLOC 724unsigned int _debug_guardpage_minorder; 725 726bool _debug_pagealloc_enabled_early __read_mostly 727 = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT); 728EXPORT_SYMBOL(_debug_pagealloc_enabled_early); 729DEFINE_STATIC_KEY_FALSE(_debug_pagealloc_enabled); 730EXPORT_SYMBOL(_debug_pagealloc_enabled); 731 732DEFINE_STATIC_KEY_FALSE(_debug_guardpage_enabled); 733 734static int __init early_debug_pagealloc(char *buf) 735{ 736 return kstrtobool(buf, &_debug_pagealloc_enabled_early); 737} 738early_param("debug_pagealloc", early_debug_pagealloc); 739 740void init_debug_pagealloc(void) 741{ 742 if (!debug_pagealloc_enabled()) 743 return; 744 745 static_branch_enable(&_debug_pagealloc_enabled); 746 747 if (!debug_guardpage_minorder()) 748 return; 749 750 static_branch_enable(&_debug_guardpage_enabled); 751} 752 753static int __init debug_guardpage_minorder_setup(char *buf) 754{ 755 unsigned long res; 756 757 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) { 758 pr_err("Bad debug_guardpage_minorder value\n"); 759 return 0; 760 } 761 _debug_guardpage_minorder = res; 762 pr_info("Setting debug_guardpage_minorder to %lu\n", res); 763 return 0; 764} 765early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup); 766 767static inline bool set_page_guard(struct zone *zone, struct page *page, 768 unsigned int order, int migratetype) 769{ 770 if (!debug_guardpage_enabled()) 771 return false; 772 773 if (order >= debug_guardpage_minorder()) 774 return false; 775 776 __SetPageGuard(page); 777 INIT_LIST_HEAD(&page->lru); 778 set_page_private(page, order); 779 /* Guard pages are not available for any usage */ 780 __mod_zone_freepage_state(zone, -(1 << order), migratetype); 781 782 return true; 783} 784 785static inline void clear_page_guard(struct zone *zone, struct page *page, 786 unsigned int order, int migratetype) 787{ 788 if (!debug_guardpage_enabled()) 789 return; 790 791 __ClearPageGuard(page); 792 793 set_page_private(page, 0); 794 if (!is_migrate_isolate(migratetype)) 795 __mod_zone_freepage_state(zone, (1 << order), migratetype); 796} 797#else 798static inline bool set_page_guard(struct zone *zone, struct page *page, 799 unsigned int order, int migratetype) { return false; } 800static inline void clear_page_guard(struct zone *zone, struct page *page, 801 unsigned int order, int migratetype) {} 802#endif 803 804static inline void set_buddy_order(struct page *page, unsigned int order) 805{ 806 set_page_private(page, order); 807 __SetPageBuddy(page); 808} 809 810/* 811 * This function checks whether a page is free && is the buddy 812 * we can coalesce a page and its buddy if 813 * (a) the buddy is not in a hole (check before calling!) && 814 * (b) the buddy is in the buddy system && 815 * (c) a page and its buddy have the same order && 816 * (d) a page and its buddy are in the same zone. 817 * 818 * For recording whether a page is in the buddy system, we set PageBuddy. 819 * Setting, clearing, and testing PageBuddy is serialized by zone->lock. 820 * 821 * For recording page's order, we use page_private(page). 822 */ 823static inline bool page_is_buddy(struct page *page, struct page *buddy, 824 unsigned int order) 825{ 826 if (!page_is_guard(buddy) && !PageBuddy(buddy)) 827 return false; 828 829 if (buddy_order(buddy) != order) 830 return false; 831 832 /* 833 * zone check is done late to avoid uselessly calculating 834 * zone/node ids for pages that could never merge. 835 */ 836 if (page_zone_id(page) != page_zone_id(buddy)) 837 return false; 838 839 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy); 840 841 return true; 842} 843 844#ifdef CONFIG_COMPACTION 845static inline struct capture_control *task_capc(struct zone *zone) 846{ 847 struct capture_control *capc = current->capture_control; 848 849 return unlikely(capc) && 850 !(current->flags & PF_KTHREAD) && 851 !capc->page && 852 capc->cc->zone == zone ? capc : NULL; 853} 854 855static inline bool 856compaction_capture(struct capture_control *capc, struct page *page, 857 int order, int migratetype) 858{ 859 if (!capc || order != capc->cc->order) 860 return false; 861 862 /* Do not accidentally pollute CMA or isolated regions*/ 863 if (is_migrate_cma(migratetype) || 864 is_migrate_isolate(migratetype)) 865 return false; 866 867 /* 868 * Do not let lower order allocations polluate a movable pageblock. 869 * This might let an unmovable request use a reclaimable pageblock 870 * and vice-versa but no more than normal fallback logic which can 871 * have trouble finding a high-order free page. 872 */ 873 if (order < pageblock_order && migratetype == MIGRATE_MOVABLE) 874 return false; 875 876 capc->page = page; 877 return true; 878} 879 880#else 881static inline struct capture_control *task_capc(struct zone *zone) 882{ 883 return NULL; 884} 885 886static inline bool 887compaction_capture(struct capture_control *capc, struct page *page, 888 int order, int migratetype) 889{ 890 return false; 891} 892#endif /* CONFIG_COMPACTION */ 893 894/* Used for pages not on another list */ 895static inline void add_to_free_list(struct page *page, struct zone *zone, 896 unsigned int order, int migratetype) 897{ 898 struct free_area *area = &zone->free_area[order]; 899 900 list_add(&page->lru, &area->free_list[migratetype]); 901 area->nr_free++; 902} 903 904/* Used for pages not on another list */ 905static inline void add_to_free_list_tail(struct page *page, struct zone *zone, 906 unsigned int order, int migratetype) 907{ 908 struct free_area *area = &zone->free_area[order]; 909 910 list_add_tail(&page->lru, &area->free_list[migratetype]); 911 area->nr_free++; 912} 913 914/* 915 * Used for pages which are on another list. Move the pages to the tail 916 * of the list - so the moved pages won't immediately be considered for 917 * allocation again (e.g., optimization for memory onlining). 918 */ 919static inline void move_to_free_list(struct page *page, struct zone *zone, 920 unsigned int order, int migratetype) 921{ 922 struct free_area *area = &zone->free_area[order]; 923 924 list_move_tail(&page->lru, &area->free_list[migratetype]); 925} 926 927static inline void del_page_from_free_list(struct page *page, struct zone *zone, 928 unsigned int order) 929{ 930 /* clear reported state and update reported page count */ 931 if (page_reported(page)) 932 __ClearPageReported(page); 933 934 list_del(&page->lru); 935 __ClearPageBuddy(page); 936 set_page_private(page, 0); 937 zone->free_area[order].nr_free--; 938} 939 940/* 941 * If this is not the largest possible page, check if the buddy 942 * of the next-highest order is free. If it is, it's possible 943 * that pages are being freed that will coalesce soon. In case, 944 * that is happening, add the free page to the tail of the list 945 * so it's less likely to be used soon and more likely to be merged 946 * as a higher order page 947 */ 948static inline bool 949buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn, 950 struct page *page, unsigned int order) 951{ 952 struct page *higher_page, *higher_buddy; 953 unsigned long combined_pfn; 954 955 if (order >= MAX_ORDER - 2) 956 return false; 957 958 if (!pfn_valid_within(buddy_pfn)) 959 return false; 960 961 combined_pfn = buddy_pfn & pfn; 962 higher_page = page + (combined_pfn - pfn); 963 buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1); 964 higher_buddy = higher_page + (buddy_pfn - combined_pfn); 965 966 return pfn_valid_within(buddy_pfn) && 967 page_is_buddy(higher_page, higher_buddy, order + 1); 968} 969 970/* 971 * Freeing function for a buddy system allocator. 972 * 973 * The concept of a buddy system is to maintain direct-mapped table 974 * (containing bit values) for memory blocks of various "orders". 975 * The bottom level table contains the map for the smallest allocatable 976 * units of memory (here, pages), and each level above it describes 977 * pairs of units from the levels below, hence, "buddies". 978 * At a high level, all that happens here is marking the table entry 979 * at the bottom level available, and propagating the changes upward 980 * as necessary, plus some accounting needed to play nicely with other 981 * parts of the VM system. 982 * At each level, we keep a list of pages, which are heads of continuous 983 * free pages of length of (1 << order) and marked with PageBuddy. 984 * Page's order is recorded in page_private(page) field. 985 * So when we are allocating or freeing one, we can derive the state of the 986 * other. That is, if we allocate a small block, and both were 987 * free, the remainder of the region must be split into blocks. 988 * If a block is freed, and its buddy is also free, then this 989 * triggers coalescing into a block of larger size. 990 * 991 * -- nyc 992 */ 993 994static inline void __free_one_page(struct page *page, 995 unsigned long pfn, 996 struct zone *zone, unsigned int order, 997 int migratetype, fpi_t fpi_flags) 998{ 999 struct capture_control *capc = task_capc(zone); 1000 unsigned long buddy_pfn; 1001 unsigned long combined_pfn; 1002 unsigned int max_order; 1003 struct page *buddy; 1004 bool to_tail; 1005 1006 max_order = min_t(unsigned int, MAX_ORDER - 1, pageblock_order); 1007 1008 VM_BUG_ON(!zone_is_initialized(zone)); 1009 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page); 1010 1011 VM_BUG_ON(migratetype == -1); 1012 if (likely(!is_migrate_isolate(migratetype))) 1013 __mod_zone_freepage_state(zone, 1 << order, migratetype); 1014 1015 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page); 1016 VM_BUG_ON_PAGE(bad_range(zone, page), page); 1017 1018continue_merging: 1019 while (order < max_order) { 1020 if (compaction_capture(capc, page, order, migratetype)) { 1021 __mod_zone_freepage_state(zone, -(1 << order), 1022 migratetype); 1023 return; 1024 } 1025 buddy_pfn = __find_buddy_pfn(pfn, order); 1026 buddy = page + (buddy_pfn - pfn); 1027 1028 if (!pfn_valid_within(buddy_pfn)) 1029 goto done_merging; 1030 if (!page_is_buddy(page, buddy, order)) 1031 goto done_merging; 1032 /* 1033 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page, 1034 * merge with it and move up one order. 1035 */ 1036 if (page_is_guard(buddy)) 1037 clear_page_guard(zone, buddy, order, migratetype); 1038 else 1039 del_page_from_free_list(buddy, zone, order); 1040 combined_pfn = buddy_pfn & pfn; 1041 page = page + (combined_pfn - pfn); 1042 pfn = combined_pfn; 1043 order++; 1044 } 1045 if (order < MAX_ORDER - 1) { 1046 /* If we are here, it means order is >= pageblock_order. 1047 * We want to prevent merge between freepages on isolate 1048 * pageblock and normal pageblock. Without this, pageblock 1049 * isolation could cause incorrect freepage or CMA accounting. 1050 * 1051 * We don't want to hit this code for the more frequent 1052 * low-order merging. 1053 */ 1054 if (unlikely(has_isolate_pageblock(zone))) { 1055 int buddy_mt; 1056 1057 buddy_pfn = __find_buddy_pfn(pfn, order); 1058 buddy = page + (buddy_pfn - pfn); 1059 buddy_mt = get_pageblock_migratetype(buddy); 1060 1061 if (migratetype != buddy_mt 1062 && (is_migrate_isolate(migratetype) || 1063 is_migrate_isolate(buddy_mt))) 1064 goto done_merging; 1065 } 1066 max_order = order + 1; 1067 goto continue_merging; 1068 } 1069 1070done_merging: 1071 set_buddy_order(page, order); 1072 1073 if (fpi_flags & FPI_TO_TAIL) 1074 to_tail = true; 1075 else if (is_shuffle_order(order)) 1076 to_tail = shuffle_pick_tail(); 1077 else 1078 to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order); 1079 1080 if (to_tail) 1081 add_to_free_list_tail(page, zone, order, migratetype); 1082 else 1083 add_to_free_list(page, zone, order, migratetype); 1084 1085 /* Notify page reporting subsystem of freed page */ 1086 if (!(fpi_flags & FPI_SKIP_REPORT_NOTIFY)) 1087 page_reporting_notify_free(order); 1088} 1089 1090/* 1091 * A bad page could be due to a number of fields. Instead of multiple branches, 1092 * try and check multiple fields with one check. The caller must do a detailed 1093 * check if necessary. 1094 */ 1095static inline bool page_expected_state(struct page *page, 1096 unsigned long check_flags) 1097{ 1098 if (unlikely(atomic_read(&page->_mapcount) != -1)) 1099 return false; 1100 1101 if (unlikely((unsigned long)page->mapping | 1102 page_ref_count(page) | 1103#ifdef CONFIG_MEMCG 1104 (unsigned long)page->mem_cgroup | 1105#endif 1106 (page->flags & check_flags))) 1107 return false; 1108 1109 return true; 1110} 1111 1112static const char *page_bad_reason(struct page *page, unsigned long flags) 1113{ 1114 const char *bad_reason = NULL; 1115 1116 if (unlikely(atomic_read(&page->_mapcount) != -1)) 1117 bad_reason = "nonzero mapcount"; 1118 if (unlikely(page->mapping != NULL)) 1119 bad_reason = "non-NULL mapping"; 1120 if (unlikely(page_ref_count(page) != 0)) 1121 bad_reason = "nonzero _refcount"; 1122 if (unlikely(page->flags & flags)) { 1123 if (flags == PAGE_FLAGS_CHECK_AT_PREP) 1124 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag(s) set"; 1125 else 1126 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set"; 1127 } 1128#ifdef CONFIG_MEMCG 1129 if (unlikely(page->mem_cgroup)) 1130 bad_reason = "page still charged to cgroup"; 1131#endif 1132 return bad_reason; 1133} 1134 1135static void check_free_page_bad(struct page *page) 1136{ 1137 bad_page(page, 1138 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_FREE)); 1139} 1140 1141static inline int check_free_page(struct page *page) 1142{ 1143 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE))) 1144 return 0; 1145 1146 /* Something has gone sideways, find it */ 1147 check_free_page_bad(page); 1148 return 1; 1149} 1150 1151static int free_tail_pages_check(struct page *head_page, struct page *page) 1152{ 1153 int ret = 1; 1154 1155 /* 1156 * We rely page->lru.next never has bit 0 set, unless the page 1157 * is PageTail(). Let's make sure that's true even for poisoned ->lru. 1158 */ 1159 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1); 1160 1161 if (!IS_ENABLED(CONFIG_DEBUG_VM)) { 1162 ret = 0; 1163 goto out; 1164 } 1165 switch (page - head_page) { 1166 case 1: 1167 /* the first tail page: ->mapping may be compound_mapcount() */ 1168 if (unlikely(compound_mapcount(page))) { 1169 bad_page(page, "nonzero compound_mapcount"); 1170 goto out; 1171 } 1172 break; 1173 case 2: 1174 /* 1175 * the second tail page: ->mapping is 1176 * deferred_list.next -- ignore value. 1177 */ 1178 break; 1179 default: 1180 if (page->mapping != TAIL_MAPPING) { 1181 bad_page(page, "corrupted mapping in tail page"); 1182 goto out; 1183 } 1184 break; 1185 } 1186 if (unlikely(!PageTail(page))) { 1187 bad_page(page, "PageTail not set"); 1188 goto out; 1189 } 1190 if (unlikely(compound_head(page) != head_page)) { 1191 bad_page(page, "compound_head not consistent"); 1192 goto out; 1193 } 1194 ret = 0; 1195out: 1196 page->mapping = NULL; 1197 clear_compound_head(page); 1198 return ret; 1199} 1200 1201static void kernel_init_free_pages(struct page *page, int numpages) 1202{ 1203 int i; 1204 1205 /* s390's use of memset() could override KASAN redzones. */ 1206 kasan_disable_current(); 1207 for (i = 0; i < numpages; i++) 1208 clear_highpage(page + i); 1209 kasan_enable_current(); 1210} 1211 1212static __always_inline bool free_pages_prepare(struct page *page, 1213 unsigned int order, bool check_free) 1214{ 1215 int bad = 0; 1216 1217 VM_BUG_ON_PAGE(PageTail(page), page); 1218 1219 trace_mm_page_free(page, order); 1220 1221 if (unlikely(PageHWPoison(page)) && !order) { 1222 /* 1223 * Do not let hwpoison pages hit pcplists/buddy 1224 * Untie memcg state and reset page's owner 1225 */ 1226 if (memcg_kmem_enabled() && PageKmemcg(page)) 1227 __memcg_kmem_uncharge_page(page, order); 1228 reset_page_owner(page, order); 1229 return false; 1230 } 1231 1232 /* 1233 * Check tail pages before head page information is cleared to 1234 * avoid checking PageCompound for order-0 pages. 1235 */ 1236 if (unlikely(order)) { 1237 bool compound = PageCompound(page); 1238 int i; 1239 1240 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page); 1241 1242 if (compound) 1243 ClearPageDoubleMap(page); 1244 for (i = 1; i < (1 << order); i++) { 1245 if (compound) 1246 bad += free_tail_pages_check(page, page + i); 1247 if (unlikely(check_free_page(page + i))) { 1248 bad++; 1249 continue; 1250 } 1251 (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP; 1252 } 1253 } 1254 if (PageMappingFlags(page)) 1255 page->mapping = NULL; 1256 if (memcg_kmem_enabled() && PageKmemcg(page)) 1257 __memcg_kmem_uncharge_page(page, order); 1258 if (check_free) 1259 bad += check_free_page(page); 1260 if (bad) 1261 return false; 1262 1263 page_cpupid_reset_last(page); 1264 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP; 1265 reset_page_owner(page, order); 1266 1267 if (!PageHighMem(page)) { 1268 debug_check_no_locks_freed(page_address(page), 1269 PAGE_SIZE << order); 1270 debug_check_no_obj_freed(page_address(page), 1271 PAGE_SIZE << order); 1272 } 1273 if (want_init_on_free()) 1274 kernel_init_free_pages(page, 1 << order); 1275 1276 kernel_poison_pages(page, 1 << order, 0); 1277 /* 1278 * arch_free_page() can make the page's contents inaccessible. s390 1279 * does this. So nothing which can access the page's contents should 1280 * happen after this. 1281 */ 1282 arch_free_page(page, order); 1283 1284 if (debug_pagealloc_enabled_static()) 1285 kernel_map_pages(page, 1 << order, 0); 1286 1287 kasan_free_nondeferred_pages(page, order); 1288 1289 return true; 1290} 1291 1292#ifdef CONFIG_DEBUG_VM 1293/* 1294 * With DEBUG_VM enabled, order-0 pages are checked immediately when being freed 1295 * to pcp lists. With debug_pagealloc also enabled, they are also rechecked when 1296 * moved from pcp lists to free lists. 1297 */ 1298static bool free_pcp_prepare(struct page *page) 1299{ 1300 return free_pages_prepare(page, 0, true); 1301} 1302 1303static bool bulkfree_pcp_prepare(struct page *page) 1304{ 1305 if (debug_pagealloc_enabled_static()) 1306 return check_free_page(page); 1307 else 1308 return false; 1309} 1310#else 1311/* 1312 * With DEBUG_VM disabled, order-0 pages being freed are checked only when 1313 * moving from pcp lists to free list in order to reduce overhead. With 1314 * debug_pagealloc enabled, they are checked also immediately when being freed 1315 * to the pcp lists. 1316 */ 1317static bool free_pcp_prepare(struct page *page) 1318{ 1319 if (debug_pagealloc_enabled_static()) 1320 return free_pages_prepare(page, 0, true); 1321 else 1322 return free_pages_prepare(page, 0, false); 1323} 1324 1325static bool bulkfree_pcp_prepare(struct page *page) 1326{ 1327 return check_free_page(page); 1328} 1329#endif /* CONFIG_DEBUG_VM */ 1330 1331static inline void prefetch_buddy(struct page *page) 1332{ 1333 unsigned long pfn = page_to_pfn(page); 1334 unsigned long buddy_pfn = __find_buddy_pfn(pfn, 0); 1335 struct page *buddy = page + (buddy_pfn - pfn); 1336 1337 prefetch(buddy); 1338} 1339 1340/* 1341 * Frees a number of pages from the PCP lists 1342 * Assumes all pages on list are in same zone, and of same order. 1343 * count is the number of pages to free. 1344 * 1345 * If the zone was previously in an "all pages pinned" state then look to 1346 * see if this freeing clears that state. 1347 * 1348 * And clear the zone's pages_scanned counter, to hold off the "all pages are 1349 * pinned" detection logic. 1350 */ 1351static void free_pcppages_bulk(struct zone *zone, int count, 1352 struct per_cpu_pages *pcp) 1353{ 1354 int migratetype = 0; 1355 int batch_free = 0; 1356 int prefetch_nr = 0; 1357 bool isolated_pageblocks; 1358 struct page *page, *tmp; 1359 LIST_HEAD(head); 1360 1361 /* 1362 * Ensure proper count is passed which otherwise would stuck in the 1363 * below while (list_empty(list)) loop. 1364 */ 1365 count = min(pcp->count, count); 1366 while (count) { 1367 struct list_head *list; 1368 1369 /* 1370 * Remove pages from lists in a round-robin fashion. A 1371 * batch_free count is maintained that is incremented when an 1372 * empty list is encountered. This is so more pages are freed 1373 * off fuller lists instead of spinning excessively around empty 1374 * lists 1375 */ 1376 do { 1377 batch_free++; 1378 if (++migratetype == MIGRATE_PCPTYPES) 1379 migratetype = 0; 1380 list = &pcp->lists[migratetype]; 1381 } while (list_empty(list)); 1382 1383 /* This is the only non-empty list. Free them all. */ 1384 if (batch_free == MIGRATE_PCPTYPES) 1385 batch_free = count; 1386 1387 do { 1388 page = list_last_entry(list, struct page, lru); 1389 /* must delete to avoid corrupting pcp list */ 1390 list_del(&page->lru); 1391 pcp->count--; 1392 1393 if (bulkfree_pcp_prepare(page)) 1394 continue; 1395 1396 list_add_tail(&page->lru, &head); 1397 1398 /* 1399 * We are going to put the page back to the global 1400 * pool, prefetch its buddy to speed up later access 1401 * under zone->lock. It is believed the overhead of 1402 * an additional test and calculating buddy_pfn here 1403 * can be offset by reduced memory latency later. To 1404 * avoid excessive prefetching due to large count, only 1405 * prefetch buddy for the first pcp->batch nr of pages. 1406 */ 1407 if (prefetch_nr++ < pcp->batch) 1408 prefetch_buddy(page); 1409 } while (--count && --batch_free && !list_empty(list)); 1410 } 1411 1412 spin_lock(&zone->lock); 1413 isolated_pageblocks = has_isolate_pageblock(zone); 1414 1415 /* 1416 * Use safe version since after __free_one_page(), 1417 * page->lru.next will not point to original list. 1418 */ 1419 list_for_each_entry_safe(page, tmp, &head, lru) { 1420 int mt = get_pcppage_migratetype(page); 1421 /* MIGRATE_ISOLATE page should not go to pcplists */ 1422 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page); 1423 /* Pageblock could have been isolated meanwhile */ 1424 if (unlikely(isolated_pageblocks)) 1425 mt = get_pageblock_migratetype(page); 1426 1427 __free_one_page(page, page_to_pfn(page), zone, 0, mt, FPI_NONE); 1428 trace_mm_page_pcpu_drain(page, 0, mt); 1429 } 1430 spin_unlock(&zone->lock); 1431} 1432 1433static void free_one_page(struct zone *zone, 1434 struct page *page, unsigned long pfn, 1435 unsigned int order, 1436 int migratetype, fpi_t fpi_flags) 1437{ 1438 spin_lock(&zone->lock); 1439 if (unlikely(has_isolate_pageblock(zone) || 1440 is_migrate_isolate(migratetype))) { 1441 migratetype = get_pfnblock_migratetype(page, pfn); 1442 } 1443 __free_one_page(page, pfn, zone, order, migratetype, fpi_flags); 1444 spin_unlock(&zone->lock); 1445} 1446 1447static void __meminit __init_single_page(struct page *page, unsigned long pfn, 1448 unsigned long zone, int nid) 1449{ 1450 mm_zero_struct_page(page); 1451 set_page_links(page, zone, nid, pfn); 1452 init_page_count(page); 1453 page_mapcount_reset(page); 1454 page_cpupid_reset_last(page); 1455 page_kasan_tag_reset(page); 1456 1457 INIT_LIST_HEAD(&page->lru); 1458#ifdef WANT_PAGE_VIRTUAL 1459 /* The shift won't overflow because ZONE_NORMAL is below 4G. */ 1460 if (!is_highmem_idx(zone)) 1461 set_page_address(page, __va(pfn << PAGE_SHIFT)); 1462#endif 1463} 1464 1465#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 1466static void __meminit init_reserved_page(unsigned long pfn) 1467{ 1468 pg_data_t *pgdat; 1469 int nid, zid; 1470 1471 if (!early_page_uninitialised(pfn)) 1472 return; 1473 1474 nid = early_pfn_to_nid(pfn); 1475 pgdat = NODE_DATA(nid); 1476 1477 for (zid = 0; zid < MAX_NR_ZONES; zid++) { 1478 struct zone *zone = &pgdat->node_zones[zid]; 1479 1480 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone)) 1481 break; 1482 } 1483 __init_single_page(pfn_to_page(pfn), pfn, zid, nid); 1484} 1485#else 1486static inline void init_reserved_page(unsigned long pfn) 1487{ 1488} 1489#endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */ 1490 1491/* 1492 * Initialised pages do not have PageReserved set. This function is 1493 * called for each range allocated by the bootmem allocator and 1494 * marks the pages PageReserved. The remaining valid pages are later 1495 * sent to the buddy page allocator. 1496 */ 1497void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end) 1498{ 1499 unsigned long start_pfn = PFN_DOWN(start); 1500 unsigned long end_pfn = PFN_UP(end); 1501 1502 for (; start_pfn < end_pfn; start_pfn++) { 1503 if (pfn_valid(start_pfn)) { 1504 struct page *page = pfn_to_page(start_pfn); 1505 1506 init_reserved_page(start_pfn); 1507 1508 /* Avoid false-positive PageTail() */ 1509 INIT_LIST_HEAD(&page->lru); 1510 1511 /* 1512 * no need for atomic set_bit because the struct 1513 * page is not visible yet so nobody should 1514 * access it yet. 1515 */ 1516 __SetPageReserved(page); 1517 } 1518 } 1519} 1520 1521static void __free_pages_ok(struct page *page, unsigned int order, 1522 fpi_t fpi_flags) 1523{ 1524 unsigned long flags; 1525 int migratetype; 1526 unsigned long pfn = page_to_pfn(page); 1527 1528 if (!free_pages_prepare(page, order, true)) 1529 return; 1530 1531 migratetype = get_pfnblock_migratetype(page, pfn); 1532 local_irq_save(flags); 1533 __count_vm_events(PGFREE, 1 << order); 1534 free_one_page(page_zone(page), page, pfn, order, migratetype, 1535 fpi_flags); 1536 local_irq_restore(flags); 1537} 1538 1539void __free_pages_core(struct page *page, unsigned int order) 1540{ 1541 unsigned int nr_pages = 1 << order; 1542 struct page *p = page; 1543 unsigned int loop; 1544 1545 /* 1546 * When initializing the memmap, __init_single_page() sets the refcount 1547 * of all pages to 1 ("allocated"/"not free"). We have to set the 1548 * refcount of all involved pages to 0. 1549 */ 1550 prefetchw(p); 1551 for (loop = 0; loop < (nr_pages - 1); loop++, p++) { 1552 prefetchw(p + 1); 1553 __ClearPageReserved(p); 1554 set_page_count(p, 0); 1555 } 1556 __ClearPageReserved(p); 1557 set_page_count(p, 0); 1558 1559 atomic_long_add(nr_pages, &page_zone(page)->managed_pages); 1560 1561 /* 1562 * Bypass PCP and place fresh pages right to the tail, primarily 1563 * relevant for memory onlining. 1564 */ 1565 __free_pages_ok(page, order, FPI_TO_TAIL); 1566} 1567 1568#ifdef CONFIG_NEED_MULTIPLE_NODES 1569 1570static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata; 1571 1572#ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID 1573 1574/* 1575 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on. 1576 */ 1577int __meminit __early_pfn_to_nid(unsigned long pfn, 1578 struct mminit_pfnnid_cache *state) 1579{ 1580 unsigned long start_pfn, end_pfn; 1581 int nid; 1582 1583 if (state->last_start <= pfn && pfn < state->last_end) 1584 return state->last_nid; 1585 1586 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn); 1587 if (nid != NUMA_NO_NODE) { 1588 state->last_start = start_pfn; 1589 state->last_end = end_pfn; 1590 state->last_nid = nid; 1591 } 1592 1593 return nid; 1594} 1595#endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */ 1596 1597int __meminit early_pfn_to_nid(unsigned long pfn) 1598{ 1599 static DEFINE_SPINLOCK(early_pfn_lock); 1600 int nid; 1601 1602 spin_lock(&early_pfn_lock); 1603 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache); 1604 if (nid < 0) 1605 nid = first_online_node; 1606 spin_unlock(&early_pfn_lock); 1607 1608 return nid; 1609} 1610#endif /* CONFIG_NEED_MULTIPLE_NODES */ 1611 1612void __init memblock_free_pages(struct page *page, unsigned long pfn, 1613 unsigned int order) 1614{ 1615 if (early_page_uninitialised(pfn)) 1616 return; 1617 __free_pages_core(page, order); 1618} 1619 1620/* 1621 * Check that the whole (or subset of) a pageblock given by the interval of 1622 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it 1623 * with the migration of free compaction scanner. The scanners then need to 1624 * use only pfn_valid_within() check for arches that allow holes within 1625 * pageblocks. 1626 * 1627 * Return struct page pointer of start_pfn, or NULL if checks were not passed. 1628 * 1629 * It's possible on some configurations to have a setup like node0 node1 node0 1630 * i.e. it's possible that all pages within a zones range of pages do not 1631 * belong to a single zone. We assume that a border between node0 and node1 1632 * can occur within a single pageblock, but not a node0 node1 node0 1633 * interleaving within a single pageblock. It is therefore sufficient to check 1634 * the first and last page of a pageblock and avoid checking each individual 1635 * page in a pageblock. 1636 */ 1637struct page *__pageblock_pfn_to_page(unsigned long start_pfn, 1638 unsigned long end_pfn, struct zone *zone) 1639{ 1640 struct page *start_page; 1641 struct page *end_page; 1642 1643 /* end_pfn is one past the range we are checking */ 1644 end_pfn--; 1645 1646 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn)) 1647 return NULL; 1648 1649 start_page = pfn_to_online_page(start_pfn); 1650 if (!start_page) 1651 return NULL; 1652 1653 if (page_zone(start_page) != zone) 1654 return NULL; 1655 1656 end_page = pfn_to_page(end_pfn); 1657 1658 /* This gives a shorter code than deriving page_zone(end_page) */ 1659 if (page_zone_id(start_page) != page_zone_id(end_page)) 1660 return NULL; 1661 1662 return start_page; 1663} 1664 1665void set_zone_contiguous(struct zone *zone) 1666{ 1667 unsigned long block_start_pfn = zone->zone_start_pfn; 1668 unsigned long block_end_pfn; 1669 1670 block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages); 1671 for (; block_start_pfn < zone_end_pfn(zone); 1672 block_start_pfn = block_end_pfn, 1673 block_end_pfn += pageblock_nr_pages) { 1674 1675 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone)); 1676 1677 if (!__pageblock_pfn_to_page(block_start_pfn, 1678 block_end_pfn, zone)) 1679 return; 1680 cond_resched(); 1681 } 1682 1683 /* We confirm that there is no hole */ 1684 zone->contiguous = true; 1685} 1686 1687void clear_zone_contiguous(struct zone *zone) 1688{ 1689 zone->contiguous = false; 1690} 1691 1692#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 1693static void __init deferred_free_range(unsigned long pfn, 1694 unsigned long nr_pages) 1695{ 1696 struct page *page; 1697 unsigned long i; 1698 1699 if (!nr_pages) 1700 return; 1701 1702 page = pfn_to_page(pfn); 1703 1704 /* Free a large naturally-aligned chunk if possible */ 1705 if (nr_pages == pageblock_nr_pages && 1706 (pfn & (pageblock_nr_pages - 1)) == 0) { 1707 set_pageblock_migratetype(page, MIGRATE_MOVABLE); 1708 __free_pages_core(page, pageblock_order); 1709 return; 1710 } 1711 1712 for (i = 0; i < nr_pages; i++, page++, pfn++) { 1713 if ((pfn & (pageblock_nr_pages - 1)) == 0) 1714 set_pageblock_migratetype(page, MIGRATE_MOVABLE); 1715 __free_pages_core(page, 0); 1716 } 1717} 1718 1719/* Completion tracking for deferred_init_memmap() threads */ 1720static atomic_t pgdat_init_n_undone __initdata; 1721static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp); 1722 1723static inline void __init pgdat_init_report_one_done(void) 1724{ 1725 if (atomic_dec_and_test(&pgdat_init_n_undone)) 1726 complete(&pgdat_init_all_done_comp); 1727} 1728 1729/* 1730 * Returns true if page needs to be initialized or freed to buddy allocator. 1731 * 1732 * First we check if pfn is valid on architectures where it is possible to have 1733 * holes within pageblock_nr_pages. On systems where it is not possible, this 1734 * function is optimized out. 1735 * 1736 * Then, we check if a current large page is valid by only checking the validity 1737 * of the head pfn. 1738 */ 1739static inline bool __init deferred_pfn_valid(unsigned long pfn) 1740{ 1741 if (!pfn_valid_within(pfn)) 1742 return false; 1743 if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn)) 1744 return false; 1745 return true; 1746} 1747 1748/* 1749 * Free pages to buddy allocator. Try to free aligned pages in 1750 * pageblock_nr_pages sizes. 1751 */ 1752static void __init deferred_free_pages(unsigned long pfn, 1753 unsigned long end_pfn) 1754{ 1755 unsigned long nr_pgmask = pageblock_nr_pages - 1; 1756 unsigned long nr_free = 0; 1757 1758 for (; pfn < end_pfn; pfn++) { 1759 if (!deferred_pfn_valid(pfn)) { 1760 deferred_free_range(pfn - nr_free, nr_free); 1761 nr_free = 0; 1762 } else if (!(pfn & nr_pgmask)) { 1763 deferred_free_range(pfn - nr_free, nr_free); 1764 nr_free = 1; 1765 } else { 1766 nr_free++; 1767 } 1768 } 1769 /* Free the last block of pages to allocator */ 1770 deferred_free_range(pfn - nr_free, nr_free); 1771} 1772 1773/* 1774 * Initialize struct pages. We minimize pfn page lookups and scheduler checks 1775 * by performing it only once every pageblock_nr_pages. 1776 * Return number of pages initialized. 1777 */ 1778static unsigned long __init deferred_init_pages(struct zone *zone, 1779 unsigned long pfn, 1780 unsigned long end_pfn) 1781{ 1782 unsigned long nr_pgmask = pageblock_nr_pages - 1; 1783 int nid = zone_to_nid(zone); 1784 unsigned long nr_pages = 0; 1785 int zid = zone_idx(zone); 1786 struct page *page = NULL; 1787 1788 for (; pfn < end_pfn; pfn++) { 1789 if (!deferred_pfn_valid(pfn)) { 1790 page = NULL; 1791 continue; 1792 } else if (!page || !(pfn & nr_pgmask)) { 1793 page = pfn_to_page(pfn); 1794 } else { 1795 page++; 1796 } 1797 __init_single_page(page, pfn, zid, nid); 1798 nr_pages++; 1799 } 1800 return (nr_pages); 1801} 1802 1803/* 1804 * This function is meant to pre-load the iterator for the zone init. 1805 * Specifically it walks through the ranges until we are caught up to the 1806 * first_init_pfn value and exits there. If we never encounter the value we 1807 * return false indicating there are no valid ranges left. 1808 */ 1809static bool __init 1810deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone, 1811 unsigned long *spfn, unsigned long *epfn, 1812 unsigned long first_init_pfn) 1813{ 1814 u64 j; 1815 1816 /* 1817 * Start out by walking through the ranges in this zone that have 1818 * already been initialized. We don't need to do anything with them 1819 * so we just need to flush them out of the system. 1820 */ 1821 for_each_free_mem_pfn_range_in_zone(j, zone, spfn, epfn) { 1822 if (*epfn <= first_init_pfn) 1823 continue; 1824 if (*spfn < first_init_pfn) 1825 *spfn = first_init_pfn; 1826 *i = j; 1827 return true; 1828 } 1829 1830 return false; 1831} 1832 1833/* 1834 * Initialize and free pages. We do it in two loops: first we initialize 1835 * struct page, then free to buddy allocator, because while we are 1836 * freeing pages we can access pages that are ahead (computing buddy 1837 * page in __free_one_page()). 1838 * 1839 * In order to try and keep some memory in the cache we have the loop 1840 * broken along max page order boundaries. This way we will not cause 1841 * any issues with the buddy page computation. 1842 */ 1843static unsigned long __init 1844deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn, 1845 unsigned long *end_pfn) 1846{ 1847 unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES); 1848 unsigned long spfn = *start_pfn, epfn = *end_pfn; 1849 unsigned long nr_pages = 0; 1850 u64 j = *i; 1851 1852 /* First we loop through and initialize the page values */ 1853 for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) { 1854 unsigned long t; 1855 1856 if (mo_pfn <= *start_pfn) 1857 break; 1858 1859 t = min(mo_pfn, *end_pfn); 1860 nr_pages += deferred_init_pages(zone, *start_pfn, t); 1861 1862 if (mo_pfn < *end_pfn) { 1863 *start_pfn = mo_pfn; 1864 break; 1865 } 1866 } 1867 1868 /* Reset values and now loop through freeing pages as needed */ 1869 swap(j, *i); 1870 1871 for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) { 1872 unsigned long t; 1873 1874 if (mo_pfn <= spfn) 1875 break; 1876 1877 t = min(mo_pfn, epfn); 1878 deferred_free_pages(spfn, t); 1879 1880 if (mo_pfn <= epfn) 1881 break; 1882 } 1883 1884 return nr_pages; 1885} 1886 1887static void __init 1888deferred_init_memmap_chunk(unsigned long start_pfn, unsigned long end_pfn, 1889 void *arg) 1890{ 1891 unsigned long spfn, epfn; 1892 struct zone *zone = arg; 1893 u64 i; 1894 1895 deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, start_pfn); 1896 1897 /* 1898 * Initialize and free pages in MAX_ORDER sized increments so that we 1899 * can avoid introducing any issues with the buddy allocator. 1900 */ 1901 while (spfn < end_pfn) { 1902 deferred_init_maxorder(&i, zone, &spfn, &epfn); 1903 cond_resched(); 1904 } 1905} 1906 1907/* An arch may override for more concurrency. */ 1908__weak int __init 1909deferred_page_init_max_threads(const struct cpumask *node_cpumask) 1910{ 1911 return 1; 1912} 1913 1914/* Initialise remaining memory on a node */ 1915static int __init deferred_init_memmap(void *data) 1916{ 1917 pg_data_t *pgdat = data; 1918 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id); 1919 unsigned long spfn = 0, epfn = 0; 1920 unsigned long first_init_pfn, flags; 1921 unsigned long start = jiffies; 1922 struct zone *zone; 1923 int zid, max_threads; 1924 u64 i; 1925 1926 /* Bind memory initialisation thread to a local node if possible */ 1927 if (!cpumask_empty(cpumask)) 1928 set_cpus_allowed_ptr(current, cpumask); 1929 1930 pgdat_resize_lock(pgdat, &flags); 1931 first_init_pfn = pgdat->first_deferred_pfn; 1932 if (first_init_pfn == ULONG_MAX) { 1933 pgdat_resize_unlock(pgdat, &flags); 1934 pgdat_init_report_one_done(); 1935 return 0; 1936 } 1937 1938 /* Sanity check boundaries */ 1939 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn); 1940 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat)); 1941 pgdat->first_deferred_pfn = ULONG_MAX; 1942 1943 /* 1944 * Once we unlock here, the zone cannot be grown anymore, thus if an 1945 * interrupt thread must allocate this early in boot, zone must be 1946 * pre-grown prior to start of deferred page initialization. 1947 */ 1948 pgdat_resize_unlock(pgdat, &flags); 1949 1950 /* Only the highest zone is deferred so find it */ 1951 for (zid = 0; zid < MAX_NR_ZONES; zid++) { 1952 zone = pgdat->node_zones + zid; 1953 if (first_init_pfn < zone_end_pfn(zone)) 1954 break; 1955 } 1956 1957 /* If the zone is empty somebody else may have cleared out the zone */ 1958 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, 1959 first_init_pfn)) 1960 goto zone_empty; 1961 1962 max_threads = deferred_page_init_max_threads(cpumask); 1963 1964 while (spfn < epfn) { 1965 unsigned long epfn_align = ALIGN(epfn, PAGES_PER_SECTION); 1966 struct padata_mt_job job = { 1967 .thread_fn = deferred_init_memmap_chunk, 1968 .fn_arg = zone, 1969 .start = spfn, 1970 .size = epfn_align - spfn, 1971 .align = PAGES_PER_SECTION, 1972 .min_chunk = PAGES_PER_SECTION, 1973 .max_threads = max_threads, 1974 }; 1975 1976 padata_do_multithreaded(&job); 1977 deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, 1978 epfn_align); 1979 } 1980zone_empty: 1981 /* Sanity check that the next zone really is unpopulated */ 1982 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone)); 1983 1984 pr_info("node %d deferred pages initialised in %ums\n", 1985 pgdat->node_id, jiffies_to_msecs(jiffies - start)); 1986 1987 pgdat_init_report_one_done(); 1988 return 0; 1989} 1990 1991/* 1992 * If this zone has deferred pages, try to grow it by initializing enough 1993 * deferred pages to satisfy the allocation specified by order, rounded up to 1994 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments 1995 * of SECTION_SIZE bytes by initializing struct pages in increments of 1996 * PAGES_PER_SECTION * sizeof(struct page) bytes. 1997 * 1998 * Return true when zone was grown, otherwise return false. We return true even 1999 * when we grow less than requested, to let the caller decide if there are 2000 * enough pages to satisfy the allocation. 2001 * 2002 * Note: We use noinline because this function is needed only during boot, and 2003 * it is called from a __ref function _deferred_grow_zone. This way we are 2004 * making sure that it is not inlined into permanent text section. 2005 */ 2006static noinline bool __init 2007deferred_grow_zone(struct zone *zone, unsigned int order) 2008{ 2009 unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION); 2010 pg_data_t *pgdat = zone->zone_pgdat; 2011 unsigned long first_deferred_pfn = pgdat->first_deferred_pfn; 2012 unsigned long spfn, epfn, flags; 2013 unsigned long nr_pages = 0; 2014 u64 i; 2015 2016 /* Only the last zone may have deferred pages */ 2017 if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat)) 2018 return false; 2019 2020 pgdat_resize_lock(pgdat, &flags); 2021 2022 /* 2023 * If someone grew this zone while we were waiting for spinlock, return 2024 * true, as there might be enough pages already. 2025 */ 2026 if (first_deferred_pfn != pgdat->first_deferred_pfn) { 2027 pgdat_resize_unlock(pgdat, &flags); 2028 return true; 2029 } 2030 2031 /* If the zone is empty somebody else may have cleared out the zone */ 2032 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, 2033 first_deferred_pfn)) { 2034 pgdat->first_deferred_pfn = ULONG_MAX; 2035 pgdat_resize_unlock(pgdat, &flags); 2036 /* Retry only once. */ 2037 return first_deferred_pfn != ULONG_MAX; 2038 } 2039 2040 /* 2041 * Initialize and free pages in MAX_ORDER sized increments so 2042 * that we can avoid introducing any issues with the buddy 2043 * allocator. 2044 */ 2045 while (spfn < epfn) { 2046 /* update our first deferred PFN for this section */ 2047 first_deferred_pfn = spfn; 2048 2049 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn); 2050 touch_nmi_watchdog(); 2051 2052 /* We should only stop along section boundaries */ 2053 if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION) 2054 continue; 2055 2056 /* If our quota has been met we can stop here */ 2057 if (nr_pages >= nr_pages_needed) 2058 break; 2059 } 2060 2061 pgdat->first_deferred_pfn = spfn; 2062 pgdat_resize_unlock(pgdat, &flags); 2063 2064 return nr_pages > 0; 2065} 2066 2067/* 2068 * deferred_grow_zone() is __init, but it is called from 2069 * get_page_from_freelist() during early boot until deferred_pages permanently 2070 * disables this call. This is why we have refdata wrapper to avoid warning, 2071 * and to ensure that the function body gets unloaded. 2072 */ 2073static bool __ref 2074_deferred_grow_zone(struct zone *zone, unsigned int order) 2075{ 2076 return deferred_grow_zone(zone, order); 2077} 2078 2079#endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */ 2080 2081void __init page_alloc_init_late(void) 2082{ 2083 struct zone *zone; 2084 int nid; 2085 2086#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 2087 2088 /* There will be num_node_state(N_MEMORY) threads */ 2089 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY)); 2090 for_each_node_state(nid, N_MEMORY) { 2091 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid); 2092 } 2093 2094 /* Block until all are initialised */ 2095 wait_for_completion(&pgdat_init_all_done_comp); 2096 2097 /* 2098 * The number of managed pages has changed due to the initialisation 2099 * so the pcpu batch and high limits needs to be updated or the limits 2100 * will be artificially small. 2101 */ 2102 for_each_populated_zone(zone) 2103 zone_pcp_update(zone); 2104 2105 /* 2106 * We initialized the rest of the deferred pages. Permanently disable 2107 * on-demand struct page initialization. 2108 */ 2109 static_branch_disable(&deferred_pages); 2110 2111 /* Reinit limits that are based on free pages after the kernel is up */ 2112 files_maxfiles_init(); 2113#endif 2114 2115 /* Discard memblock private memory */ 2116 memblock_discard(); 2117 2118 for_each_node_state(nid, N_MEMORY) 2119 shuffle_free_memory(NODE_DATA(nid)); 2120 2121 for_each_populated_zone(zone) 2122 set_zone_contiguous(zone); 2123} 2124 2125#ifdef CONFIG_CMA 2126/* Free whole pageblock and set its migration type to MIGRATE_CMA. */ 2127void __init init_cma_reserved_pageblock(struct page *page) 2128{ 2129 unsigned i = pageblock_nr_pages; 2130 struct page *p = page; 2131 2132 do { 2133 __ClearPageReserved(p); 2134 set_page_count(p, 0); 2135 } while (++p, --i); 2136 2137 set_pageblock_migratetype(page, MIGRATE_CMA); 2138 2139 if (pageblock_order >= MAX_ORDER) { 2140 i = pageblock_nr_pages; 2141 p = page; 2142 do { 2143 set_page_refcounted(p); 2144 __free_pages(p, MAX_ORDER - 1); 2145 p += MAX_ORDER_NR_PAGES; 2146 } while (i -= MAX_ORDER_NR_PAGES); 2147 } else { 2148 set_page_refcounted(page); 2149 __free_pages(page, pageblock_order); 2150 } 2151 2152 adjust_managed_page_count(page, pageblock_nr_pages); 2153} 2154#endif 2155 2156/* 2157 * The order of subdivision here is critical for the IO subsystem. 2158 * Please do not alter this order without good reasons and regression 2159 * testing. Specifically, as large blocks of memory are subdivided, 2160 * the order in which smaller blocks are delivered depends on the order 2161 * they're subdivided in this function. This is the primary factor 2162 * influencing the order in which pages are delivered to the IO 2163 * subsystem according to empirical testing, and this is also justified 2164 * by considering the behavior of a buddy system containing a single 2165 * large block of memory acted on by a series of small allocations. 2166 * This behavior is a critical factor in sglist merging's success. 2167 * 2168 * -- nyc 2169 */ 2170static inline void expand(struct zone *zone, struct page *page, 2171 int low, int high, int migratetype) 2172{ 2173 unsigned long size = 1 << high; 2174 2175 while (high > low) { 2176 high--; 2177 size >>= 1; 2178 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]); 2179 2180 /* 2181 * Mark as guard pages (or page), that will allow to 2182 * merge back to allocator when buddy will be freed. 2183 * Corresponding page table entries will not be touched, 2184 * pages will stay not present in virtual address space 2185 */ 2186 if (set_page_guard(zone, &page[size], high, migratetype)) 2187 continue; 2188 2189 add_to_free_list(&page[size], zone, high, migratetype); 2190 set_buddy_order(&page[size], high); 2191 } 2192} 2193 2194static void check_new_page_bad(struct page *page) 2195{ 2196 if (unlikely(page->flags & __PG_HWPOISON)) { 2197 /* Don't complain about hwpoisoned pages */ 2198 page_mapcount_reset(page); /* remove PageBuddy */ 2199 return; 2200 } 2201 2202 bad_page(page, 2203 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_PREP)); 2204} 2205 2206/* 2207 * This page is about to be returned from the page allocator 2208 */ 2209static inline int check_new_page(struct page *page) 2210{ 2211 if (likely(page_expected_state(page, 2212 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON))) 2213 return 0; 2214 2215 check_new_page_bad(page); 2216 return 1; 2217} 2218 2219static inline bool free_pages_prezeroed(void) 2220{ 2221 return (IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) && 2222 page_poisoning_enabled()) || want_init_on_free(); 2223} 2224 2225#ifdef CONFIG_DEBUG_VM 2226/* 2227 * With DEBUG_VM enabled, order-0 pages are checked for expected state when 2228 * being allocated from pcp lists. With debug_pagealloc also enabled, they are 2229 * also checked when pcp lists are refilled from the free lists. 2230 */ 2231static inline bool check_pcp_refill(struct page *page) 2232{ 2233 if (debug_pagealloc_enabled_static()) 2234 return check_new_page(page); 2235 else 2236 return false; 2237} 2238 2239static inline bool check_new_pcp(struct page *page) 2240{ 2241 return check_new_page(page); 2242} 2243#else 2244/* 2245 * With DEBUG_VM disabled, free order-0 pages are checked for expected state 2246 * when pcp lists are being refilled from the free lists. With debug_pagealloc 2247 * enabled, they are also checked when being allocated from the pcp lists. 2248 */ 2249static inline bool check_pcp_refill(struct page *page) 2250{ 2251 return check_new_page(page); 2252} 2253static inline bool check_new_pcp(struct page *page) 2254{ 2255 if (debug_pagealloc_enabled_static()) 2256 return check_new_page(page); 2257 else 2258 return false; 2259} 2260#endif /* CONFIG_DEBUG_VM */ 2261 2262static bool check_new_pages(struct page *page, unsigned int order) 2263{ 2264 int i; 2265 for (i = 0; i < (1 << order); i++) { 2266 struct page *p = page + i; 2267 2268 if (unlikely(check_new_page(p))) 2269 return true; 2270 } 2271 2272 return false; 2273} 2274 2275inline void post_alloc_hook(struct page *page, unsigned int order, 2276 gfp_t gfp_flags) 2277{ 2278 set_page_private(page, 0); 2279 set_page_refcounted(page); 2280 2281 arch_alloc_page(page, order); 2282 if (debug_pagealloc_enabled_static()) 2283 kernel_map_pages(page, 1 << order, 1); 2284 kasan_alloc_pages(page, order); 2285 kernel_poison_pages(page, 1 << order, 1); 2286 set_page_owner(page, order, gfp_flags); 2287} 2288 2289static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags, 2290 unsigned int alloc_flags) 2291{ 2292 post_alloc_hook(page, order, gfp_flags); 2293 2294 if (!free_pages_prezeroed() && want_init_on_alloc(gfp_flags)) 2295 kernel_init_free_pages(page, 1 << order); 2296 2297 if (order && (gfp_flags & __GFP_COMP)) 2298 prep_compound_page(page, order); 2299 2300 /* 2301 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to 2302 * allocate the page. The expectation is that the caller is taking 2303 * steps that will free more memory. The caller should avoid the page 2304 * being used for !PFMEMALLOC purposes. 2305 */ 2306 if (alloc_flags & ALLOC_NO_WATERMARKS) 2307 set_page_pfmemalloc(page); 2308 else 2309 clear_page_pfmemalloc(page); 2310} 2311 2312/* 2313 * Go through the free lists for the given migratetype and remove 2314 * the smallest available page from the freelists 2315 */ 2316static __always_inline 2317struct page *__rmqueue_smallest(struct zone *zone, unsigned int order, 2318 int migratetype) 2319{ 2320 unsigned int current_order; 2321 struct free_area *area; 2322 struct page *page; 2323 2324 /* Find a page of the appropriate size in the preferred list */ 2325 for (current_order = order; current_order < MAX_ORDER; ++current_order) { 2326 area = &(zone->free_area[current_order]); 2327 page = get_page_from_free_area(area, migratetype); 2328 if (!page) 2329 continue; 2330 del_page_from_free_list(page, zone, current_order); 2331 expand(zone, page, order, current_order, migratetype); 2332 set_pcppage_migratetype(page, migratetype); 2333 return page; 2334 } 2335 2336 return NULL; 2337} 2338 2339 2340/* 2341 * This array describes the order lists are fallen back to when 2342 * the free lists for the desirable migrate type are depleted 2343 */ 2344static int fallbacks[MIGRATE_TYPES][3] = { 2345 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES }, 2346 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES }, 2347 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES }, 2348#ifdef CONFIG_CMA 2349 [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */ 2350#endif 2351#ifdef CONFIG_MEMORY_ISOLATION 2352 [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */ 2353#endif 2354}; 2355 2356#ifdef CONFIG_CMA 2357static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone, 2358 unsigned int order) 2359{ 2360 return __rmqueue_smallest(zone, order, MIGRATE_CMA); 2361} 2362#else 2363static inline struct page *__rmqueue_cma_fallback(struct zone *zone, 2364 unsigned int order) { return NULL; } 2365#endif 2366 2367/* 2368 * Move the free pages in a range to the freelist tail of the requested type. 2369 * Note that start_page and end_pages are not aligned on a pageblock 2370 * boundary. If alignment is required, use move_freepages_block() 2371 */ 2372static int move_freepages(struct zone *zone, 2373 unsigned long start_pfn, unsigned long end_pfn, 2374 int migratetype, int *num_movable) 2375{ 2376 struct page *page; 2377 unsigned long pfn; 2378 unsigned int order; 2379 int pages_moved = 0; 2380 2381 for (pfn = start_pfn; pfn <= end_pfn;) { 2382 if (!pfn_valid_within(pfn)) { 2383 pfn++; 2384 continue; 2385 } 2386 2387 page = pfn_to_page(pfn); 2388 if (!PageBuddy(page)) { 2389 /* 2390 * We assume that pages that could be isolated for 2391 * migration are movable. But we don't actually try 2392 * isolating, as that would be expensive. 2393 */ 2394 if (num_movable && 2395 (PageLRU(page) || __PageMovable(page))) 2396 (*num_movable)++; 2397 pfn++; 2398 continue; 2399 } 2400 2401 /* Make sure we are not inadvertently changing nodes */ 2402 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page); 2403 VM_BUG_ON_PAGE(page_zone(page) != zone, page); 2404 2405 order = buddy_order(page); 2406 move_to_free_list(page, zone, order, migratetype); 2407 pfn += 1 << order; 2408 pages_moved += 1 << order; 2409 } 2410 2411 return pages_moved; 2412} 2413 2414int move_freepages_block(struct zone *zone, struct page *page, 2415 int migratetype, int *num_movable) 2416{ 2417 unsigned long start_pfn, end_pfn, pfn; 2418 2419 if (num_movable) 2420 *num_movable = 0; 2421 2422 pfn = page_to_pfn(page); 2423 start_pfn = pfn & ~(pageblock_nr_pages - 1); 2424 end_pfn = start_pfn + pageblock_nr_pages - 1; 2425 2426 /* Do not cross zone boundaries */ 2427 if (!zone_spans_pfn(zone, start_pfn)) 2428 start_pfn = pfn; 2429 if (!zone_spans_pfn(zone, end_pfn)) 2430 return 0; 2431 2432 return move_freepages(zone, start_pfn, end_pfn, migratetype, 2433 num_movable); 2434} 2435 2436static void change_pageblock_range(struct page *pageblock_page, 2437 int start_order, int migratetype) 2438{ 2439 int nr_pageblocks = 1 << (start_order - pageblock_order); 2440 2441 while (nr_pageblocks--) { 2442 set_pageblock_migratetype(pageblock_page, migratetype); 2443 pageblock_page += pageblock_nr_pages; 2444 } 2445} 2446 2447/* 2448 * When we are falling back to another migratetype during allocation, try to 2449 * steal extra free pages from the same pageblocks to satisfy further 2450 * allocations, instead of polluting multiple pageblocks. 2451 * 2452 * If we are stealing a relatively large buddy page, it is likely there will 2453 * be more free pages in the pageblock, so try to steal them all. For 2454 * reclaimable and unmovable allocations, we steal regardless of page size, 2455 * as fragmentation caused by those allocations polluting movable pageblocks 2456 * is worse than movable allocations stealing from unmovable and reclaimable 2457 * pageblocks. 2458 */ 2459static bool can_steal_fallback(unsigned int order, int start_mt) 2460{ 2461 /* 2462 * Leaving this order check is intended, although there is 2463 * relaxed order check in next check. The reason is that 2464 * we can actually steal whole pageblock if this condition met, 2465 * but, below check doesn't guarantee it and that is just heuristic 2466 * so could be changed anytime. 2467 */ 2468 if (order >= pageblock_order) 2469 return true; 2470 2471 if (order >= pageblock_order / 2 || 2472 start_mt == MIGRATE_RECLAIMABLE || 2473 start_mt == MIGRATE_UNMOVABLE || 2474 page_group_by_mobility_disabled) 2475 return true; 2476 2477 return false; 2478} 2479 2480static inline bool boost_watermark(struct zone *zone) 2481{ 2482 unsigned long max_boost; 2483 2484 if (!watermark_boost_factor) 2485 return false; 2486 /* 2487 * Don't bother in zones that are unlikely to produce results. 2488 * On small machines, including kdump capture kernels running 2489 * in a small area, boosting the watermark can cause an out of 2490 * memory situation immediately. 2491 */ 2492 if ((pageblock_nr_pages * 4) > zone_managed_pages(zone)) 2493 return false; 2494 2495 max_boost = mult_frac(zone->_watermark[WMARK_HIGH], 2496 watermark_boost_factor, 10000); 2497 2498 /* 2499 * high watermark may be uninitialised if fragmentation occurs 2500 * very early in boot so do not boost. We do not fall 2501 * through and boost by pageblock_nr_pages as failing 2502 * allocations that early means that reclaim is not going 2503 * to help and it may even be impossible to reclaim the 2504 * boosted watermark resulting in a hang. 2505 */ 2506 if (!max_boost) 2507 return false; 2508 2509 max_boost = max(pageblock_nr_pages, max_boost); 2510 2511 zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages, 2512 max_boost); 2513 2514 return true; 2515} 2516 2517/* 2518 * This function implements actual steal behaviour. If order is large enough, 2519 * we can steal whole pageblock. If not, we first move freepages in this 2520 * pageblock to our migratetype and determine how many already-allocated pages 2521 * are there in the pageblock with a compatible migratetype. If at least half 2522 * of pages are free or compatible, we can change migratetype of the pageblock 2523 * itself, so pages freed in the future will be put on the correct free list. 2524 */ 2525static void steal_suitable_fallback(struct zone *zone, struct page *page, 2526 unsigned int alloc_flags, int start_type, bool whole_block) 2527{ 2528 unsigned int current_order = buddy_order(page); 2529 int free_pages, movable_pages, alike_pages; 2530 int old_block_type; 2531 2532 old_block_type = get_pageblock_migratetype(page); 2533 2534 /* 2535 * This can happen due to races and we want to prevent broken 2536 * highatomic accounting. 2537 */ 2538 if (is_migrate_highatomic(old_block_type)) 2539 goto single_page; 2540 2541 /* Take ownership for orders >= pageblock_order */ 2542 if (current_order >= pageblock_order) { 2543 change_pageblock_range(page, current_order, start_type); 2544 goto single_page; 2545 } 2546 2547 /* 2548 * Boost watermarks to increase reclaim pressure to reduce the 2549 * likelihood of future fallbacks. Wake kswapd now as the node 2550 * may be balanced overall and kswapd will not wake naturally. 2551 */ 2552 if (boost_watermark(zone) && (alloc_flags & ALLOC_KSWAPD)) 2553 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags); 2554 2555 /* We are not allowed to try stealing from the whole block */ 2556 if (!whole_block) 2557 goto single_page; 2558 2559 free_pages = move_freepages_block(zone, page, start_type, 2560 &movable_pages); 2561 /* 2562 * Determine how many pages are compatible with our allocation. 2563 * For movable allocation, it's the number of movable pages which 2564 * we just obtained. For other types it's a bit more tricky. 2565 */ 2566 if (start_type == MIGRATE_MOVABLE) { 2567 alike_pages = movable_pages; 2568 } else { 2569 /* 2570 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation 2571 * to MOVABLE pageblock, consider all non-movable pages as 2572 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or 2573 * vice versa, be conservative since we can't distinguish the 2574 * exact migratetype of non-movable pages. 2575 */ 2576 if (old_block_type == MIGRATE_MOVABLE) 2577 alike_pages = pageblock_nr_pages 2578 - (free_pages + movable_pages); 2579 else 2580 alike_pages = 0; 2581 } 2582 2583 /* moving whole block can fail due to zone boundary conditions */ 2584 if (!free_pages) 2585 goto single_page; 2586 2587 /* 2588 * If a sufficient number of pages in the block are either free or of 2589 * comparable migratability as our allocation, claim the whole block. 2590 */ 2591 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) || 2592 page_group_by_mobility_disabled) 2593 set_pageblock_migratetype(page, start_type); 2594 2595 return; 2596 2597single_page: 2598 move_to_free_list(page, zone, current_order, start_type); 2599} 2600 2601/* 2602 * Check whether there is a suitable fallback freepage with requested order. 2603 * If only_stealable is true, this function returns fallback_mt only if 2604 * we can steal other freepages all together. This would help to reduce 2605 * fragmentation due to mixed migratetype pages in one pageblock. 2606 */ 2607int find_suitable_fallback(struct free_area *area, unsigned int order, 2608 int migratetype, bool only_stealable, bool *can_steal) 2609{ 2610 int i; 2611 int fallback_mt; 2612 2613 if (area->nr_free == 0) 2614 return -1; 2615 2616 *can_steal = false; 2617 for (i = 0;; i++) { 2618 fallback_mt = fallbacks[migratetype][i]; 2619 if (fallback_mt == MIGRATE_TYPES) 2620 break; 2621 2622 if (free_area_empty(area, fallback_mt)) 2623 continue; 2624 2625 if (can_steal_fallback(order, migratetype)) 2626 *can_steal = true; 2627 2628 if (!only_stealable) 2629 return fallback_mt; 2630 2631 if (*can_steal) 2632 return fallback_mt; 2633 } 2634 2635 return -1; 2636} 2637 2638/* 2639 * Reserve a pageblock for exclusive use of high-order atomic allocations if 2640 * there are no empty page blocks that contain a page with a suitable order 2641 */ 2642static void reserve_highatomic_pageblock(struct page *page, struct zone *zone, 2643 unsigned int alloc_order) 2644{ 2645 int mt; 2646 unsigned long max_managed, flags; 2647 2648 /* 2649 * Limit the number reserved to 1 pageblock or roughly 1% of a zone. 2650 * Check is race-prone but harmless. 2651 */ 2652 max_managed = (zone_managed_pages(zone) / 100) + pageblock_nr_pages; 2653 if (zone->nr_reserved_highatomic >= max_managed) 2654 return; 2655 2656 spin_lock_irqsave(&zone->lock, flags); 2657 2658 /* Recheck the nr_reserved_highatomic limit under the lock */ 2659 if (zone->nr_reserved_highatomic >= max_managed) 2660 goto out_unlock; 2661 2662 /* Yoink! */ 2663 mt = get_pageblock_migratetype(page); 2664 if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt) 2665 && !is_migrate_cma(mt)) { 2666 zone->nr_reserved_highatomic += pageblock_nr_pages; 2667 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC); 2668 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL); 2669 } 2670 2671out_unlock: 2672 spin_unlock_irqrestore(&zone->lock, flags); 2673} 2674 2675/* 2676 * Used when an allocation is about to fail under memory pressure. This 2677 * potentially hurts the reliability of high-order allocations when under 2678 * intense memory pressure but failed atomic allocations should be easier 2679 * to recover from than an OOM. 2680 * 2681 * If @force is true, try to unreserve a pageblock even though highatomic 2682 * pageblock is exhausted. 2683 */ 2684static bool unreserve_highatomic_pageblock(const struct alloc_context *ac, 2685 bool force) 2686{ 2687 struct zonelist *zonelist = ac->zonelist; 2688 unsigned long flags; 2689 struct zoneref *z; 2690 struct zone *zone; 2691 struct page *page; 2692 int order; 2693 bool ret; 2694 2695 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->highest_zoneidx, 2696 ac->nodemask) { 2697 /* 2698 * Preserve at least one pageblock unless memory pressure 2699 * is really high. 2700 */ 2701 if (!force && zone->nr_reserved_highatomic <= 2702 pageblock_nr_pages) 2703 continue; 2704 2705 spin_lock_irqsave(&zone->lock, flags); 2706 for (order = 0; order < MAX_ORDER; order++) { 2707 struct free_area *area = &(zone->free_area[order]); 2708 2709 page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC); 2710 if (!page) 2711 continue; 2712 2713 /* 2714 * In page freeing path, migratetype change is racy so 2715 * we can counter several free pages in a pageblock 2716 * in this loop althoug we changed the pageblock type 2717 * from highatomic to ac->migratetype. So we should 2718 * adjust the count once. 2719 */ 2720 if (is_migrate_highatomic_page(page)) { 2721 /* 2722 * It should never happen but changes to 2723 * locking could inadvertently allow a per-cpu 2724 * drain to add pages to MIGRATE_HIGHATOMIC 2725 * while unreserving so be safe and watch for 2726 * underflows. 2727 */ 2728 zone->nr_reserved_highatomic -= min( 2729 pageblock_nr_pages, 2730 zone->nr_reserved_highatomic); 2731 } 2732 2733 /* 2734 * Convert to ac->migratetype and avoid the normal 2735 * pageblock stealing heuristics. Minimally, the caller 2736 * is doing the work and needs the pages. More 2737 * importantly, if the block was always converted to 2738 * MIGRATE_UNMOVABLE or another type then the number 2739 * of pageblocks that cannot be completely freed 2740 * may increase. 2741 */ 2742 set_pageblock_migratetype(page, ac->migratetype); 2743 ret = move_freepages_block(zone, page, ac->migratetype, 2744 NULL); 2745 if (ret) { 2746 spin_unlock_irqrestore(&zone->lock, flags); 2747 return ret; 2748 } 2749 } 2750 spin_unlock_irqrestore(&zone->lock, flags); 2751 } 2752 2753 return false; 2754} 2755 2756/* 2757 * Try finding a free buddy page on the fallback list and put it on the free 2758 * list of requested migratetype, possibly along with other pages from the same 2759 * block, depending on fragmentation avoidance heuristics. Returns true if 2760 * fallback was found so that __rmqueue_smallest() can grab it. 2761 * 2762 * The use of signed ints for order and current_order is a deliberate 2763 * deviation from the rest of this file, to make the for loop 2764 * condition simpler. 2765 */ 2766static __always_inline bool 2767__rmqueue_fallback(struct zone *zone, int order, int start_migratetype, 2768 unsigned int alloc_flags) 2769{ 2770 struct free_area *area; 2771 int current_order; 2772 int min_order = order; 2773 struct page *page; 2774 int fallback_mt; 2775 bool can_steal; 2776 2777 /* 2778 * Do not steal pages from freelists belonging to other pageblocks 2779 * i.e. orders < pageblock_order. If there are no local zones free, 2780 * the zonelists will be reiterated without ALLOC_NOFRAGMENT. 2781 */ 2782 if (alloc_flags & ALLOC_NOFRAGMENT) 2783 min_order = pageblock_order; 2784 2785 /* 2786 * Find the largest available free page in the other list. This roughly 2787 * approximates finding the pageblock with the most free pages, which 2788 * would be too costly to do exactly. 2789 */ 2790 for (current_order = MAX_ORDER - 1; current_order >= min_order; 2791 --current_order) { 2792 area = &(zone->free_area[current_order]); 2793 fallback_mt = find_suitable_fallback(area, current_order, 2794 start_migratetype, false, &can_steal); 2795 if (fallback_mt == -1) 2796 continue; 2797 2798 /* 2799 * We cannot steal all free pages from the pageblock and the 2800 * requested migratetype is movable. In that case it's better to 2801 * steal and split the smallest available page instead of the 2802 * largest available page, because even if the next movable 2803 * allocation falls back into a different pageblock than this 2804 * one, it won't cause permanent fragmentation. 2805 */ 2806 if (!can_steal && start_migratetype == MIGRATE_MOVABLE 2807 && current_order > order) 2808 goto find_smallest; 2809 2810 goto do_steal; 2811 } 2812 2813 return false; 2814 2815find_smallest: 2816 for (current_order = order; current_order < MAX_ORDER; 2817 current_order++) { 2818 area = &(zone->free_area[current_order]); 2819 fallback_mt = find_suitable_fallback(area, current_order, 2820 start_migratetype, false, &can_steal); 2821 if (fallback_mt != -1) 2822 break; 2823 } 2824 2825 /* 2826 * This should not happen - we already found a suitable fallback 2827 * when looking for the largest page. 2828 */ 2829 VM_BUG_ON(current_order == MAX_ORDER); 2830 2831do_steal: 2832 page = get_page_from_free_area(area, fallback_mt); 2833 2834 steal_suitable_fallback(zone, page, alloc_flags, start_migratetype, 2835 can_steal); 2836 2837 trace_mm_page_alloc_extfrag(page, order, current_order, 2838 start_migratetype, fallback_mt); 2839 2840 return true; 2841 2842} 2843 2844static __always_inline struct page * 2845__rmqueue_with_cma_reuse(struct zone *zone, unsigned int order, 2846 int migratetype, unsigned int alloc_flags) 2847{ 2848 struct page *page = NULL; 2849retry: 2850 page = __rmqueue_smallest(zone, order, migratetype); 2851 2852 if (unlikely(!page) && is_migrate_cma(migratetype)) { 2853 migratetype = MIGRATE_MOVABLE; 2854 alloc_flags &= ~ALLOC_CMA; 2855 page = __rmqueue_smallest(zone, order, migratetype); 2856 } 2857 2858 if (unlikely(!page) && 2859 __rmqueue_fallback(zone, order, migratetype, alloc_flags)) 2860 goto retry; 2861 2862 return page; 2863} 2864 2865/* 2866 * Do the hard work of removing an element from the buddy allocator. 2867 * Call me with the zone->lock already held. 2868 */ 2869static __always_inline struct page * 2870__rmqueue(struct zone *zone, unsigned int order, int migratetype, 2871 unsigned int alloc_flags) 2872{ 2873 struct page *page; 2874 2875#ifdef CONFIG_CMA_REUSE 2876 page = __rmqueue_with_cma_reuse(zone, order, migratetype, alloc_flags); 2877 goto out; 2878#endif 2879 2880 if (IS_ENABLED(CONFIG_CMA)) { 2881 /* 2882 * Balance movable allocations between regular and CMA areas by 2883 * allocating from CMA when over half of the zone's free memory 2884 * is in the CMA area. 2885 */ 2886 if (alloc_flags & ALLOC_CMA && 2887 zone_page_state(zone, NR_FREE_CMA_PAGES) > 2888 zone_page_state(zone, NR_FREE_PAGES) / 2) { 2889 page = __rmqueue_cma_fallback(zone, order); 2890 if (page) 2891 goto out; 2892 } 2893 } 2894retry: 2895 page = __rmqueue_smallest(zone, order, migratetype); 2896 if (unlikely(!page)) { 2897 if (alloc_flags & ALLOC_CMA) 2898 page = __rmqueue_cma_fallback(zone, order); 2899 2900 if (!page && __rmqueue_fallback(zone, order, migratetype, 2901 alloc_flags)) 2902 goto retry; 2903 } 2904out: 2905 if (page) 2906 trace_mm_page_alloc_zone_locked(page, order, migratetype); 2907 return page; 2908} 2909 2910/* 2911 * Obtain a specified number of elements from the buddy allocator, all under 2912 * a single hold of the lock, for efficiency. Add them to the supplied list. 2913 * Returns the number of new pages which were placed at *list. 2914 */ 2915static int rmqueue_bulk(struct zone *zone, unsigned int order, 2916 unsigned long count, struct list_head *list, 2917 int migratetype, unsigned int alloc_flags) 2918{ 2919 int i, alloced = 0; 2920 2921 spin_lock(&zone->lock); 2922 for (i = 0; i < count; ++i) { 2923 struct page *page = __rmqueue(zone, order, migratetype, 2924 alloc_flags); 2925 if (unlikely(page == NULL)) 2926 break; 2927 2928 if (unlikely(check_pcp_refill(page))) 2929 continue; 2930 2931 /* 2932 * Split buddy pages returned by expand() are received here in 2933 * physical page order. The page is added to the tail of 2934 * caller's list. From the callers perspective, the linked list 2935 * is ordered by page number under some conditions. This is 2936 * useful for IO devices that can forward direction from the 2937 * head, thus also in the physical page order. This is useful 2938 * for IO devices that can merge IO requests if the physical 2939 * pages are ordered properly. 2940 */ 2941 list_add_tail(&page->lru, list); 2942 alloced++; 2943 if (is_migrate_cma(get_pcppage_migratetype(page))) 2944 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES, 2945 -(1 << order)); 2946 } 2947 2948 /* 2949 * i pages were removed from the buddy list even if some leak due 2950 * to check_pcp_refill failing so adjust NR_FREE_PAGES based 2951 * on i. Do not confuse with 'alloced' which is the number of 2952 * pages added to the pcp list. 2953 */ 2954 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order)); 2955 spin_unlock(&zone->lock); 2956 return alloced; 2957} 2958 2959#ifdef CONFIG_NUMA 2960/* 2961 * Called from the vmstat counter updater to drain pagesets of this 2962 * currently executing processor on remote nodes after they have 2963 * expired. 2964 * 2965 * Note that this function must be called with the thread pinned to 2966 * a single processor. 2967 */ 2968void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp) 2969{ 2970 unsigned long flags; 2971 int to_drain, batch; 2972 2973 local_irq_save(flags); 2974 batch = READ_ONCE(pcp->batch); 2975 to_drain = min(pcp->count, batch); 2976 if (to_drain > 0) 2977 free_pcppages_bulk(zone, to_drain, pcp); 2978 local_irq_restore(flags); 2979} 2980#endif 2981 2982/* 2983 * Drain pcplists of the indicated processor and zone. 2984 * 2985 * The processor must either be the current processor and the 2986 * thread pinned to the current processor or a processor that 2987 * is not online. 2988 */ 2989static void drain_pages_zone(unsigned int cpu, struct zone *zone) 2990{ 2991 unsigned long flags; 2992 struct per_cpu_pageset *pset; 2993 struct per_cpu_pages *pcp; 2994 2995 local_irq_save(flags); 2996 pset = per_cpu_ptr(zone->pageset, cpu); 2997 2998 pcp = &pset->pcp; 2999 if (pcp->count) 3000 free_pcppages_bulk(zone, pcp->count, pcp); 3001 local_irq_restore(flags); 3002} 3003 3004/* 3005 * Drain pcplists of all zones on the indicated processor. 3006 * 3007 * The processor must either be the current processor and the 3008 * thread pinned to the current processor or a processor that 3009 * is not online. 3010 */ 3011static void drain_pages(unsigned int cpu) 3012{ 3013 struct zone *zone; 3014 3015 for_each_populated_zone(zone) { 3016 drain_pages_zone(cpu, zone); 3017 } 3018} 3019 3020/* 3021 * Spill all of this CPU's per-cpu pages back into the buddy allocator. 3022 * 3023 * The CPU has to be pinned. When zone parameter is non-NULL, spill just 3024 * the single zone's pages. 3025 */ 3026void drain_local_pages(struct zone *zone) 3027{ 3028 int cpu = smp_processor_id(); 3029 3030 if (zone) 3031 drain_pages_zone(cpu, zone); 3032 else 3033 drain_pages(cpu); 3034} 3035 3036static void drain_local_pages_wq(struct work_struct *work) 3037{ 3038 struct pcpu_drain *drain; 3039 3040 drain = container_of(work, struct pcpu_drain, work); 3041 3042 /* 3043 * drain_all_pages doesn't use proper cpu hotplug protection so 3044 * we can race with cpu offline when the WQ can move this from 3045 * a cpu pinned worker to an unbound one. We can operate on a different 3046 * cpu which is allright but we also have to make sure to not move to 3047 * a different one. 3048 */ 3049 preempt_disable(); 3050 drain_local_pages(drain->zone); 3051 preempt_enable(); 3052} 3053 3054/* 3055 * Spill all the per-cpu pages from all CPUs back into the buddy allocator. 3056 * 3057 * When zone parameter is non-NULL, spill just the single zone's pages. 3058 * 3059 * Note that this can be extremely slow as the draining happens in a workqueue. 3060 */ 3061void drain_all_pages(struct zone *zone) 3062{ 3063 int cpu; 3064 3065 /* 3066 * Allocate in the BSS so we wont require allocation in 3067 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y 3068 */ 3069 static cpumask_t cpus_with_pcps; 3070 3071 /* 3072 * Make sure nobody triggers this path before mm_percpu_wq is fully 3073 * initialized. 3074 */ 3075 if (WARN_ON_ONCE(!mm_percpu_wq)) 3076 return; 3077 3078 /* 3079 * Do not drain if one is already in progress unless it's specific to 3080 * a zone. Such callers are primarily CMA and memory hotplug and need 3081 * the drain to be complete when the call returns. 3082 */ 3083 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) { 3084 if (!zone) 3085 return; 3086 mutex_lock(&pcpu_drain_mutex); 3087 } 3088 3089 /* 3090 * We don't care about racing with CPU hotplug event 3091 * as offline notification will cause the notified 3092 * cpu to drain that CPU pcps and on_each_cpu_mask 3093 * disables preemption as part of its processing 3094 */ 3095 for_each_online_cpu(cpu) { 3096 struct per_cpu_pageset *pcp; 3097 struct zone *z; 3098 bool has_pcps = false; 3099 3100 if (zone) { 3101 pcp = per_cpu_ptr(zone->pageset, cpu); 3102 if (pcp->pcp.count) 3103 has_pcps = true; 3104 } else { 3105 for_each_populated_zone(z) { 3106 pcp = per_cpu_ptr(z->pageset, cpu); 3107 if (pcp->pcp.count) { 3108 has_pcps = true; 3109 break; 3110 } 3111 } 3112 } 3113 3114 if (has_pcps) 3115 cpumask_set_cpu(cpu, &cpus_with_pcps); 3116 else 3117 cpumask_clear_cpu(cpu, &cpus_with_pcps); 3118 } 3119 3120 for_each_cpu(cpu, &cpus_with_pcps) { 3121 struct pcpu_drain *drain = per_cpu_ptr(&pcpu_drain, cpu); 3122 3123 drain->zone = zone; 3124 INIT_WORK(&drain->work, drain_local_pages_wq); 3125 queue_work_on(cpu, mm_percpu_wq, &drain->work); 3126 } 3127 for_each_cpu(cpu, &cpus_with_pcps) 3128 flush_work(&per_cpu_ptr(&pcpu_drain, cpu)->work); 3129 3130 mutex_unlock(&pcpu_drain_mutex); 3131} 3132 3133#ifdef CONFIG_HIBERNATION 3134 3135/* 3136 * Touch the watchdog for every WD_PAGE_COUNT pages. 3137 */ 3138#define WD_PAGE_COUNT (128*1024) 3139 3140void mark_free_pages(struct zone *zone) 3141{ 3142 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT; 3143 unsigned long flags; 3144 unsigned int order, t; 3145 struct page *page; 3146 3147 if (zone_is_empty(zone)) 3148 return; 3149 3150 spin_lock_irqsave(&zone->lock, flags); 3151 3152 max_zone_pfn = zone_end_pfn(zone); 3153 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) 3154 if (pfn_valid(pfn)) { 3155 page = pfn_to_page(pfn); 3156 3157 if (!--page_count) { 3158 touch_nmi_watchdog(); 3159 page_count = WD_PAGE_COUNT; 3160 } 3161 3162 if (page_zone(page) != zone) 3163 continue; 3164 3165 if (!swsusp_page_is_forbidden(page)) 3166 swsusp_unset_page_free(page); 3167 } 3168 3169 for_each_migratetype_order(order, t) { 3170 list_for_each_entry(page, 3171 &zone->free_area[order].free_list[t], lru) { 3172 unsigned long i; 3173 3174 pfn = page_to_pfn(page); 3175 for (i = 0; i < (1UL << order); i++) { 3176 if (!--page_count) { 3177 touch_nmi_watchdog(); 3178 page_count = WD_PAGE_COUNT; 3179 } 3180 swsusp_set_page_free(pfn_to_page(pfn + i)); 3181 } 3182 } 3183 } 3184 spin_unlock_irqrestore(&zone->lock, flags); 3185} 3186#endif /* CONFIG_PM */ 3187 3188static bool free_unref_page_prepare(struct page *page, unsigned long pfn) 3189{ 3190 int migratetype; 3191 3192 if (!free_pcp_prepare(page)) 3193 return false; 3194 3195 migratetype = get_pfnblock_migratetype(page, pfn); 3196 set_pcppage_migratetype(page, migratetype); 3197 return true; 3198} 3199 3200static void free_unref_page_commit(struct page *page, unsigned long pfn) 3201{ 3202 struct zone *zone = page_zone(page); 3203 struct per_cpu_pages *pcp; 3204 int migratetype; 3205 3206 migratetype = get_pcppage_migratetype(page); 3207 __count_vm_event(PGFREE); 3208 3209 /* 3210 * We only track unmovable, reclaimable and movable on pcp lists. 3211 * Free ISOLATE pages back to the allocator because they are being 3212 * offlined but treat HIGHATOMIC as movable pages so we can get those 3213 * areas back if necessary. Otherwise, we may have to free 3214 * excessively into the page allocator 3215 */ 3216 if (migratetype >= MIGRATE_PCPTYPES) { 3217 if (unlikely(is_migrate_isolate(migratetype))) { 3218 free_one_page(zone, page, pfn, 0, migratetype, 3219 FPI_NONE); 3220 return; 3221 } 3222 migratetype = MIGRATE_MOVABLE; 3223 } 3224 3225 pcp = &this_cpu_ptr(zone->pageset)->pcp; 3226 list_add(&page->lru, &pcp->lists[migratetype]); 3227 pcp->count++; 3228 if (pcp->count >= pcp->high) { 3229 unsigned long batch = READ_ONCE(pcp->batch); 3230 free_pcppages_bulk(zone, batch, pcp); 3231 } 3232} 3233 3234/* 3235 * Free a 0-order page 3236 */ 3237void free_unref_page(struct page *page) 3238{ 3239 unsigned long flags; 3240 unsigned long pfn = page_to_pfn(page); 3241 3242 if (!free_unref_page_prepare(page, pfn)) 3243 return; 3244 3245 local_irq_save(flags); 3246 free_unref_page_commit(page, pfn); 3247 local_irq_restore(flags); 3248} 3249 3250/* 3251 * Free a list of 0-order pages 3252 */ 3253void free_unref_page_list(struct list_head *list) 3254{ 3255 struct page *page, *next; 3256 unsigned long flags, pfn; 3257 int batch_count = 0; 3258 3259 /* Prepare pages for freeing */ 3260 list_for_each_entry_safe(page, next, list, lru) { 3261 pfn = page_to_pfn(page); 3262 if (!free_unref_page_prepare(page, pfn)) 3263 list_del(&page->lru); 3264 set_page_private(page, pfn); 3265 } 3266 3267 local_irq_save(flags); 3268 list_for_each_entry_safe(page, next, list, lru) { 3269 unsigned long pfn = page_private(page); 3270 3271 set_page_private(page, 0); 3272 trace_mm_page_free_batched(page); 3273 free_unref_page_commit(page, pfn); 3274 3275 /* 3276 * Guard against excessive IRQ disabled times when we get 3277 * a large list of pages to free. 3278 */ 3279 if (++batch_count == SWAP_CLUSTER_MAX) { 3280 local_irq_restore(flags); 3281 batch_count = 0; 3282 local_irq_save(flags); 3283 } 3284 } 3285 local_irq_restore(flags); 3286} 3287 3288/* 3289 * split_page takes a non-compound higher-order page, and splits it into 3290 * n (1<<order) sub-pages: page[0..n] 3291 * Each sub-page must be freed individually. 3292 * 3293 * Note: this is probably too low level an operation for use in drivers. 3294 * Please consult with lkml before using this in your driver. 3295 */ 3296void split_page(struct page *page, unsigned int order) 3297{ 3298 int i; 3299 3300 VM_BUG_ON_PAGE(PageCompound(page), page); 3301 VM_BUG_ON_PAGE(!page_count(page), page); 3302 3303 for (i = 1; i < (1 << order); i++) 3304 set_page_refcounted(page + i); 3305 split_page_owner(page, 1 << order); 3306 split_page_memcg(page, 1 << order); 3307} 3308EXPORT_SYMBOL_GPL(split_page); 3309 3310int __isolate_free_page(struct page *page, unsigned int order) 3311{ 3312 unsigned long watermark; 3313 struct zone *zone; 3314 int mt; 3315 3316 BUG_ON(!PageBuddy(page)); 3317 3318 zone = page_zone(page); 3319 mt = get_pageblock_migratetype(page); 3320 3321 if (!is_migrate_isolate(mt)) { 3322 /* 3323 * Obey watermarks as if the page was being allocated. We can 3324 * emulate a high-order watermark check with a raised order-0 3325 * watermark, because we already know our high-order page 3326 * exists. 3327 */ 3328 watermark = zone->_watermark[WMARK_MIN] + (1UL << order); 3329 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA)) 3330 return 0; 3331 3332 __mod_zone_freepage_state(zone, -(1UL << order), mt); 3333 } 3334 3335 /* Remove page from free list */ 3336 3337 del_page_from_free_list(page, zone, order); 3338 3339 /* 3340 * Set the pageblock if the isolated page is at least half of a 3341 * pageblock 3342 */ 3343 if (order >= pageblock_order - 1) { 3344 struct page *endpage = page + (1 << order) - 1; 3345 for (; page < endpage; page += pageblock_nr_pages) { 3346 int mt = get_pageblock_migratetype(page); 3347 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt) 3348 && !is_migrate_highatomic(mt)) 3349 set_pageblock_migratetype(page, 3350 MIGRATE_MOVABLE); 3351 } 3352 } 3353 3354 3355 return 1UL << order; 3356} 3357 3358/** 3359 * __putback_isolated_page - Return a now-isolated page back where we got it 3360 * @page: Page that was isolated 3361 * @order: Order of the isolated page 3362 * @mt: The page's pageblock's migratetype 3363 * 3364 * This function is meant to return a page pulled from the free lists via 3365 * __isolate_free_page back to the free lists they were pulled from. 3366 */ 3367void __putback_isolated_page(struct page *page, unsigned int order, int mt) 3368{ 3369 struct zone *zone = page_zone(page); 3370 3371 /* zone lock should be held when this function is called */ 3372 lockdep_assert_held(&zone->lock); 3373 3374 /* Return isolated page to tail of freelist. */ 3375 __free_one_page(page, page_to_pfn(page), zone, order, mt, 3376 FPI_SKIP_REPORT_NOTIFY | FPI_TO_TAIL); 3377} 3378 3379/* 3380 * Update NUMA hit/miss statistics 3381 * 3382 * Must be called with interrupts disabled. 3383 */ 3384static inline void zone_statistics(struct zone *preferred_zone, struct zone *z) 3385{ 3386#ifdef CONFIG_NUMA 3387 enum numa_stat_item local_stat = NUMA_LOCAL; 3388 3389 /* skip numa counters update if numa stats is disabled */ 3390 if (!static_branch_likely(&vm_numa_stat_key)) 3391 return; 3392 3393 if (zone_to_nid(z) != numa_node_id()) 3394 local_stat = NUMA_OTHER; 3395 3396 if (zone_to_nid(z) == zone_to_nid(preferred_zone)) 3397 __inc_numa_state(z, NUMA_HIT); 3398 else { 3399 __inc_numa_state(z, NUMA_MISS); 3400 __inc_numa_state(preferred_zone, NUMA_FOREIGN); 3401 } 3402 __inc_numa_state(z, local_stat); 3403#endif 3404} 3405 3406/* Remove page from the per-cpu list, caller must protect the list */ 3407static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype, 3408 unsigned int alloc_flags, 3409 struct per_cpu_pages *pcp, 3410 struct list_head *list) 3411{ 3412 struct page *page; 3413 3414 do { 3415 if (list_empty(list)) { 3416 pcp->count += rmqueue_bulk(zone, 0, 3417 pcp->batch, list, 3418 migratetype, alloc_flags); 3419 if (unlikely(list_empty(list))) 3420 return NULL; 3421 } 3422 3423 page = list_first_entry(list, struct page, lru); 3424 list_del(&page->lru); 3425 pcp->count--; 3426 } while (check_new_pcp(page)); 3427 3428 return page; 3429} 3430 3431/* Lock and remove page from the per-cpu list */ 3432static struct page *rmqueue_pcplist(struct zone *preferred_zone, 3433 struct zone *zone, gfp_t gfp_flags, 3434 int migratetype, unsigned int alloc_flags) 3435{ 3436 struct per_cpu_pages *pcp; 3437 struct list_head *list; 3438 struct page *page; 3439 unsigned long flags; 3440 3441 local_irq_save(flags); 3442 pcp = &this_cpu_ptr(zone->pageset)->pcp; 3443 list = &pcp->lists[migratetype]; 3444 page = __rmqueue_pcplist(zone, migratetype, alloc_flags, pcp, list); 3445 if (page) { 3446 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1); 3447 zone_statistics(preferred_zone, zone); 3448 } 3449 local_irq_restore(flags); 3450 return page; 3451} 3452 3453/* 3454 * Allocate a page from the given zone. Use pcplists for order-0 allocations. 3455 */ 3456static inline 3457struct page *rmqueue(struct zone *preferred_zone, 3458 struct zone *zone, unsigned int order, 3459 gfp_t gfp_flags, unsigned int alloc_flags, 3460 int migratetype) 3461{ 3462 unsigned long flags; 3463 struct page *page; 3464 3465 if (likely(order == 0)) { 3466 /* 3467 * MIGRATE_MOVABLE pcplist could have the pages on CMA area and 3468 * we need to skip it when CMA area isn't allowed. 3469 */ 3470 if (!IS_ENABLED(CONFIG_CMA) || alloc_flags & ALLOC_CMA || 3471 migratetype != MIGRATE_MOVABLE || 3472 IS_ENABLED(CONFIG_CMA_REUSE)) { 3473 page = rmqueue_pcplist(preferred_zone, zone, gfp_flags, 3474 migratetype, alloc_flags); 3475 goto out; 3476 } 3477 } 3478 3479 /* 3480 * We most definitely don't want callers attempting to 3481 * allocate greater than order-1 page units with __GFP_NOFAIL. 3482 */ 3483 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1)); 3484 spin_lock_irqsave(&zone->lock, flags); 3485 3486 do { 3487 page = NULL; 3488 /* 3489 * order-0 request can reach here when the pcplist is skipped 3490 * due to non-CMA allocation context. HIGHATOMIC area is 3491 * reserved for high-order atomic allocation, so order-0 3492 * request should skip it. 3493 */ 3494 if (order > 0 && alloc_flags & ALLOC_HARDER) { 3495 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC); 3496 if (page) 3497 trace_mm_page_alloc_zone_locked(page, order, migratetype); 3498 } 3499 if (!page) 3500 page = __rmqueue(zone, order, migratetype, alloc_flags); 3501 } while (page && check_new_pages(page, order)); 3502 spin_unlock(&zone->lock); 3503 if (!page) 3504 goto failed; 3505 __mod_zone_freepage_state(zone, -(1 << order), 3506 get_pcppage_migratetype(page)); 3507 3508 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order); 3509 zone_statistics(preferred_zone, zone); 3510 local_irq_restore(flags); 3511 3512out: 3513 /* Separate test+clear to avoid unnecessary atomics */ 3514 if (test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags)) { 3515 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags); 3516 wakeup_kswapd(zone, 0, 0, zone_idx(zone)); 3517 } 3518 3519 VM_BUG_ON_PAGE(page && bad_range(zone, page), page); 3520 return page; 3521 3522failed: 3523 local_irq_restore(flags); 3524 return NULL; 3525} 3526 3527#ifdef CONFIG_FAIL_PAGE_ALLOC 3528 3529static struct { 3530 struct fault_attr attr; 3531 3532 bool ignore_gfp_highmem; 3533 bool ignore_gfp_reclaim; 3534 u32 min_order; 3535} fail_page_alloc = { 3536 .attr = FAULT_ATTR_INITIALIZER, 3537 .ignore_gfp_reclaim = true, 3538 .ignore_gfp_highmem = true, 3539 .min_order = 1, 3540}; 3541 3542static int __init setup_fail_page_alloc(char *str) 3543{ 3544 return setup_fault_attr(&fail_page_alloc.attr, str); 3545} 3546__setup("fail_page_alloc=", setup_fail_page_alloc); 3547 3548static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order) 3549{ 3550 if (order < fail_page_alloc.min_order) 3551 return false; 3552 if (gfp_mask & __GFP_NOFAIL) 3553 return false; 3554 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM)) 3555 return false; 3556 if (fail_page_alloc.ignore_gfp_reclaim && 3557 (gfp_mask & __GFP_DIRECT_RECLAIM)) 3558 return false; 3559 3560 return should_fail(&fail_page_alloc.attr, 1 << order); 3561} 3562 3563#ifdef CONFIG_FAULT_INJECTION_DEBUG_FS 3564 3565static int __init fail_page_alloc_debugfs(void) 3566{ 3567 umode_t mode = S_IFREG | 0600; 3568 struct dentry *dir; 3569 3570 dir = fault_create_debugfs_attr("fail_page_alloc", NULL, 3571 &fail_page_alloc.attr); 3572 3573 debugfs_create_bool("ignore-gfp-wait", mode, dir, 3574 &fail_page_alloc.ignore_gfp_reclaim); 3575 debugfs_create_bool("ignore-gfp-highmem", mode, dir, 3576 &fail_page_alloc.ignore_gfp_highmem); 3577 debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order); 3578 3579 return 0; 3580} 3581 3582late_initcall(fail_page_alloc_debugfs); 3583 3584#endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */ 3585 3586#else /* CONFIG_FAIL_PAGE_ALLOC */ 3587 3588static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order) 3589{ 3590 return false; 3591} 3592 3593#endif /* CONFIG_FAIL_PAGE_ALLOC */ 3594 3595noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order) 3596{ 3597 return __should_fail_alloc_page(gfp_mask, order); 3598} 3599ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE); 3600 3601static inline long __zone_watermark_unusable_free(struct zone *z, 3602 unsigned int order, unsigned int alloc_flags) 3603{ 3604 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM)); 3605 long unusable_free = (1 << order) - 1; 3606 3607 /* 3608 * If the caller does not have rights to ALLOC_HARDER then subtract 3609 * the high-atomic reserves. This will over-estimate the size of the 3610 * atomic reserve but it avoids a search. 3611 */ 3612 if (likely(!alloc_harder)) 3613 unusable_free += z->nr_reserved_highatomic; 3614 3615#ifdef CONFIG_CMA 3616 /* If allocation can't use CMA areas don't use free CMA pages */ 3617 if (!(alloc_flags & ALLOC_CMA)) 3618 unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES); 3619#endif 3620 3621 return unusable_free; 3622} 3623 3624/* 3625 * Return true if free base pages are above 'mark'. For high-order checks it 3626 * will return true of the order-0 watermark is reached and there is at least 3627 * one free page of a suitable size. Checking now avoids taking the zone lock 3628 * to check in the allocation paths if no pages are free. 3629 */ 3630bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark, 3631 int highest_zoneidx, unsigned int alloc_flags, 3632 long free_pages) 3633{ 3634 long min = mark; 3635 int o; 3636 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM)); 3637 3638 /* free_pages may go negative - that's OK */ 3639 free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags); 3640 3641 if (alloc_flags & ALLOC_HIGH) 3642 min -= min / 2; 3643 3644 if (unlikely(alloc_harder)) { 3645 /* 3646 * OOM victims can try even harder than normal ALLOC_HARDER 3647 * users on the grounds that it's definitely going to be in 3648 * the exit path shortly and free memory. Any allocation it 3649 * makes during the free path will be small and short-lived. 3650 */ 3651 if (alloc_flags & ALLOC_OOM) 3652 min -= min / 2; 3653 else 3654 min -= min / 4; 3655 } 3656 3657 /* 3658 * Check watermarks for an order-0 allocation request. If these 3659 * are not met, then a high-order request also cannot go ahead 3660 * even if a suitable page happened to be free. 3661 */ 3662 if (free_pages <= min + z->lowmem_reserve[highest_zoneidx]) 3663 return false; 3664 3665 /* If this is an order-0 request then the watermark is fine */ 3666 if (!order) 3667 return true; 3668 3669 /* For a high-order request, check at least one suitable page is free */ 3670 for (o = order; o < MAX_ORDER; o++) { 3671 struct free_area *area = &z->free_area[o]; 3672 int mt; 3673 3674 if (!area->nr_free) 3675 continue; 3676 3677 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) { 3678 if (!free_area_empty(area, mt)) 3679 return true; 3680 } 3681 3682#ifdef CONFIG_CMA 3683 if ((alloc_flags & ALLOC_CMA) && 3684 !free_area_empty(area, MIGRATE_CMA)) { 3685 return true; 3686 } 3687#endif 3688 if (alloc_harder && !free_area_empty(area, MIGRATE_HIGHATOMIC)) 3689 return true; 3690 } 3691 return false; 3692} 3693 3694bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark, 3695 int highest_zoneidx, unsigned int alloc_flags) 3696{ 3697 return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags, 3698 zone_page_state(z, NR_FREE_PAGES)); 3699} 3700 3701static inline bool zone_watermark_fast(struct zone *z, unsigned int order, 3702 unsigned long mark, int highest_zoneidx, 3703 unsigned int alloc_flags, gfp_t gfp_mask) 3704{ 3705 long free_pages; 3706 3707 free_pages = zone_page_state(z, NR_FREE_PAGES); 3708 3709 /* 3710 * Fast check for order-0 only. If this fails then the reserves 3711 * need to be calculated. 3712 */ 3713 if (!order) { 3714 long usable_free; 3715 long reserved; 3716 3717 usable_free = free_pages; 3718 reserved = __zone_watermark_unusable_free(z, 0, alloc_flags); 3719 3720 /* reserved may over estimate high-atomic reserves. */ 3721 usable_free -= min(usable_free, reserved); 3722 if (usable_free > mark + z->lowmem_reserve[highest_zoneidx]) 3723 return true; 3724 } 3725 3726 if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags, 3727 free_pages)) 3728 return true; 3729 /* 3730 * Ignore watermark boosting for GFP_ATOMIC order-0 allocations 3731 * when checking the min watermark. The min watermark is the 3732 * point where boosting is ignored so that kswapd is woken up 3733 * when below the low watermark. 3734 */ 3735 if (unlikely(!order && (gfp_mask & __GFP_ATOMIC) && z->watermark_boost 3736 && ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) { 3737 mark = z->_watermark[WMARK_MIN]; 3738 return __zone_watermark_ok(z, order, mark, highest_zoneidx, 3739 alloc_flags, free_pages); 3740 } 3741 3742 return false; 3743} 3744 3745bool zone_watermark_ok_safe(struct zone *z, unsigned int order, 3746 unsigned long mark, int highest_zoneidx) 3747{ 3748 long free_pages = zone_page_state(z, NR_FREE_PAGES); 3749 3750 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark) 3751 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES); 3752 3753 return __zone_watermark_ok(z, order, mark, highest_zoneidx, 0, 3754 free_pages); 3755} 3756 3757#ifdef CONFIG_NUMA 3758static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone) 3759{ 3760 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <= 3761 node_reclaim_distance; 3762} 3763#else /* CONFIG_NUMA */ 3764static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone) 3765{ 3766 return true; 3767} 3768#endif /* CONFIG_NUMA */ 3769 3770/* 3771 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid 3772 * fragmentation is subtle. If the preferred zone was HIGHMEM then 3773 * premature use of a lower zone may cause lowmem pressure problems that 3774 * are worse than fragmentation. If the next zone is ZONE_DMA then it is 3775 * probably too small. It only makes sense to spread allocations to avoid 3776 * fragmentation between the Normal and DMA32 zones. 3777 */ 3778static inline unsigned int 3779alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask) 3780{ 3781 unsigned int alloc_flags; 3782 3783 /* 3784 * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD 3785 * to save a branch. 3786 */ 3787 alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM); 3788 3789#ifdef CONFIG_ZONE_DMA32 3790 if (!zone) 3791 return alloc_flags; 3792 3793 if (zone_idx(zone) != ZONE_NORMAL) 3794 return alloc_flags; 3795 3796 /* 3797 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and 3798 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume 3799 * on UMA that if Normal is populated then so is DMA32. 3800 */ 3801 BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1); 3802 if (nr_online_nodes > 1 && !populated_zone(--zone)) 3803 return alloc_flags; 3804 3805 alloc_flags |= ALLOC_NOFRAGMENT; 3806#endif /* CONFIG_ZONE_DMA32 */ 3807 return alloc_flags; 3808} 3809 3810static inline unsigned int current_alloc_flags(gfp_t gfp_mask, 3811 unsigned int alloc_flags) 3812{ 3813#ifdef CONFIG_CMA 3814 unsigned int pflags = current->flags; 3815 3816 if (!(pflags & PF_MEMALLOC_NOCMA) && 3817 gfp_migratetype(gfp_mask) == get_cma_migratetype()) 3818 alloc_flags |= ALLOC_CMA; 3819 3820#endif 3821 return alloc_flags; 3822} 3823 3824/* 3825 * get_page_from_freelist goes through the zonelist trying to allocate 3826 * a page. 3827 */ 3828static struct page * 3829get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, 3830 const struct alloc_context *ac) 3831{ 3832 struct zoneref *z; 3833 struct zone *zone; 3834 struct pglist_data *last_pgdat_dirty_limit = NULL; 3835 bool no_fallback; 3836 3837retry: 3838 /* 3839 * Scan zonelist, looking for a zone with enough free. 3840 * See also __cpuset_node_allowed() comment in kernel/cpuset.c. 3841 */ 3842 no_fallback = alloc_flags & ALLOC_NOFRAGMENT; 3843 z = ac->preferred_zoneref; 3844 for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx, 3845 ac->nodemask) { 3846 struct page *page; 3847 unsigned long mark; 3848 3849 if (cpusets_enabled() && 3850 (alloc_flags & ALLOC_CPUSET) && 3851 !__cpuset_zone_allowed(zone, gfp_mask)) 3852 continue; 3853 /* 3854 * When allocating a page cache page for writing, we 3855 * want to get it from a node that is within its dirty 3856 * limit, such that no single node holds more than its 3857 * proportional share of globally allowed dirty pages. 3858 * The dirty limits take into account the node's 3859 * lowmem reserves and high watermark so that kswapd 3860 * should be able to balance it without having to 3861 * write pages from its LRU list. 3862 * 3863 * XXX: For now, allow allocations to potentially 3864 * exceed the per-node dirty limit in the slowpath 3865 * (spread_dirty_pages unset) before going into reclaim, 3866 * which is important when on a NUMA setup the allowed 3867 * nodes are together not big enough to reach the 3868 * global limit. The proper fix for these situations 3869 * will require awareness of nodes in the 3870 * dirty-throttling and the flusher threads. 3871 */ 3872 if (ac->spread_dirty_pages) { 3873 if (last_pgdat_dirty_limit == zone->zone_pgdat) 3874 continue; 3875 3876 if (!node_dirty_ok(zone->zone_pgdat)) { 3877 last_pgdat_dirty_limit = zone->zone_pgdat; 3878 continue; 3879 } 3880 } 3881 3882 if (no_fallback && nr_online_nodes > 1 && 3883 zone != ac->preferred_zoneref->zone) { 3884 int local_nid; 3885 3886 /* 3887 * If moving to a remote node, retry but allow 3888 * fragmenting fallbacks. Locality is more important 3889 * than fragmentation avoidance. 3890 */ 3891 local_nid = zone_to_nid(ac->preferred_zoneref->zone); 3892 if (zone_to_nid(zone) != local_nid) { 3893 alloc_flags &= ~ALLOC_NOFRAGMENT; 3894 goto retry; 3895 } 3896 } 3897 3898 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK); 3899 if (!zone_watermark_fast(zone, order, mark, 3900 ac->highest_zoneidx, alloc_flags, 3901 gfp_mask)) { 3902 int ret; 3903 3904#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 3905 /* 3906 * Watermark failed for this zone, but see if we can 3907 * grow this zone if it contains deferred pages. 3908 */ 3909 if (static_branch_unlikely(&deferred_pages)) { 3910 if (_deferred_grow_zone(zone, order)) 3911 goto try_this_zone; 3912 } 3913#endif 3914 /* Checked here to keep the fast path fast */ 3915 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK); 3916 if (alloc_flags & ALLOC_NO_WATERMARKS) 3917 goto try_this_zone; 3918 3919 if (node_reclaim_mode == 0 || 3920 !zone_allows_reclaim(ac->preferred_zoneref->zone, zone)) 3921 continue; 3922 3923 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order); 3924 switch (ret) { 3925 case NODE_RECLAIM_NOSCAN: 3926 /* did not scan */ 3927 continue; 3928 case NODE_RECLAIM_FULL: 3929 /* scanned but unreclaimable */ 3930 continue; 3931 default: 3932 /* did we reclaim enough */ 3933 if (zone_watermark_ok(zone, order, mark, 3934 ac->highest_zoneidx, alloc_flags)) 3935 goto try_this_zone; 3936 3937 continue; 3938 } 3939 } 3940 3941try_this_zone: 3942 page = rmqueue(ac->preferred_zoneref->zone, zone, order, 3943 gfp_mask, alloc_flags, ac->migratetype); 3944 if (page) { 3945 prep_new_page(page, order, gfp_mask, alloc_flags); 3946 3947 /* 3948 * If this is a high-order atomic allocation then check 3949 * if the pageblock should be reserved for the future 3950 */ 3951 if (unlikely(order && (alloc_flags & ALLOC_HARDER))) 3952 reserve_highatomic_pageblock(page, zone, order); 3953 3954 return page; 3955 } else { 3956#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 3957 /* Try again if zone has deferred pages */ 3958 if (static_branch_unlikely(&deferred_pages)) { 3959 if (_deferred_grow_zone(zone, order)) 3960 goto try_this_zone; 3961 } 3962#endif 3963 } 3964 } 3965 3966 /* 3967 * It's possible on a UMA machine to get through all zones that are 3968 * fragmented. If avoiding fragmentation, reset and try again. 3969 */ 3970 if (no_fallback) { 3971 alloc_flags &= ~ALLOC_NOFRAGMENT; 3972 goto retry; 3973 } 3974 3975 return NULL; 3976} 3977 3978static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask) 3979{ 3980 unsigned int filter = SHOW_MEM_FILTER_NODES; 3981 3982 /* 3983 * This documents exceptions given to allocations in certain 3984 * contexts that are allowed to allocate outside current's set 3985 * of allowed nodes. 3986 */ 3987 if (!(gfp_mask & __GFP_NOMEMALLOC)) 3988 if (tsk_is_oom_victim(current) || 3989 (current->flags & (PF_MEMALLOC | PF_EXITING))) 3990 filter &= ~SHOW_MEM_FILTER_NODES; 3991 if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM)) 3992 filter &= ~SHOW_MEM_FILTER_NODES; 3993 3994 show_mem(filter, nodemask); 3995} 3996 3997void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...) 3998{ 3999 struct va_format vaf; 4000 va_list args; 4001 static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1); 4002 4003 if ((gfp_mask & __GFP_NOWARN) || 4004 !__ratelimit(&nopage_rs) || 4005 ((gfp_mask & __GFP_DMA) && !has_managed_dma())) 4006 return; 4007 4008 va_start(args, fmt); 4009 vaf.fmt = fmt; 4010 vaf.va = &args; 4011 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl", 4012 current->comm, &vaf, gfp_mask, &gfp_mask, 4013 nodemask_pr_args(nodemask)); 4014 va_end(args); 4015 4016 cpuset_print_current_mems_allowed(); 4017 pr_cont("\n"); 4018 dump_stack(); 4019 warn_alloc_show_mem(gfp_mask, nodemask); 4020} 4021 4022static inline struct page * 4023__alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order, 4024 unsigned int alloc_flags, 4025 const struct alloc_context *ac) 4026{ 4027 struct page *page; 4028 4029 page = get_page_from_freelist(gfp_mask, order, 4030 alloc_flags|ALLOC_CPUSET, ac); 4031 /* 4032 * fallback to ignore cpuset restriction if our nodes 4033 * are depleted 4034 */ 4035 if (!page) 4036 page = get_page_from_freelist(gfp_mask, order, 4037 alloc_flags, ac); 4038 4039 return page; 4040} 4041 4042static inline struct page * 4043__alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order, 4044 const struct alloc_context *ac, unsigned long *did_some_progress) 4045{ 4046 struct oom_control oc = { 4047 .zonelist = ac->zonelist, 4048 .nodemask = ac->nodemask, 4049 .memcg = NULL, 4050 .gfp_mask = gfp_mask, 4051 .order = order, 4052 }; 4053 struct page *page; 4054 4055 *did_some_progress = 0; 4056 4057 /* 4058 * Acquire the oom lock. If that fails, somebody else is 4059 * making progress for us. 4060 */ 4061 if (!mutex_trylock(&oom_lock)) { 4062 *did_some_progress = 1; 4063 schedule_timeout_uninterruptible(1); 4064 return NULL; 4065 } 4066 4067 /* 4068 * Go through the zonelist yet one more time, keep very high watermark 4069 * here, this is only to catch a parallel oom killing, we must fail if 4070 * we're still under heavy pressure. But make sure that this reclaim 4071 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY 4072 * allocation which will never fail due to oom_lock already held. 4073 */ 4074 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) & 4075 ~__GFP_DIRECT_RECLAIM, order, 4076 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac); 4077 if (page) 4078 goto out; 4079 4080 /* Coredumps can quickly deplete all memory reserves */ 4081 if (current->flags & PF_DUMPCORE) 4082 goto out; 4083 /* The OOM killer will not help higher order allocs */ 4084 if (order > PAGE_ALLOC_COSTLY_ORDER) 4085 goto out; 4086 /* 4087 * We have already exhausted all our reclaim opportunities without any 4088 * success so it is time to admit defeat. We will skip the OOM killer 4089 * because it is very likely that the caller has a more reasonable 4090 * fallback than shooting a random task. 4091 * 4092 * The OOM killer may not free memory on a specific node. 4093 */ 4094 if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE)) 4095 goto out; 4096 /* The OOM killer does not needlessly kill tasks for lowmem */ 4097 if (ac->highest_zoneidx < ZONE_NORMAL) 4098 goto out; 4099 if (pm_suspended_storage()) 4100 goto out; 4101 /* 4102 * XXX: GFP_NOFS allocations should rather fail than rely on 4103 * other request to make a forward progress. 4104 * We are in an unfortunate situation where out_of_memory cannot 4105 * do much for this context but let's try it to at least get 4106 * access to memory reserved if the current task is killed (see 4107 * out_of_memory). Once filesystems are ready to handle allocation 4108 * failures more gracefully we should just bail out here. 4109 */ 4110 4111 /* Exhausted what can be done so it's blame time */ 4112 if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) { 4113 *did_some_progress = 1; 4114 4115 /* 4116 * Help non-failing allocations by giving them access to memory 4117 * reserves 4118 */ 4119 if (gfp_mask & __GFP_NOFAIL) 4120 page = __alloc_pages_cpuset_fallback(gfp_mask, order, 4121 ALLOC_NO_WATERMARKS, ac); 4122 } 4123out: 4124 mutex_unlock(&oom_lock); 4125 return page; 4126} 4127 4128/* 4129 * Maximum number of compaction retries wit a progress before OOM 4130 * killer is consider as the only way to move forward. 4131 */ 4132#define MAX_COMPACT_RETRIES 16 4133 4134#ifdef CONFIG_COMPACTION 4135/* Try memory compaction for high-order allocations before reclaim */ 4136static struct page * 4137__alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order, 4138 unsigned int alloc_flags, const struct alloc_context *ac, 4139 enum compact_priority prio, enum compact_result *compact_result) 4140{ 4141 struct page *page = NULL; 4142 unsigned long pflags; 4143 unsigned int noreclaim_flag; 4144 4145 if (!order) 4146 return NULL; 4147 4148 psi_memstall_enter(&pflags); 4149 noreclaim_flag = memalloc_noreclaim_save(); 4150 4151 *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac, 4152 prio, &page); 4153 4154 memalloc_noreclaim_restore(noreclaim_flag); 4155 psi_memstall_leave(&pflags); 4156 4157 /* 4158 * At least in one zone compaction wasn't deferred or skipped, so let's 4159 * count a compaction stall 4160 */ 4161 count_vm_event(COMPACTSTALL); 4162 4163 /* Prep a captured page if available */ 4164 if (page) 4165 prep_new_page(page, order, gfp_mask, alloc_flags); 4166 4167 /* Try get a page from the freelist if available */ 4168 if (!page) 4169 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 4170 4171 if (page) { 4172 struct zone *zone = page_zone(page); 4173 4174 zone->compact_blockskip_flush = false; 4175 compaction_defer_reset(zone, order, true); 4176 count_vm_event(COMPACTSUCCESS); 4177 return page; 4178 } 4179 4180 /* 4181 * It's bad if compaction run occurs and fails. The most likely reason 4182 * is that pages exist, but not enough to satisfy watermarks. 4183 */ 4184 count_vm_event(COMPACTFAIL); 4185 4186 cond_resched(); 4187 4188 return NULL; 4189} 4190 4191static inline bool 4192should_compact_retry(struct alloc_context *ac, int order, int alloc_flags, 4193 enum compact_result compact_result, 4194 enum compact_priority *compact_priority, 4195 int *compaction_retries) 4196{ 4197 int max_retries = MAX_COMPACT_RETRIES; 4198 int min_priority; 4199 bool ret = false; 4200 int retries = *compaction_retries; 4201 enum compact_priority priority = *compact_priority; 4202 4203 if (!order) 4204 return false; 4205 4206 if (compaction_made_progress(compact_result)) 4207 (*compaction_retries)++; 4208 4209 /* 4210 * compaction considers all the zone as desperately out of memory 4211 * so it doesn't really make much sense to retry except when the 4212 * failure could be caused by insufficient priority 4213 */ 4214 if (compaction_failed(compact_result)) 4215 goto check_priority; 4216 4217 /* 4218 * compaction was skipped because there are not enough order-0 pages 4219 * to work with, so we retry only if it looks like reclaim can help. 4220 */ 4221 if (compaction_needs_reclaim(compact_result)) { 4222 ret = compaction_zonelist_suitable(ac, order, alloc_flags); 4223 goto out; 4224 } 4225 4226 /* 4227 * make sure the compaction wasn't deferred or didn't bail out early 4228 * due to locks contention before we declare that we should give up. 4229 * But the next retry should use a higher priority if allowed, so 4230 * we don't just keep bailing out endlessly. 4231 */ 4232 if (compaction_withdrawn(compact_result)) { 4233 goto check_priority; 4234 } 4235 4236 /* 4237 * !costly requests are much more important than __GFP_RETRY_MAYFAIL 4238 * costly ones because they are de facto nofail and invoke OOM 4239 * killer to move on while costly can fail and users are ready 4240 * to cope with that. 1/4 retries is rather arbitrary but we 4241 * would need much more detailed feedback from compaction to 4242 * make a better decision. 4243 */ 4244 if (order > PAGE_ALLOC_COSTLY_ORDER) 4245 max_retries /= 4; 4246 if (*compaction_retries <= max_retries) { 4247 ret = true; 4248 goto out; 4249 } 4250 4251 /* 4252 * Make sure there are attempts at the highest priority if we exhausted 4253 * all retries or failed at the lower priorities. 4254 */ 4255check_priority: 4256 min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ? 4257 MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY; 4258 4259 if (*compact_priority > min_priority) { 4260 (*compact_priority)--; 4261 *compaction_retries = 0; 4262 ret = true; 4263 } 4264out: 4265 trace_compact_retry(order, priority, compact_result, retries, max_retries, ret); 4266 return ret; 4267} 4268#else 4269static inline struct page * 4270__alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order, 4271 unsigned int alloc_flags, const struct alloc_context *ac, 4272 enum compact_priority prio, enum compact_result *compact_result) 4273{ 4274 *compact_result = COMPACT_SKIPPED; 4275 return NULL; 4276} 4277 4278static inline bool 4279should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags, 4280 enum compact_result compact_result, 4281 enum compact_priority *compact_priority, 4282 int *compaction_retries) 4283{ 4284 struct zone *zone; 4285 struct zoneref *z; 4286 4287 if (!order || order > PAGE_ALLOC_COSTLY_ORDER) 4288 return false; 4289 4290 /* 4291 * There are setups with compaction disabled which would prefer to loop 4292 * inside the allocator rather than hit the oom killer prematurely. 4293 * Let's give them a good hope and keep retrying while the order-0 4294 * watermarks are OK. 4295 */ 4296 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, 4297 ac->highest_zoneidx, ac->nodemask) { 4298 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone), 4299 ac->highest_zoneidx, alloc_flags)) 4300 return true; 4301 } 4302 return false; 4303} 4304#endif /* CONFIG_COMPACTION */ 4305 4306#ifdef CONFIG_LOCKDEP 4307static struct lockdep_map __fs_reclaim_map = 4308 STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map); 4309 4310static bool __need_fs_reclaim(gfp_t gfp_mask) 4311{ 4312 gfp_mask = current_gfp_context(gfp_mask); 4313 4314 /* no reclaim without waiting on it */ 4315 if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) 4316 return false; 4317 4318 /* this guy won't enter reclaim */ 4319 if (current->flags & PF_MEMALLOC) 4320 return false; 4321 4322 /* We're only interested __GFP_FS allocations for now */ 4323 if (!(gfp_mask & __GFP_FS)) 4324 return false; 4325 4326 if (gfp_mask & __GFP_NOLOCKDEP) 4327 return false; 4328 4329 return true; 4330} 4331 4332void __fs_reclaim_acquire(void) 4333{ 4334 lock_map_acquire(&__fs_reclaim_map); 4335} 4336 4337void __fs_reclaim_release(void) 4338{ 4339 lock_map_release(&__fs_reclaim_map); 4340} 4341 4342void fs_reclaim_acquire(gfp_t gfp_mask) 4343{ 4344 if (__need_fs_reclaim(gfp_mask)) 4345 __fs_reclaim_acquire(); 4346} 4347EXPORT_SYMBOL_GPL(fs_reclaim_acquire); 4348 4349void fs_reclaim_release(gfp_t gfp_mask) 4350{ 4351 if (__need_fs_reclaim(gfp_mask)) 4352 __fs_reclaim_release(); 4353} 4354EXPORT_SYMBOL_GPL(fs_reclaim_release); 4355#endif 4356 4357/* 4358 * Zonelists may change due to hotplug during allocation. Detect when zonelists 4359 * have been rebuilt so allocation retries. Reader side does not lock and 4360 * retries the allocation if zonelist changes. Writer side is protected by the 4361 * embedded spin_lock. 4362 */ 4363static DEFINE_SEQLOCK(zonelist_update_seq); 4364 4365static unsigned int zonelist_iter_begin(void) 4366{ 4367 if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) 4368 return read_seqbegin(&zonelist_update_seq); 4369 4370 return 0; 4371} 4372 4373static unsigned int check_retry_zonelist(unsigned int seq) 4374{ 4375 if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) 4376 return read_seqretry(&zonelist_update_seq, seq); 4377 4378 return seq; 4379} 4380 4381/* Perform direct synchronous page reclaim */ 4382static unsigned long 4383__perform_reclaim(gfp_t gfp_mask, unsigned int order, 4384 const struct alloc_context *ac) 4385{ 4386 unsigned int noreclaim_flag; 4387 unsigned long pflags, progress; 4388 4389 cond_resched(); 4390 4391 /* We now go into synchronous reclaim */ 4392 cpuset_memory_pressure_bump(); 4393 psi_memstall_enter(&pflags); 4394 fs_reclaim_acquire(gfp_mask); 4395 noreclaim_flag = memalloc_noreclaim_save(); 4396 4397 progress = try_to_free_pages(ac->zonelist, order, gfp_mask, 4398 ac->nodemask); 4399 4400 memalloc_noreclaim_restore(noreclaim_flag); 4401 fs_reclaim_release(gfp_mask); 4402 psi_memstall_leave(&pflags); 4403 4404 cond_resched(); 4405 4406 return progress; 4407} 4408 4409/* The really slow allocator path where we enter direct reclaim */ 4410static inline struct page * 4411__alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order, 4412 unsigned int alloc_flags, const struct alloc_context *ac, 4413 unsigned long *did_some_progress) 4414{ 4415 struct page *page = NULL; 4416 bool drained = false; 4417 4418 *did_some_progress = __perform_reclaim(gfp_mask, order, ac); 4419 if (unlikely(!(*did_some_progress))) 4420 return NULL; 4421 4422retry: 4423 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 4424 4425 /* 4426 * If an allocation failed after direct reclaim, it could be because 4427 * pages are pinned on the per-cpu lists or in high alloc reserves. 4428 * Shrink them and try again 4429 */ 4430 if (!page && !drained) { 4431 unreserve_highatomic_pageblock(ac, false); 4432#ifdef CONFIG_RECLAIM_ACCT 4433 reclaimacct_substage_start(RA_DRAINALLPAGES); 4434#endif 4435 drain_all_pages(NULL); 4436#ifdef CONFIG_RECLAIM_ACCT 4437 reclaimacct_substage_end(RA_DRAINALLPAGES, 0, NULL); 4438#endif 4439 drained = true; 4440 goto retry; 4441 } 4442 4443 return page; 4444} 4445 4446static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask, 4447 const struct alloc_context *ac) 4448{ 4449 struct zoneref *z; 4450 struct zone *zone; 4451 pg_data_t *last_pgdat = NULL; 4452 enum zone_type highest_zoneidx = ac->highest_zoneidx; 4453 4454 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx, 4455 ac->nodemask) { 4456 if (last_pgdat != zone->zone_pgdat) 4457 wakeup_kswapd(zone, gfp_mask, order, highest_zoneidx); 4458 last_pgdat = zone->zone_pgdat; 4459 } 4460} 4461 4462static inline unsigned int 4463gfp_to_alloc_flags(gfp_t gfp_mask) 4464{ 4465 unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET; 4466 4467 /* 4468 * __GFP_HIGH is assumed to be the same as ALLOC_HIGH 4469 * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD 4470 * to save two branches. 4471 */ 4472 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH); 4473 BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD); 4474 4475 /* 4476 * The caller may dip into page reserves a bit more if the caller 4477 * cannot run direct reclaim, or if the caller has realtime scheduling 4478 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will 4479 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH). 4480 */ 4481 alloc_flags |= (__force int) 4482 (gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM)); 4483 4484 if (gfp_mask & __GFP_ATOMIC) { 4485 /* 4486 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even 4487 * if it can't schedule. 4488 */ 4489 if (!(gfp_mask & __GFP_NOMEMALLOC)) 4490 alloc_flags |= ALLOC_HARDER; 4491 /* 4492 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the 4493 * comment for __cpuset_node_allowed(). 4494 */ 4495 alloc_flags &= ~ALLOC_CPUSET; 4496 } else if (unlikely(rt_task(current)) && !in_interrupt()) 4497 alloc_flags |= ALLOC_HARDER; 4498 4499 alloc_flags = current_alloc_flags(gfp_mask, alloc_flags); 4500 4501 return alloc_flags; 4502} 4503 4504static bool oom_reserves_allowed(struct task_struct *tsk) 4505{ 4506 if (!tsk_is_oom_victim(tsk)) 4507 return false; 4508 4509 /* 4510 * !MMU doesn't have oom reaper so give access to memory reserves 4511 * only to the thread with TIF_MEMDIE set 4512 */ 4513 if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE)) 4514 return false; 4515 4516 return true; 4517} 4518 4519/* 4520 * Distinguish requests which really need access to full memory 4521 * reserves from oom victims which can live with a portion of it 4522 */ 4523static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask) 4524{ 4525 if (unlikely(gfp_mask & __GFP_NOMEMALLOC)) 4526 return 0; 4527 if (gfp_mask & __GFP_MEMALLOC) 4528 return ALLOC_NO_WATERMARKS; 4529 if (in_serving_softirq() && (current->flags & PF_MEMALLOC)) 4530 return ALLOC_NO_WATERMARKS; 4531 if (!in_interrupt()) { 4532 if (current->flags & PF_MEMALLOC) 4533 return ALLOC_NO_WATERMARKS; 4534 else if (oom_reserves_allowed(current)) 4535 return ALLOC_OOM; 4536 } 4537 4538 return 0; 4539} 4540 4541bool gfp_pfmemalloc_allowed(gfp_t gfp_mask) 4542{ 4543 return !!__gfp_pfmemalloc_flags(gfp_mask); 4544} 4545 4546/* 4547 * Checks whether it makes sense to retry the reclaim to make a forward progress 4548 * for the given allocation request. 4549 * 4550 * We give up when we either have tried MAX_RECLAIM_RETRIES in a row 4551 * without success, or when we couldn't even meet the watermark if we 4552 * reclaimed all remaining pages on the LRU lists. 4553 * 4554 * Returns true if a retry is viable or false to enter the oom path. 4555 */ 4556static inline bool 4557should_reclaim_retry(gfp_t gfp_mask, unsigned order, 4558 struct alloc_context *ac, int alloc_flags, 4559 bool did_some_progress, int *no_progress_loops) 4560{ 4561 struct zone *zone; 4562 struct zoneref *z; 4563 bool ret = false; 4564 4565 /* 4566 * Costly allocations might have made a progress but this doesn't mean 4567 * their order will become available due to high fragmentation so 4568 * always increment the no progress counter for them 4569 */ 4570 if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER) 4571 *no_progress_loops = 0; 4572 else 4573 (*no_progress_loops)++; 4574 4575 /* 4576 * Make sure we converge to OOM if we cannot make any progress 4577 * several times in the row. 4578 */ 4579 if (*no_progress_loops > MAX_RECLAIM_RETRIES) { 4580 /* Before OOM, exhaust highatomic_reserve */ 4581 return unreserve_highatomic_pageblock(ac, true); 4582 } 4583 4584 /* 4585 * Keep reclaiming pages while there is a chance this will lead 4586 * somewhere. If none of the target zones can satisfy our allocation 4587 * request even if all reclaimable pages are considered then we are 4588 * screwed and have to go OOM. 4589 */ 4590 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, 4591 ac->highest_zoneidx, ac->nodemask) { 4592 unsigned long available; 4593 unsigned long reclaimable; 4594 unsigned long min_wmark = min_wmark_pages(zone); 4595 bool wmark; 4596 4597 available = reclaimable = zone_reclaimable_pages(zone); 4598 available += zone_page_state_snapshot(zone, NR_FREE_PAGES); 4599 4600 /* 4601 * Would the allocation succeed if we reclaimed all 4602 * reclaimable pages? 4603 */ 4604 wmark = __zone_watermark_ok(zone, order, min_wmark, 4605 ac->highest_zoneidx, alloc_flags, available); 4606 trace_reclaim_retry_zone(z, order, reclaimable, 4607 available, min_wmark, *no_progress_loops, wmark); 4608 if (wmark) { 4609 /* 4610 * If we didn't make any progress and have a lot of 4611 * dirty + writeback pages then we should wait for 4612 * an IO to complete to slow down the reclaim and 4613 * prevent from pre mature OOM 4614 */ 4615 if (!did_some_progress) { 4616 unsigned long write_pending; 4617 4618 write_pending = zone_page_state_snapshot(zone, 4619 NR_ZONE_WRITE_PENDING); 4620 4621 if (2 * write_pending > reclaimable) { 4622 congestion_wait(BLK_RW_ASYNC, HZ/10); 4623 return true; 4624 } 4625 } 4626 4627 ret = true; 4628 goto out; 4629 } 4630 } 4631 4632out: 4633 /* 4634 * Memory allocation/reclaim might be called from a WQ context and the 4635 * current implementation of the WQ concurrency control doesn't 4636 * recognize that a particular WQ is congested if the worker thread is 4637 * looping without ever sleeping. Therefore we have to do a short sleep 4638 * here rather than calling cond_resched(). 4639 */ 4640 if (current->flags & PF_WQ_WORKER) 4641 schedule_timeout_uninterruptible(1); 4642 else 4643 cond_resched(); 4644 return ret; 4645} 4646 4647static inline bool 4648check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac) 4649{ 4650 /* 4651 * It's possible that cpuset's mems_allowed and the nodemask from 4652 * mempolicy don't intersect. This should be normally dealt with by 4653 * policy_nodemask(), but it's possible to race with cpuset update in 4654 * such a way the check therein was true, and then it became false 4655 * before we got our cpuset_mems_cookie here. 4656 * This assumes that for all allocations, ac->nodemask can come only 4657 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored 4658 * when it does not intersect with the cpuset restrictions) or the 4659 * caller can deal with a violated nodemask. 4660 */ 4661 if (cpusets_enabled() && ac->nodemask && 4662 !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) { 4663 ac->nodemask = NULL; 4664 return true; 4665 } 4666 4667 /* 4668 * When updating a task's mems_allowed or mempolicy nodemask, it is 4669 * possible to race with parallel threads in such a way that our 4670 * allocation can fail while the mask is being updated. If we are about 4671 * to fail, check if the cpuset changed during allocation and if so, 4672 * retry. 4673 */ 4674 if (read_mems_allowed_retry(cpuset_mems_cookie)) 4675 return true; 4676 4677 return false; 4678} 4679 4680static inline struct page * 4681__alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order, 4682 struct alloc_context *ac) 4683{ 4684 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM; 4685 const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER; 4686 struct page *page = NULL; 4687 unsigned int alloc_flags; 4688 unsigned long did_some_progress; 4689 enum compact_priority compact_priority; 4690 enum compact_result compact_result; 4691 int compaction_retries; 4692 int no_progress_loops; 4693 unsigned int cpuset_mems_cookie; 4694 unsigned int zonelist_iter_cookie; 4695 int reserve_flags; 4696#ifdef CONFIG_RECLAIM_ACCT 4697 struct reclaim_acct ra = {0}; 4698#endif 4699 4700 /* 4701 * We also sanity check to catch abuse of atomic reserves being used by 4702 * callers that are not in atomic context. 4703 */ 4704 if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) == 4705 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM))) 4706 gfp_mask &= ~__GFP_ATOMIC; 4707 4708restart: 4709 compaction_retries = 0; 4710 no_progress_loops = 0; 4711 compact_priority = DEF_COMPACT_PRIORITY; 4712 cpuset_mems_cookie = read_mems_allowed_begin(); 4713 zonelist_iter_cookie = zonelist_iter_begin(); 4714 4715 /* 4716 * The fast path uses conservative alloc_flags to succeed only until 4717 * kswapd needs to be woken up, and to avoid the cost of setting up 4718 * alloc_flags precisely. So we do that now. 4719 */ 4720 alloc_flags = gfp_to_alloc_flags(gfp_mask); 4721 4722 /* 4723 * We need to recalculate the starting point for the zonelist iterator 4724 * because we might have used different nodemask in the fast path, or 4725 * there was a cpuset modification and we are retrying - otherwise we 4726 * could end up iterating over non-eligible zones endlessly. 4727 */ 4728 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist, 4729 ac->highest_zoneidx, ac->nodemask); 4730 if (!ac->preferred_zoneref->zone) 4731 goto nopage; 4732 4733 if (alloc_flags & ALLOC_KSWAPD) 4734 wake_all_kswapds(order, gfp_mask, ac); 4735 4736 /* 4737 * The adjusted alloc_flags might result in immediate success, so try 4738 * that first 4739 */ 4740 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 4741 if (page) 4742 goto got_pg; 4743 4744 /* 4745 * For costly allocations, try direct compaction first, as it's likely 4746 * that we have enough base pages and don't need to reclaim. For non- 4747 * movable high-order allocations, do that as well, as compaction will 4748 * try prevent permanent fragmentation by migrating from blocks of the 4749 * same migratetype. 4750 * Don't try this for allocations that are allowed to ignore 4751 * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen. 4752 */ 4753 if (can_direct_reclaim && 4754 (costly_order || 4755 (order > 0 && ac->migratetype != MIGRATE_MOVABLE)) 4756 && !gfp_pfmemalloc_allowed(gfp_mask)) { 4757 page = __alloc_pages_direct_compact(gfp_mask, order, 4758 alloc_flags, ac, 4759 INIT_COMPACT_PRIORITY, 4760 &compact_result); 4761 if (page) 4762 goto got_pg; 4763 4764 /* 4765 * Checks for costly allocations with __GFP_NORETRY, which 4766 * includes some THP page fault allocations 4767 */ 4768 if (costly_order && (gfp_mask & __GFP_NORETRY)) { 4769 /* 4770 * If allocating entire pageblock(s) and compaction 4771 * failed because all zones are below low watermarks 4772 * or is prohibited because it recently failed at this 4773 * order, fail immediately unless the allocator has 4774 * requested compaction and reclaim retry. 4775 * 4776 * Reclaim is 4777 * - potentially very expensive because zones are far 4778 * below their low watermarks or this is part of very 4779 * bursty high order allocations, 4780 * - not guaranteed to help because isolate_freepages() 4781 * may not iterate over freed pages as part of its 4782 * linear scan, and 4783 * - unlikely to make entire pageblocks free on its 4784 * own. 4785 */ 4786 if (compact_result == COMPACT_SKIPPED || 4787 compact_result == COMPACT_DEFERRED) 4788 goto nopage; 4789 4790 /* 4791 * Looks like reclaim/compaction is worth trying, but 4792 * sync compaction could be very expensive, so keep 4793 * using async compaction. 4794 */ 4795 compact_priority = INIT_COMPACT_PRIORITY; 4796 } 4797 } 4798 4799retry: 4800 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */ 4801 if (alloc_flags & ALLOC_KSWAPD) 4802 wake_all_kswapds(order, gfp_mask, ac); 4803 4804 reserve_flags = __gfp_pfmemalloc_flags(gfp_mask); 4805 if (reserve_flags) 4806 alloc_flags = current_alloc_flags(gfp_mask, reserve_flags); 4807 4808 /* 4809 * Reset the nodemask and zonelist iterators if memory policies can be 4810 * ignored. These allocations are high priority and system rather than 4811 * user oriented. 4812 */ 4813 if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) { 4814 ac->nodemask = NULL; 4815 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist, 4816 ac->highest_zoneidx, ac->nodemask); 4817 } 4818 4819 /* Attempt with potentially adjusted zonelist and alloc_flags */ 4820 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac); 4821 if (page) 4822 goto got_pg; 4823 4824 /* Caller is not willing to reclaim, we can't balance anything */ 4825 if (!can_direct_reclaim) 4826 goto nopage; 4827 4828 /* Avoid recursion of direct reclaim */ 4829 if (current->flags & PF_MEMALLOC) 4830 goto nopage; 4831 4832 /* Try direct reclaim and then allocating */ 4833#ifdef CONFIG_RECLAIM_ACCT 4834 reclaimacct_start(DIRECT_RECLAIMS, &ra); 4835#endif 4836 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac, 4837 &did_some_progress); 4838#ifdef CONFIG_RECLAIM_ACCT 4839 reclaimacct_end(DIRECT_RECLAIMS); 4840#endif 4841 if (page) 4842 goto got_pg; 4843 4844 /* Try direct compaction and then allocating */ 4845 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac, 4846 compact_priority, &compact_result); 4847 if (page) 4848 goto got_pg; 4849 4850 /* Do not loop if specifically requested */ 4851 if (gfp_mask & __GFP_NORETRY) 4852 goto nopage; 4853 4854 /* 4855 * Do not retry costly high order allocations unless they are 4856 * __GFP_RETRY_MAYFAIL 4857 */ 4858 if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL)) 4859 goto nopage; 4860 4861 if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags, 4862 did_some_progress > 0, &no_progress_loops)) 4863 goto retry; 4864 4865 /* 4866 * It doesn't make any sense to retry for the compaction if the order-0 4867 * reclaim is not able to make any progress because the current 4868 * implementation of the compaction depends on the sufficient amount 4869 * of free memory (see __compaction_suitable) 4870 */ 4871 if (did_some_progress > 0 && 4872 should_compact_retry(ac, order, alloc_flags, 4873 compact_result, &compact_priority, 4874 &compaction_retries)) 4875 goto retry; 4876 4877 4878 /* 4879 * Deal with possible cpuset update races or zonelist updates to avoid 4880 * a unnecessary OOM kill. 4881 */ 4882 if (check_retry_cpuset(cpuset_mems_cookie, ac) || 4883 check_retry_zonelist(zonelist_iter_cookie)) 4884 goto restart; 4885 4886 /* Reclaim has failed us, start killing things */ 4887 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress); 4888 if (page) 4889 goto got_pg; 4890 4891 /* Avoid allocations with no watermarks from looping endlessly */ 4892 if (tsk_is_oom_victim(current) && 4893 (alloc_flags & ALLOC_OOM || 4894 (gfp_mask & __GFP_NOMEMALLOC))) 4895 goto nopage; 4896 4897 /* Retry as long as the OOM killer is making progress */ 4898 if (did_some_progress) { 4899 no_progress_loops = 0; 4900 goto retry; 4901 } 4902 4903nopage: 4904 /* 4905 * Deal with possible cpuset update races or zonelist updates to avoid 4906 * a unnecessary OOM kill. 4907 */ 4908 if (check_retry_cpuset(cpuset_mems_cookie, ac) || 4909 check_retry_zonelist(zonelist_iter_cookie)) 4910 goto restart; 4911 4912 /* 4913 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure 4914 * we always retry 4915 */ 4916 if (gfp_mask & __GFP_NOFAIL) { 4917 /* 4918 * All existing users of the __GFP_NOFAIL are blockable, so warn 4919 * of any new users that actually require GFP_NOWAIT 4920 */ 4921 if (WARN_ON_ONCE(!can_direct_reclaim)) 4922 goto fail; 4923 4924 /* 4925 * PF_MEMALLOC request from this context is rather bizarre 4926 * because we cannot reclaim anything and only can loop waiting 4927 * for somebody to do a work for us 4928 */ 4929 WARN_ON_ONCE(current->flags & PF_MEMALLOC); 4930 4931 /* 4932 * non failing costly orders are a hard requirement which we 4933 * are not prepared for much so let's warn about these users 4934 * so that we can identify them and convert them to something 4935 * else. 4936 */ 4937 WARN_ON_ONCE(order > PAGE_ALLOC_COSTLY_ORDER); 4938 4939 /* 4940 * Help non-failing allocations by giving them access to memory 4941 * reserves but do not use ALLOC_NO_WATERMARKS because this 4942 * could deplete whole memory reserves which would just make 4943 * the situation worse 4944 */ 4945 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac); 4946 if (page) 4947 goto got_pg; 4948 4949 cond_resched(); 4950 goto retry; 4951 } 4952fail: 4953 warn_alloc(gfp_mask, ac->nodemask, 4954 "page allocation failure: order:%u", order); 4955got_pg: 4956 return page; 4957} 4958 4959static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order, 4960 int preferred_nid, nodemask_t *nodemask, 4961 struct alloc_context *ac, gfp_t *alloc_mask, 4962 unsigned int *alloc_flags) 4963{ 4964 ac->highest_zoneidx = gfp_zone(gfp_mask); 4965 ac->zonelist = node_zonelist(preferred_nid, gfp_mask); 4966 ac->nodemask = nodemask; 4967 ac->migratetype = gfp_migratetype(gfp_mask); 4968 4969 if (cpusets_enabled()) { 4970 *alloc_mask |= __GFP_HARDWALL; 4971 /* 4972 * When we are in the interrupt context, it is irrelevant 4973 * to the current task context. It means that any node ok. 4974 */ 4975 if (!in_interrupt() && !ac->nodemask) 4976 ac->nodemask = &cpuset_current_mems_allowed; 4977 else 4978 *alloc_flags |= ALLOC_CPUSET; 4979 } 4980 4981 fs_reclaim_acquire(gfp_mask); 4982 fs_reclaim_release(gfp_mask); 4983 4984 might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM); 4985 4986#ifdef CONFIG_HYPERHOLD_ZSWAPD 4987 if (gfp_mask & __GFP_KSWAPD_RECLAIM) 4988 wake_all_zswapd(); 4989#endif 4990 4991 if (should_fail_alloc_page(gfp_mask, order)) 4992 return false; 4993 4994 *alloc_flags = current_alloc_flags(gfp_mask, *alloc_flags); 4995 4996 /* Dirty zone balancing only done in the fast path */ 4997 ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE); 4998 4999 /* 5000 * The preferred zone is used for statistics but crucially it is 5001 * also used as the starting point for the zonelist iterator. It 5002 * may get reset for allocations that ignore memory policies. 5003 */ 5004 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist, 5005 ac->highest_zoneidx, ac->nodemask); 5006 5007 return true; 5008} 5009 5010/* 5011 * This is the 'heart' of the zoned buddy allocator. 5012 */ 5013struct page * 5014__alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order, int preferred_nid, 5015 nodemask_t *nodemask) 5016{ 5017 struct page *page; 5018 unsigned int alloc_flags = ALLOC_WMARK_LOW; 5019 gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */ 5020 struct alloc_context ac = { }; 5021 5022 /* 5023 * There are several places where we assume that the order value is sane 5024 * so bail out early if the request is out of bound. 5025 */ 5026 if (unlikely(order >= MAX_ORDER)) { 5027 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN)); 5028 return NULL; 5029 } 5030 5031 gfp_mask &= gfp_allowed_mask; 5032 alloc_mask = gfp_mask; 5033 if (!prepare_alloc_pages(gfp_mask, order, preferred_nid, nodemask, &ac, &alloc_mask, &alloc_flags)) 5034 return NULL; 5035 5036 /* 5037 * Forbid the first pass from falling back to types that fragment 5038 * memory until all local zones are considered. 5039 */ 5040 alloc_flags |= alloc_flags_nofragment(ac.preferred_zoneref->zone, gfp_mask); 5041 5042 /* First allocation attempt */ 5043 page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac); 5044 if (likely(page)) 5045 goto out; 5046 5047 /* 5048 * Apply scoped allocation constraints. This is mainly about GFP_NOFS 5049 * resp. GFP_NOIO which has to be inherited for all allocation requests 5050 * from a particular context which has been marked by 5051 * memalloc_no{fs,io}_{save,restore}. 5052 */ 5053 alloc_mask = current_gfp_context(gfp_mask); 5054 ac.spread_dirty_pages = false; 5055 5056 /* 5057 * Restore the original nodemask if it was potentially replaced with 5058 * &cpuset_current_mems_allowed to optimize the fast-path attempt. 5059 */ 5060 ac.nodemask = nodemask; 5061 5062 page = __alloc_pages_slowpath(alloc_mask, order, &ac); 5063 5064out: 5065 if (memcg_kmem_enabled() && (gfp_mask & __GFP_ACCOUNT) && page && 5066 unlikely(__memcg_kmem_charge_page(page, gfp_mask, order) != 0)) { 5067 __free_pages(page, order); 5068 page = NULL; 5069 } 5070 5071 trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype); 5072 5073 return page; 5074} 5075EXPORT_SYMBOL(__alloc_pages_nodemask); 5076 5077/* 5078 * Common helper functions. Never use with __GFP_HIGHMEM because the returned 5079 * address cannot represent highmem pages. Use alloc_pages and then kmap if 5080 * you need to access high mem. 5081 */ 5082unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order) 5083{ 5084 struct page *page; 5085 5086 page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order); 5087 if (!page) 5088 return 0; 5089 return (unsigned long) page_address(page); 5090} 5091EXPORT_SYMBOL(__get_free_pages); 5092 5093unsigned long get_zeroed_page(gfp_t gfp_mask) 5094{ 5095 return __get_free_pages(gfp_mask | __GFP_ZERO, 0); 5096} 5097EXPORT_SYMBOL(get_zeroed_page); 5098 5099static inline void free_the_page(struct page *page, unsigned int order) 5100{ 5101 if (order == 0) /* Via pcp? */ 5102 free_unref_page(page); 5103 else 5104 __free_pages_ok(page, order, FPI_NONE); 5105} 5106 5107void __free_pages(struct page *page, unsigned int order) 5108{ 5109 /* get PageHead before we drop reference */ 5110 int head = PageHead(page); 5111 5112 if (put_page_testzero(page)) 5113 free_the_page(page, order); 5114 else if (!head) 5115 while (order-- > 0) 5116 free_the_page(page + (1 << order), order); 5117} 5118EXPORT_SYMBOL(__free_pages); 5119 5120void free_pages(unsigned long addr, unsigned int order) 5121{ 5122 if (addr != 0) { 5123 VM_BUG_ON(!virt_addr_valid((void *)addr)); 5124 __free_pages(virt_to_page((void *)addr), order); 5125 } 5126} 5127 5128EXPORT_SYMBOL(free_pages); 5129 5130/* 5131 * Page Fragment: 5132 * An arbitrary-length arbitrary-offset area of memory which resides 5133 * within a 0 or higher order page. Multiple fragments within that page 5134 * are individually refcounted, in the page's reference counter. 5135 * 5136 * The page_frag functions below provide a simple allocation framework for 5137 * page fragments. This is used by the network stack and network device 5138 * drivers to provide a backing region of memory for use as either an 5139 * sk_buff->head, or to be used in the "frags" portion of skb_shared_info. 5140 */ 5141static struct page *__page_frag_cache_refill(struct page_frag_cache *nc, 5142 gfp_t gfp_mask) 5143{ 5144 struct page *page = NULL; 5145 gfp_t gfp = gfp_mask; 5146 5147#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE) 5148 gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY | 5149 __GFP_NOMEMALLOC; 5150 page = alloc_pages_node(NUMA_NO_NODE, gfp_mask, 5151 PAGE_FRAG_CACHE_MAX_ORDER); 5152 nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE; 5153#endif 5154 if (unlikely(!page)) 5155 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0); 5156 5157 nc->va = page ? page_address(page) : NULL; 5158 5159#ifdef CONFIG_PAGE_TRACING 5160 if (likely(page)) { 5161 int order = get_order(nc->size); 5162 int i; 5163 struct page *newpage = page; 5164 unsigned int deta = 1U << (unsigned int)order; 5165 5166 for (i = 0; i < (1 << order); i++) { 5167 if (!newpage) 5168 break; 5169 SetPageSKB(newpage); 5170 newpage++; 5171 } 5172 mod_zone_page_state(page_zone(page), NR_SKB_PAGES, (long)deta); 5173 } 5174#endif 5175 5176 return page; 5177} 5178 5179void __page_frag_cache_drain(struct page *page, unsigned int count) 5180{ 5181 VM_BUG_ON_PAGE(page_ref_count(page) == 0, page); 5182 5183 if (page_ref_sub_and_test(page, count)) { 5184#ifdef CONFIG_PAGE_TRACING 5185 if (likely(page)) { 5186 unsigned int deta = 1U << compound_order(page); 5187 5188 mod_zone_page_state(page_zone(page), NR_SKB_PAGES, -(long)deta); 5189 } 5190#endif 5191 free_the_page(page, compound_order(page)); 5192 } 5193} 5194EXPORT_SYMBOL(__page_frag_cache_drain); 5195 5196void *page_frag_alloc(struct page_frag_cache *nc, 5197 unsigned int fragsz, gfp_t gfp_mask) 5198{ 5199 unsigned int size = PAGE_SIZE; 5200 struct page *page; 5201 int offset; 5202 5203 if (unlikely(!nc->va)) { 5204refill: 5205 page = __page_frag_cache_refill(nc, gfp_mask); 5206 if (!page) 5207 return NULL; 5208 5209#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE) 5210 /* if size can vary use size else just use PAGE_SIZE */ 5211 size = nc->size; 5212#endif 5213 /* Even if we own the page, we do not use atomic_set(). 5214 * This would break get_page_unless_zero() users. 5215 */ 5216 page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE); 5217 5218 /* reset page count bias and offset to start of new frag */ 5219 nc->pfmemalloc = page_is_pfmemalloc(page); 5220 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1; 5221 nc->offset = size; 5222 } 5223 5224 offset = nc->offset - fragsz; 5225 if (unlikely(offset < 0)) { 5226 page = virt_to_page(nc->va); 5227 5228 if (!page_ref_sub_and_test(page, nc->pagecnt_bias)) 5229 goto refill; 5230 5231 if (unlikely(nc->pfmemalloc)) { 5232 free_the_page(page, compound_order(page)); 5233 goto refill; 5234 } 5235 5236#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE) 5237 /* if size can vary use size else just use PAGE_SIZE */ 5238 size = nc->size; 5239#endif 5240 /* OK, page count is 0, we can safely set it */ 5241 set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1); 5242 5243 /* reset page count bias and offset to start of new frag */ 5244 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1; 5245 offset = size - fragsz; 5246 if (unlikely(offset < 0)) { 5247 /* 5248 * The caller is trying to allocate a fragment 5249 * with fragsz > PAGE_SIZE but the cache isn't big 5250 * enough to satisfy the request, this may 5251 * happen in low memory conditions. 5252 * We don't release the cache page because 5253 * it could make memory pressure worse 5254 * so we simply return NULL here. 5255 */ 5256 return NULL; 5257 } 5258 } 5259 5260 nc->pagecnt_bias--; 5261 nc->offset = offset; 5262 5263 return nc->va + offset; 5264} 5265EXPORT_SYMBOL(page_frag_alloc); 5266 5267/* 5268 * Frees a page fragment allocated out of either a compound or order 0 page. 5269 */ 5270void page_frag_free(void *addr) 5271{ 5272 struct page *page = virt_to_head_page(addr); 5273 5274 if (unlikely(put_page_testzero(page))) { 5275#ifdef CONFIG_PAGE_TRACING 5276 if (likely(page)) { 5277 unsigned int deta = 1U << compound_order(page); 5278 5279 mod_zone_page_state(page_zone(page), NR_SKB_PAGES, -(long)deta); 5280 } 5281#endif 5282 free_the_page(page, compound_order(page)); 5283 } 5284} 5285EXPORT_SYMBOL(page_frag_free); 5286 5287static void *make_alloc_exact(unsigned long addr, unsigned int order, 5288 size_t size) 5289{ 5290 if (addr) { 5291 unsigned long alloc_end = addr + (PAGE_SIZE << order); 5292 unsigned long used = addr + PAGE_ALIGN(size); 5293 5294 split_page(virt_to_page((void *)addr), order); 5295 while (used < alloc_end) { 5296 free_page(used); 5297 used += PAGE_SIZE; 5298 } 5299 } 5300 return (void *)addr; 5301} 5302 5303/** 5304 * alloc_pages_exact - allocate an exact number physically-contiguous pages. 5305 * @size: the number of bytes to allocate 5306 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP 5307 * 5308 * This function is similar to alloc_pages(), except that it allocates the 5309 * minimum number of pages to satisfy the request. alloc_pages() can only 5310 * allocate memory in power-of-two pages. 5311 * 5312 * This function is also limited by MAX_ORDER. 5313 * 5314 * Memory allocated by this function must be released by free_pages_exact(). 5315 * 5316 * Return: pointer to the allocated area or %NULL in case of error. 5317 */ 5318void *alloc_pages_exact(size_t size, gfp_t gfp_mask) 5319{ 5320 unsigned int order = get_order(size); 5321 unsigned long addr; 5322 5323 if (WARN_ON_ONCE(gfp_mask & __GFP_COMP)) 5324 gfp_mask &= ~__GFP_COMP; 5325 5326 addr = __get_free_pages(gfp_mask, order); 5327 return make_alloc_exact(addr, order, size); 5328} 5329EXPORT_SYMBOL(alloc_pages_exact); 5330 5331/** 5332 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous 5333 * pages on a node. 5334 * @nid: the preferred node ID where memory should be allocated 5335 * @size: the number of bytes to allocate 5336 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP 5337 * 5338 * Like alloc_pages_exact(), but try to allocate on node nid first before falling 5339 * back. 5340 * 5341 * Return: pointer to the allocated area or %NULL in case of error. 5342 */ 5343void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask) 5344{ 5345 unsigned int order = get_order(size); 5346 struct page *p; 5347 5348 if (WARN_ON_ONCE(gfp_mask & __GFP_COMP)) 5349 gfp_mask &= ~__GFP_COMP; 5350 5351 p = alloc_pages_node(nid, gfp_mask, order); 5352 if (!p) 5353 return NULL; 5354 return make_alloc_exact((unsigned long)page_address(p), order, size); 5355} 5356 5357/** 5358 * free_pages_exact - release memory allocated via alloc_pages_exact() 5359 * @virt: the value returned by alloc_pages_exact. 5360 * @size: size of allocation, same value as passed to alloc_pages_exact(). 5361 * 5362 * Release the memory allocated by a previous call to alloc_pages_exact. 5363 */ 5364void free_pages_exact(void *virt, size_t size) 5365{ 5366 unsigned long addr = (unsigned long)virt; 5367 unsigned long end = addr + PAGE_ALIGN(size); 5368 5369 while (addr < end) { 5370 free_page(addr); 5371 addr += PAGE_SIZE; 5372 } 5373} 5374EXPORT_SYMBOL(free_pages_exact); 5375 5376/** 5377 * nr_free_zone_pages - count number of pages beyond high watermark 5378 * @offset: The zone index of the highest zone 5379 * 5380 * nr_free_zone_pages() counts the number of pages which are beyond the 5381 * high watermark within all zones at or below a given zone index. For each 5382 * zone, the number of pages is calculated as: 5383 * 5384 * nr_free_zone_pages = managed_pages - high_pages 5385 * 5386 * Return: number of pages beyond high watermark. 5387 */ 5388static unsigned long nr_free_zone_pages(int offset) 5389{ 5390 struct zoneref *z; 5391 struct zone *zone; 5392 5393 /* Just pick one node, since fallback list is circular */ 5394 unsigned long sum = 0; 5395 5396 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL); 5397 5398 for_each_zone_zonelist(zone, z, zonelist, offset) { 5399 unsigned long size = zone_managed_pages(zone); 5400 unsigned long high = high_wmark_pages(zone); 5401 if (size > high) 5402 sum += size - high; 5403 } 5404 5405 return sum; 5406} 5407 5408/** 5409 * nr_free_buffer_pages - count number of pages beyond high watermark 5410 * 5411 * nr_free_buffer_pages() counts the number of pages which are beyond the high 5412 * watermark within ZONE_DMA and ZONE_NORMAL. 5413 * 5414 * Return: number of pages beyond high watermark within ZONE_DMA and 5415 * ZONE_NORMAL. 5416 */ 5417unsigned long nr_free_buffer_pages(void) 5418{ 5419 return nr_free_zone_pages(gfp_zone(GFP_USER)); 5420} 5421EXPORT_SYMBOL_GPL(nr_free_buffer_pages); 5422 5423static inline void show_node(struct zone *zone) 5424{ 5425 if (IS_ENABLED(CONFIG_NUMA)) 5426 printk("Node %d ", zone_to_nid(zone)); 5427} 5428 5429long si_mem_available(void) 5430{ 5431 long available; 5432 unsigned long pagecache; 5433 unsigned long wmark_low = 0; 5434 unsigned long pages[NR_LRU_LISTS]; 5435 unsigned long reclaimable; 5436 struct zone *zone; 5437 int lru; 5438 5439 for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++) 5440 pages[lru] = global_node_page_state(NR_LRU_BASE + lru); 5441 5442 for_each_zone(zone) 5443 wmark_low += low_wmark_pages(zone); 5444 5445 /* 5446 * Estimate the amount of memory available for userspace allocations, 5447 * without causing swapping. 5448 */ 5449 available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages; 5450 5451 /* 5452 * Not all the page cache can be freed, otherwise the system will 5453 * start swapping. Assume at least half of the page cache, or the 5454 * low watermark worth of cache, needs to stay. 5455 */ 5456 pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE]; 5457 pagecache -= min(pagecache / 2, wmark_low); 5458 available += pagecache; 5459 5460 /* 5461 * Part of the reclaimable slab and other kernel memory consists of 5462 * items that are in use, and cannot be freed. Cap this estimate at the 5463 * low watermark. 5464 */ 5465 reclaimable = global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B) + 5466 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE); 5467 available += reclaimable - min(reclaimable / 2, wmark_low); 5468 5469 if (available < 0) 5470 available = 0; 5471 return available; 5472} 5473EXPORT_SYMBOL_GPL(si_mem_available); 5474 5475void si_meminfo(struct sysinfo *val) 5476{ 5477 val->totalram = totalram_pages(); 5478 val->sharedram = global_node_page_state(NR_SHMEM); 5479 val->freeram = global_zone_page_state(NR_FREE_PAGES); 5480 val->bufferram = nr_blockdev_pages(); 5481 val->totalhigh = totalhigh_pages(); 5482 val->freehigh = nr_free_highpages(); 5483 val->mem_unit = PAGE_SIZE; 5484} 5485 5486EXPORT_SYMBOL(si_meminfo); 5487 5488#ifdef CONFIG_NUMA 5489void si_meminfo_node(struct sysinfo *val, int nid) 5490{ 5491 int zone_type; /* needs to be signed */ 5492 unsigned long managed_pages = 0; 5493 unsigned long managed_highpages = 0; 5494 unsigned long free_highpages = 0; 5495 pg_data_t *pgdat = NODE_DATA(nid); 5496 5497 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) 5498 managed_pages += zone_managed_pages(&pgdat->node_zones[zone_type]); 5499 val->totalram = managed_pages; 5500 val->sharedram = node_page_state(pgdat, NR_SHMEM); 5501 val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES); 5502#ifdef CONFIG_HIGHMEM 5503 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) { 5504 struct zone *zone = &pgdat->node_zones[zone_type]; 5505 5506 if (is_highmem(zone)) { 5507 managed_highpages += zone_managed_pages(zone); 5508 free_highpages += zone_page_state(zone, NR_FREE_PAGES); 5509 } 5510 } 5511 val->totalhigh = managed_highpages; 5512 val->freehigh = free_highpages; 5513#else 5514 val->totalhigh = managed_highpages; 5515 val->freehigh = free_highpages; 5516#endif 5517 val->mem_unit = PAGE_SIZE; 5518} 5519#endif 5520 5521/* 5522 * Determine whether the node should be displayed or not, depending on whether 5523 * SHOW_MEM_FILTER_NODES was passed to show_free_areas(). 5524 */ 5525static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask) 5526{ 5527 if (!(flags & SHOW_MEM_FILTER_NODES)) 5528 return false; 5529 5530 /* 5531 * no node mask - aka implicit memory numa policy. Do not bother with 5532 * the synchronization - read_mems_allowed_begin - because we do not 5533 * have to be precise here. 5534 */ 5535 if (!nodemask) 5536 nodemask = &cpuset_current_mems_allowed; 5537 5538 return !node_isset(nid, *nodemask); 5539} 5540 5541#define K(x) ((x) << (PAGE_SHIFT-10)) 5542 5543static void show_migration_types(unsigned char type) 5544{ 5545 static const char types[MIGRATE_TYPES] = { 5546 [MIGRATE_UNMOVABLE] = 'U', 5547 [MIGRATE_MOVABLE] = 'M', 5548 [MIGRATE_RECLAIMABLE] = 'E', 5549 [MIGRATE_HIGHATOMIC] = 'H', 5550#ifdef CONFIG_CMA 5551 [MIGRATE_CMA] = 'C', 5552#endif 5553#ifdef CONFIG_MEMORY_ISOLATION 5554 [MIGRATE_ISOLATE] = 'I', 5555#endif 5556 }; 5557 char tmp[MIGRATE_TYPES + 1]; 5558 char *p = tmp; 5559 int i; 5560 5561 for (i = 0; i < MIGRATE_TYPES; i++) { 5562 if (type & (1 << i)) 5563 *p++ = types[i]; 5564 } 5565 5566 *p = '\0'; 5567 printk(KERN_CONT "(%s) ", tmp); 5568} 5569 5570/* 5571 * Show free area list (used inside shift_scroll-lock stuff) 5572 * We also calculate the percentage fragmentation. We do this by counting the 5573 * memory on each free list with the exception of the first item on the list. 5574 * 5575 * Bits in @filter: 5576 * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's 5577 * cpuset. 5578 */ 5579void show_free_areas(unsigned int filter, nodemask_t *nodemask) 5580{ 5581 unsigned long free_pcp = 0; 5582 int cpu; 5583 struct zone *zone; 5584 pg_data_t *pgdat; 5585 5586 for_each_populated_zone(zone) { 5587 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask)) 5588 continue; 5589 5590 for_each_online_cpu(cpu) 5591 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count; 5592 } 5593 5594 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n" 5595 " active_file:%lu inactive_file:%lu isolated_file:%lu\n" 5596 " unevictable:%lu dirty:%lu writeback:%lu\n" 5597 " slab_reclaimable:%lu slab_unreclaimable:%lu\n" 5598 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n" 5599 " free:%lu free_pcp:%lu free_cma:%lu\n", 5600 global_node_page_state(NR_ACTIVE_ANON), 5601 global_node_page_state(NR_INACTIVE_ANON), 5602 global_node_page_state(NR_ISOLATED_ANON), 5603 global_node_page_state(NR_ACTIVE_FILE), 5604 global_node_page_state(NR_INACTIVE_FILE), 5605 global_node_page_state(NR_ISOLATED_FILE), 5606 global_node_page_state(NR_UNEVICTABLE), 5607 global_node_page_state(NR_FILE_DIRTY), 5608 global_node_page_state(NR_WRITEBACK), 5609 global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B), 5610 global_node_page_state_pages(NR_SLAB_UNRECLAIMABLE_B), 5611 global_node_page_state(NR_FILE_MAPPED), 5612 global_node_page_state(NR_SHMEM), 5613 global_zone_page_state(NR_PAGETABLE), 5614 global_zone_page_state(NR_BOUNCE), 5615 global_zone_page_state(NR_FREE_PAGES), 5616 free_pcp, 5617 global_zone_page_state(NR_FREE_CMA_PAGES)); 5618 5619 for_each_online_pgdat(pgdat) { 5620 if (show_mem_node_skip(filter, pgdat->node_id, nodemask)) 5621 continue; 5622 5623 printk("Node %d" 5624 " active_anon:%lukB" 5625 " inactive_anon:%lukB" 5626 " active_file:%lukB" 5627 " inactive_file:%lukB" 5628 " unevictable:%lukB" 5629 " isolated(anon):%lukB" 5630 " isolated(file):%lukB" 5631 " mapped:%lukB" 5632 " dirty:%lukB" 5633 " writeback:%lukB" 5634 " shmem:%lukB" 5635#ifdef CONFIG_TRANSPARENT_HUGEPAGE 5636 " shmem_thp: %lukB" 5637 " shmem_pmdmapped: %lukB" 5638 " anon_thp: %lukB" 5639#endif 5640 " writeback_tmp:%lukB" 5641 " kernel_stack:%lukB" 5642#ifdef CONFIG_SHADOW_CALL_STACK 5643 " shadow_call_stack:%lukB" 5644#endif 5645 " all_unreclaimable? %s" 5646 "\n", 5647 pgdat->node_id, 5648 K(node_page_state(pgdat, NR_ACTIVE_ANON)), 5649 K(node_page_state(pgdat, NR_INACTIVE_ANON)), 5650 K(node_page_state(pgdat, NR_ACTIVE_FILE)), 5651 K(node_page_state(pgdat, NR_INACTIVE_FILE)), 5652 K(node_page_state(pgdat, NR_UNEVICTABLE)), 5653 K(node_page_state(pgdat, NR_ISOLATED_ANON)), 5654 K(node_page_state(pgdat, NR_ISOLATED_FILE)), 5655 K(node_page_state(pgdat, NR_FILE_MAPPED)), 5656 K(node_page_state(pgdat, NR_FILE_DIRTY)), 5657 K(node_page_state(pgdat, NR_WRITEBACK)), 5658 K(node_page_state(pgdat, NR_SHMEM)), 5659#ifdef CONFIG_TRANSPARENT_HUGEPAGE 5660 K(node_page_state(pgdat, NR_SHMEM_THPS) * HPAGE_PMD_NR), 5661 K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED) 5662 * HPAGE_PMD_NR), 5663 K(node_page_state(pgdat, NR_ANON_THPS) * HPAGE_PMD_NR), 5664#endif 5665 K(node_page_state(pgdat, NR_WRITEBACK_TEMP)), 5666 node_page_state(pgdat, NR_KERNEL_STACK_KB), 5667#ifdef CONFIG_SHADOW_CALL_STACK 5668 node_page_state(pgdat, NR_KERNEL_SCS_KB), 5669#endif 5670 pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ? 5671 "yes" : "no"); 5672 } 5673 5674 for_each_populated_zone(zone) { 5675 int i; 5676 5677 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask)) 5678 continue; 5679 5680 free_pcp = 0; 5681 for_each_online_cpu(cpu) 5682 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count; 5683 5684 show_node(zone); 5685 printk(KERN_CONT 5686 "%s" 5687 " free:%lukB" 5688 " min:%lukB" 5689 " low:%lukB" 5690 " high:%lukB" 5691 " reserved_highatomic:%luKB" 5692 " active_anon:%lukB" 5693 " inactive_anon:%lukB" 5694 " active_file:%lukB" 5695 " inactive_file:%lukB" 5696 " unevictable:%lukB" 5697 " writepending:%lukB" 5698 " present:%lukB" 5699 " managed:%lukB" 5700 " mlocked:%lukB" 5701 " pagetables:%lukB" 5702 " bounce:%lukB" 5703 " free_pcp:%lukB" 5704 " local_pcp:%ukB" 5705 " free_cma:%lukB" 5706 "\n", 5707 zone->name, 5708 K(zone_page_state(zone, NR_FREE_PAGES)), 5709 K(min_wmark_pages(zone)), 5710 K(low_wmark_pages(zone)), 5711 K(high_wmark_pages(zone)), 5712 K(zone->nr_reserved_highatomic), 5713 K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)), 5714 K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)), 5715 K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)), 5716 K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)), 5717 K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)), 5718 K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)), 5719 K(zone->present_pages), 5720 K(zone_managed_pages(zone)), 5721 K(zone_page_state(zone, NR_MLOCK)), 5722 K(zone_page_state(zone, NR_PAGETABLE)), 5723 K(zone_page_state(zone, NR_BOUNCE)), 5724 K(free_pcp), 5725 K(this_cpu_read(zone->pageset->pcp.count)), 5726 K(zone_page_state(zone, NR_FREE_CMA_PAGES))); 5727 printk("lowmem_reserve[]:"); 5728 for (i = 0; i < MAX_NR_ZONES; i++) 5729 printk(KERN_CONT " %ld", zone->lowmem_reserve[i]); 5730 printk(KERN_CONT "\n"); 5731 } 5732 5733 for_each_populated_zone(zone) { 5734 unsigned int order; 5735 unsigned long nr[MAX_ORDER], flags, total = 0; 5736 unsigned char types[MAX_ORDER]; 5737 5738 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask)) 5739 continue; 5740 show_node(zone); 5741 printk(KERN_CONT "%s: ", zone->name); 5742 5743 spin_lock_irqsave(&zone->lock, flags); 5744 for (order = 0; order < MAX_ORDER; order++) { 5745 struct free_area *area = &zone->free_area[order]; 5746 int type; 5747 5748 nr[order] = area->nr_free; 5749 total += nr[order] << order; 5750 5751 types[order] = 0; 5752 for (type = 0; type < MIGRATE_TYPES; type++) { 5753 if (!free_area_empty(area, type)) 5754 types[order] |= 1 << type; 5755 } 5756 } 5757 spin_unlock_irqrestore(&zone->lock, flags); 5758 for (order = 0; order < MAX_ORDER; order++) { 5759 printk(KERN_CONT "%lu*%lukB ", 5760 nr[order], K(1UL) << order); 5761 if (nr[order]) 5762 show_migration_types(types[order]); 5763 } 5764 printk(KERN_CONT "= %lukB\n", K(total)); 5765 } 5766 5767 hugetlb_show_meminfo(); 5768 5769 printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES)); 5770 5771 show_swap_cache_info(); 5772} 5773 5774static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref) 5775{ 5776 zoneref->zone = zone; 5777 zoneref->zone_idx = zone_idx(zone); 5778} 5779 5780/* 5781 * Builds allocation fallback zone lists. 5782 * 5783 * Add all populated zones of a node to the zonelist. 5784 */ 5785static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs) 5786{ 5787 struct zone *zone; 5788 enum zone_type zone_type = MAX_NR_ZONES; 5789 int nr_zones = 0; 5790 5791 do { 5792 zone_type--; 5793 zone = pgdat->node_zones + zone_type; 5794 if (populated_zone(zone)) { 5795 zoneref_set_zone(zone, &zonerefs[nr_zones++]); 5796 check_highest_zone(zone_type); 5797 } 5798 } while (zone_type); 5799 5800 return nr_zones; 5801} 5802 5803#ifdef CONFIG_NUMA 5804 5805static int __parse_numa_zonelist_order(char *s) 5806{ 5807 /* 5808 * We used to support different zonlists modes but they turned 5809 * out to be just not useful. Let's keep the warning in place 5810 * if somebody still use the cmd line parameter so that we do 5811 * not fail it silently 5812 */ 5813 if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) { 5814 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s); 5815 return -EINVAL; 5816 } 5817 return 0; 5818} 5819 5820char numa_zonelist_order[] = "Node"; 5821 5822/* 5823 * sysctl handler for numa_zonelist_order 5824 */ 5825int numa_zonelist_order_handler(struct ctl_table *table, int write, 5826 void *buffer, size_t *length, loff_t *ppos) 5827{ 5828 if (write) 5829 return __parse_numa_zonelist_order(buffer); 5830 return proc_dostring(table, write, buffer, length, ppos); 5831} 5832 5833 5834#define MAX_NODE_LOAD (nr_online_nodes) 5835static int node_load[MAX_NUMNODES]; 5836 5837/** 5838 * find_next_best_node - find the next node that should appear in a given node's fallback list 5839 * @node: node whose fallback list we're appending 5840 * @used_node_mask: nodemask_t of already used nodes 5841 * 5842 * We use a number of factors to determine which is the next node that should 5843 * appear on a given node's fallback list. The node should not have appeared 5844 * already in @node's fallback list, and it should be the next closest node 5845 * according to the distance array (which contains arbitrary distance values 5846 * from each node to each node in the system), and should also prefer nodes 5847 * with no CPUs, since presumably they'll have very little allocation pressure 5848 * on them otherwise. 5849 * 5850 * Return: node id of the found node or %NUMA_NO_NODE if no node is found. 5851 */ 5852static int find_next_best_node(int node, nodemask_t *used_node_mask) 5853{ 5854 int n, val; 5855 int min_val = INT_MAX; 5856 int best_node = NUMA_NO_NODE; 5857 5858 /* Use the local node if we haven't already */ 5859 if (!node_isset(node, *used_node_mask)) { 5860 node_set(node, *used_node_mask); 5861 return node; 5862 } 5863 5864 for_each_node_state(n, N_MEMORY) { 5865 5866 /* Don't want a node to appear more than once */ 5867 if (node_isset(n, *used_node_mask)) 5868 continue; 5869 5870 /* Use the distance array to find the distance */ 5871 val = node_distance(node, n); 5872 5873 /* Penalize nodes under us ("prefer the next node") */ 5874 val += (n < node); 5875 5876 /* Give preference to headless and unused nodes */ 5877 if (!cpumask_empty(cpumask_of_node(n))) 5878 val += PENALTY_FOR_NODE_WITH_CPUS; 5879 5880 /* Slight preference for less loaded node */ 5881 val *= (MAX_NODE_LOAD*MAX_NUMNODES); 5882 val += node_load[n]; 5883 5884 if (val < min_val) { 5885 min_val = val; 5886 best_node = n; 5887 } 5888 } 5889 5890 if (best_node >= 0) 5891 node_set(best_node, *used_node_mask); 5892 5893 return best_node; 5894} 5895 5896 5897/* 5898 * Build zonelists ordered by node and zones within node. 5899 * This results in maximum locality--normal zone overflows into local 5900 * DMA zone, if any--but risks exhausting DMA zone. 5901 */ 5902static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order, 5903 unsigned nr_nodes) 5904{ 5905 struct zoneref *zonerefs; 5906 int i; 5907 5908 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs; 5909 5910 for (i = 0; i < nr_nodes; i++) { 5911 int nr_zones; 5912 5913 pg_data_t *node = NODE_DATA(node_order[i]); 5914 5915 nr_zones = build_zonerefs_node(node, zonerefs); 5916 zonerefs += nr_zones; 5917 } 5918 zonerefs->zone = NULL; 5919 zonerefs->zone_idx = 0; 5920} 5921 5922/* 5923 * Build gfp_thisnode zonelists 5924 */ 5925static void build_thisnode_zonelists(pg_data_t *pgdat) 5926{ 5927 struct zoneref *zonerefs; 5928 int nr_zones; 5929 5930 zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs; 5931 nr_zones = build_zonerefs_node(pgdat, zonerefs); 5932 zonerefs += nr_zones; 5933 zonerefs->zone = NULL; 5934 zonerefs->zone_idx = 0; 5935} 5936 5937/* 5938 * Build zonelists ordered by zone and nodes within zones. 5939 * This results in conserving DMA zone[s] until all Normal memory is 5940 * exhausted, but results in overflowing to remote node while memory 5941 * may still exist in local DMA zone. 5942 */ 5943 5944static void build_zonelists(pg_data_t *pgdat) 5945{ 5946 static int node_order[MAX_NUMNODES]; 5947 int node, load, nr_nodes = 0; 5948 nodemask_t used_mask = NODE_MASK_NONE; 5949 int local_node, prev_node; 5950 5951 /* NUMA-aware ordering of nodes */ 5952 local_node = pgdat->node_id; 5953 load = nr_online_nodes; 5954 prev_node = local_node; 5955 5956 memset(node_order, 0, sizeof(node_order)); 5957 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) { 5958 /* 5959 * We don't want to pressure a particular node. 5960 * So adding penalty to the first node in same 5961 * distance group to make it round-robin. 5962 */ 5963 if (node_distance(local_node, node) != 5964 node_distance(local_node, prev_node)) 5965 node_load[node] = load; 5966 5967 node_order[nr_nodes++] = node; 5968 prev_node = node; 5969 load--; 5970 } 5971 5972 build_zonelists_in_node_order(pgdat, node_order, nr_nodes); 5973 build_thisnode_zonelists(pgdat); 5974} 5975 5976#ifdef CONFIG_HAVE_MEMORYLESS_NODES 5977/* 5978 * Return node id of node used for "local" allocations. 5979 * I.e., first node id of first zone in arg node's generic zonelist. 5980 * Used for initializing percpu 'numa_mem', which is used primarily 5981 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist. 5982 */ 5983int local_memory_node(int node) 5984{ 5985 struct zoneref *z; 5986 5987 z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL), 5988 gfp_zone(GFP_KERNEL), 5989 NULL); 5990 return zone_to_nid(z->zone); 5991} 5992#endif 5993 5994static void setup_min_unmapped_ratio(void); 5995static void setup_min_slab_ratio(void); 5996#else /* CONFIG_NUMA */ 5997 5998static void build_zonelists(pg_data_t *pgdat) 5999{ 6000 int node, local_node; 6001 struct zoneref *zonerefs; 6002 int nr_zones; 6003 6004 local_node = pgdat->node_id; 6005 6006 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs; 6007 nr_zones = build_zonerefs_node(pgdat, zonerefs); 6008 zonerefs += nr_zones; 6009 6010 /* 6011 * Now we build the zonelist so that it contains the zones 6012 * of all the other nodes. 6013 * We don't want to pressure a particular node, so when 6014 * building the zones for node N, we make sure that the 6015 * zones coming right after the local ones are those from 6016 * node N+1 (modulo N) 6017 */ 6018 for (node = local_node + 1; node < MAX_NUMNODES; node++) { 6019 if (!node_online(node)) 6020 continue; 6021 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs); 6022 zonerefs += nr_zones; 6023 } 6024 for (node = 0; node < local_node; node++) { 6025 if (!node_online(node)) 6026 continue; 6027 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs); 6028 zonerefs += nr_zones; 6029 } 6030 6031 zonerefs->zone = NULL; 6032 zonerefs->zone_idx = 0; 6033} 6034 6035#endif /* CONFIG_NUMA */ 6036 6037/* 6038 * Boot pageset table. One per cpu which is going to be used for all 6039 * zones and all nodes. The parameters will be set in such a way 6040 * that an item put on a list will immediately be handed over to 6041 * the buddy list. This is safe since pageset manipulation is done 6042 * with interrupts disabled. 6043 * 6044 * The boot_pagesets must be kept even after bootup is complete for 6045 * unused processors and/or zones. They do play a role for bootstrapping 6046 * hotplugged processors. 6047 * 6048 * zoneinfo_show() and maybe other functions do 6049 * not check if the processor is online before following the pageset pointer. 6050 * Other parts of the kernel may not check if the zone is available. 6051 */ 6052static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch); 6053static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset); 6054static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats); 6055 6056static void __build_all_zonelists(void *data) 6057{ 6058 int nid; 6059 int __maybe_unused cpu; 6060 pg_data_t *self = data; 6061 unsigned long flags; 6062 6063 /* 6064 * Explicitly disable this CPU's interrupts before taking seqlock 6065 * to prevent any IRQ handler from calling into the page allocator 6066 * (e.g. GFP_ATOMIC) that could hit zonelist_iter_begin and livelock. 6067 */ 6068 local_irq_save(flags); 6069 /* 6070 * Explicitly disable this CPU's synchronous printk() before taking 6071 * seqlock to prevent any printk() from trying to hold port->lock, for 6072 * tty_insert_flip_string_and_push_buffer() on other CPU might be 6073 * calling kmalloc(GFP_ATOMIC | __GFP_NOWARN) with port->lock held. 6074 */ 6075 printk_deferred_enter(); 6076 write_seqlock(&zonelist_update_seq); 6077 6078#ifdef CONFIG_NUMA 6079 memset(node_load, 0, sizeof(node_load)); 6080#endif 6081 6082 /* 6083 * This node is hotadded and no memory is yet present. So just 6084 * building zonelists is fine - no need to touch other nodes. 6085 */ 6086 if (self && !node_online(self->node_id)) { 6087 build_zonelists(self); 6088 } else { 6089 for_each_online_node(nid) { 6090 pg_data_t *pgdat = NODE_DATA(nid); 6091 6092 build_zonelists(pgdat); 6093 } 6094 6095#ifdef CONFIG_HAVE_MEMORYLESS_NODES 6096 /* 6097 * We now know the "local memory node" for each node-- 6098 * i.e., the node of the first zone in the generic zonelist. 6099 * Set up numa_mem percpu variable for on-line cpus. During 6100 * boot, only the boot cpu should be on-line; we'll init the 6101 * secondary cpus' numa_mem as they come on-line. During 6102 * node/memory hotplug, we'll fixup all on-line cpus. 6103 */ 6104 for_each_online_cpu(cpu) 6105 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu))); 6106#endif 6107 } 6108 6109 write_sequnlock(&zonelist_update_seq); 6110 printk_deferred_exit(); 6111 local_irq_restore(flags); 6112} 6113 6114static noinline void __init 6115build_all_zonelists_init(void) 6116{ 6117 int cpu; 6118 6119 __build_all_zonelists(NULL); 6120 6121 /* 6122 * Initialize the boot_pagesets that are going to be used 6123 * for bootstrapping processors. The real pagesets for 6124 * each zone will be allocated later when the per cpu 6125 * allocator is available. 6126 * 6127 * boot_pagesets are used also for bootstrapping offline 6128 * cpus if the system is already booted because the pagesets 6129 * are needed to initialize allocators on a specific cpu too. 6130 * F.e. the percpu allocator needs the page allocator which 6131 * needs the percpu allocator in order to allocate its pagesets 6132 * (a chicken-egg dilemma). 6133 */ 6134 for_each_possible_cpu(cpu) 6135 setup_pageset(&per_cpu(boot_pageset, cpu), 0); 6136 6137 mminit_verify_zonelist(); 6138 cpuset_init_current_mems_allowed(); 6139} 6140 6141/* 6142 * unless system_state == SYSTEM_BOOTING. 6143 * 6144 * __ref due to call of __init annotated helper build_all_zonelists_init 6145 * [protected by SYSTEM_BOOTING]. 6146 */ 6147void __ref build_all_zonelists(pg_data_t *pgdat) 6148{ 6149 unsigned long vm_total_pages; 6150 6151 if (system_state == SYSTEM_BOOTING) { 6152 build_all_zonelists_init(); 6153 } else { 6154 __build_all_zonelists(pgdat); 6155 /* cpuset refresh routine should be here */ 6156 } 6157 /* Get the number of free pages beyond high watermark in all zones. */ 6158 vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE)); 6159 /* 6160 * Disable grouping by mobility if the number of pages in the 6161 * system is too low to allow the mechanism to work. It would be 6162 * more accurate, but expensive to check per-zone. This check is 6163 * made on memory-hotadd so a system can start with mobility 6164 * disabled and enable it later 6165 */ 6166 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES)) 6167 page_group_by_mobility_disabled = 1; 6168 else 6169 page_group_by_mobility_disabled = 0; 6170 6171 pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n", 6172 nr_online_nodes, 6173 page_group_by_mobility_disabled ? "off" : "on", 6174 vm_total_pages); 6175#ifdef CONFIG_NUMA 6176 pr_info("Policy zone: %s\n", zone_names[policy_zone]); 6177#endif 6178} 6179 6180/* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */ 6181static bool __meminit 6182overlap_memmap_init(unsigned long zone, unsigned long *pfn) 6183{ 6184 static struct memblock_region *r; 6185 6186 if (mirrored_kernelcore && zone == ZONE_MOVABLE) { 6187 if (!r || *pfn >= memblock_region_memory_end_pfn(r)) { 6188 for_each_mem_region(r) { 6189 if (*pfn < memblock_region_memory_end_pfn(r)) 6190 break; 6191 } 6192 } 6193 if (*pfn >= memblock_region_memory_base_pfn(r) && 6194 memblock_is_mirror(r)) { 6195 *pfn = memblock_region_memory_end_pfn(r); 6196 return true; 6197 } 6198 } 6199 return false; 6200} 6201 6202/* 6203 * Initially all pages are reserved - free ones are freed 6204 * up by memblock_free_all() once the early boot process is 6205 * done. Non-atomic initialization, single-pass. 6206 * 6207 * All aligned pageblocks are initialized to the specified migratetype 6208 * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related 6209 * zone stats (e.g., nr_isolate_pageblock) are touched. 6210 */ 6211void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone, 6212 unsigned long start_pfn, unsigned long zone_end_pfn, 6213 enum meminit_context context, 6214 struct vmem_altmap *altmap, int migratetype) 6215{ 6216 unsigned long pfn, end_pfn = start_pfn + size; 6217 struct page *page; 6218 6219 if (highest_memmap_pfn < end_pfn - 1) 6220 highest_memmap_pfn = end_pfn - 1; 6221 6222#ifdef CONFIG_ZONE_DEVICE 6223 /* 6224 * Honor reservation requested by the driver for this ZONE_DEVICE 6225 * memory. We limit the total number of pages to initialize to just 6226 * those that might contain the memory mapping. We will defer the 6227 * ZONE_DEVICE page initialization until after we have released 6228 * the hotplug lock. 6229 */ 6230 if (zone == ZONE_DEVICE) { 6231 if (!altmap) 6232 return; 6233 6234 if (start_pfn == altmap->base_pfn) 6235 start_pfn += altmap->reserve; 6236 end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap); 6237 } 6238#endif 6239 6240 for (pfn = start_pfn; pfn < end_pfn; ) { 6241 /* 6242 * There can be holes in boot-time mem_map[]s handed to this 6243 * function. They do not exist on hotplugged memory. 6244 */ 6245 if (context == MEMINIT_EARLY) { 6246 if (overlap_memmap_init(zone, &pfn)) 6247 continue; 6248 if (defer_init(nid, pfn, zone_end_pfn)) 6249 break; 6250 } 6251 6252 page = pfn_to_page(pfn); 6253 __init_single_page(page, pfn, zone, nid); 6254 if (context == MEMINIT_HOTPLUG) 6255 __SetPageReserved(page); 6256 6257 /* 6258 * Usually, we want to mark the pageblock MIGRATE_MOVABLE, 6259 * such that unmovable allocations won't be scattered all 6260 * over the place during system boot. 6261 */ 6262 if (IS_ALIGNED(pfn, pageblock_nr_pages)) { 6263 set_pageblock_migratetype(page, migratetype); 6264 cond_resched(); 6265 } 6266 pfn++; 6267 } 6268} 6269 6270#ifdef CONFIG_ZONE_DEVICE 6271void __ref memmap_init_zone_device(struct zone *zone, 6272 unsigned long start_pfn, 6273 unsigned long nr_pages, 6274 struct dev_pagemap *pgmap) 6275{ 6276 unsigned long pfn, end_pfn = start_pfn + nr_pages; 6277 struct pglist_data *pgdat = zone->zone_pgdat; 6278 struct vmem_altmap *altmap = pgmap_altmap(pgmap); 6279 unsigned long zone_idx = zone_idx(zone); 6280 unsigned long start = jiffies; 6281 int nid = pgdat->node_id; 6282 6283 if (WARN_ON_ONCE(!pgmap || zone_idx(zone) != ZONE_DEVICE)) 6284 return; 6285 6286 /* 6287 * The call to memmap_init should have already taken care 6288 * of the pages reserved for the memmap, so we can just jump to 6289 * the end of that region and start processing the device pages. 6290 */ 6291 if (altmap) { 6292 start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap); 6293 nr_pages = end_pfn - start_pfn; 6294 } 6295 6296 for (pfn = start_pfn; pfn < end_pfn; pfn++) { 6297 struct page *page = pfn_to_page(pfn); 6298 6299 __init_single_page(page, pfn, zone_idx, nid); 6300 6301 /* 6302 * Mark page reserved as it will need to wait for onlining 6303 * phase for it to be fully associated with a zone. 6304 * 6305 * We can use the non-atomic __set_bit operation for setting 6306 * the flag as we are still initializing the pages. 6307 */ 6308 __SetPageReserved(page); 6309 6310 /* 6311 * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer 6312 * and zone_device_data. It is a bug if a ZONE_DEVICE page is 6313 * ever freed or placed on a driver-private list. 6314 */ 6315 page->pgmap = pgmap; 6316 page->zone_device_data = NULL; 6317 6318 /* 6319 * Mark the block movable so that blocks are reserved for 6320 * movable at startup. This will force kernel allocations 6321 * to reserve their blocks rather than leaking throughout 6322 * the address space during boot when many long-lived 6323 * kernel allocations are made. 6324 * 6325 * Please note that MEMINIT_HOTPLUG path doesn't clear memmap 6326 * because this is done early in section_activate() 6327 */ 6328 if (IS_ALIGNED(pfn, pageblock_nr_pages)) { 6329 set_pageblock_migratetype(page, MIGRATE_MOVABLE); 6330 cond_resched(); 6331 } 6332 } 6333 6334 pr_info("%s initialised %lu pages in %ums\n", __func__, 6335 nr_pages, jiffies_to_msecs(jiffies - start)); 6336} 6337 6338#endif 6339static void __meminit zone_init_free_lists(struct zone *zone) 6340{ 6341 unsigned int order, t; 6342 for_each_migratetype_order(order, t) { 6343 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]); 6344 zone->free_area[order].nr_free = 0; 6345 } 6346} 6347 6348#if !defined(CONFIG_FLAT_NODE_MEM_MAP) 6349/* 6350 * Only struct pages that correspond to ranges defined by memblock.memory 6351 * are zeroed and initialized by going through __init_single_page() during 6352 * memmap_init_zone_range(). 6353 * 6354 * But, there could be struct pages that correspond to holes in 6355 * memblock.memory. This can happen because of the following reasons: 6356 * - physical memory bank size is not necessarily the exact multiple of the 6357 * arbitrary section size 6358 * - early reserved memory may not be listed in memblock.memory 6359 * - memory layouts defined with memmap= kernel parameter may not align 6360 * nicely with memmap sections 6361 * 6362 * Explicitly initialize those struct pages so that: 6363 * - PG_Reserved is set 6364 * - zone and node links point to zone and node that span the page if the 6365 * hole is in the middle of a zone 6366 * - zone and node links point to adjacent zone/node if the hole falls on 6367 * the zone boundary; the pages in such holes will be prepended to the 6368 * zone/node above the hole except for the trailing pages in the last 6369 * section that will be appended to the zone/node below. 6370 */ 6371static void __init init_unavailable_range(unsigned long spfn, 6372 unsigned long epfn, 6373 int zone, int node) 6374{ 6375 unsigned long pfn; 6376 u64 pgcnt = 0; 6377 6378 for (pfn = spfn; pfn < epfn; pfn++) { 6379 if (!pfn_valid(ALIGN_DOWN(pfn, pageblock_nr_pages))) { 6380 pfn = ALIGN_DOWN(pfn, pageblock_nr_pages) 6381 + pageblock_nr_pages - 1; 6382 continue; 6383 } 6384 __init_single_page(pfn_to_page(pfn), pfn, zone, node); 6385 __SetPageReserved(pfn_to_page(pfn)); 6386 pgcnt++; 6387 } 6388 6389 if (pgcnt) 6390 pr_info("On node %d, zone %s: %lld pages in unavailable ranges", 6391 node, zone_names[zone], pgcnt); 6392} 6393#else 6394static inline void init_unavailable_range(unsigned long spfn, 6395 unsigned long epfn, 6396 int zone, int node) 6397{ 6398} 6399#endif 6400 6401static void __init memmap_init_zone_range(struct zone *zone, 6402 unsigned long start_pfn, 6403 unsigned long end_pfn, 6404 unsigned long *hole_pfn) 6405{ 6406 unsigned long zone_start_pfn = zone->zone_start_pfn; 6407 unsigned long zone_end_pfn = zone_start_pfn + zone->spanned_pages; 6408 int nid = zone_to_nid(zone), zone_id = zone_idx(zone); 6409 6410 start_pfn = clamp(start_pfn, zone_start_pfn, zone_end_pfn); 6411 end_pfn = clamp(end_pfn, zone_start_pfn, zone_end_pfn); 6412 6413 if (start_pfn >= end_pfn) 6414 return; 6415 6416 memmap_init_zone(end_pfn - start_pfn, nid, zone_id, start_pfn, 6417 zone_end_pfn, MEMINIT_EARLY, NULL, MIGRATE_MOVABLE); 6418 6419 if (*hole_pfn < start_pfn) 6420 init_unavailable_range(*hole_pfn, start_pfn, zone_id, nid); 6421 6422 *hole_pfn = end_pfn; 6423} 6424 6425void __init __weak memmap_init(void) 6426{ 6427 unsigned long start_pfn, end_pfn; 6428 unsigned long hole_pfn = 0; 6429 int i, j, zone_id, nid; 6430 6431 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) { 6432 struct pglist_data *node = NODE_DATA(nid); 6433 6434 for (j = 0; j < MAX_NR_ZONES; j++) { 6435 struct zone *zone = node->node_zones + j; 6436 6437 if (!populated_zone(zone)) 6438 continue; 6439 6440 memmap_init_zone_range(zone, start_pfn, end_pfn, 6441 &hole_pfn); 6442 zone_id = j; 6443 } 6444 } 6445 6446#ifdef CONFIG_SPARSEMEM 6447 /* 6448 * Initialize the memory map for hole in the range [memory_end, 6449 * section_end]. 6450 * Append the pages in this hole to the highest zone in the last 6451 * node. 6452 * The call to init_unavailable_range() is outside the ifdef to 6453 * silence the compiler warining about zone_id set but not used; 6454 * for FLATMEM it is a nop anyway 6455 */ 6456 end_pfn = round_up(end_pfn, PAGES_PER_SECTION); 6457 if (hole_pfn < end_pfn) 6458#endif 6459 init_unavailable_range(hole_pfn, end_pfn, zone_id, nid); 6460} 6461 6462/* A stub for backwards compatibility with custom implementatin on IA-64 */ 6463void __meminit __weak arch_memmap_init(unsigned long size, int nid, 6464 unsigned long zone, 6465 unsigned long range_start_pfn) 6466{ 6467} 6468 6469static int zone_batchsize(struct zone *zone) 6470{ 6471#ifdef CONFIG_MMU 6472 int batch; 6473 6474 /* 6475 * The per-cpu-pages pools are set to around 1000th of the 6476 * size of the zone. 6477 */ 6478 batch = zone_managed_pages(zone) / 1024; 6479 /* But no more than a meg. */ 6480 if (batch * PAGE_SIZE > 1024 * 1024) 6481 batch = (1024 * 1024) / PAGE_SIZE; 6482 batch /= 4; /* We effectively *= 4 below */ 6483 if (batch < 1) 6484 batch = 1; 6485 6486 /* 6487 * Clamp the batch to a 2^n - 1 value. Having a power 6488 * of 2 value was found to be more likely to have 6489 * suboptimal cache aliasing properties in some cases. 6490 * 6491 * For example if 2 tasks are alternately allocating 6492 * batches of pages, one task can end up with a lot 6493 * of pages of one half of the possible page colors 6494 * and the other with pages of the other colors. 6495 */ 6496 batch = rounddown_pow_of_two(batch + batch/2) - 1; 6497 6498 return batch; 6499 6500#else 6501 /* The deferral and batching of frees should be suppressed under NOMMU 6502 * conditions. 6503 * 6504 * The problem is that NOMMU needs to be able to allocate large chunks 6505 * of contiguous memory as there's no hardware page translation to 6506 * assemble apparent contiguous memory from discontiguous pages. 6507 * 6508 * Queueing large contiguous runs of pages for batching, however, 6509 * causes the pages to actually be freed in smaller chunks. As there 6510 * can be a significant delay between the individual batches being 6511 * recycled, this leads to the once large chunks of space being 6512 * fragmented and becoming unavailable for high-order allocations. 6513 */ 6514 return 0; 6515#endif 6516} 6517 6518/* 6519 * pcp->high and pcp->batch values are related and dependent on one another: 6520 * ->batch must never be higher then ->high. 6521 * The following function updates them in a safe manner without read side 6522 * locking. 6523 * 6524 * Any new users of pcp->batch and pcp->high should ensure they can cope with 6525 * those fields changing asynchronously (acording to the above rule). 6526 * 6527 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function 6528 * outside of boot time (or some other assurance that no concurrent updaters 6529 * exist). 6530 */ 6531static void pageset_update(struct per_cpu_pages *pcp, unsigned long high, 6532 unsigned long batch) 6533{ 6534 /* start with a fail safe value for batch */ 6535 pcp->batch = 1; 6536 smp_wmb(); 6537 6538 /* Update high, then batch, in order */ 6539 pcp->high = high; 6540 smp_wmb(); 6541 6542 pcp->batch = batch; 6543} 6544 6545/* a companion to pageset_set_high() */ 6546static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch) 6547{ 6548 pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch)); 6549} 6550 6551static void pageset_init(struct per_cpu_pageset *p) 6552{ 6553 struct per_cpu_pages *pcp; 6554 int migratetype; 6555 6556 memset(p, 0, sizeof(*p)); 6557 6558 pcp = &p->pcp; 6559 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++) 6560 INIT_LIST_HEAD(&pcp->lists[migratetype]); 6561} 6562 6563static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch) 6564{ 6565 pageset_init(p); 6566 pageset_set_batch(p, batch); 6567} 6568 6569/* 6570 * pageset_set_high() sets the high water mark for hot per_cpu_pagelist 6571 * to the value high for the pageset p. 6572 */ 6573static void pageset_set_high(struct per_cpu_pageset *p, 6574 unsigned long high) 6575{ 6576 unsigned long batch = max(1UL, high / 4); 6577 if ((high / 4) > (PAGE_SHIFT * 8)) 6578 batch = PAGE_SHIFT * 8; 6579 6580 pageset_update(&p->pcp, high, batch); 6581} 6582 6583static void pageset_set_high_and_batch(struct zone *zone, 6584 struct per_cpu_pageset *pcp) 6585{ 6586 if (percpu_pagelist_fraction) 6587 pageset_set_high(pcp, 6588 (zone_managed_pages(zone) / 6589 percpu_pagelist_fraction)); 6590 else 6591 pageset_set_batch(pcp, zone_batchsize(zone)); 6592} 6593 6594static void __meminit zone_pageset_init(struct zone *zone, int cpu) 6595{ 6596 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu); 6597 6598 pageset_init(pcp); 6599 pageset_set_high_and_batch(zone, pcp); 6600} 6601 6602void __meminit setup_zone_pageset(struct zone *zone) 6603{ 6604 int cpu; 6605 zone->pageset = alloc_percpu(struct per_cpu_pageset); 6606 for_each_possible_cpu(cpu) 6607 zone_pageset_init(zone, cpu); 6608} 6609 6610/* 6611 * Allocate per cpu pagesets and initialize them. 6612 * Before this call only boot pagesets were available. 6613 */ 6614void __init setup_per_cpu_pageset(void) 6615{ 6616 struct pglist_data *pgdat; 6617 struct zone *zone; 6618 int __maybe_unused cpu; 6619 6620 for_each_populated_zone(zone) 6621 setup_zone_pageset(zone); 6622 6623#ifdef CONFIG_NUMA 6624 /* 6625 * Unpopulated zones continue using the boot pagesets. 6626 * The numa stats for these pagesets need to be reset. 6627 * Otherwise, they will end up skewing the stats of 6628 * the nodes these zones are associated with. 6629 */ 6630 for_each_possible_cpu(cpu) { 6631 struct per_cpu_pageset *pcp = &per_cpu(boot_pageset, cpu); 6632 memset(pcp->vm_numa_stat_diff, 0, 6633 sizeof(pcp->vm_numa_stat_diff)); 6634 } 6635#endif 6636 6637 for_each_online_pgdat(pgdat) 6638 pgdat->per_cpu_nodestats = 6639 alloc_percpu(struct per_cpu_nodestat); 6640} 6641 6642static __meminit void zone_pcp_init(struct zone *zone) 6643{ 6644 /* 6645 * per cpu subsystem is not up at this point. The following code 6646 * relies on the ability of the linker to provide the 6647 * offset of a (static) per cpu variable into the per cpu area. 6648 */ 6649 zone->pageset = &boot_pageset; 6650 6651 if (populated_zone(zone)) 6652 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n", 6653 zone->name, zone->present_pages, 6654 zone_batchsize(zone)); 6655} 6656 6657void __meminit init_currently_empty_zone(struct zone *zone, 6658 unsigned long zone_start_pfn, 6659 unsigned long size) 6660{ 6661 struct pglist_data *pgdat = zone->zone_pgdat; 6662 int zone_idx = zone_idx(zone) + 1; 6663 6664 if (zone_idx > pgdat->nr_zones) 6665 pgdat->nr_zones = zone_idx; 6666 6667 zone->zone_start_pfn = zone_start_pfn; 6668 6669 mminit_dprintk(MMINIT_TRACE, "memmap_init", 6670 "Initialising map node %d zone %lu pfns %lu -> %lu\n", 6671 pgdat->node_id, 6672 (unsigned long)zone_idx(zone), 6673 zone_start_pfn, (zone_start_pfn + size)); 6674 6675 zone_init_free_lists(zone); 6676 zone->initialized = 1; 6677} 6678 6679/** 6680 * get_pfn_range_for_nid - Return the start and end page frames for a node 6681 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned. 6682 * @start_pfn: Passed by reference. On return, it will have the node start_pfn. 6683 * @end_pfn: Passed by reference. On return, it will have the node end_pfn. 6684 * 6685 * It returns the start and end page frame of a node based on information 6686 * provided by memblock_set_node(). If called for a node 6687 * with no available memory, a warning is printed and the start and end 6688 * PFNs will be 0. 6689 */ 6690void __init get_pfn_range_for_nid(unsigned int nid, 6691 unsigned long *start_pfn, unsigned long *end_pfn) 6692{ 6693 unsigned long this_start_pfn, this_end_pfn; 6694 int i; 6695 6696 *start_pfn = -1UL; 6697 *end_pfn = 0; 6698 6699 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) { 6700 *start_pfn = min(*start_pfn, this_start_pfn); 6701 *end_pfn = max(*end_pfn, this_end_pfn); 6702 } 6703 6704 if (*start_pfn == -1UL) 6705 *start_pfn = 0; 6706} 6707 6708/* 6709 * This finds a zone that can be used for ZONE_MOVABLE pages. The 6710 * assumption is made that zones within a node are ordered in monotonic 6711 * increasing memory addresses so that the "highest" populated zone is used 6712 */ 6713static void __init find_usable_zone_for_movable(void) 6714{ 6715 int zone_index; 6716 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) { 6717 if (zone_index == ZONE_MOVABLE) 6718 continue; 6719 6720 if (arch_zone_highest_possible_pfn[zone_index] > 6721 arch_zone_lowest_possible_pfn[zone_index]) 6722 break; 6723 } 6724 6725 VM_BUG_ON(zone_index == -1); 6726 movable_zone = zone_index; 6727} 6728 6729/* 6730 * The zone ranges provided by the architecture do not include ZONE_MOVABLE 6731 * because it is sized independent of architecture. Unlike the other zones, 6732 * the starting point for ZONE_MOVABLE is not fixed. It may be different 6733 * in each node depending on the size of each node and how evenly kernelcore 6734 * is distributed. This helper function adjusts the zone ranges 6735 * provided by the architecture for a given node by using the end of the 6736 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that 6737 * zones within a node are in order of monotonic increases memory addresses 6738 */ 6739static void __init adjust_zone_range_for_zone_movable(int nid, 6740 unsigned long zone_type, 6741 unsigned long node_start_pfn, 6742 unsigned long node_end_pfn, 6743 unsigned long *zone_start_pfn, 6744 unsigned long *zone_end_pfn) 6745{ 6746 /* Only adjust if ZONE_MOVABLE is on this node */ 6747 if (zone_movable_pfn[nid]) { 6748 /* Size ZONE_MOVABLE */ 6749 if (zone_type == ZONE_MOVABLE) { 6750 *zone_start_pfn = zone_movable_pfn[nid]; 6751 *zone_end_pfn = min(node_end_pfn, 6752 arch_zone_highest_possible_pfn[movable_zone]); 6753 6754 /* Adjust for ZONE_MOVABLE starting within this range */ 6755 } else if (!mirrored_kernelcore && 6756 *zone_start_pfn < zone_movable_pfn[nid] && 6757 *zone_end_pfn > zone_movable_pfn[nid]) { 6758 *zone_end_pfn = zone_movable_pfn[nid]; 6759 6760 /* Check if this whole range is within ZONE_MOVABLE */ 6761 } else if (*zone_start_pfn >= zone_movable_pfn[nid]) 6762 *zone_start_pfn = *zone_end_pfn; 6763 } 6764} 6765 6766/* 6767 * Return the number of pages a zone spans in a node, including holes 6768 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node() 6769 */ 6770static unsigned long __init zone_spanned_pages_in_node(int nid, 6771 unsigned long zone_type, 6772 unsigned long node_start_pfn, 6773 unsigned long node_end_pfn, 6774 unsigned long *zone_start_pfn, 6775 unsigned long *zone_end_pfn) 6776{ 6777 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type]; 6778 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type]; 6779 /* When hotadd a new node from cpu_up(), the node should be empty */ 6780 if (!node_start_pfn && !node_end_pfn) 6781 return 0; 6782 6783 /* Get the start and end of the zone */ 6784 *zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high); 6785 *zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high); 6786 adjust_zone_range_for_zone_movable(nid, zone_type, 6787 node_start_pfn, node_end_pfn, 6788 zone_start_pfn, zone_end_pfn); 6789 6790 /* Check that this node has pages within the zone's required range */ 6791 if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn) 6792 return 0; 6793 6794 /* Move the zone boundaries inside the node if necessary */ 6795 *zone_end_pfn = min(*zone_end_pfn, node_end_pfn); 6796 *zone_start_pfn = max(*zone_start_pfn, node_start_pfn); 6797 6798 /* Return the spanned pages */ 6799 return *zone_end_pfn - *zone_start_pfn; 6800} 6801 6802/* 6803 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES, 6804 * then all holes in the requested range will be accounted for. 6805 */ 6806unsigned long __init __absent_pages_in_range(int nid, 6807 unsigned long range_start_pfn, 6808 unsigned long range_end_pfn) 6809{ 6810 unsigned long nr_absent = range_end_pfn - range_start_pfn; 6811 unsigned long start_pfn, end_pfn; 6812 int i; 6813 6814 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) { 6815 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn); 6816 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn); 6817 nr_absent -= end_pfn - start_pfn; 6818 } 6819 return nr_absent; 6820} 6821 6822/** 6823 * absent_pages_in_range - Return number of page frames in holes within a range 6824 * @start_pfn: The start PFN to start searching for holes 6825 * @end_pfn: The end PFN to stop searching for holes 6826 * 6827 * Return: the number of pages frames in memory holes within a range. 6828 */ 6829unsigned long __init absent_pages_in_range(unsigned long start_pfn, 6830 unsigned long end_pfn) 6831{ 6832 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn); 6833} 6834 6835/* Return the number of page frames in holes in a zone on a node */ 6836static unsigned long __init zone_absent_pages_in_node(int nid, 6837 unsigned long zone_type, 6838 unsigned long node_start_pfn, 6839 unsigned long node_end_pfn) 6840{ 6841 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type]; 6842 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type]; 6843 unsigned long zone_start_pfn, zone_end_pfn; 6844 unsigned long nr_absent; 6845 6846 /* When hotadd a new node from cpu_up(), the node should be empty */ 6847 if (!node_start_pfn && !node_end_pfn) 6848 return 0; 6849 6850 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high); 6851 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high); 6852 6853 adjust_zone_range_for_zone_movable(nid, zone_type, 6854 node_start_pfn, node_end_pfn, 6855 &zone_start_pfn, &zone_end_pfn); 6856 nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn); 6857 6858 /* 6859 * ZONE_MOVABLE handling. 6860 * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages 6861 * and vice versa. 6862 */ 6863 if (mirrored_kernelcore && zone_movable_pfn[nid]) { 6864 unsigned long start_pfn, end_pfn; 6865 struct memblock_region *r; 6866 6867 for_each_mem_region(r) { 6868 start_pfn = clamp(memblock_region_memory_base_pfn(r), 6869 zone_start_pfn, zone_end_pfn); 6870 end_pfn = clamp(memblock_region_memory_end_pfn(r), 6871 zone_start_pfn, zone_end_pfn); 6872 6873 if (zone_type == ZONE_MOVABLE && 6874 memblock_is_mirror(r)) 6875 nr_absent += end_pfn - start_pfn; 6876 6877 if (zone_type == ZONE_NORMAL && 6878 !memblock_is_mirror(r)) 6879 nr_absent += end_pfn - start_pfn; 6880 } 6881 } 6882 6883 return nr_absent; 6884} 6885 6886static void __init calculate_node_totalpages(struct pglist_data *pgdat, 6887 unsigned long node_start_pfn, 6888 unsigned long node_end_pfn) 6889{ 6890 unsigned long realtotalpages = 0, totalpages = 0; 6891 enum zone_type i; 6892 6893 for (i = 0; i < MAX_NR_ZONES; i++) { 6894 struct zone *zone = pgdat->node_zones + i; 6895 unsigned long zone_start_pfn, zone_end_pfn; 6896 unsigned long spanned, absent; 6897 unsigned long size, real_size; 6898 6899 spanned = zone_spanned_pages_in_node(pgdat->node_id, i, 6900 node_start_pfn, 6901 node_end_pfn, 6902 &zone_start_pfn, 6903 &zone_end_pfn); 6904 absent = zone_absent_pages_in_node(pgdat->node_id, i, 6905 node_start_pfn, 6906 node_end_pfn); 6907 6908 size = spanned; 6909 real_size = size - absent; 6910 6911 if (size) 6912 zone->zone_start_pfn = zone_start_pfn; 6913 else 6914 zone->zone_start_pfn = 0; 6915 zone->spanned_pages = size; 6916 zone->present_pages = real_size; 6917 6918 totalpages += size; 6919 realtotalpages += real_size; 6920 } 6921 6922 pgdat->node_spanned_pages = totalpages; 6923 pgdat->node_present_pages = realtotalpages; 6924 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id, 6925 realtotalpages); 6926} 6927 6928#ifndef CONFIG_SPARSEMEM 6929/* 6930 * Calculate the size of the zone->blockflags rounded to an unsigned long 6931 * Start by making sure zonesize is a multiple of pageblock_order by rounding 6932 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally 6933 * round what is now in bits to nearest long in bits, then return it in 6934 * bytes. 6935 */ 6936static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize) 6937{ 6938 unsigned long usemapsize; 6939 6940 zonesize += zone_start_pfn & (pageblock_nr_pages-1); 6941 usemapsize = roundup(zonesize, pageblock_nr_pages); 6942 usemapsize = usemapsize >> pageblock_order; 6943 usemapsize *= NR_PAGEBLOCK_BITS; 6944 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long)); 6945 6946 return usemapsize / 8; 6947} 6948 6949static void __ref setup_usemap(struct pglist_data *pgdat, 6950 struct zone *zone, 6951 unsigned long zone_start_pfn, 6952 unsigned long zonesize) 6953{ 6954 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize); 6955 zone->pageblock_flags = NULL; 6956 if (usemapsize) { 6957 zone->pageblock_flags = 6958 memblock_alloc_node(usemapsize, SMP_CACHE_BYTES, 6959 pgdat->node_id); 6960 if (!zone->pageblock_flags) 6961 panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n", 6962 usemapsize, zone->name, pgdat->node_id); 6963 } 6964} 6965#else 6966static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone, 6967 unsigned long zone_start_pfn, unsigned long zonesize) {} 6968#endif /* CONFIG_SPARSEMEM */ 6969 6970#ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE 6971 6972/* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */ 6973void __init set_pageblock_order(void) 6974{ 6975 unsigned int order; 6976 6977 /* Check that pageblock_nr_pages has not already been setup */ 6978 if (pageblock_order) 6979 return; 6980 6981 if (HPAGE_SHIFT > PAGE_SHIFT) 6982 order = HUGETLB_PAGE_ORDER; 6983 else 6984 order = MAX_ORDER - 1; 6985 6986 /* 6987 * Assume the largest contiguous order of interest is a huge page. 6988 * This value may be variable depending on boot parameters on IA64 and 6989 * powerpc. 6990 */ 6991 pageblock_order = order; 6992} 6993#else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */ 6994 6995/* 6996 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order() 6997 * is unused as pageblock_order is set at compile-time. See 6998 * include/linux/pageblock-flags.h for the values of pageblock_order based on 6999 * the kernel config 7000 */ 7001void __init set_pageblock_order(void) 7002{ 7003} 7004 7005#endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */ 7006 7007static unsigned long __init calc_memmap_size(unsigned long spanned_pages, 7008 unsigned long present_pages) 7009{ 7010 unsigned long pages = spanned_pages; 7011 7012 /* 7013 * Provide a more accurate estimation if there are holes within 7014 * the zone and SPARSEMEM is in use. If there are holes within the 7015 * zone, each populated memory region may cost us one or two extra 7016 * memmap pages due to alignment because memmap pages for each 7017 * populated regions may not be naturally aligned on page boundary. 7018 * So the (present_pages >> 4) heuristic is a tradeoff for that. 7019 */ 7020 if (spanned_pages > present_pages + (present_pages >> 4) && 7021 IS_ENABLED(CONFIG_SPARSEMEM)) 7022 pages = present_pages; 7023 7024 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT; 7025} 7026 7027#ifdef CONFIG_TRANSPARENT_HUGEPAGE 7028static void pgdat_init_split_queue(struct pglist_data *pgdat) 7029{ 7030 struct deferred_split *ds_queue = &pgdat->deferred_split_queue; 7031 7032 spin_lock_init(&ds_queue->split_queue_lock); 7033 INIT_LIST_HEAD(&ds_queue->split_queue); 7034 ds_queue->split_queue_len = 0; 7035} 7036#else 7037static void pgdat_init_split_queue(struct pglist_data *pgdat) {} 7038#endif 7039 7040#ifdef CONFIG_COMPACTION 7041static void pgdat_init_kcompactd(struct pglist_data *pgdat) 7042{ 7043 init_waitqueue_head(&pgdat->kcompactd_wait); 7044} 7045#else 7046static void pgdat_init_kcompactd(struct pglist_data *pgdat) {} 7047#endif 7048 7049static void __meminit pgdat_init_internals(struct pglist_data *pgdat) 7050{ 7051 pgdat_resize_init(pgdat); 7052 7053 pgdat_init_split_queue(pgdat); 7054 pgdat_init_kcompactd(pgdat); 7055 7056 init_waitqueue_head(&pgdat->kswapd_wait); 7057 init_waitqueue_head(&pgdat->pfmemalloc_wait); 7058#ifdef CONFIG_HYPERHOLD_ZSWAPD 7059 init_waitqueue_head(&pgdat->zswapd_wait); 7060#endif 7061 7062 pgdat_page_ext_init(pgdat); 7063 spin_lock_init(&pgdat->lru_lock); 7064 lruvec_init(&pgdat->__lruvec); 7065#if defined(CONFIG_HYPERHOLD_FILE_LRU) && defined(CONFIG_MEMCG) 7066 pgdat->__lruvec.pgdat = pgdat; 7067#endif 7068} 7069 7070static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid, 7071 unsigned long remaining_pages) 7072{ 7073 atomic_long_set(&zone->managed_pages, remaining_pages); 7074 zone_set_nid(zone, nid); 7075 zone->name = zone_names[idx]; 7076 zone->zone_pgdat = NODE_DATA(nid); 7077 spin_lock_init(&zone->lock); 7078 zone_seqlock_init(zone); 7079 zone_pcp_init(zone); 7080} 7081 7082/* 7083 * Set up the zone data structures 7084 * - init pgdat internals 7085 * - init all zones belonging to this node 7086 * 7087 * NOTE: this function is only called during memory hotplug 7088 */ 7089#ifdef CONFIG_MEMORY_HOTPLUG 7090void __ref free_area_init_core_hotplug(int nid) 7091{ 7092 enum zone_type z; 7093 pg_data_t *pgdat = NODE_DATA(nid); 7094 7095 pgdat_init_internals(pgdat); 7096 for (z = 0; z < MAX_NR_ZONES; z++) 7097 zone_init_internals(&pgdat->node_zones[z], z, nid, 0); 7098} 7099#endif 7100 7101/* 7102 * Set up the zone data structures: 7103 * - mark all pages reserved 7104 * - mark all memory queues empty 7105 * - clear the memory bitmaps 7106 * 7107 * NOTE: pgdat should get zeroed by caller. 7108 * NOTE: this function is only called during early init. 7109 */ 7110static void __init free_area_init_core(struct pglist_data *pgdat) 7111{ 7112 enum zone_type j; 7113 int nid = pgdat->node_id; 7114 7115 pgdat_init_internals(pgdat); 7116 pgdat->per_cpu_nodestats = &boot_nodestats; 7117 7118 for (j = 0; j < MAX_NR_ZONES; j++) { 7119 struct zone *zone = pgdat->node_zones + j; 7120 unsigned long size, freesize, memmap_pages; 7121 unsigned long zone_start_pfn = zone->zone_start_pfn; 7122 7123 size = zone->spanned_pages; 7124 freesize = zone->present_pages; 7125 7126 /* 7127 * Adjust freesize so that it accounts for how much memory 7128 * is used by this zone for memmap. This affects the watermark 7129 * and per-cpu initialisations 7130 */ 7131 memmap_pages = calc_memmap_size(size, freesize); 7132 if (!is_highmem_idx(j)) { 7133 if (freesize >= memmap_pages) { 7134 freesize -= memmap_pages; 7135 if (memmap_pages) 7136 printk(KERN_DEBUG 7137 " %s zone: %lu pages used for memmap\n", 7138 zone_names[j], memmap_pages); 7139 } else 7140 pr_warn(" %s zone: %lu pages exceeds freesize %lu\n", 7141 zone_names[j], memmap_pages, freesize); 7142 } 7143 7144 /* Account for reserved pages */ 7145 if (j == 0 && freesize > dma_reserve) { 7146 freesize -= dma_reserve; 7147 printk(KERN_DEBUG " %s zone: %lu pages reserved\n", 7148 zone_names[0], dma_reserve); 7149 } 7150 7151 if (!is_highmem_idx(j)) 7152 nr_kernel_pages += freesize; 7153 /* Charge for highmem memmap if there are enough kernel pages */ 7154 else if (nr_kernel_pages > memmap_pages * 2) 7155 nr_kernel_pages -= memmap_pages; 7156 nr_all_pages += freesize; 7157 7158 /* 7159 * Set an approximate value for lowmem here, it will be adjusted 7160 * when the bootmem allocator frees pages into the buddy system. 7161 * And all highmem pages will be managed by the buddy system. 7162 */ 7163 zone_init_internals(zone, j, nid, freesize); 7164 7165 if (!size) 7166 continue; 7167 7168 set_pageblock_order(); 7169 setup_usemap(pgdat, zone, zone_start_pfn, size); 7170 init_currently_empty_zone(zone, zone_start_pfn, size); 7171 arch_memmap_init(size, nid, j, zone_start_pfn); 7172 } 7173} 7174 7175#ifdef CONFIG_FLAT_NODE_MEM_MAP 7176static void __ref alloc_node_mem_map(struct pglist_data *pgdat) 7177{ 7178 unsigned long __maybe_unused start = 0; 7179 unsigned long __maybe_unused offset = 0; 7180 7181 /* Skip empty nodes */ 7182 if (!pgdat->node_spanned_pages) 7183 return; 7184 7185 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1); 7186 offset = pgdat->node_start_pfn - start; 7187 /* ia64 gets its own node_mem_map, before this, without bootmem */ 7188 if (!pgdat->node_mem_map) { 7189 unsigned long size, end; 7190 struct page *map; 7191 7192 /* 7193 * The zone's endpoints aren't required to be MAX_ORDER 7194 * aligned but the node_mem_map endpoints must be in order 7195 * for the buddy allocator to function correctly. 7196 */ 7197 end = pgdat_end_pfn(pgdat); 7198 end = ALIGN(end, MAX_ORDER_NR_PAGES); 7199 size = (end - start) * sizeof(struct page); 7200 map = memblock_alloc_node(size, SMP_CACHE_BYTES, 7201 pgdat->node_id); 7202 if (!map) 7203 panic("Failed to allocate %ld bytes for node %d memory map\n", 7204 size, pgdat->node_id); 7205 pgdat->node_mem_map = map + offset; 7206 } 7207 pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n", 7208 __func__, pgdat->node_id, (unsigned long)pgdat, 7209 (unsigned long)pgdat->node_mem_map); 7210#ifndef CONFIG_NEED_MULTIPLE_NODES 7211 /* 7212 * With no DISCONTIG, the global mem_map is just set as node 0's 7213 */ 7214 if (pgdat == NODE_DATA(0)) { 7215 mem_map = NODE_DATA(0)->node_mem_map; 7216 if (page_to_pfn(mem_map) != pgdat->node_start_pfn) 7217 mem_map -= offset; 7218 } 7219#endif 7220} 7221#else 7222static void __ref alloc_node_mem_map(struct pglist_data *pgdat) { } 7223#endif /* CONFIG_FLAT_NODE_MEM_MAP */ 7224 7225#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT 7226static inline void pgdat_set_deferred_range(pg_data_t *pgdat) 7227{ 7228 pgdat->first_deferred_pfn = ULONG_MAX; 7229} 7230#else 7231static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {} 7232#endif 7233 7234static void __init free_area_init_node(int nid) 7235{ 7236 pg_data_t *pgdat = NODE_DATA(nid); 7237 unsigned long start_pfn = 0; 7238 unsigned long end_pfn = 0; 7239 7240 /* pg_data_t should be reset to zero when it's allocated */ 7241 WARN_ON(pgdat->nr_zones || pgdat->kswapd_highest_zoneidx); 7242 7243 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn); 7244 7245 pgdat->node_id = nid; 7246 pgdat->node_start_pfn = start_pfn; 7247 pgdat->per_cpu_nodestats = NULL; 7248 7249 pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid, 7250 (u64)start_pfn << PAGE_SHIFT, 7251 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0); 7252 calculate_node_totalpages(pgdat, start_pfn, end_pfn); 7253 7254 alloc_node_mem_map(pgdat); 7255 pgdat_set_deferred_range(pgdat); 7256 7257 free_area_init_core(pgdat); 7258} 7259 7260void __init free_area_init_memoryless_node(int nid) 7261{ 7262 free_area_init_node(nid); 7263} 7264 7265#if MAX_NUMNODES > 1 7266/* 7267 * Figure out the number of possible node ids. 7268 */ 7269void __init setup_nr_node_ids(void) 7270{ 7271 unsigned int highest; 7272 7273 highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES); 7274 nr_node_ids = highest + 1; 7275} 7276#endif 7277 7278/** 7279 * node_map_pfn_alignment - determine the maximum internode alignment 7280 * 7281 * This function should be called after node map is populated and sorted. 7282 * It calculates the maximum power of two alignment which can distinguish 7283 * all the nodes. 7284 * 7285 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value 7286 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the 7287 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is 7288 * shifted, 1GiB is enough and this function will indicate so. 7289 * 7290 * This is used to test whether pfn -> nid mapping of the chosen memory 7291 * model has fine enough granularity to avoid incorrect mapping for the 7292 * populated node map. 7293 * 7294 * Return: the determined alignment in pfn's. 0 if there is no alignment 7295 * requirement (single node). 7296 */ 7297unsigned long __init node_map_pfn_alignment(void) 7298{ 7299 unsigned long accl_mask = 0, last_end = 0; 7300 unsigned long start, end, mask; 7301 int last_nid = NUMA_NO_NODE; 7302 int i, nid; 7303 7304 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) { 7305 if (!start || last_nid < 0 || last_nid == nid) { 7306 last_nid = nid; 7307 last_end = end; 7308 continue; 7309 } 7310 7311 /* 7312 * Start with a mask granular enough to pin-point to the 7313 * start pfn and tick off bits one-by-one until it becomes 7314 * too coarse to separate the current node from the last. 7315 */ 7316 mask = ~((1 << __ffs(start)) - 1); 7317 while (mask && last_end <= (start & (mask << 1))) 7318 mask <<= 1; 7319 7320 /* accumulate all internode masks */ 7321 accl_mask |= mask; 7322 } 7323 7324 /* convert mask to number of pages */ 7325 return ~accl_mask + 1; 7326} 7327 7328/** 7329 * find_min_pfn_with_active_regions - Find the minimum PFN registered 7330 * 7331 * Return: the minimum PFN based on information provided via 7332 * memblock_set_node(). 7333 */ 7334unsigned long __init find_min_pfn_with_active_regions(void) 7335{ 7336 return PHYS_PFN(memblock_start_of_DRAM()); 7337} 7338 7339/* 7340 * early_calculate_totalpages() 7341 * Sum pages in active regions for movable zone. 7342 * Populate N_MEMORY for calculating usable_nodes. 7343 */ 7344static unsigned long __init early_calculate_totalpages(void) 7345{ 7346 unsigned long totalpages = 0; 7347 unsigned long start_pfn, end_pfn; 7348 int i, nid; 7349 7350 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) { 7351 unsigned long pages = end_pfn - start_pfn; 7352 7353 totalpages += pages; 7354 if (pages) 7355 node_set_state(nid, N_MEMORY); 7356 } 7357 return totalpages; 7358} 7359 7360/* 7361 * Find the PFN the Movable zone begins in each node. Kernel memory 7362 * is spread evenly between nodes as long as the nodes have enough 7363 * memory. When they don't, some nodes will have more kernelcore than 7364 * others 7365 */ 7366static void __init find_zone_movable_pfns_for_nodes(void) 7367{ 7368 int i, nid; 7369 unsigned long usable_startpfn; 7370 unsigned long kernelcore_node, kernelcore_remaining; 7371 /* save the state before borrow the nodemask */ 7372 nodemask_t saved_node_state = node_states[N_MEMORY]; 7373 unsigned long totalpages = early_calculate_totalpages(); 7374 int usable_nodes = nodes_weight(node_states[N_MEMORY]); 7375 struct memblock_region *r; 7376 7377 /* Need to find movable_zone earlier when movable_node is specified. */ 7378 find_usable_zone_for_movable(); 7379 7380 /* 7381 * If movable_node is specified, ignore kernelcore and movablecore 7382 * options. 7383 */ 7384 if (movable_node_is_enabled()) { 7385 for_each_mem_region(r) { 7386 if (!memblock_is_hotpluggable(r)) 7387 continue; 7388 7389 nid = memblock_get_region_node(r); 7390 7391 usable_startpfn = PFN_DOWN(r->base); 7392 zone_movable_pfn[nid] = zone_movable_pfn[nid] ? 7393 min(usable_startpfn, zone_movable_pfn[nid]) : 7394 usable_startpfn; 7395 } 7396 7397 goto out2; 7398 } 7399 7400 /* 7401 * If kernelcore=mirror is specified, ignore movablecore option 7402 */ 7403 if (mirrored_kernelcore) { 7404 bool mem_below_4gb_not_mirrored = false; 7405 7406 for_each_mem_region(r) { 7407 if (memblock_is_mirror(r)) 7408 continue; 7409 7410 nid = memblock_get_region_node(r); 7411 7412 usable_startpfn = memblock_region_memory_base_pfn(r); 7413 7414 if (usable_startpfn < 0x100000) { 7415 mem_below_4gb_not_mirrored = true; 7416 continue; 7417 } 7418 7419 zone_movable_pfn[nid] = zone_movable_pfn[nid] ? 7420 min(usable_startpfn, zone_movable_pfn[nid]) : 7421 usable_startpfn; 7422 } 7423 7424 if (mem_below_4gb_not_mirrored) 7425 pr_warn("This configuration results in unmirrored kernel memory.\n"); 7426 7427 goto out2; 7428 } 7429 7430 /* 7431 * If kernelcore=nn% or movablecore=nn% was specified, calculate the 7432 * amount of necessary memory. 7433 */ 7434 if (required_kernelcore_percent) 7435 required_kernelcore = (totalpages * 100 * required_kernelcore_percent) / 7436 10000UL; 7437 if (required_movablecore_percent) 7438 required_movablecore = (totalpages * 100 * required_movablecore_percent) / 7439 10000UL; 7440 7441 /* 7442 * If movablecore= was specified, calculate what size of 7443 * kernelcore that corresponds so that memory usable for 7444 * any allocation type is evenly spread. If both kernelcore 7445 * and movablecore are specified, then the value of kernelcore 7446 * will be used for required_kernelcore if it's greater than 7447 * what movablecore would have allowed. 7448 */ 7449 if (required_movablecore) { 7450 unsigned long corepages; 7451 7452 /* 7453 * Round-up so that ZONE_MOVABLE is at least as large as what 7454 * was requested by the user 7455 */ 7456 required_movablecore = 7457 roundup(required_movablecore, MAX_ORDER_NR_PAGES); 7458 required_movablecore = min(totalpages, required_movablecore); 7459 corepages = totalpages - required_movablecore; 7460 7461 required_kernelcore = max(required_kernelcore, corepages); 7462 } 7463 7464 /* 7465 * If kernelcore was not specified or kernelcore size is larger 7466 * than totalpages, there is no ZONE_MOVABLE. 7467 */ 7468 if (!required_kernelcore || required_kernelcore >= totalpages) 7469 goto out; 7470 7471 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */ 7472 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone]; 7473 7474restart: 7475 /* Spread kernelcore memory as evenly as possible throughout nodes */ 7476 kernelcore_node = required_kernelcore / usable_nodes; 7477 for_each_node_state(nid, N_MEMORY) { 7478 unsigned long start_pfn, end_pfn; 7479 7480 /* 7481 * Recalculate kernelcore_node if the division per node 7482 * now exceeds what is necessary to satisfy the requested 7483 * amount of memory for the kernel 7484 */ 7485 if (required_kernelcore < kernelcore_node) 7486 kernelcore_node = required_kernelcore / usable_nodes; 7487 7488 /* 7489 * As the map is walked, we track how much memory is usable 7490 * by the kernel using kernelcore_remaining. When it is 7491 * 0, the rest of the node is usable by ZONE_MOVABLE 7492 */ 7493 kernelcore_remaining = kernelcore_node; 7494 7495 /* Go through each range of PFNs within this node */ 7496 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) { 7497 unsigned long size_pages; 7498 7499 start_pfn = max(start_pfn, zone_movable_pfn[nid]); 7500 if (start_pfn >= end_pfn) 7501 continue; 7502 7503 /* Account for what is only usable for kernelcore */ 7504 if (start_pfn < usable_startpfn) { 7505 unsigned long kernel_pages; 7506 kernel_pages = min(end_pfn, usable_startpfn) 7507 - start_pfn; 7508 7509 kernelcore_remaining -= min(kernel_pages, 7510 kernelcore_remaining); 7511 required_kernelcore -= min(kernel_pages, 7512 required_kernelcore); 7513 7514 /* Continue if range is now fully accounted */ 7515 if (end_pfn <= usable_startpfn) { 7516 7517 /* 7518 * Push zone_movable_pfn to the end so 7519 * that if we have to rebalance 7520 * kernelcore across nodes, we will 7521 * not double account here 7522 */ 7523 zone_movable_pfn[nid] = end_pfn; 7524 continue; 7525 } 7526 start_pfn = usable_startpfn; 7527 } 7528 7529 /* 7530 * The usable PFN range for ZONE_MOVABLE is from 7531 * start_pfn->end_pfn. Calculate size_pages as the 7532 * number of pages used as kernelcore 7533 */ 7534 size_pages = end_pfn - start_pfn; 7535 if (size_pages > kernelcore_remaining) 7536 size_pages = kernelcore_remaining; 7537 zone_movable_pfn[nid] = start_pfn + size_pages; 7538 7539 /* 7540 * Some kernelcore has been met, update counts and 7541 * break if the kernelcore for this node has been 7542 * satisfied 7543 */ 7544 required_kernelcore -= min(required_kernelcore, 7545 size_pages); 7546 kernelcore_remaining -= size_pages; 7547 if (!kernelcore_remaining) 7548 break; 7549 } 7550 } 7551 7552 /* 7553 * If there is still required_kernelcore, we do another pass with one 7554 * less node in the count. This will push zone_movable_pfn[nid] further 7555 * along on the nodes that still have memory until kernelcore is 7556 * satisfied 7557 */ 7558 usable_nodes--; 7559 if (usable_nodes && required_kernelcore > usable_nodes) 7560 goto restart; 7561 7562out2: 7563 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */ 7564 for (nid = 0; nid < MAX_NUMNODES; nid++) { 7565 unsigned long start_pfn, end_pfn; 7566 7567 zone_movable_pfn[nid] = 7568 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES); 7569 7570 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn); 7571 if (zone_movable_pfn[nid] >= end_pfn) 7572 zone_movable_pfn[nid] = 0; 7573 } 7574 7575out: 7576 /* restore the node_state */ 7577 node_states[N_MEMORY] = saved_node_state; 7578} 7579 7580/* Any regular or high memory on that node ? */ 7581static void check_for_memory(pg_data_t *pgdat, int nid) 7582{ 7583 enum zone_type zone_type; 7584 7585 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) { 7586 struct zone *zone = &pgdat->node_zones[zone_type]; 7587 if (populated_zone(zone)) { 7588 if (IS_ENABLED(CONFIG_HIGHMEM)) 7589 node_set_state(nid, N_HIGH_MEMORY); 7590 if (zone_type <= ZONE_NORMAL) 7591 node_set_state(nid, N_NORMAL_MEMORY); 7592 break; 7593 } 7594 } 7595} 7596 7597/* 7598 * Some architecturs, e.g. ARC may have ZONE_HIGHMEM below ZONE_NORMAL. For 7599 * such cases we allow max_zone_pfn sorted in the descending order 7600 */ 7601bool __weak arch_has_descending_max_zone_pfns(void) 7602{ 7603 return false; 7604} 7605 7606/** 7607 * free_area_init - Initialise all pg_data_t and zone data 7608 * @max_zone_pfn: an array of max PFNs for each zone 7609 * 7610 * This will call free_area_init_node() for each active node in the system. 7611 * Using the page ranges provided by memblock_set_node(), the size of each 7612 * zone in each node and their holes is calculated. If the maximum PFN 7613 * between two adjacent zones match, it is assumed that the zone is empty. 7614 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed 7615 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone 7616 * starts where the previous one ended. For example, ZONE_DMA32 starts 7617 * at arch_max_dma_pfn. 7618 */ 7619void __init free_area_init(unsigned long *max_zone_pfn) 7620{ 7621 unsigned long start_pfn, end_pfn; 7622 int i, nid, zone; 7623 bool descending; 7624 7625 /* Record where the zone boundaries are */ 7626 memset(arch_zone_lowest_possible_pfn, 0, 7627 sizeof(arch_zone_lowest_possible_pfn)); 7628 memset(arch_zone_highest_possible_pfn, 0, 7629 sizeof(arch_zone_highest_possible_pfn)); 7630 7631 start_pfn = find_min_pfn_with_active_regions(); 7632 descending = arch_has_descending_max_zone_pfns(); 7633 7634 for (i = 0; i < MAX_NR_ZONES; i++) { 7635 if (descending) 7636 zone = MAX_NR_ZONES - i - 1; 7637 else 7638 zone = i; 7639 7640 if (zone == ZONE_MOVABLE) 7641 continue; 7642 7643 end_pfn = max(max_zone_pfn[zone], start_pfn); 7644 arch_zone_lowest_possible_pfn[zone] = start_pfn; 7645 arch_zone_highest_possible_pfn[zone] = end_pfn; 7646 7647 start_pfn = end_pfn; 7648 } 7649 7650 /* Find the PFNs that ZONE_MOVABLE begins at in each node */ 7651 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn)); 7652 find_zone_movable_pfns_for_nodes(); 7653 7654 /* Print out the zone ranges */ 7655 pr_info("Zone ranges:\n"); 7656 for (i = 0; i < MAX_NR_ZONES; i++) { 7657 if (i == ZONE_MOVABLE) 7658 continue; 7659 pr_info(" %-8s ", zone_names[i]); 7660 if (arch_zone_lowest_possible_pfn[i] == 7661 arch_zone_highest_possible_pfn[i]) 7662 pr_cont("empty\n"); 7663 else 7664 pr_cont("[mem %#018Lx-%#018Lx]\n", 7665 (u64)arch_zone_lowest_possible_pfn[i] 7666 << PAGE_SHIFT, 7667 ((u64)arch_zone_highest_possible_pfn[i] 7668 << PAGE_SHIFT) - 1); 7669 } 7670 7671 /* Print out the PFNs ZONE_MOVABLE begins at in each node */ 7672 pr_info("Movable zone start for each node\n"); 7673 for (i = 0; i < MAX_NUMNODES; i++) { 7674 if (zone_movable_pfn[i]) 7675 pr_info(" Node %d: %#018Lx\n", i, 7676 (u64)zone_movable_pfn[i] << PAGE_SHIFT); 7677 } 7678 7679 /* 7680 * Print out the early node map, and initialize the 7681 * subsection-map relative to active online memory ranges to 7682 * enable future "sub-section" extensions of the memory map. 7683 */ 7684 pr_info("Early memory node ranges\n"); 7685 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) { 7686 pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid, 7687 (u64)start_pfn << PAGE_SHIFT, 7688 ((u64)end_pfn << PAGE_SHIFT) - 1); 7689 subsection_map_init(start_pfn, end_pfn - start_pfn); 7690 } 7691 7692 /* Initialise every node */ 7693 mminit_verify_pageflags_layout(); 7694 setup_nr_node_ids(); 7695 for_each_online_node(nid) { 7696 pg_data_t *pgdat = NODE_DATA(nid); 7697 free_area_init_node(nid); 7698 7699 /* Any memory on that node */ 7700 if (pgdat->node_present_pages) 7701 node_set_state(nid, N_MEMORY); 7702 check_for_memory(pgdat, nid); 7703 } 7704 7705 memmap_init(); 7706} 7707 7708static int __init cmdline_parse_core(char *p, unsigned long *core, 7709 unsigned long *percent) 7710{ 7711 unsigned long long coremem; 7712 char *endptr; 7713 7714 if (!p) 7715 return -EINVAL; 7716 7717 /* Value may be a percentage of total memory, otherwise bytes */ 7718 coremem = simple_strtoull(p, &endptr, 0); 7719 if (*endptr == '%') { 7720 /* Paranoid check for percent values greater than 100 */ 7721 WARN_ON(coremem > 100); 7722 7723 *percent = coremem; 7724 } else { 7725 coremem = memparse(p, &p); 7726 /* Paranoid check that UL is enough for the coremem value */ 7727 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX); 7728 7729 *core = coremem >> PAGE_SHIFT; 7730 *percent = 0UL; 7731 } 7732 return 0; 7733} 7734 7735/* 7736 * kernelcore=size sets the amount of memory for use for allocations that 7737 * cannot be reclaimed or migrated. 7738 */ 7739static int __init cmdline_parse_kernelcore(char *p) 7740{ 7741 /* parse kernelcore=mirror */ 7742 if (parse_option_str(p, "mirror")) { 7743 mirrored_kernelcore = true; 7744 return 0; 7745 } 7746 7747 return cmdline_parse_core(p, &required_kernelcore, 7748 &required_kernelcore_percent); 7749} 7750 7751/* 7752 * movablecore=size sets the amount of memory for use for allocations that 7753 * can be reclaimed or migrated. 7754 */ 7755static int __init cmdline_parse_movablecore(char *p) 7756{ 7757 return cmdline_parse_core(p, &required_movablecore, 7758 &required_movablecore_percent); 7759} 7760 7761early_param("kernelcore", cmdline_parse_kernelcore); 7762early_param("movablecore", cmdline_parse_movablecore); 7763 7764void adjust_managed_page_count(struct page *page, long count) 7765{ 7766 atomic_long_add(count, &page_zone(page)->managed_pages); 7767 totalram_pages_add(count); 7768#ifdef CONFIG_HIGHMEM 7769 if (PageHighMem(page)) 7770 totalhigh_pages_add(count); 7771#endif 7772} 7773EXPORT_SYMBOL(adjust_managed_page_count); 7774 7775unsigned long free_reserved_area(void *start, void *end, int poison, const char *s) 7776{ 7777 void *pos; 7778 unsigned long pages = 0; 7779 7780 start = (void *)PAGE_ALIGN((unsigned long)start); 7781 end = (void *)((unsigned long)end & PAGE_MASK); 7782 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) { 7783 struct page *page = virt_to_page(pos); 7784 void *direct_map_addr; 7785 7786 /* 7787 * 'direct_map_addr' might be different from 'pos' 7788 * because some architectures' virt_to_page() 7789 * work with aliases. Getting the direct map 7790 * address ensures that we get a _writeable_ 7791 * alias for the memset(). 7792 */ 7793 direct_map_addr = page_address(page); 7794 if ((unsigned int)poison <= 0xFF) 7795 memset(direct_map_addr, poison, PAGE_SIZE); 7796 7797 free_reserved_page(page); 7798 } 7799 7800 if (pages && s) 7801 pr_info("Freeing %s memory: %ldK\n", 7802 s, pages << (PAGE_SHIFT - 10)); 7803 7804 return pages; 7805} 7806 7807#ifdef CONFIG_HIGHMEM 7808void free_highmem_page(struct page *page) 7809{ 7810 __free_reserved_page(page); 7811 totalram_pages_inc(); 7812 atomic_long_inc(&page_zone(page)->managed_pages); 7813 totalhigh_pages_inc(); 7814} 7815#endif 7816 7817 7818void __init mem_init_print_info(const char *str) 7819{ 7820 unsigned long physpages, codesize, datasize, rosize, bss_size; 7821 unsigned long init_code_size, init_data_size; 7822 7823 physpages = get_num_physpages(); 7824 codesize = _etext - _stext; 7825 datasize = _edata - _sdata; 7826 rosize = __end_rodata - __start_rodata; 7827 bss_size = __bss_stop - __bss_start; 7828 init_data_size = __init_end - __init_begin; 7829 init_code_size = _einittext - _sinittext; 7830 7831 /* 7832 * Detect special cases and adjust section sizes accordingly: 7833 * 1) .init.* may be embedded into .data sections 7834 * 2) .init.text.* may be out of [__init_begin, __init_end], 7835 * please refer to arch/tile/kernel/vmlinux.lds.S. 7836 * 3) .rodata.* may be embedded into .text or .data sections. 7837 */ 7838#define adj_init_size(start, end, size, pos, adj) \ 7839 do { \ 7840 if (&start[0] <= &pos[0] && &pos[0] < &end[0] && size > adj) \ 7841 size -= adj; \ 7842 } while (0) 7843 7844 adj_init_size(__init_begin, __init_end, init_data_size, 7845 _sinittext, init_code_size); 7846 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size); 7847 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size); 7848 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize); 7849 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize); 7850 7851#undef adj_init_size 7852 7853 pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved" 7854#ifdef CONFIG_HIGHMEM 7855 ", %luK highmem" 7856#endif 7857 "%s%s)\n", 7858 nr_free_pages() << (PAGE_SHIFT - 10), 7859 physpages << (PAGE_SHIFT - 10), 7860 codesize >> 10, datasize >> 10, rosize >> 10, 7861 (init_data_size + init_code_size) >> 10, bss_size >> 10, 7862 (physpages - totalram_pages() - totalcma_pages) << (PAGE_SHIFT - 10), 7863 totalcma_pages << (PAGE_SHIFT - 10), 7864#ifdef CONFIG_HIGHMEM 7865 totalhigh_pages() << (PAGE_SHIFT - 10), 7866#endif 7867 str ? ", " : "", str ? str : ""); 7868} 7869 7870/** 7871 * set_dma_reserve - set the specified number of pages reserved in the first zone 7872 * @new_dma_reserve: The number of pages to mark reserved 7873 * 7874 * The per-cpu batchsize and zone watermarks are determined by managed_pages. 7875 * In the DMA zone, a significant percentage may be consumed by kernel image 7876 * and other unfreeable allocations which can skew the watermarks badly. This 7877 * function may optionally be used to account for unfreeable pages in the 7878 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and 7879 * smaller per-cpu batchsize. 7880 */ 7881void __init set_dma_reserve(unsigned long new_dma_reserve) 7882{ 7883 dma_reserve = new_dma_reserve; 7884} 7885 7886static int page_alloc_cpu_dead(unsigned int cpu) 7887{ 7888 7889 lru_add_drain_cpu(cpu); 7890 drain_pages(cpu); 7891 7892 /* 7893 * Spill the event counters of the dead processor 7894 * into the current processors event counters. 7895 * This artificially elevates the count of the current 7896 * processor. 7897 */ 7898 vm_events_fold_cpu(cpu); 7899 7900 /* 7901 * Zero the differential counters of the dead processor 7902 * so that the vm statistics are consistent. 7903 * 7904 * This is only okay since the processor is dead and cannot 7905 * race with what we are doing. 7906 */ 7907 cpu_vm_stats_fold(cpu); 7908 return 0; 7909} 7910 7911#ifdef CONFIG_NUMA 7912int hashdist = HASHDIST_DEFAULT; 7913 7914static int __init set_hashdist(char *str) 7915{ 7916 if (!str) 7917 return 0; 7918 hashdist = simple_strtoul(str, &str, 0); 7919 return 1; 7920} 7921__setup("hashdist=", set_hashdist); 7922#endif 7923 7924void __init page_alloc_init(void) 7925{ 7926 int ret; 7927 7928#ifdef CONFIG_NUMA 7929 if (num_node_state(N_MEMORY) == 1) 7930 hashdist = 0; 7931#endif 7932 7933 ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC_DEAD, 7934 "mm/page_alloc:dead", NULL, 7935 page_alloc_cpu_dead); 7936 WARN_ON(ret < 0); 7937} 7938 7939/* 7940 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio 7941 * or min_free_kbytes changes. 7942 */ 7943static void calculate_totalreserve_pages(void) 7944{ 7945 struct pglist_data *pgdat; 7946 unsigned long reserve_pages = 0; 7947 enum zone_type i, j; 7948 7949 for_each_online_pgdat(pgdat) { 7950 7951 pgdat->totalreserve_pages = 0; 7952 7953 for (i = 0; i < MAX_NR_ZONES; i++) { 7954 struct zone *zone = pgdat->node_zones + i; 7955 long max = 0; 7956 unsigned long managed_pages = zone_managed_pages(zone); 7957 7958 /* Find valid and maximum lowmem_reserve in the zone */ 7959 for (j = i; j < MAX_NR_ZONES; j++) { 7960 if (zone->lowmem_reserve[j] > max) 7961 max = zone->lowmem_reserve[j]; 7962 } 7963 7964 /* we treat the high watermark as reserved pages. */ 7965 max += high_wmark_pages(zone); 7966 7967 if (max > managed_pages) 7968 max = managed_pages; 7969 7970 pgdat->totalreserve_pages += max; 7971 7972 reserve_pages += max; 7973 } 7974 } 7975 totalreserve_pages = reserve_pages; 7976} 7977 7978/* 7979 * setup_per_zone_lowmem_reserve - called whenever 7980 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone 7981 * has a correct pages reserved value, so an adequate number of 7982 * pages are left in the zone after a successful __alloc_pages(). 7983 */ 7984static void setup_per_zone_lowmem_reserve(void) 7985{ 7986 struct pglist_data *pgdat; 7987 enum zone_type i, j; 7988 7989 for_each_online_pgdat(pgdat) { 7990 for (i = 0; i < MAX_NR_ZONES - 1; i++) { 7991 struct zone *zone = &pgdat->node_zones[i]; 7992 int ratio = sysctl_lowmem_reserve_ratio[i]; 7993 bool clear = !ratio || !zone_managed_pages(zone); 7994 unsigned long managed_pages = 0; 7995 7996 for (j = i + 1; j < MAX_NR_ZONES; j++) { 7997 struct zone *upper_zone = &pgdat->node_zones[j]; 7998 7999 managed_pages += zone_managed_pages(upper_zone); 8000 8001 if (clear) 8002 zone->lowmem_reserve[j] = 0; 8003 else 8004 zone->lowmem_reserve[j] = managed_pages / ratio; 8005 } 8006 } 8007 } 8008 8009 /* update totalreserve_pages */ 8010 calculate_totalreserve_pages(); 8011} 8012 8013static void __setup_per_zone_wmarks(void) 8014{ 8015 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10); 8016 unsigned long lowmem_pages = 0; 8017 struct zone *zone; 8018 unsigned long flags; 8019 8020 /* Calculate total number of !ZONE_HIGHMEM pages */ 8021 for_each_zone(zone) { 8022 if (!is_highmem(zone)) 8023 lowmem_pages += zone_managed_pages(zone); 8024 } 8025 8026 for_each_zone(zone) { 8027 u64 tmp; 8028 8029 spin_lock_irqsave(&zone->lock, flags); 8030 tmp = (u64)pages_min * zone_managed_pages(zone); 8031 do_div(tmp, lowmem_pages); 8032 if (is_highmem(zone)) { 8033 /* 8034 * __GFP_HIGH and PF_MEMALLOC allocations usually don't 8035 * need highmem pages, so cap pages_min to a small 8036 * value here. 8037 * 8038 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN) 8039 * deltas control async page reclaim, and so should 8040 * not be capped for highmem. 8041 */ 8042 unsigned long min_pages; 8043 8044 min_pages = zone_managed_pages(zone) / 1024; 8045 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL); 8046 zone->_watermark[WMARK_MIN] = min_pages; 8047 } else { 8048 /* 8049 * If it's a lowmem zone, reserve a number of pages 8050 * proportionate to the zone's size. 8051 */ 8052 zone->_watermark[WMARK_MIN] = tmp; 8053 } 8054 8055 /* 8056 * Set the kswapd watermarks distance according to the 8057 * scale factor in proportion to available memory, but 8058 * ensure a minimum size on small systems. 8059 */ 8060 tmp = max_t(u64, tmp >> 2, 8061 mult_frac(zone_managed_pages(zone), 8062 watermark_scale_factor, 10000)); 8063 8064 zone->watermark_boost = 0; 8065 zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp; 8066 zone->_watermark[WMARK_HIGH] = min_wmark_pages(zone) + tmp * 2; 8067 8068 spin_unlock_irqrestore(&zone->lock, flags); 8069 } 8070 8071 /* update totalreserve_pages */ 8072 calculate_totalreserve_pages(); 8073} 8074 8075/** 8076 * setup_per_zone_wmarks - called when min_free_kbytes changes 8077 * or when memory is hot-{added|removed} 8078 * 8079 * Ensures that the watermark[min,low,high] values for each zone are set 8080 * correctly with respect to min_free_kbytes. 8081 */ 8082void setup_per_zone_wmarks(void) 8083{ 8084 static DEFINE_SPINLOCK(lock); 8085 8086 spin_lock(&lock); 8087 __setup_per_zone_wmarks(); 8088 spin_unlock(&lock); 8089} 8090 8091/* 8092 * Initialise min_free_kbytes. 8093 * 8094 * For small machines we want it small (128k min). For large machines 8095 * we want it large (256MB max). But it is not linear, because network 8096 * bandwidth does not increase linearly with machine size. We use 8097 * 8098 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy: 8099 * min_free_kbytes = sqrt(lowmem_kbytes * 16) 8100 * 8101 * which yields 8102 * 8103 * 16MB: 512k 8104 * 32MB: 724k 8105 * 64MB: 1024k 8106 * 128MB: 1448k 8107 * 256MB: 2048k 8108 * 512MB: 2896k 8109 * 1024MB: 4096k 8110 * 2048MB: 5792k 8111 * 4096MB: 8192k 8112 * 8192MB: 11584k 8113 * 16384MB: 16384k 8114 */ 8115int __meminit init_per_zone_wmark_min(void) 8116{ 8117 unsigned long lowmem_kbytes; 8118 int new_min_free_kbytes; 8119 8120 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10); 8121 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16); 8122 8123 if (new_min_free_kbytes > user_min_free_kbytes) { 8124 min_free_kbytes = new_min_free_kbytes; 8125 if (min_free_kbytes < 128) 8126 min_free_kbytes = 128; 8127 if (min_free_kbytes > 262144) 8128 min_free_kbytes = 262144; 8129 } else { 8130 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n", 8131 new_min_free_kbytes, user_min_free_kbytes); 8132 } 8133 setup_per_zone_wmarks(); 8134 refresh_zone_stat_thresholds(); 8135 setup_per_zone_lowmem_reserve(); 8136 8137#ifdef CONFIG_NUMA 8138 setup_min_unmapped_ratio(); 8139 setup_min_slab_ratio(); 8140#endif 8141 8142 khugepaged_min_free_kbytes_update(); 8143 8144 return 0; 8145} 8146postcore_initcall(init_per_zone_wmark_min) 8147 8148/* 8149 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so 8150 * that we can call two helper functions whenever min_free_kbytes 8151 * changes. 8152 */ 8153int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write, 8154 void *buffer, size_t *length, loff_t *ppos) 8155{ 8156 int rc; 8157 8158 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 8159 if (rc) 8160 return rc; 8161 8162 if (write) { 8163 user_min_free_kbytes = min_free_kbytes; 8164 setup_per_zone_wmarks(); 8165 } 8166 return 0; 8167} 8168 8169int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write, 8170 void *buffer, size_t *length, loff_t *ppos) 8171{ 8172 int rc; 8173 8174 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 8175 if (rc) 8176 return rc; 8177 8178 if (write) 8179 setup_per_zone_wmarks(); 8180 8181 return 0; 8182} 8183 8184#ifdef CONFIG_NUMA 8185static void setup_min_unmapped_ratio(void) 8186{ 8187 pg_data_t *pgdat; 8188 struct zone *zone; 8189 8190 for_each_online_pgdat(pgdat) 8191 pgdat->min_unmapped_pages = 0; 8192 8193 for_each_zone(zone) 8194 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) * 8195 sysctl_min_unmapped_ratio) / 100; 8196} 8197 8198 8199int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write, 8200 void *buffer, size_t *length, loff_t *ppos) 8201{ 8202 int rc; 8203 8204 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 8205 if (rc) 8206 return rc; 8207 8208 setup_min_unmapped_ratio(); 8209 8210 return 0; 8211} 8212 8213static void setup_min_slab_ratio(void) 8214{ 8215 pg_data_t *pgdat; 8216 struct zone *zone; 8217 8218 for_each_online_pgdat(pgdat) 8219 pgdat->min_slab_pages = 0; 8220 8221 for_each_zone(zone) 8222 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) * 8223 sysctl_min_slab_ratio) / 100; 8224} 8225 8226int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write, 8227 void *buffer, size_t *length, loff_t *ppos) 8228{ 8229 int rc; 8230 8231 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 8232 if (rc) 8233 return rc; 8234 8235 setup_min_slab_ratio(); 8236 8237 return 0; 8238} 8239#endif 8240 8241/* 8242 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around 8243 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve() 8244 * whenever sysctl_lowmem_reserve_ratio changes. 8245 * 8246 * The reserve ratio obviously has absolutely no relation with the 8247 * minimum watermarks. The lowmem reserve ratio can only make sense 8248 * if in function of the boot time zone sizes. 8249 */ 8250int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write, 8251 void *buffer, size_t *length, loff_t *ppos) 8252{ 8253 int i; 8254 8255 proc_dointvec_minmax(table, write, buffer, length, ppos); 8256 8257 for (i = 0; i < MAX_NR_ZONES; i++) { 8258 if (sysctl_lowmem_reserve_ratio[i] < 1) 8259 sysctl_lowmem_reserve_ratio[i] = 0; 8260 } 8261 8262 setup_per_zone_lowmem_reserve(); 8263 return 0; 8264} 8265 8266static void __zone_pcp_update(struct zone *zone) 8267{ 8268 unsigned int cpu; 8269 8270 for_each_possible_cpu(cpu) 8271 pageset_set_high_and_batch(zone, 8272 per_cpu_ptr(zone->pageset, cpu)); 8273} 8274 8275/* 8276 * percpu_pagelist_fraction - changes the pcp->high for each zone on each 8277 * cpu. It is the fraction of total pages in each zone that a hot per cpu 8278 * pagelist can have before it gets flushed back to buddy allocator. 8279 */ 8280int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write, 8281 void *buffer, size_t *length, loff_t *ppos) 8282{ 8283 struct zone *zone; 8284 int old_percpu_pagelist_fraction; 8285 int ret; 8286 8287 mutex_lock(&pcp_batch_high_lock); 8288 old_percpu_pagelist_fraction = percpu_pagelist_fraction; 8289 8290 ret = proc_dointvec_minmax(table, write, buffer, length, ppos); 8291 if (!write || ret < 0) 8292 goto out; 8293 8294 /* Sanity checking to avoid pcp imbalance */ 8295 if (percpu_pagelist_fraction && 8296 percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) { 8297 percpu_pagelist_fraction = old_percpu_pagelist_fraction; 8298 ret = -EINVAL; 8299 goto out; 8300 } 8301 8302 /* No change? */ 8303 if (percpu_pagelist_fraction == old_percpu_pagelist_fraction) 8304 goto out; 8305 8306 for_each_populated_zone(zone) 8307 __zone_pcp_update(zone); 8308out: 8309 mutex_unlock(&pcp_batch_high_lock); 8310 return ret; 8311} 8312 8313#ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES 8314/* 8315 * Returns the number of pages that arch has reserved but 8316 * is not known to alloc_large_system_hash(). 8317 */ 8318static unsigned long __init arch_reserved_kernel_pages(void) 8319{ 8320 return 0; 8321} 8322#endif 8323 8324/* 8325 * Adaptive scale is meant to reduce sizes of hash tables on large memory 8326 * machines. As memory size is increased the scale is also increased but at 8327 * slower pace. Starting from ADAPT_SCALE_BASE (64G), every time memory 8328 * quadruples the scale is increased by one, which means the size of hash table 8329 * only doubles, instead of quadrupling as well. 8330 * Because 32-bit systems cannot have large physical memory, where this scaling 8331 * makes sense, it is disabled on such platforms. 8332 */ 8333#if __BITS_PER_LONG > 32 8334#define ADAPT_SCALE_BASE (64ul << 30) 8335#define ADAPT_SCALE_SHIFT 2 8336#define ADAPT_SCALE_NPAGES (ADAPT_SCALE_BASE >> PAGE_SHIFT) 8337#endif 8338 8339/* 8340 * allocate a large system hash table from bootmem 8341 * - it is assumed that the hash table must contain an exact power-of-2 8342 * quantity of entries 8343 * - limit is the number of hash buckets, not the total allocation size 8344 */ 8345void *__init alloc_large_system_hash(const char *tablename, 8346 unsigned long bucketsize, 8347 unsigned long numentries, 8348 int scale, 8349 int flags, 8350 unsigned int *_hash_shift, 8351 unsigned int *_hash_mask, 8352 unsigned long low_limit, 8353 unsigned long high_limit) 8354{ 8355 unsigned long long max = high_limit; 8356 unsigned long log2qty, size; 8357 void *table = NULL; 8358 gfp_t gfp_flags; 8359 bool virt; 8360 8361 /* allow the kernel cmdline to have a say */ 8362 if (!numentries) { 8363 /* round applicable memory size up to nearest megabyte */ 8364 numentries = nr_kernel_pages; 8365 numentries -= arch_reserved_kernel_pages(); 8366 8367 /* It isn't necessary when PAGE_SIZE >= 1MB */ 8368 if (PAGE_SHIFT < 20) 8369 numentries = round_up(numentries, (1<<20)/PAGE_SIZE); 8370 8371#if __BITS_PER_LONG > 32 8372 if (!high_limit) { 8373 unsigned long adapt; 8374 8375 for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries; 8376 adapt <<= ADAPT_SCALE_SHIFT) 8377 scale++; 8378 } 8379#endif 8380 8381 /* limit to 1 bucket per 2^scale bytes of low memory */ 8382 if (scale > PAGE_SHIFT) 8383 numentries >>= (scale - PAGE_SHIFT); 8384 else 8385 numentries <<= (PAGE_SHIFT - scale); 8386 8387 /* Make sure we've got at least a 0-order allocation.. */ 8388 if (unlikely(flags & HASH_SMALL)) { 8389 /* Makes no sense without HASH_EARLY */ 8390 WARN_ON(!(flags & HASH_EARLY)); 8391 if (!(numentries >> *_hash_shift)) { 8392 numentries = 1UL << *_hash_shift; 8393 BUG_ON(!numentries); 8394 } 8395 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE)) 8396 numentries = PAGE_SIZE / bucketsize; 8397 } 8398 numentries = roundup_pow_of_two(numentries); 8399 8400 /* limit allocation size to 1/16 total memory by default */ 8401 if (max == 0) { 8402 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4; 8403 do_div(max, bucketsize); 8404 } 8405 max = min(max, 0x80000000ULL); 8406 8407 if (numentries < low_limit) 8408 numentries = low_limit; 8409 if (numentries > max) 8410 numentries = max; 8411 8412 log2qty = ilog2(numentries); 8413 8414 gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC; 8415 do { 8416 virt = false; 8417 size = bucketsize << log2qty; 8418 if (flags & HASH_EARLY) { 8419 if (flags & HASH_ZERO) 8420 table = memblock_alloc(size, SMP_CACHE_BYTES); 8421 else 8422 table = memblock_alloc_raw(size, 8423 SMP_CACHE_BYTES); 8424 } else if (get_order(size) >= MAX_ORDER || hashdist) { 8425 table = __vmalloc(size, gfp_flags); 8426 virt = true; 8427 } else { 8428 /* 8429 * If bucketsize is not a power-of-two, we may free 8430 * some pages at the end of hash table which 8431 * alloc_pages_exact() automatically does 8432 */ 8433 table = alloc_pages_exact(size, gfp_flags); 8434 kmemleak_alloc(table, size, 1, gfp_flags); 8435 } 8436 } while (!table && size > PAGE_SIZE && --log2qty); 8437 8438 if (!table) 8439 panic("Failed to allocate %s hash table\n", tablename); 8440 8441 pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n", 8442 tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size, 8443 virt ? "vmalloc" : "linear"); 8444 8445 if (_hash_shift) 8446 *_hash_shift = log2qty; 8447 if (_hash_mask) 8448 *_hash_mask = (1 << log2qty) - 1; 8449 8450 return table; 8451} 8452 8453/* 8454 * This function checks whether pageblock includes unmovable pages or not. 8455 * 8456 * PageLRU check without isolation or lru_lock could race so that 8457 * MIGRATE_MOVABLE block might include unmovable pages. And __PageMovable 8458 * check without lock_page also may miss some movable non-lru pages at 8459 * race condition. So you can't expect this function should be exact. 8460 * 8461 * Returns a page without holding a reference. If the caller wants to 8462 * dereference that page (e.g., dumping), it has to make sure that it 8463 * cannot get removed (e.g., via memory unplug) concurrently. 8464 * 8465 */ 8466struct page *has_unmovable_pages(struct zone *zone, struct page *page, 8467 int migratetype, int flags) 8468{ 8469 unsigned long iter = 0; 8470 unsigned long pfn = page_to_pfn(page); 8471 unsigned long offset = pfn % pageblock_nr_pages; 8472 8473 if (is_migrate_cma_page(page)) { 8474 /* 8475 * CMA allocations (alloc_contig_range) really need to mark 8476 * isolate CMA pageblocks even when they are not movable in fact 8477 * so consider them movable here. 8478 */ 8479 if (is_migrate_cma(migratetype)) 8480 return NULL; 8481 8482 return page; 8483 } 8484 8485 for (; iter < pageblock_nr_pages - offset; iter++) { 8486 if (!pfn_valid_within(pfn + iter)) 8487 continue; 8488 8489 page = pfn_to_page(pfn + iter); 8490 8491 /* 8492 * Both, bootmem allocations and memory holes are marked 8493 * PG_reserved and are unmovable. We can even have unmovable 8494 * allocations inside ZONE_MOVABLE, for example when 8495 * specifying "movablecore". 8496 */ 8497 if (PageReserved(page)) 8498 return page; 8499 8500 /* 8501 * If the zone is movable and we have ruled out all reserved 8502 * pages then it should be reasonably safe to assume the rest 8503 * is movable. 8504 */ 8505 if (zone_idx(zone) == ZONE_MOVABLE) 8506 continue; 8507 8508 /* 8509 * Hugepages are not in LRU lists, but they're movable. 8510 * THPs are on the LRU, but need to be counted as #small pages. 8511 * We need not scan over tail pages because we don't 8512 * handle each tail page individually in migration. 8513 */ 8514 if (PageHuge(page) || PageTransCompound(page)) { 8515 struct page *head = compound_head(page); 8516 unsigned int skip_pages; 8517 8518 if (PageHuge(page)) { 8519 if (!hugepage_migration_supported(page_hstate(head))) 8520 return page; 8521 } else if (!PageLRU(head) && !__PageMovable(head)) { 8522 return page; 8523 } 8524 8525 skip_pages = compound_nr(head) - (page - head); 8526 iter += skip_pages - 1; 8527 continue; 8528 } 8529 8530 /* 8531 * We can't use page_count without pin a page 8532 * because another CPU can free compound page. 8533 * This check already skips compound tails of THP 8534 * because their page->_refcount is zero at all time. 8535 */ 8536 if (!page_ref_count(page)) { 8537 if (PageBuddy(page)) 8538 iter += (1 << buddy_order(page)) - 1; 8539 continue; 8540 } 8541 8542 /* 8543 * The HWPoisoned page may be not in buddy system, and 8544 * page_count() is not 0. 8545 */ 8546 if ((flags & MEMORY_OFFLINE) && PageHWPoison(page)) 8547 continue; 8548 8549 /* 8550 * We treat all PageOffline() pages as movable when offlining 8551 * to give drivers a chance to decrement their reference count 8552 * in MEM_GOING_OFFLINE in order to indicate that these pages 8553 * can be offlined as there are no direct references anymore. 8554 * For actually unmovable PageOffline() where the driver does 8555 * not support this, we will fail later when trying to actually 8556 * move these pages that still have a reference count > 0. 8557 * (false negatives in this function only) 8558 */ 8559 if ((flags & MEMORY_OFFLINE) && PageOffline(page)) 8560 continue; 8561 8562 if (__PageMovable(page) || PageLRU(page)) 8563 continue; 8564 8565 /* 8566 * If there are RECLAIMABLE pages, we need to check 8567 * it. But now, memory offline itself doesn't call 8568 * shrink_node_slabs() and it still to be fixed. 8569 */ 8570 return page; 8571 } 8572 return NULL; 8573} 8574 8575#ifdef CONFIG_CONTIG_ALLOC 8576static unsigned long pfn_max_align_down(unsigned long pfn) 8577{ 8578 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES, 8579 pageblock_nr_pages) - 1); 8580} 8581 8582static unsigned long pfn_max_align_up(unsigned long pfn) 8583{ 8584 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES, 8585 pageblock_nr_pages)); 8586} 8587 8588/* [start, end) must belong to a single zone. */ 8589static int __alloc_contig_migrate_range(struct compact_control *cc, 8590 unsigned long start, unsigned long end) 8591{ 8592 /* This function is based on compact_zone() from compaction.c. */ 8593 unsigned int nr_reclaimed; 8594 unsigned long pfn = start; 8595 unsigned int tries = 0; 8596 int ret = 0; 8597 struct migration_target_control mtc = { 8598 .nid = zone_to_nid(cc->zone), 8599 .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL, 8600 }; 8601 8602 migrate_prep(); 8603 8604 while (pfn < end || !list_empty(&cc->migratepages)) { 8605 if (fatal_signal_pending(current)) { 8606 ret = -EINTR; 8607 break; 8608 } 8609 8610 if (list_empty(&cc->migratepages)) { 8611 cc->nr_migratepages = 0; 8612 pfn = isolate_migratepages_range(cc, pfn, end); 8613 if (!pfn) { 8614 ret = -EINTR; 8615 break; 8616 } 8617 tries = 0; 8618 } else if (++tries == 5) { 8619 ret = ret < 0 ? ret : -EBUSY; 8620 break; 8621 } 8622 8623 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone, 8624 &cc->migratepages); 8625 cc->nr_migratepages -= nr_reclaimed; 8626 8627 ret = migrate_pages(&cc->migratepages, alloc_migration_target, 8628 NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE); 8629 } 8630 if (ret < 0) { 8631 putback_movable_pages(&cc->migratepages); 8632 return ret; 8633 } 8634 return 0; 8635} 8636 8637/** 8638 * alloc_contig_range() -- tries to allocate given range of pages 8639 * @start: start PFN to allocate 8640 * @end: one-past-the-last PFN to allocate 8641 * @migratetype: migratetype of the underlaying pageblocks (either 8642 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks 8643 * in range must have the same migratetype and it must 8644 * be either of the two. 8645 * @gfp_mask: GFP mask to use during compaction 8646 * 8647 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES 8648 * aligned. The PFN range must belong to a single zone. 8649 * 8650 * The first thing this routine does is attempt to MIGRATE_ISOLATE all 8651 * pageblocks in the range. Once isolated, the pageblocks should not 8652 * be modified by others. 8653 * 8654 * Return: zero on success or negative error code. On success all 8655 * pages which PFN is in [start, end) are allocated for the caller and 8656 * need to be freed with free_contig_range(). 8657 */ 8658int alloc_contig_range(unsigned long start, unsigned long end, 8659 unsigned migratetype, gfp_t gfp_mask) 8660{ 8661 unsigned long outer_start, outer_end; 8662 unsigned int order; 8663 int ret = 0; 8664 8665 struct compact_control cc = { 8666 .nr_migratepages = 0, 8667 .order = -1, 8668 .zone = page_zone(pfn_to_page(start)), 8669 .mode = MIGRATE_SYNC, 8670 .ignore_skip_hint = true, 8671 .no_set_skip_hint = true, 8672 .gfp_mask = current_gfp_context(gfp_mask), 8673 .alloc_contig = true, 8674 }; 8675 INIT_LIST_HEAD(&cc.migratepages); 8676 8677 /* 8678 * What we do here is we mark all pageblocks in range as 8679 * MIGRATE_ISOLATE. Because pageblock and max order pages may 8680 * have different sizes, and due to the way page allocator 8681 * work, we align the range to biggest of the two pages so 8682 * that page allocator won't try to merge buddies from 8683 * different pageblocks and change MIGRATE_ISOLATE to some 8684 * other migration type. 8685 * 8686 * Once the pageblocks are marked as MIGRATE_ISOLATE, we 8687 * migrate the pages from an unaligned range (ie. pages that 8688 * we are interested in). This will put all the pages in 8689 * range back to page allocator as MIGRATE_ISOLATE. 8690 * 8691 * When this is done, we take the pages in range from page 8692 * allocator removing them from the buddy system. This way 8693 * page allocator will never consider using them. 8694 * 8695 * This lets us mark the pageblocks back as 8696 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the 8697 * aligned range but not in the unaligned, original range are 8698 * put back to page allocator so that buddy can use them. 8699 */ 8700 8701 ret = start_isolate_page_range(pfn_max_align_down(start), 8702 pfn_max_align_up(end), migratetype, 0); 8703 if (ret) 8704 return ret; 8705 8706 /* 8707 * In case of -EBUSY, we'd like to know which page causes problem. 8708 * So, just fall through. test_pages_isolated() has a tracepoint 8709 * which will report the busy page. 8710 * 8711 * It is possible that busy pages could become available before 8712 * the call to test_pages_isolated, and the range will actually be 8713 * allocated. So, if we fall through be sure to clear ret so that 8714 * -EBUSY is not accidentally used or returned to caller. 8715 */ 8716 ret = __alloc_contig_migrate_range(&cc, start, end); 8717 if (ret && ret != -EBUSY) 8718 goto done; 8719 ret =0; 8720 8721 /* 8722 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES 8723 * aligned blocks that are marked as MIGRATE_ISOLATE. What's 8724 * more, all pages in [start, end) are free in page allocator. 8725 * What we are going to do is to allocate all pages from 8726 * [start, end) (that is remove them from page allocator). 8727 * 8728 * The only problem is that pages at the beginning and at the 8729 * end of interesting range may be not aligned with pages that 8730 * page allocator holds, ie. they can be part of higher order 8731 * pages. Because of this, we reserve the bigger range and 8732 * once this is done free the pages we are not interested in. 8733 * 8734 * We don't have to hold zone->lock here because the pages are 8735 * isolated thus they won't get removed from buddy. 8736 */ 8737 8738 lru_add_drain_all(); 8739 8740 order = 0; 8741 outer_start = start; 8742 while (!PageBuddy(pfn_to_page(outer_start))) { 8743 if (++order >= MAX_ORDER) { 8744 outer_start = start; 8745 break; 8746 } 8747 outer_start &= ~0UL << order; 8748 } 8749 8750 if (outer_start != start) { 8751 order = buddy_order(pfn_to_page(outer_start)); 8752 8753 /* 8754 * outer_start page could be small order buddy page and 8755 * it doesn't include start page. Adjust outer_start 8756 * in this case to report failed page properly 8757 * on tracepoint in test_pages_isolated() 8758 */ 8759 if (outer_start + (1UL << order) <= start) 8760 outer_start = start; 8761 } 8762 8763 /* Make sure the range is really isolated. */ 8764 if (test_pages_isolated(outer_start, end, 0)) { 8765 pr_info_ratelimited("%s: [%lx, %lx) PFNs busy\n", 8766 __func__, outer_start, end); 8767 ret = -EBUSY; 8768 goto done; 8769 } 8770 8771 /* Grab isolated pages from freelists. */ 8772 outer_end = isolate_freepages_range(&cc, outer_start, end); 8773 if (!outer_end) { 8774 ret = -EBUSY; 8775 goto done; 8776 } 8777 8778 /* Free head and tail (if any) */ 8779 if (start != outer_start) 8780 free_contig_range(outer_start, start - outer_start); 8781 if (end != outer_end) 8782 free_contig_range(end, outer_end - end); 8783 8784done: 8785 undo_isolate_page_range(pfn_max_align_down(start), 8786 pfn_max_align_up(end), migratetype); 8787 return ret; 8788} 8789EXPORT_SYMBOL(alloc_contig_range); 8790 8791static int __alloc_contig_pages(unsigned long start_pfn, 8792 unsigned long nr_pages, gfp_t gfp_mask) 8793{ 8794 unsigned long end_pfn = start_pfn + nr_pages; 8795 8796 return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE, 8797 gfp_mask); 8798} 8799 8800static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn, 8801 unsigned long nr_pages) 8802{ 8803 unsigned long i, end_pfn = start_pfn + nr_pages; 8804 struct page *page; 8805 8806 for (i = start_pfn; i < end_pfn; i++) { 8807 page = pfn_to_online_page(i); 8808 if (!page) 8809 return false; 8810 8811 if (page_zone(page) != z) 8812 return false; 8813 8814 if (PageReserved(page)) 8815 return false; 8816 8817 if (page_count(page) > 0) 8818 return false; 8819 8820 if (PageHuge(page)) 8821 return false; 8822 } 8823 return true; 8824} 8825 8826static bool zone_spans_last_pfn(const struct zone *zone, 8827 unsigned long start_pfn, unsigned long nr_pages) 8828{ 8829 unsigned long last_pfn = start_pfn + nr_pages - 1; 8830 8831 return zone_spans_pfn(zone, last_pfn); 8832} 8833 8834/** 8835 * alloc_contig_pages() -- tries to find and allocate contiguous range of pages 8836 * @nr_pages: Number of contiguous pages to allocate 8837 * @gfp_mask: GFP mask to limit search and used during compaction 8838 * @nid: Target node 8839 * @nodemask: Mask for other possible nodes 8840 * 8841 * This routine is a wrapper around alloc_contig_range(). It scans over zones 8842 * on an applicable zonelist to find a contiguous pfn range which can then be 8843 * tried for allocation with alloc_contig_range(). This routine is intended 8844 * for allocation requests which can not be fulfilled with the buddy allocator. 8845 * 8846 * The allocated memory is always aligned to a page boundary. If nr_pages is a 8847 * power of two then the alignment is guaranteed to be to the given nr_pages 8848 * (e.g. 1GB request would be aligned to 1GB). 8849 * 8850 * Allocated pages can be freed with free_contig_range() or by manually calling 8851 * __free_page() on each allocated page. 8852 * 8853 * Return: pointer to contiguous pages on success, or NULL if not successful. 8854 */ 8855struct page *alloc_contig_pages(unsigned long nr_pages, gfp_t gfp_mask, 8856 int nid, nodemask_t *nodemask) 8857{ 8858 unsigned long ret, pfn, flags; 8859 struct zonelist *zonelist; 8860 struct zone *zone; 8861 struct zoneref *z; 8862 8863 zonelist = node_zonelist(nid, gfp_mask); 8864 for_each_zone_zonelist_nodemask(zone, z, zonelist, 8865 gfp_zone(gfp_mask), nodemask) { 8866 spin_lock_irqsave(&zone->lock, flags); 8867 8868 pfn = ALIGN(zone->zone_start_pfn, nr_pages); 8869 while (zone_spans_last_pfn(zone, pfn, nr_pages)) { 8870 if (pfn_range_valid_contig(zone, pfn, nr_pages)) { 8871 /* 8872 * We release the zone lock here because 8873 * alloc_contig_range() will also lock the zone 8874 * at some point. If there's an allocation 8875 * spinning on this lock, it may win the race 8876 * and cause alloc_contig_range() to fail... 8877 */ 8878 spin_unlock_irqrestore(&zone->lock, flags); 8879 ret = __alloc_contig_pages(pfn, nr_pages, 8880 gfp_mask); 8881 if (!ret) 8882 return pfn_to_page(pfn); 8883 spin_lock_irqsave(&zone->lock, flags); 8884 } 8885 pfn += nr_pages; 8886 } 8887 spin_unlock_irqrestore(&zone->lock, flags); 8888 } 8889 return NULL; 8890} 8891#endif /* CONFIG_CONTIG_ALLOC */ 8892 8893void free_contig_range(unsigned long pfn, unsigned int nr_pages) 8894{ 8895 unsigned int count = 0; 8896 8897 for (; nr_pages--; pfn++) { 8898 struct page *page = pfn_to_page(pfn); 8899 8900 count += page_count(page) != 1; 8901 __free_page(page); 8902 } 8903 WARN(count != 0, "%d pages are still in use!\n", count); 8904} 8905EXPORT_SYMBOL(free_contig_range); 8906 8907/* 8908 * The zone indicated has a new number of managed_pages; batch sizes and percpu 8909 * page high values need to be recalulated. 8910 */ 8911void __meminit zone_pcp_update(struct zone *zone) 8912{ 8913 mutex_lock(&pcp_batch_high_lock); 8914 __zone_pcp_update(zone); 8915 mutex_unlock(&pcp_batch_high_lock); 8916} 8917 8918void zone_pcp_reset(struct zone *zone) 8919{ 8920 unsigned long flags; 8921 int cpu; 8922 struct per_cpu_pageset *pset; 8923 8924 /* avoid races with drain_pages() */ 8925 local_irq_save(flags); 8926 if (zone->pageset != &boot_pageset) { 8927 for_each_online_cpu(cpu) { 8928 pset = per_cpu_ptr(zone->pageset, cpu); 8929 drain_zonestat(zone, pset); 8930 } 8931 free_percpu(zone->pageset); 8932 zone->pageset = &boot_pageset; 8933 } 8934 local_irq_restore(flags); 8935} 8936 8937#ifdef CONFIG_MEMORY_HOTREMOVE 8938/* 8939 * All pages in the range must be in a single zone, must not contain holes, 8940 * must span full sections, and must be isolated before calling this function. 8941 */ 8942void __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn) 8943{ 8944 unsigned long pfn = start_pfn; 8945 struct page *page; 8946 struct zone *zone; 8947 unsigned int order; 8948 unsigned long flags; 8949 8950 offline_mem_sections(pfn, end_pfn); 8951 zone = page_zone(pfn_to_page(pfn)); 8952 spin_lock_irqsave(&zone->lock, flags); 8953 while (pfn < end_pfn) { 8954 page = pfn_to_page(pfn); 8955 /* 8956 * The HWPoisoned page may be not in buddy system, and 8957 * page_count() is not 0. 8958 */ 8959 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) { 8960 pfn++; 8961 continue; 8962 } 8963 /* 8964 * At this point all remaining PageOffline() pages have a 8965 * reference count of 0 and can simply be skipped. 8966 */ 8967 if (PageOffline(page)) { 8968 BUG_ON(page_count(page)); 8969 BUG_ON(PageBuddy(page)); 8970 pfn++; 8971 continue; 8972 } 8973 8974 BUG_ON(page_count(page)); 8975 BUG_ON(!PageBuddy(page)); 8976 order = buddy_order(page); 8977 del_page_from_free_list(page, zone, order); 8978 pfn += (1 << order); 8979 } 8980 spin_unlock_irqrestore(&zone->lock, flags); 8981} 8982#endif 8983 8984bool is_free_buddy_page(struct page *page) 8985{ 8986 struct zone *zone = page_zone(page); 8987 unsigned long pfn = page_to_pfn(page); 8988 unsigned long flags; 8989 unsigned int order; 8990 8991 spin_lock_irqsave(&zone->lock, flags); 8992 for (order = 0; order < MAX_ORDER; order++) { 8993 struct page *page_head = page - (pfn & ((1 << order) - 1)); 8994 8995 if (PageBuddy(page_head) && buddy_order(page_head) >= order) 8996 break; 8997 } 8998 spin_unlock_irqrestore(&zone->lock, flags); 8999 9000 return order < MAX_ORDER; 9001} 9002 9003#ifdef CONFIG_MEMORY_FAILURE 9004/* 9005 * Break down a higher-order page in sub-pages, and keep our target out of 9006 * buddy allocator. 9007 */ 9008static void break_down_buddy_pages(struct zone *zone, struct page *page, 9009 struct page *target, int low, int high, 9010 int migratetype) 9011{ 9012 unsigned long size = 1 << high; 9013 struct page *current_buddy, *next_page; 9014 9015 while (high > low) { 9016 high--; 9017 size >>= 1; 9018 9019 if (target >= &page[size]) { 9020 next_page = page + size; 9021 current_buddy = page; 9022 } else { 9023 next_page = page; 9024 current_buddy = page + size; 9025 } 9026 page = next_page; 9027 9028 if (set_page_guard(zone, current_buddy, high, migratetype)) 9029 continue; 9030 9031 if (current_buddy != target) { 9032 add_to_free_list(current_buddy, zone, high, migratetype); 9033 set_buddy_order(current_buddy, high); 9034 } 9035 } 9036} 9037 9038/* 9039 * Take a page that will be marked as poisoned off the buddy allocator. 9040 */ 9041bool take_page_off_buddy(struct page *page) 9042{ 9043 struct zone *zone = page_zone(page); 9044 unsigned long pfn = page_to_pfn(page); 9045 unsigned long flags; 9046 unsigned int order; 9047 bool ret = false; 9048 9049 spin_lock_irqsave(&zone->lock, flags); 9050 for (order = 0; order < MAX_ORDER; order++) { 9051 struct page *page_head = page - (pfn & ((1 << order) - 1)); 9052 int page_order = buddy_order(page_head); 9053 9054 if (PageBuddy(page_head) && page_order >= order) { 9055 unsigned long pfn_head = page_to_pfn(page_head); 9056 int migratetype = get_pfnblock_migratetype(page_head, 9057 pfn_head); 9058 9059 del_page_from_free_list(page_head, zone, page_order); 9060 break_down_buddy_pages(zone, page_head, page, 0, 9061 page_order, migratetype); 9062 if (!is_migrate_isolate(migratetype)) 9063 __mod_zone_freepage_state(zone, -1, migratetype); 9064 ret = true; 9065 break; 9066 } 9067 if (page_count(page_head) > 0) 9068 break; 9069 } 9070 spin_unlock_irqrestore(&zone->lock, flags); 9071 return ret; 9072} 9073#endif 9074 9075#ifdef CONFIG_ZONE_DMA 9076bool has_managed_dma(void) 9077{ 9078 struct pglist_data *pgdat; 9079 9080 for_each_online_pgdat(pgdat) { 9081 struct zone *zone = &pgdat->node_zones[ZONE_DMA]; 9082 9083 if (managed_zone(zone)) 9084 return true; 9085 } 9086 return false; 9087} 9088#endif /* CONFIG_ZONE_DMA */ 9089