1 // SPDX-License-Identifier: GPL-2.0-only
3 * linux/mm/page_alloc.c
5 * Manages the free list, the system allocates free pages here.
6 * Note that kmalloc() lives in slab.c
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)
18 #include <linux/stddef.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/mmu_notifier.h>
61 #include <linux/migrate.h>
62 #include <linux/hugetlb.h>
63 #include <linux/sched/rt.h>
64 #include <linux/sched/mm.h>
65 #include <linux/page_owner.h>
66 #include <linux/kthread.h>
67 #include <linux/memcontrol.h>
68 #include <linux/ftrace.h>
69 #include <linux/lockdep.h>
70 #include <linux/nmi.h>
71 #include <linux/psi.h>
72 #include <linux/padata.h>
73 #include <linux/khugepaged.h>
74 #include <linux/buffer_head.h>
75 #include <asm/sections.h>
76 #include <asm/tlbflush.h>
77 #include <asm/div64.h>
80 #include "page_reporting.h"
82 /* Free Page Internal flags: for internal, non-pcp variants of free_pages(). */
83 typedef int __bitwise fpi_t;
85 /* No special request */
86 #define FPI_NONE ((__force fpi_t)0)
89 * Skip free page reporting notification for the (possibly merged) page.
90 * This does not hinder free page reporting from grabbing the page,
91 * reporting it and marking it "reported" - it only skips notifying
92 * the free page reporting infrastructure about a newly freed page. For
93 * example, used when temporarily pulling a page from a freelist and
94 * putting it back unmodified.
96 #define FPI_SKIP_REPORT_NOTIFY ((__force fpi_t)BIT(0))
99 * Place the (possibly merged) page to the tail of the freelist. Will ignore
100 * page shuffling (relevant code - e.g., memory onlining - is expected to
101 * shuffle the whole zone).
103 * Note: No code should rely on this flag for correctness - it's purely
104 * to allow for optimizations when handing back either fresh pages
105 * (memory onlining) or untouched pages (page isolation, free page
108 #define FPI_TO_TAIL ((__force fpi_t)BIT(1))
111 * Don't poison memory with KASAN (only for the tag-based modes).
112 * During boot, all non-reserved memblock memory is exposed to page_alloc.
113 * Poisoning all that memory lengthens boot time, especially on systems with
114 * large amount of RAM. This flag is used to skip that poisoning.
115 * This is only done for the tag-based KASAN modes, as those are able to
116 * detect memory corruptions with the memory tags assigned by default.
117 * All memory allocated normally after boot gets poisoned as usual.
119 #define FPI_SKIP_KASAN_POISON ((__force fpi_t)BIT(2))
121 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
122 static DEFINE_MUTEX(pcp_batch_high_lock);
126 #if defined(CONFIG_DEBUG_INFO_BTF) && \
127 !defined(CONFIG_DEBUG_LOCK_ALLOC) && \
128 !defined(CONFIG_PAHOLE_HAS_ZEROSIZE_PERCPU_SUPPORT)
130 * pahole 1.21 and earlier gets confused by zero-sized per-CPU
131 * variables and produces invalid BTF. Ensure that
132 * sizeof(struct pagesets) != 0 for older versions of pahole.
135 #warning "pahole too old to support zero-sized struct pagesets"
138 static DEFINE_PER_CPU(struct pagesets, pagesets) = {
139 .lock = INIT_LOCAL_LOCK(lock),
142 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
143 DEFINE_PER_CPU(int, numa_node);
144 EXPORT_PER_CPU_SYMBOL(numa_node);
147 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
149 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
151 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
152 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
153 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
154 * defined in <linux/topology.h>.
156 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
157 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
160 /* work_structs for global per-cpu drains */
163 struct work_struct work;
165 static DEFINE_MUTEX(pcpu_drain_mutex);
166 static DEFINE_PER_CPU(struct pcpu_drain, pcpu_drain);
168 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
169 volatile unsigned long latent_entropy __latent_entropy;
170 EXPORT_SYMBOL(latent_entropy);
174 * Array of node states.
176 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
177 [N_POSSIBLE] = NODE_MASK_ALL,
178 [N_ONLINE] = { { [0] = 1UL } },
180 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
181 #ifdef CONFIG_HIGHMEM
182 [N_HIGH_MEMORY] = { { [0] = 1UL } },
184 [N_MEMORY] = { { [0] = 1UL } },
185 [N_CPU] = { { [0] = 1UL } },
188 EXPORT_SYMBOL(node_states);
190 atomic_long_t _totalram_pages __read_mostly;
191 EXPORT_SYMBOL(_totalram_pages);
192 unsigned long totalreserve_pages __read_mostly;
193 unsigned long totalcma_pages __read_mostly;
195 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
196 DEFINE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_ALLOC_DEFAULT_ON, init_on_alloc);
197 EXPORT_SYMBOL(init_on_alloc);
199 DEFINE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_FREE_DEFAULT_ON, init_on_free);
200 EXPORT_SYMBOL(init_on_free);
202 static bool _init_on_alloc_enabled_early __read_mostly
203 = IS_ENABLED(CONFIG_INIT_ON_ALLOC_DEFAULT_ON);
204 static int __init early_init_on_alloc(char *buf)
207 return kstrtobool(buf, &_init_on_alloc_enabled_early);
209 early_param("init_on_alloc", early_init_on_alloc);
211 static bool _init_on_free_enabled_early __read_mostly
212 = IS_ENABLED(CONFIG_INIT_ON_FREE_DEFAULT_ON);
213 static int __init early_init_on_free(char *buf)
215 return kstrtobool(buf, &_init_on_free_enabled_early);
217 early_param("init_on_free", early_init_on_free);
220 * A cached value of the page's pageblock's migratetype, used when the page is
221 * put on a pcplist. Used to avoid the pageblock migratetype lookup when
222 * freeing from pcplists in most cases, at the cost of possibly becoming stale.
223 * Also the migratetype set in the page does not necessarily match the pcplist
224 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
225 * other index - this ensures that it will be put on the correct CMA freelist.
227 static inline int get_pcppage_migratetype(struct page *page)
232 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
234 page->index = migratetype;
237 #ifdef CONFIG_PM_SLEEP
239 * The following functions are used by the suspend/hibernate code to temporarily
240 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
241 * while devices are suspended. To avoid races with the suspend/hibernate code,
242 * they should always be called with system_transition_mutex held
243 * (gfp_allowed_mask also should only be modified with system_transition_mutex
244 * held, unless the suspend/hibernate code is guaranteed not to run in parallel
245 * with that modification).
248 static gfp_t saved_gfp_mask;
250 void pm_restore_gfp_mask(void)
252 WARN_ON(!mutex_is_locked(&system_transition_mutex));
253 if (saved_gfp_mask) {
254 gfp_allowed_mask = saved_gfp_mask;
259 void pm_restrict_gfp_mask(void)
261 WARN_ON(!mutex_is_locked(&system_transition_mutex));
262 WARN_ON(saved_gfp_mask);
263 saved_gfp_mask = gfp_allowed_mask;
264 gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
267 bool pm_suspended_storage(void)
269 if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
273 #endif /* CONFIG_PM_SLEEP */
275 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
276 unsigned int pageblock_order __read_mostly;
279 static void __free_pages_ok(struct page *page, unsigned int order,
283 * results with 256, 32 in the lowmem_reserve sysctl:
284 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
285 * 1G machine -> (16M dma, 784M normal, 224M high)
286 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
287 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
288 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
290 * TBD: should special case ZONE_DMA32 machines here - in those we normally
291 * don't need any ZONE_NORMAL reservation
293 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
294 #ifdef CONFIG_ZONE_DMA
297 #ifdef CONFIG_ZONE_DMA32
301 #ifdef CONFIG_HIGHMEM
307 static char * const zone_names[MAX_NR_ZONES] = {
308 #ifdef CONFIG_ZONE_DMA
311 #ifdef CONFIG_ZONE_DMA32
315 #ifdef CONFIG_HIGHMEM
319 #ifdef CONFIG_ZONE_DEVICE
324 const char * const migratetype_names[MIGRATE_TYPES] = {
332 #ifdef CONFIG_MEMORY_ISOLATION
337 compound_page_dtor * const compound_page_dtors[NR_COMPOUND_DTORS] = {
338 [NULL_COMPOUND_DTOR] = NULL,
339 [COMPOUND_PAGE_DTOR] = free_compound_page,
340 #ifdef CONFIG_HUGETLB_PAGE
341 [HUGETLB_PAGE_DTOR] = free_huge_page,
343 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
344 [TRANSHUGE_PAGE_DTOR] = free_transhuge_page,
348 int min_free_kbytes = 1024;
349 int user_min_free_kbytes = -1;
350 #ifdef CONFIG_DISCONTIGMEM
352 * DiscontigMem defines memory ranges as separate pg_data_t even if the ranges
353 * are not on separate NUMA nodes. Functionally this works but with
354 * watermark_boost_factor, it can reclaim prematurely as the ranges can be
355 * quite small. By default, do not boost watermarks on discontigmem as in
356 * many cases very high-order allocations like THP are likely to be
357 * unsupported and the premature reclaim offsets the advantage of long-term
358 * fragmentation avoidance.
360 int watermark_boost_factor __read_mostly;
362 int watermark_boost_factor __read_mostly = 15000;
364 int watermark_scale_factor = 10;
366 static unsigned long nr_kernel_pages __initdata;
367 static unsigned long nr_all_pages __initdata;
368 static unsigned long dma_reserve __initdata;
370 static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata;
371 static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata;
372 static unsigned long required_kernelcore __initdata;
373 static unsigned long required_kernelcore_percent __initdata;
374 static unsigned long required_movablecore __initdata;
375 static unsigned long required_movablecore_percent __initdata;
376 static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata;
377 static bool mirrored_kernelcore __meminitdata;
379 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
381 EXPORT_SYMBOL(movable_zone);
384 unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
385 unsigned int nr_online_nodes __read_mostly = 1;
386 EXPORT_SYMBOL(nr_node_ids);
387 EXPORT_SYMBOL(nr_online_nodes);
390 int page_group_by_mobility_disabled __read_mostly;
392 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
394 * During boot we initialize deferred pages on-demand, as needed, but once
395 * page_alloc_init_late() has finished, the deferred pages are all initialized,
396 * and we can permanently disable that path.
398 static DEFINE_STATIC_KEY_TRUE(deferred_pages);
401 * Calling kasan_free_pages() only after deferred memory initialization
402 * has completed. Poisoning pages during deferred memory init will greatly
403 * lengthen the process and cause problem in large memory systems as the
404 * deferred pages initialization is done with interrupt disabled.
406 * Assuming that there will be no reference to those newly initialized
407 * pages before they are ever allocated, this should have no effect on
408 * KASAN memory tracking as the poison will be properly inserted at page
409 * allocation time. The only corner case is when pages are allocated by
410 * on-demand allocation and then freed again before the deferred pages
411 * initialization is done, but this is not likely to happen.
413 static inline void kasan_free_nondeferred_pages(struct page *page, int order,
414 bool init, fpi_t fpi_flags)
416 if (static_branch_unlikely(&deferred_pages))
418 if (!IS_ENABLED(CONFIG_KASAN_GENERIC) &&
419 (fpi_flags & FPI_SKIP_KASAN_POISON))
421 kasan_free_pages(page, order, init);
424 /* Returns true if the struct page for the pfn is uninitialised */
425 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
427 int nid = early_pfn_to_nid(pfn);
429 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
436 * Returns true when the remaining initialisation should be deferred until
437 * later in the boot cycle when it can be parallelised.
439 static bool __meminit
440 defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
442 static unsigned long prev_end_pfn, nr_initialised;
445 * prev_end_pfn static that contains the end of previous zone
446 * No need to protect because called very early in boot before smp_init.
448 if (prev_end_pfn != end_pfn) {
449 prev_end_pfn = end_pfn;
453 /* Always populate low zones for address-constrained allocations */
454 if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
457 if (NODE_DATA(nid)->first_deferred_pfn != ULONG_MAX)
460 * We start only with one section of pages, more pages are added as
461 * needed until the rest of deferred pages are initialized.
464 if ((nr_initialised > PAGES_PER_SECTION) &&
465 (pfn & (PAGES_PER_SECTION - 1)) == 0) {
466 NODE_DATA(nid)->first_deferred_pfn = pfn;
472 static inline void kasan_free_nondeferred_pages(struct page *page, int order,
473 bool init, fpi_t fpi_flags)
475 if (!IS_ENABLED(CONFIG_KASAN_GENERIC) &&
476 (fpi_flags & FPI_SKIP_KASAN_POISON))
478 kasan_free_pages(page, order, init);
481 static inline bool early_page_uninitialised(unsigned long pfn)
486 static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
492 /* Return a pointer to the bitmap storing bits affecting a block of pages */
493 static inline unsigned long *get_pageblock_bitmap(const struct page *page,
496 #ifdef CONFIG_SPARSEMEM
497 return section_to_usemap(__pfn_to_section(pfn));
499 return page_zone(page)->pageblock_flags;
500 #endif /* CONFIG_SPARSEMEM */
503 static inline int pfn_to_bitidx(const struct page *page, unsigned long pfn)
505 #ifdef CONFIG_SPARSEMEM
506 pfn &= (PAGES_PER_SECTION-1);
508 pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
509 #endif /* CONFIG_SPARSEMEM */
510 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
513 static __always_inline
514 unsigned long __get_pfnblock_flags_mask(const struct page *page,
518 unsigned long *bitmap;
519 unsigned long bitidx, word_bitidx;
522 bitmap = get_pageblock_bitmap(page, pfn);
523 bitidx = pfn_to_bitidx(page, pfn);
524 word_bitidx = bitidx / BITS_PER_LONG;
525 bitidx &= (BITS_PER_LONG-1);
527 word = bitmap[word_bitidx];
528 return (word >> bitidx) & mask;
532 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
533 * @page: The page within the block of interest
534 * @pfn: The target page frame number
535 * @mask: mask of bits that the caller is interested in
537 * Return: pageblock_bits flags
539 unsigned long get_pfnblock_flags_mask(const struct page *page,
540 unsigned long pfn, unsigned long mask)
542 return __get_pfnblock_flags_mask(page, pfn, mask);
545 static __always_inline int get_pfnblock_migratetype(const struct page *page,
548 return __get_pfnblock_flags_mask(page, pfn, MIGRATETYPE_MASK);
552 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
553 * @page: The page within the block of interest
554 * @flags: The flags to set
555 * @pfn: The target page frame number
556 * @mask: mask of bits that the caller is interested in
558 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
562 unsigned long *bitmap;
563 unsigned long bitidx, word_bitidx;
564 unsigned long old_word, word;
566 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
567 BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits));
569 bitmap = get_pageblock_bitmap(page, pfn);
570 bitidx = pfn_to_bitidx(page, pfn);
571 word_bitidx = bitidx / BITS_PER_LONG;
572 bitidx &= (BITS_PER_LONG-1);
574 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
579 word = READ_ONCE(bitmap[word_bitidx]);
581 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
582 if (word == old_word)
588 void set_pageblock_migratetype(struct page *page, int migratetype)
590 if (unlikely(page_group_by_mobility_disabled &&
591 migratetype < MIGRATE_PCPTYPES))
592 migratetype = MIGRATE_UNMOVABLE;
594 set_pfnblock_flags_mask(page, (unsigned long)migratetype,
595 page_to_pfn(page), MIGRATETYPE_MASK);
598 #ifdef CONFIG_DEBUG_VM
599 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
603 unsigned long pfn = page_to_pfn(page);
604 unsigned long sp, start_pfn;
607 seq = zone_span_seqbegin(zone);
608 start_pfn = zone->zone_start_pfn;
609 sp = zone->spanned_pages;
610 if (!zone_spans_pfn(zone, pfn))
612 } while (zone_span_seqretry(zone, seq));
615 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
616 pfn, zone_to_nid(zone), zone->name,
617 start_pfn, start_pfn + sp);
622 static int page_is_consistent(struct zone *zone, struct page *page)
624 if (!pfn_valid_within(page_to_pfn(page)))
626 if (zone != page_zone(page))
632 * Temporary debugging check for pages not lying within a given zone.
634 static int __maybe_unused bad_range(struct zone *zone, struct page *page)
636 if (page_outside_zone_boundaries(zone, page))
638 if (!page_is_consistent(zone, page))
644 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
650 static void bad_page(struct page *page, const char *reason)
652 static unsigned long resume;
653 static unsigned long nr_shown;
654 static unsigned long nr_unshown;
657 * Allow a burst of 60 reports, then keep quiet for that minute;
658 * or allow a steady drip of one report per second.
660 if (nr_shown == 60) {
661 if (time_before(jiffies, resume)) {
667 "BUG: Bad page state: %lu messages suppressed\n",
674 resume = jiffies + 60 * HZ;
676 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
677 current->comm, page_to_pfn(page));
678 dump_page(page, reason);
683 /* Leave bad fields for debug, except PageBuddy could make trouble */
684 page_mapcount_reset(page); /* remove PageBuddy */
685 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
689 * Higher-order pages are called "compound pages". They are structured thusly:
691 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
693 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
694 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
696 * The first tail page's ->compound_dtor holds the offset in array of compound
697 * page destructors. See compound_page_dtors.
699 * The first tail page's ->compound_order holds the order of allocation.
700 * This usage means that zero-order pages may not be compound.
703 void free_compound_page(struct page *page)
705 mem_cgroup_uncharge(page);
706 __free_pages_ok(page, compound_order(page), FPI_NONE);
709 void prep_compound_page(struct page *page, unsigned int order)
712 int nr_pages = 1 << order;
715 for (i = 1; i < nr_pages; i++) {
716 struct page *p = page + i;
717 set_page_count(p, 0);
718 p->mapping = TAIL_MAPPING;
719 set_compound_head(p, page);
722 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
723 set_compound_order(page, order);
724 atomic_set(compound_mapcount_ptr(page), -1);
725 if (hpage_pincount_available(page))
726 atomic_set(compound_pincount_ptr(page), 0);
729 #ifdef CONFIG_DEBUG_PAGEALLOC
730 unsigned int _debug_guardpage_minorder;
732 bool _debug_pagealloc_enabled_early __read_mostly
733 = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
734 EXPORT_SYMBOL(_debug_pagealloc_enabled_early);
735 DEFINE_STATIC_KEY_FALSE(_debug_pagealloc_enabled);
736 EXPORT_SYMBOL(_debug_pagealloc_enabled);
738 DEFINE_STATIC_KEY_FALSE(_debug_guardpage_enabled);
740 static int __init early_debug_pagealloc(char *buf)
742 return kstrtobool(buf, &_debug_pagealloc_enabled_early);
744 early_param("debug_pagealloc", early_debug_pagealloc);
746 static int __init debug_guardpage_minorder_setup(char *buf)
750 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
751 pr_err("Bad debug_guardpage_minorder value\n");
754 _debug_guardpage_minorder = res;
755 pr_info("Setting debug_guardpage_minorder to %lu\n", res);
758 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
760 static inline bool set_page_guard(struct zone *zone, struct page *page,
761 unsigned int order, int migratetype)
763 if (!debug_guardpage_enabled())
766 if (order >= debug_guardpage_minorder())
769 __SetPageGuard(page);
770 INIT_LIST_HEAD(&page->lru);
771 set_page_private(page, order);
772 /* Guard pages are not available for any usage */
773 __mod_zone_freepage_state(zone, -(1 << order), migratetype);
778 static inline void clear_page_guard(struct zone *zone, struct page *page,
779 unsigned int order, int migratetype)
781 if (!debug_guardpage_enabled())
784 __ClearPageGuard(page);
786 set_page_private(page, 0);
787 if (!is_migrate_isolate(migratetype))
788 __mod_zone_freepage_state(zone, (1 << order), migratetype);
791 static inline bool set_page_guard(struct zone *zone, struct page *page,
792 unsigned int order, int migratetype) { return false; }
793 static inline void clear_page_guard(struct zone *zone, struct page *page,
794 unsigned int order, int migratetype) {}
798 * Enable static keys related to various memory debugging and hardening options.
799 * Some override others, and depend on early params that are evaluated in the
800 * order of appearance. So we need to first gather the full picture of what was
801 * enabled, and then make decisions.
803 void init_mem_debugging_and_hardening(void)
805 bool page_poisoning_requested = false;
807 #ifdef CONFIG_PAGE_POISONING
809 * Page poisoning is debug page alloc for some arches. If
810 * either of those options are enabled, enable poisoning.
812 if (page_poisoning_enabled() ||
813 (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_DEBUG_PAGEALLOC) &&
814 debug_pagealloc_enabled())) {
815 static_branch_enable(&_page_poisoning_enabled);
816 page_poisoning_requested = true;
820 if (_init_on_alloc_enabled_early) {
821 if (page_poisoning_requested)
822 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, "
823 "will take precedence over init_on_alloc\n");
825 static_branch_enable(&init_on_alloc);
827 if (_init_on_free_enabled_early) {
828 if (page_poisoning_requested)
829 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, "
830 "will take precedence over init_on_free\n");
832 static_branch_enable(&init_on_free);
835 #ifdef CONFIG_DEBUG_PAGEALLOC
836 if (!debug_pagealloc_enabled())
839 static_branch_enable(&_debug_pagealloc_enabled);
841 if (!debug_guardpage_minorder())
844 static_branch_enable(&_debug_guardpage_enabled);
848 static inline void set_buddy_order(struct page *page, unsigned int order)
850 set_page_private(page, order);
851 __SetPageBuddy(page);
855 * This function checks whether a page is free && is the buddy
856 * we can coalesce a page and its buddy if
857 * (a) the buddy is not in a hole (check before calling!) &&
858 * (b) the buddy is in the buddy system &&
859 * (c) a page and its buddy have the same order &&
860 * (d) a page and its buddy are in the same zone.
862 * For recording whether a page is in the buddy system, we set PageBuddy.
863 * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
865 * For recording page's order, we use page_private(page).
867 static inline bool page_is_buddy(struct page *page, struct page *buddy,
870 if (!page_is_guard(buddy) && !PageBuddy(buddy))
873 if (buddy_order(buddy) != order)
877 * zone check is done late to avoid uselessly calculating
878 * zone/node ids for pages that could never merge.
880 if (page_zone_id(page) != page_zone_id(buddy))
883 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
888 #ifdef CONFIG_COMPACTION
889 static inline struct capture_control *task_capc(struct zone *zone)
891 struct capture_control *capc = current->capture_control;
893 return unlikely(capc) &&
894 !(current->flags & PF_KTHREAD) &&
896 capc->cc->zone == zone ? capc : NULL;
900 compaction_capture(struct capture_control *capc, struct page *page,
901 int order, int migratetype)
903 if (!capc || order != capc->cc->order)
906 /* Do not accidentally pollute CMA or isolated regions*/
907 if (is_migrate_cma(migratetype) ||
908 is_migrate_isolate(migratetype))
912 * Do not let lower order allocations pollute a movable pageblock.
913 * This might let an unmovable request use a reclaimable pageblock
914 * and vice-versa but no more than normal fallback logic which can
915 * have trouble finding a high-order free page.
917 if (order < pageblock_order && migratetype == MIGRATE_MOVABLE)
925 static inline struct capture_control *task_capc(struct zone *zone)
931 compaction_capture(struct capture_control *capc, struct page *page,
932 int order, int migratetype)
936 #endif /* CONFIG_COMPACTION */
938 /* Used for pages not on another list */
939 static inline void add_to_free_list(struct page *page, struct zone *zone,
940 unsigned int order, int migratetype)
942 struct free_area *area = &zone->free_area[order];
944 list_add(&page->lru, &area->free_list[migratetype]);
948 /* Used for pages not on another list */
949 static inline void add_to_free_list_tail(struct page *page, struct zone *zone,
950 unsigned int order, int migratetype)
952 struct free_area *area = &zone->free_area[order];
954 list_add_tail(&page->lru, &area->free_list[migratetype]);
959 * Used for pages which are on another list. Move the pages to the tail
960 * of the list - so the moved pages won't immediately be considered for
961 * allocation again (e.g., optimization for memory onlining).
963 static inline void move_to_free_list(struct page *page, struct zone *zone,
964 unsigned int order, int migratetype)
966 struct free_area *area = &zone->free_area[order];
968 list_move_tail(&page->lru, &area->free_list[migratetype]);
971 static inline void del_page_from_free_list(struct page *page, struct zone *zone,
974 /* clear reported state and update reported page count */
975 if (page_reported(page))
976 __ClearPageReported(page);
978 list_del(&page->lru);
979 __ClearPageBuddy(page);
980 set_page_private(page, 0);
981 zone->free_area[order].nr_free--;
985 * If this is not the largest possible page, check if the buddy
986 * of the next-highest order is free. If it is, it's possible
987 * that pages are being freed that will coalesce soon. In case,
988 * that is happening, add the free page to the tail of the list
989 * so it's less likely to be used soon and more likely to be merged
990 * as a higher order page
993 buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
994 struct page *page, unsigned int order)
996 struct page *higher_page, *higher_buddy;
997 unsigned long combined_pfn;
999 if (order >= MAX_ORDER - 2)
1002 if (!pfn_valid_within(buddy_pfn))
1005 combined_pfn = buddy_pfn & pfn;
1006 higher_page = page + (combined_pfn - pfn);
1007 buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
1008 higher_buddy = higher_page + (buddy_pfn - combined_pfn);
1010 return pfn_valid_within(buddy_pfn) &&
1011 page_is_buddy(higher_page, higher_buddy, order + 1);
1015 * Freeing function for a buddy system allocator.
1017 * The concept of a buddy system is to maintain direct-mapped table
1018 * (containing bit values) for memory blocks of various "orders".
1019 * The bottom level table contains the map for the smallest allocatable
1020 * units of memory (here, pages), and each level above it describes
1021 * pairs of units from the levels below, hence, "buddies".
1022 * At a high level, all that happens here is marking the table entry
1023 * at the bottom level available, and propagating the changes upward
1024 * as necessary, plus some accounting needed to play nicely with other
1025 * parts of the VM system.
1026 * At each level, we keep a list of pages, which are heads of continuous
1027 * free pages of length of (1 << order) and marked with PageBuddy.
1028 * Page's order is recorded in page_private(page) field.
1029 * So when we are allocating or freeing one, we can derive the state of the
1030 * other. That is, if we allocate a small block, and both were
1031 * free, the remainder of the region must be split into blocks.
1032 * If a block is freed, and its buddy is also free, then this
1033 * triggers coalescing into a block of larger size.
1038 static inline void __free_one_page(struct page *page,
1040 struct zone *zone, unsigned int order,
1041 int migratetype, fpi_t fpi_flags)
1043 struct capture_control *capc = task_capc(zone);
1044 unsigned long buddy_pfn;
1045 unsigned long combined_pfn;
1046 unsigned int max_order;
1050 max_order = min_t(unsigned int, MAX_ORDER - 1, pageblock_order);
1052 VM_BUG_ON(!zone_is_initialized(zone));
1053 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
1055 VM_BUG_ON(migratetype == -1);
1056 if (likely(!is_migrate_isolate(migratetype)))
1057 __mod_zone_freepage_state(zone, 1 << order, migratetype);
1059 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
1060 VM_BUG_ON_PAGE(bad_range(zone, page), page);
1063 while (order < max_order) {
1064 if (compaction_capture(capc, page, order, migratetype)) {
1065 __mod_zone_freepage_state(zone, -(1 << order),
1069 buddy_pfn = __find_buddy_pfn(pfn, order);
1070 buddy = page + (buddy_pfn - pfn);
1072 if (!pfn_valid_within(buddy_pfn))
1074 if (!page_is_buddy(page, buddy, order))
1077 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
1078 * merge with it and move up one order.
1080 if (page_is_guard(buddy))
1081 clear_page_guard(zone, buddy, order, migratetype);
1083 del_page_from_free_list(buddy, zone, order);
1084 combined_pfn = buddy_pfn & pfn;
1085 page = page + (combined_pfn - pfn);
1089 if (order < MAX_ORDER - 1) {
1090 /* If we are here, it means order is >= pageblock_order.
1091 * We want to prevent merge between freepages on isolate
1092 * pageblock and normal pageblock. Without this, pageblock
1093 * isolation could cause incorrect freepage or CMA accounting.
1095 * We don't want to hit this code for the more frequent
1096 * low-order merging.
1098 if (unlikely(has_isolate_pageblock(zone))) {
1101 buddy_pfn = __find_buddy_pfn(pfn, order);
1102 buddy = page + (buddy_pfn - pfn);
1103 buddy_mt = get_pageblock_migratetype(buddy);
1105 if (migratetype != buddy_mt
1106 && (is_migrate_isolate(migratetype) ||
1107 is_migrate_isolate(buddy_mt)))
1110 max_order = order + 1;
1111 goto continue_merging;
1115 set_buddy_order(page, order);
1117 if (fpi_flags & FPI_TO_TAIL)
1119 else if (is_shuffle_order(order))
1120 to_tail = shuffle_pick_tail();
1122 to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
1125 add_to_free_list_tail(page, zone, order, migratetype);
1127 add_to_free_list(page, zone, order, migratetype);
1129 /* Notify page reporting subsystem of freed page */
1130 if (!(fpi_flags & FPI_SKIP_REPORT_NOTIFY))
1131 page_reporting_notify_free(order);
1135 * A bad page could be due to a number of fields. Instead of multiple branches,
1136 * try and check multiple fields with one check. The caller must do a detailed
1137 * check if necessary.
1139 static inline bool page_expected_state(struct page *page,
1140 unsigned long check_flags)
1142 if (unlikely(atomic_read(&page->_mapcount) != -1))
1145 if (unlikely((unsigned long)page->mapping |
1146 page_ref_count(page) |
1150 (page->flags & check_flags)))
1156 static const char *page_bad_reason(struct page *page, unsigned long flags)
1158 const char *bad_reason = NULL;
1160 if (unlikely(atomic_read(&page->_mapcount) != -1))
1161 bad_reason = "nonzero mapcount";
1162 if (unlikely(page->mapping != NULL))
1163 bad_reason = "non-NULL mapping";
1164 if (unlikely(page_ref_count(page) != 0))
1165 bad_reason = "nonzero _refcount";
1166 if (unlikely(page->flags & flags)) {
1167 if (flags == PAGE_FLAGS_CHECK_AT_PREP)
1168 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag(s) set";
1170 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
1173 if (unlikely(page->memcg_data))
1174 bad_reason = "page still charged to cgroup";
1179 static void check_free_page_bad(struct page *page)
1182 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_FREE));
1185 static inline int check_free_page(struct page *page)
1187 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
1190 /* Something has gone sideways, find it */
1191 check_free_page_bad(page);
1195 static int free_tail_pages_check(struct page *head_page, struct page *page)
1200 * We rely page->lru.next never has bit 0 set, unless the page
1201 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
1203 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
1205 if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
1209 switch (page - head_page) {
1211 /* the first tail page: ->mapping may be compound_mapcount() */
1212 if (unlikely(compound_mapcount(page))) {
1213 bad_page(page, "nonzero compound_mapcount");
1219 * the second tail page: ->mapping is
1220 * deferred_list.next -- ignore value.
1224 if (page->mapping != TAIL_MAPPING) {
1225 bad_page(page, "corrupted mapping in tail page");
1230 if (unlikely(!PageTail(page))) {
1231 bad_page(page, "PageTail not set");
1234 if (unlikely(compound_head(page) != head_page)) {
1235 bad_page(page, "compound_head not consistent");
1240 page->mapping = NULL;
1241 clear_compound_head(page);
1245 static void kernel_init_free_pages(struct page *page, int numpages)
1249 /* s390's use of memset() could override KASAN redzones. */
1250 kasan_disable_current();
1251 for (i = 0; i < numpages; i++) {
1252 u8 tag = page_kasan_tag(page + i);
1253 page_kasan_tag_reset(page + i);
1254 clear_highpage(page + i);
1255 page_kasan_tag_set(page + i, tag);
1257 kasan_enable_current();
1260 static __always_inline bool free_pages_prepare(struct page *page,
1261 unsigned int order, bool check_free, fpi_t fpi_flags)
1266 VM_BUG_ON_PAGE(PageTail(page), page);
1268 trace_mm_page_free(page, order);
1270 if (unlikely(PageHWPoison(page)) && !order) {
1272 * Do not let hwpoison pages hit pcplists/buddy
1273 * Untie memcg state and reset page's owner
1275 if (memcg_kmem_enabled() && PageMemcgKmem(page))
1276 __memcg_kmem_uncharge_page(page, order);
1277 reset_page_owner(page, order);
1282 * Check tail pages before head page information is cleared to
1283 * avoid checking PageCompound for order-0 pages.
1285 if (unlikely(order)) {
1286 bool compound = PageCompound(page);
1289 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1292 ClearPageDoubleMap(page);
1293 for (i = 1; i < (1 << order); i++) {
1295 bad += free_tail_pages_check(page, page + i);
1296 if (unlikely(check_free_page(page + i))) {
1300 (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1303 if (PageMappingFlags(page))
1304 page->mapping = NULL;
1305 if (memcg_kmem_enabled() && PageMemcgKmem(page))
1306 __memcg_kmem_uncharge_page(page, order);
1308 bad += check_free_page(page);
1312 page_cpupid_reset_last(page);
1313 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1314 reset_page_owner(page, order);
1316 if (!PageHighMem(page)) {
1317 debug_check_no_locks_freed(page_address(page),
1318 PAGE_SIZE << order);
1319 debug_check_no_obj_freed(page_address(page),
1320 PAGE_SIZE << order);
1323 kernel_poison_pages(page, 1 << order);
1326 * As memory initialization might be integrated into KASAN,
1327 * kasan_free_pages and kernel_init_free_pages must be
1328 * kept together to avoid discrepancies in behavior.
1330 * With hardware tag-based KASAN, memory tags must be set before the
1331 * page becomes unavailable via debug_pagealloc or arch_free_page.
1333 init = want_init_on_free();
1334 if (init && !kasan_has_integrated_init())
1335 kernel_init_free_pages(page, 1 << order);
1336 kasan_free_nondeferred_pages(page, order, init, fpi_flags);
1339 * arch_free_page() can make the page's contents inaccessible. s390
1340 * does this. So nothing which can access the page's contents should
1341 * happen after this.
1343 arch_free_page(page, order);
1345 debug_pagealloc_unmap_pages(page, 1 << order);
1350 #ifdef CONFIG_DEBUG_VM
1352 * With DEBUG_VM enabled, order-0 pages are checked immediately when being freed
1353 * to pcp lists. With debug_pagealloc also enabled, they are also rechecked when
1354 * moved from pcp lists to free lists.
1356 static bool free_pcp_prepare(struct page *page)
1358 return free_pages_prepare(page, 0, true, FPI_NONE);
1361 static bool bulkfree_pcp_prepare(struct page *page)
1363 if (debug_pagealloc_enabled_static())
1364 return check_free_page(page);
1370 * With DEBUG_VM disabled, order-0 pages being freed are checked only when
1371 * moving from pcp lists to free list in order to reduce overhead. With
1372 * debug_pagealloc enabled, they are checked also immediately when being freed
1375 static bool free_pcp_prepare(struct page *page)
1377 if (debug_pagealloc_enabled_static())
1378 return free_pages_prepare(page, 0, true, FPI_NONE);
1380 return free_pages_prepare(page, 0, false, FPI_NONE);
1383 static bool bulkfree_pcp_prepare(struct page *page)
1385 return check_free_page(page);
1387 #endif /* CONFIG_DEBUG_VM */
1389 static inline void prefetch_buddy(struct page *page)
1391 unsigned long pfn = page_to_pfn(page);
1392 unsigned long buddy_pfn = __find_buddy_pfn(pfn, 0);
1393 struct page *buddy = page + (buddy_pfn - pfn);
1399 * Frees a number of pages from the PCP lists
1400 * Assumes all pages on list are in same zone, and of same order.
1401 * count is the number of pages to free.
1403 * If the zone was previously in an "all pages pinned" state then look to
1404 * see if this freeing clears that state.
1406 * And clear the zone's pages_scanned counter, to hold off the "all pages are
1407 * pinned" detection logic.
1409 static void free_pcppages_bulk(struct zone *zone, int count,
1410 struct per_cpu_pages *pcp)
1412 int migratetype = 0;
1414 int prefetch_nr = READ_ONCE(pcp->batch);
1415 bool isolated_pageblocks;
1416 struct page *page, *tmp;
1420 * Ensure proper count is passed which otherwise would stuck in the
1421 * below while (list_empty(list)) loop.
1423 count = min(pcp->count, count);
1425 struct list_head *list;
1428 * Remove pages from lists in a round-robin fashion. A
1429 * batch_free count is maintained that is incremented when an
1430 * empty list is encountered. This is so more pages are freed
1431 * off fuller lists instead of spinning excessively around empty
1436 if (++migratetype == MIGRATE_PCPTYPES)
1438 list = &pcp->lists[migratetype];
1439 } while (list_empty(list));
1441 /* This is the only non-empty list. Free them all. */
1442 if (batch_free == MIGRATE_PCPTYPES)
1446 page = list_last_entry(list, struct page, lru);
1447 /* must delete to avoid corrupting pcp list */
1448 list_del(&page->lru);
1451 if (bulkfree_pcp_prepare(page))
1454 list_add_tail(&page->lru, &head);
1457 * We are going to put the page back to the global
1458 * pool, prefetch its buddy to speed up later access
1459 * under zone->lock. It is believed the overhead of
1460 * an additional test and calculating buddy_pfn here
1461 * can be offset by reduced memory latency later. To
1462 * avoid excessive prefetching due to large count, only
1463 * prefetch buddy for the first pcp->batch nr of pages.
1466 prefetch_buddy(page);
1469 } while (--count && --batch_free && !list_empty(list));
1473 * local_lock_irq held so equivalent to spin_lock_irqsave for
1474 * both PREEMPT_RT and non-PREEMPT_RT configurations.
1476 spin_lock(&zone->lock);
1477 isolated_pageblocks = has_isolate_pageblock(zone);
1480 * Use safe version since after __free_one_page(),
1481 * page->lru.next will not point to original list.
1483 list_for_each_entry_safe(page, tmp, &head, lru) {
1484 int mt = get_pcppage_migratetype(page);
1485 /* MIGRATE_ISOLATE page should not go to pcplists */
1486 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1487 /* Pageblock could have been isolated meanwhile */
1488 if (unlikely(isolated_pageblocks))
1489 mt = get_pageblock_migratetype(page);
1491 __free_one_page(page, page_to_pfn(page), zone, 0, mt, FPI_NONE);
1492 trace_mm_page_pcpu_drain(page, 0, mt);
1494 spin_unlock(&zone->lock);
1497 static void free_one_page(struct zone *zone,
1498 struct page *page, unsigned long pfn,
1500 int migratetype, fpi_t fpi_flags)
1502 unsigned long flags;
1504 spin_lock_irqsave(&zone->lock, flags);
1505 if (unlikely(has_isolate_pageblock(zone) ||
1506 is_migrate_isolate(migratetype))) {
1507 migratetype = get_pfnblock_migratetype(page, pfn);
1509 __free_one_page(page, pfn, zone, order, migratetype, fpi_flags);
1510 spin_unlock_irqrestore(&zone->lock, flags);
1513 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
1514 unsigned long zone, int nid)
1516 mm_zero_struct_page(page);
1517 set_page_links(page, zone, nid, pfn);
1518 init_page_count(page);
1519 page_mapcount_reset(page);
1520 page_cpupid_reset_last(page);
1521 page_kasan_tag_reset(page);
1523 INIT_LIST_HEAD(&page->lru);
1524 #ifdef WANT_PAGE_VIRTUAL
1525 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1526 if (!is_highmem_idx(zone))
1527 set_page_address(page, __va(pfn << PAGE_SHIFT));
1531 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1532 static void __meminit init_reserved_page(unsigned long pfn)
1537 if (!early_page_uninitialised(pfn))
1540 nid = early_pfn_to_nid(pfn);
1541 pgdat = NODE_DATA(nid);
1543 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1544 struct zone *zone = &pgdat->node_zones[zid];
1546 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
1549 __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
1552 static inline void init_reserved_page(unsigned long pfn)
1555 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1558 * Initialised pages do not have PageReserved set. This function is
1559 * called for each range allocated by the bootmem allocator and
1560 * marks the pages PageReserved. The remaining valid pages are later
1561 * sent to the buddy page allocator.
1563 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1565 unsigned long start_pfn = PFN_DOWN(start);
1566 unsigned long end_pfn = PFN_UP(end);
1568 for (; start_pfn < end_pfn; start_pfn++) {
1569 if (pfn_valid(start_pfn)) {
1570 struct page *page = pfn_to_page(start_pfn);
1572 init_reserved_page(start_pfn);
1574 /* Avoid false-positive PageTail() */
1575 INIT_LIST_HEAD(&page->lru);
1578 * no need for atomic set_bit because the struct
1579 * page is not visible yet so nobody should
1582 __SetPageReserved(page);
1587 static void __free_pages_ok(struct page *page, unsigned int order,
1590 unsigned long flags;
1592 unsigned long pfn = page_to_pfn(page);
1593 struct zone *zone = page_zone(page);
1595 if (!free_pages_prepare(page, order, true, fpi_flags))
1598 migratetype = get_pfnblock_migratetype(page, pfn);
1600 spin_lock_irqsave(&zone->lock, flags);
1601 if (unlikely(has_isolate_pageblock(zone) ||
1602 is_migrate_isolate(migratetype))) {
1603 migratetype = get_pfnblock_migratetype(page, pfn);
1605 __free_one_page(page, pfn, zone, order, migratetype, fpi_flags);
1606 spin_unlock_irqrestore(&zone->lock, flags);
1608 __count_vm_events(PGFREE, 1 << order);
1611 void __free_pages_core(struct page *page, unsigned int order)
1613 unsigned int nr_pages = 1 << order;
1614 struct page *p = page;
1618 * When initializing the memmap, __init_single_page() sets the refcount
1619 * of all pages to 1 ("allocated"/"not free"). We have to set the
1620 * refcount of all involved pages to 0.
1623 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1625 __ClearPageReserved(p);
1626 set_page_count(p, 0);
1628 __ClearPageReserved(p);
1629 set_page_count(p, 0);
1631 atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
1634 * Bypass PCP and place fresh pages right to the tail, primarily
1635 * relevant for memory onlining.
1637 __free_pages_ok(page, order, FPI_TO_TAIL | FPI_SKIP_KASAN_POISON);
1640 #ifdef CONFIG_NEED_MULTIPLE_NODES
1643 * During memory init memblocks map pfns to nids. The search is expensive and
1644 * this caches recent lookups. The implementation of __early_pfn_to_nid
1645 * treats start/end as pfns.
1647 struct mminit_pfnnid_cache {
1648 unsigned long last_start;
1649 unsigned long last_end;
1653 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1656 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
1658 static int __meminit __early_pfn_to_nid(unsigned long pfn,
1659 struct mminit_pfnnid_cache *state)
1661 unsigned long start_pfn, end_pfn;
1664 if (state->last_start <= pfn && pfn < state->last_end)
1665 return state->last_nid;
1667 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
1668 if (nid != NUMA_NO_NODE) {
1669 state->last_start = start_pfn;
1670 state->last_end = end_pfn;
1671 state->last_nid = nid;
1677 int __meminit early_pfn_to_nid(unsigned long pfn)
1679 static DEFINE_SPINLOCK(early_pfn_lock);
1682 spin_lock(&early_pfn_lock);
1683 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1685 nid = first_online_node;
1686 spin_unlock(&early_pfn_lock);
1690 #endif /* CONFIG_NEED_MULTIPLE_NODES */
1692 void __init memblock_free_pages(struct page *page, unsigned long pfn,
1695 if (early_page_uninitialised(pfn))
1697 __free_pages_core(page, order);
1701 * Check that the whole (or subset of) a pageblock given by the interval of
1702 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1703 * with the migration of free compaction scanner. The scanners then need to
1704 * use only pfn_valid_within() check for arches that allow holes within
1707 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1709 * It's possible on some configurations to have a setup like node0 node1 node0
1710 * i.e. it's possible that all pages within a zones range of pages do not
1711 * belong to a single zone. We assume that a border between node0 and node1
1712 * can occur within a single pageblock, but not a node0 node1 node0
1713 * interleaving within a single pageblock. It is therefore sufficient to check
1714 * the first and last page of a pageblock and avoid checking each individual
1715 * page in a pageblock.
1717 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1718 unsigned long end_pfn, struct zone *zone)
1720 struct page *start_page;
1721 struct page *end_page;
1723 /* end_pfn is one past the range we are checking */
1726 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1729 start_page = pfn_to_online_page(start_pfn);
1733 if (page_zone(start_page) != zone)
1736 end_page = pfn_to_page(end_pfn);
1738 /* This gives a shorter code than deriving page_zone(end_page) */
1739 if (page_zone_id(start_page) != page_zone_id(end_page))
1745 void set_zone_contiguous(struct zone *zone)
1747 unsigned long block_start_pfn = zone->zone_start_pfn;
1748 unsigned long block_end_pfn;
1750 block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1751 for (; block_start_pfn < zone_end_pfn(zone);
1752 block_start_pfn = block_end_pfn,
1753 block_end_pfn += pageblock_nr_pages) {
1755 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1757 if (!__pageblock_pfn_to_page(block_start_pfn,
1758 block_end_pfn, zone))
1763 /* We confirm that there is no hole */
1764 zone->contiguous = true;
1767 void clear_zone_contiguous(struct zone *zone)
1769 zone->contiguous = false;
1772 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1773 static void __init deferred_free_range(unsigned long pfn,
1774 unsigned long nr_pages)
1782 page = pfn_to_page(pfn);
1784 /* Free a large naturally-aligned chunk if possible */
1785 if (nr_pages == pageblock_nr_pages &&
1786 (pfn & (pageblock_nr_pages - 1)) == 0) {
1787 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1788 __free_pages_core(page, pageblock_order);
1792 for (i = 0; i < nr_pages; i++, page++, pfn++) {
1793 if ((pfn & (pageblock_nr_pages - 1)) == 0)
1794 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1795 __free_pages_core(page, 0);
1799 /* Completion tracking for deferred_init_memmap() threads */
1800 static atomic_t pgdat_init_n_undone __initdata;
1801 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1803 static inline void __init pgdat_init_report_one_done(void)
1805 if (atomic_dec_and_test(&pgdat_init_n_undone))
1806 complete(&pgdat_init_all_done_comp);
1810 * Returns true if page needs to be initialized or freed to buddy allocator.
1812 * First we check if pfn is valid on architectures where it is possible to have
1813 * holes within pageblock_nr_pages. On systems where it is not possible, this
1814 * function is optimized out.
1816 * Then, we check if a current large page is valid by only checking the validity
1819 static inline bool __init deferred_pfn_valid(unsigned long pfn)
1821 if (!pfn_valid_within(pfn))
1823 if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1829 * Free pages to buddy allocator. Try to free aligned pages in
1830 * pageblock_nr_pages sizes.
1832 static void __init deferred_free_pages(unsigned long pfn,
1833 unsigned long end_pfn)
1835 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1836 unsigned long nr_free = 0;
1838 for (; pfn < end_pfn; pfn++) {
1839 if (!deferred_pfn_valid(pfn)) {
1840 deferred_free_range(pfn - nr_free, nr_free);
1842 } else if (!(pfn & nr_pgmask)) {
1843 deferred_free_range(pfn - nr_free, nr_free);
1849 /* Free the last block of pages to allocator */
1850 deferred_free_range(pfn - nr_free, nr_free);
1854 * Initialize struct pages. We minimize pfn page lookups and scheduler checks
1855 * by performing it only once every pageblock_nr_pages.
1856 * Return number of pages initialized.
1858 static unsigned long __init deferred_init_pages(struct zone *zone,
1860 unsigned long end_pfn)
1862 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1863 int nid = zone_to_nid(zone);
1864 unsigned long nr_pages = 0;
1865 int zid = zone_idx(zone);
1866 struct page *page = NULL;
1868 for (; pfn < end_pfn; pfn++) {
1869 if (!deferred_pfn_valid(pfn)) {
1872 } else if (!page || !(pfn & nr_pgmask)) {
1873 page = pfn_to_page(pfn);
1877 __init_single_page(page, pfn, zid, nid);
1884 * This function is meant to pre-load the iterator for the zone init.
1885 * Specifically it walks through the ranges until we are caught up to the
1886 * first_init_pfn value and exits there. If we never encounter the value we
1887 * return false indicating there are no valid ranges left.
1890 deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone,
1891 unsigned long *spfn, unsigned long *epfn,
1892 unsigned long first_init_pfn)
1897 * Start out by walking through the ranges in this zone that have
1898 * already been initialized. We don't need to do anything with them
1899 * so we just need to flush them out of the system.
1901 for_each_free_mem_pfn_range_in_zone(j, zone, spfn, epfn) {
1902 if (*epfn <= first_init_pfn)
1904 if (*spfn < first_init_pfn)
1905 *spfn = first_init_pfn;
1914 * Initialize and free pages. We do it in two loops: first we initialize
1915 * struct page, then free to buddy allocator, because while we are
1916 * freeing pages we can access pages that are ahead (computing buddy
1917 * page in __free_one_page()).
1919 * In order to try and keep some memory in the cache we have the loop
1920 * broken along max page order boundaries. This way we will not cause
1921 * any issues with the buddy page computation.
1923 static unsigned long __init
1924 deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn,
1925 unsigned long *end_pfn)
1927 unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES);
1928 unsigned long spfn = *start_pfn, epfn = *end_pfn;
1929 unsigned long nr_pages = 0;
1932 /* First we loop through and initialize the page values */
1933 for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) {
1936 if (mo_pfn <= *start_pfn)
1939 t = min(mo_pfn, *end_pfn);
1940 nr_pages += deferred_init_pages(zone, *start_pfn, t);
1942 if (mo_pfn < *end_pfn) {
1943 *start_pfn = mo_pfn;
1948 /* Reset values and now loop through freeing pages as needed */
1951 for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) {
1957 t = min(mo_pfn, epfn);
1958 deferred_free_pages(spfn, t);
1968 deferred_init_memmap_chunk(unsigned long start_pfn, unsigned long end_pfn,
1971 unsigned long spfn, epfn;
1972 struct zone *zone = arg;
1975 deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, start_pfn);
1978 * Initialize and free pages in MAX_ORDER sized increments so that we
1979 * can avoid introducing any issues with the buddy allocator.
1981 while (spfn < end_pfn) {
1982 deferred_init_maxorder(&i, zone, &spfn, &epfn);
1987 /* An arch may override for more concurrency. */
1989 deferred_page_init_max_threads(const struct cpumask *node_cpumask)
1994 /* Initialise remaining memory on a node */
1995 static int __init deferred_init_memmap(void *data)
1997 pg_data_t *pgdat = data;
1998 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1999 unsigned long spfn = 0, epfn = 0;
2000 unsigned long first_init_pfn, flags;
2001 unsigned long start = jiffies;
2003 int zid, max_threads;
2006 /* Bind memory initialisation thread to a local node if possible */
2007 if (!cpumask_empty(cpumask))
2008 set_cpus_allowed_ptr(current, cpumask);
2010 pgdat_resize_lock(pgdat, &flags);
2011 first_init_pfn = pgdat->first_deferred_pfn;
2012 if (first_init_pfn == ULONG_MAX) {
2013 pgdat_resize_unlock(pgdat, &flags);
2014 pgdat_init_report_one_done();
2018 /* Sanity check boundaries */
2019 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
2020 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
2021 pgdat->first_deferred_pfn = ULONG_MAX;
2024 * Once we unlock here, the zone cannot be grown anymore, thus if an
2025 * interrupt thread must allocate this early in boot, zone must be
2026 * pre-grown prior to start of deferred page initialization.
2028 pgdat_resize_unlock(pgdat, &flags);
2030 /* Only the highest zone is deferred so find it */
2031 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2032 zone = pgdat->node_zones + zid;
2033 if (first_init_pfn < zone_end_pfn(zone))
2037 /* If the zone is empty somebody else may have cleared out the zone */
2038 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
2042 max_threads = deferred_page_init_max_threads(cpumask);
2044 while (spfn < epfn) {
2045 unsigned long epfn_align = ALIGN(epfn, PAGES_PER_SECTION);
2046 struct padata_mt_job job = {
2047 .thread_fn = deferred_init_memmap_chunk,
2050 .size = epfn_align - spfn,
2051 .align = PAGES_PER_SECTION,
2052 .min_chunk = PAGES_PER_SECTION,
2053 .max_threads = max_threads,
2056 padata_do_multithreaded(&job);
2057 deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
2061 /* Sanity check that the next zone really is unpopulated */
2062 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
2064 pr_info("node %d deferred pages initialised in %ums\n",
2065 pgdat->node_id, jiffies_to_msecs(jiffies - start));
2067 pgdat_init_report_one_done();
2072 * If this zone has deferred pages, try to grow it by initializing enough
2073 * deferred pages to satisfy the allocation specified by order, rounded up to
2074 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
2075 * of SECTION_SIZE bytes by initializing struct pages in increments of
2076 * PAGES_PER_SECTION * sizeof(struct page) bytes.
2078 * Return true when zone was grown, otherwise return false. We return true even
2079 * when we grow less than requested, to let the caller decide if there are
2080 * enough pages to satisfy the allocation.
2082 * Note: We use noinline because this function is needed only during boot, and
2083 * it is called from a __ref function _deferred_grow_zone. This way we are
2084 * making sure that it is not inlined into permanent text section.
2086 static noinline bool __init
2087 deferred_grow_zone(struct zone *zone, unsigned int order)
2089 unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
2090 pg_data_t *pgdat = zone->zone_pgdat;
2091 unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
2092 unsigned long spfn, epfn, flags;
2093 unsigned long nr_pages = 0;
2096 /* Only the last zone may have deferred pages */
2097 if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
2100 pgdat_resize_lock(pgdat, &flags);
2103 * If someone grew this zone while we were waiting for spinlock, return
2104 * true, as there might be enough pages already.
2106 if (first_deferred_pfn != pgdat->first_deferred_pfn) {
2107 pgdat_resize_unlock(pgdat, &flags);
2111 /* If the zone is empty somebody else may have cleared out the zone */
2112 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
2113 first_deferred_pfn)) {
2114 pgdat->first_deferred_pfn = ULONG_MAX;
2115 pgdat_resize_unlock(pgdat, &flags);
2116 /* Retry only once. */
2117 return first_deferred_pfn != ULONG_MAX;
2121 * Initialize and free pages in MAX_ORDER sized increments so
2122 * that we can avoid introducing any issues with the buddy
2125 while (spfn < epfn) {
2126 /* update our first deferred PFN for this section */
2127 first_deferred_pfn = spfn;
2129 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
2130 touch_nmi_watchdog();
2132 /* We should only stop along section boundaries */
2133 if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION)
2136 /* If our quota has been met we can stop here */
2137 if (nr_pages >= nr_pages_needed)
2141 pgdat->first_deferred_pfn = spfn;
2142 pgdat_resize_unlock(pgdat, &flags);
2144 return nr_pages > 0;
2148 * deferred_grow_zone() is __init, but it is called from
2149 * get_page_from_freelist() during early boot until deferred_pages permanently
2150 * disables this call. This is why we have refdata wrapper to avoid warning,
2151 * and to ensure that the function body gets unloaded.
2154 _deferred_grow_zone(struct zone *zone, unsigned int order)
2156 return deferred_grow_zone(zone, order);
2159 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
2161 void __init page_alloc_init_late(void)
2166 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
2168 /* There will be num_node_state(N_MEMORY) threads */
2169 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
2170 for_each_node_state(nid, N_MEMORY) {
2171 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
2174 /* Block until all are initialised */
2175 wait_for_completion(&pgdat_init_all_done_comp);
2178 * We initialized the rest of the deferred pages. Permanently disable
2179 * on-demand struct page initialization.
2181 static_branch_disable(&deferred_pages);
2183 /* Reinit limits that are based on free pages after the kernel is up */
2184 files_maxfiles_init();
2189 /* Discard memblock private memory */
2192 for_each_node_state(nid, N_MEMORY)
2193 shuffle_free_memory(NODE_DATA(nid));
2195 for_each_populated_zone(zone)
2196 set_zone_contiguous(zone);
2200 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
2201 void __init init_cma_reserved_pageblock(struct page *page)
2203 unsigned i = pageblock_nr_pages;
2204 struct page *p = page;
2207 __ClearPageReserved(p);
2208 set_page_count(p, 0);
2211 set_pageblock_migratetype(page, MIGRATE_CMA);
2213 if (pageblock_order >= MAX_ORDER) {
2214 i = pageblock_nr_pages;
2217 set_page_refcounted(p);
2218 __free_pages(p, MAX_ORDER - 1);
2219 p += MAX_ORDER_NR_PAGES;
2220 } while (i -= MAX_ORDER_NR_PAGES);
2222 set_page_refcounted(page);
2223 __free_pages(page, pageblock_order);
2226 adjust_managed_page_count(page, pageblock_nr_pages);
2227 page_zone(page)->cma_pages += pageblock_nr_pages;
2232 * The order of subdivision here is critical for the IO subsystem.
2233 * Please do not alter this order without good reasons and regression
2234 * testing. Specifically, as large blocks of memory are subdivided,
2235 * the order in which smaller blocks are delivered depends on the order
2236 * they're subdivided in this function. This is the primary factor
2237 * influencing the order in which pages are delivered to the IO
2238 * subsystem according to empirical testing, and this is also justified
2239 * by considering the behavior of a buddy system containing a single
2240 * large block of memory acted on by a series of small allocations.
2241 * This behavior is a critical factor in sglist merging's success.
2245 static inline void expand(struct zone *zone, struct page *page,
2246 int low, int high, int migratetype)
2248 unsigned long size = 1 << high;
2250 while (high > low) {
2253 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
2256 * Mark as guard pages (or page), that will allow to
2257 * merge back to allocator when buddy will be freed.
2258 * Corresponding page table entries will not be touched,
2259 * pages will stay not present in virtual address space
2261 if (set_page_guard(zone, &page[size], high, migratetype))
2264 add_to_free_list(&page[size], zone, high, migratetype);
2265 set_buddy_order(&page[size], high);
2269 static void check_new_page_bad(struct page *page)
2271 if (unlikely(page->flags & __PG_HWPOISON)) {
2272 /* Don't complain about hwpoisoned pages */
2273 page_mapcount_reset(page); /* remove PageBuddy */
2278 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_PREP));
2282 * This page is about to be returned from the page allocator
2284 static inline int check_new_page(struct page *page)
2286 if (likely(page_expected_state(page,
2287 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
2290 check_new_page_bad(page);
2294 #ifdef CONFIG_DEBUG_VM
2296 * With DEBUG_VM enabled, order-0 pages are checked for expected state when
2297 * being allocated from pcp lists. With debug_pagealloc also enabled, they are
2298 * also checked when pcp lists are refilled from the free lists.
2300 static inline bool check_pcp_refill(struct page *page)
2302 if (debug_pagealloc_enabled_static())
2303 return check_new_page(page);
2308 static inline bool check_new_pcp(struct page *page)
2310 return check_new_page(page);
2314 * With DEBUG_VM disabled, free order-0 pages are checked for expected state
2315 * when pcp lists are being refilled from the free lists. With debug_pagealloc
2316 * enabled, they are also checked when being allocated from the pcp lists.
2318 static inline bool check_pcp_refill(struct page *page)
2320 return check_new_page(page);
2322 static inline bool check_new_pcp(struct page *page)
2324 if (debug_pagealloc_enabled_static())
2325 return check_new_page(page);
2329 #endif /* CONFIG_DEBUG_VM */
2331 static bool check_new_pages(struct page *page, unsigned int order)
2334 for (i = 0; i < (1 << order); i++) {
2335 struct page *p = page + i;
2337 if (unlikely(check_new_page(p)))
2344 inline void post_alloc_hook(struct page *page, unsigned int order,
2349 set_page_private(page, 0);
2350 set_page_refcounted(page);
2352 arch_alloc_page(page, order);
2353 debug_pagealloc_map_pages(page, 1 << order);
2356 * Page unpoisoning must happen before memory initialization.
2357 * Otherwise, the poison pattern will be overwritten for __GFP_ZERO
2358 * allocations and the page unpoisoning code will complain.
2360 kernel_unpoison_pages(page, 1 << order);
2363 * As memory initialization might be integrated into KASAN,
2364 * kasan_alloc_pages and kernel_init_free_pages must be
2365 * kept together to avoid discrepancies in behavior.
2367 init = !want_init_on_free() && want_init_on_alloc(gfp_flags);
2368 kasan_alloc_pages(page, order, init);
2369 if (init && !kasan_has_integrated_init())
2370 kernel_init_free_pages(page, 1 << order);
2372 set_page_owner(page, order, gfp_flags);
2375 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
2376 unsigned int alloc_flags)
2378 post_alloc_hook(page, order, gfp_flags);
2380 if (order && (gfp_flags & __GFP_COMP))
2381 prep_compound_page(page, order);
2384 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
2385 * allocate the page. The expectation is that the caller is taking
2386 * steps that will free more memory. The caller should avoid the page
2387 * being used for !PFMEMALLOC purposes.
2389 if (alloc_flags & ALLOC_NO_WATERMARKS)
2390 set_page_pfmemalloc(page);
2392 clear_page_pfmemalloc(page);
2396 * Go through the free lists for the given migratetype and remove
2397 * the smallest available page from the freelists
2399 static __always_inline
2400 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
2403 unsigned int current_order;
2404 struct free_area *area;
2407 /* Find a page of the appropriate size in the preferred list */
2408 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
2409 area = &(zone->free_area[current_order]);
2410 page = get_page_from_free_area(area, migratetype);
2413 del_page_from_free_list(page, zone, current_order);
2414 expand(zone, page, order, current_order, migratetype);
2415 set_pcppage_migratetype(page, migratetype);
2424 * This array describes the order lists are fallen back to when
2425 * the free lists for the desirable migrate type are depleted
2427 static int fallbacks[MIGRATE_TYPES][3] = {
2428 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2429 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
2430 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2432 [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */
2434 #ifdef CONFIG_MEMORY_ISOLATION
2435 [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */
2440 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2443 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
2446 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2447 unsigned int order) { return NULL; }
2451 * Move the free pages in a range to the freelist tail of the requested type.
2452 * Note that start_page and end_pages are not aligned on a pageblock
2453 * boundary. If alignment is required, use move_freepages_block()
2455 static int move_freepages(struct zone *zone,
2456 unsigned long start_pfn, unsigned long end_pfn,
2457 int migratetype, int *num_movable)
2462 int pages_moved = 0;
2464 for (pfn = start_pfn; pfn <= end_pfn;) {
2465 if (!pfn_valid_within(pfn)) {
2470 page = pfn_to_page(pfn);
2471 if (!PageBuddy(page)) {
2473 * We assume that pages that could be isolated for
2474 * migration are movable. But we don't actually try
2475 * isolating, as that would be expensive.
2478 (PageLRU(page) || __PageMovable(page)))
2484 /* Make sure we are not inadvertently changing nodes */
2485 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2486 VM_BUG_ON_PAGE(page_zone(page) != zone, page);
2488 order = buddy_order(page);
2489 move_to_free_list(page, zone, order, migratetype);
2491 pages_moved += 1 << order;
2497 int move_freepages_block(struct zone *zone, struct page *page,
2498 int migratetype, int *num_movable)
2500 unsigned long start_pfn, end_pfn, pfn;
2505 pfn = page_to_pfn(page);
2506 start_pfn = pfn & ~(pageblock_nr_pages - 1);
2507 end_pfn = start_pfn + pageblock_nr_pages - 1;
2509 /* Do not cross zone boundaries */
2510 if (!zone_spans_pfn(zone, start_pfn))
2512 if (!zone_spans_pfn(zone, end_pfn))
2515 return move_freepages(zone, start_pfn, end_pfn, migratetype,
2519 static void change_pageblock_range(struct page *pageblock_page,
2520 int start_order, int migratetype)
2522 int nr_pageblocks = 1 << (start_order - pageblock_order);
2524 while (nr_pageblocks--) {
2525 set_pageblock_migratetype(pageblock_page, migratetype);
2526 pageblock_page += pageblock_nr_pages;
2531 * When we are falling back to another migratetype during allocation, try to
2532 * steal extra free pages from the same pageblocks to satisfy further
2533 * allocations, instead of polluting multiple pageblocks.
2535 * If we are stealing a relatively large buddy page, it is likely there will
2536 * be more free pages in the pageblock, so try to steal them all. For
2537 * reclaimable and unmovable allocations, we steal regardless of page size,
2538 * as fragmentation caused by those allocations polluting movable pageblocks
2539 * is worse than movable allocations stealing from unmovable and reclaimable
2542 static bool can_steal_fallback(unsigned int order, int start_mt)
2545 * Leaving this order check is intended, although there is
2546 * relaxed order check in next check. The reason is that
2547 * we can actually steal whole pageblock if this condition met,
2548 * but, below check doesn't guarantee it and that is just heuristic
2549 * so could be changed anytime.
2551 if (order >= pageblock_order)
2554 if (order >= pageblock_order / 2 ||
2555 start_mt == MIGRATE_RECLAIMABLE ||
2556 start_mt == MIGRATE_UNMOVABLE ||
2557 page_group_by_mobility_disabled)
2563 static inline bool boost_watermark(struct zone *zone)
2565 unsigned long max_boost;
2567 if (!watermark_boost_factor)
2570 * Don't bother in zones that are unlikely to produce results.
2571 * On small machines, including kdump capture kernels running
2572 * in a small area, boosting the watermark can cause an out of
2573 * memory situation immediately.
2575 if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
2578 max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
2579 watermark_boost_factor, 10000);
2582 * high watermark may be uninitialised if fragmentation occurs
2583 * very early in boot so do not boost. We do not fall
2584 * through and boost by pageblock_nr_pages as failing
2585 * allocations that early means that reclaim is not going
2586 * to help and it may even be impossible to reclaim the
2587 * boosted watermark resulting in a hang.
2592 max_boost = max(pageblock_nr_pages, max_boost);
2594 zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
2601 * This function implements actual steal behaviour. If order is large enough,
2602 * we can steal whole pageblock. If not, we first move freepages in this
2603 * pageblock to our migratetype and determine how many already-allocated pages
2604 * are there in the pageblock with a compatible migratetype. If at least half
2605 * of pages are free or compatible, we can change migratetype of the pageblock
2606 * itself, so pages freed in the future will be put on the correct free list.
2608 static void steal_suitable_fallback(struct zone *zone, struct page *page,
2609 unsigned int alloc_flags, int start_type, bool whole_block)
2611 unsigned int current_order = buddy_order(page);
2612 int free_pages, movable_pages, alike_pages;
2615 old_block_type = get_pageblock_migratetype(page);
2618 * This can happen due to races and we want to prevent broken
2619 * highatomic accounting.
2621 if (is_migrate_highatomic(old_block_type))
2624 /* Take ownership for orders >= pageblock_order */
2625 if (current_order >= pageblock_order) {
2626 change_pageblock_range(page, current_order, start_type);
2631 * Boost watermarks to increase reclaim pressure to reduce the
2632 * likelihood of future fallbacks. Wake kswapd now as the node
2633 * may be balanced overall and kswapd will not wake naturally.
2635 if (boost_watermark(zone) && (alloc_flags & ALLOC_KSWAPD))
2636 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
2638 /* We are not allowed to try stealing from the whole block */
2642 free_pages = move_freepages_block(zone, page, start_type,
2645 * Determine how many pages are compatible with our allocation.
2646 * For movable allocation, it's the number of movable pages which
2647 * we just obtained. For other types it's a bit more tricky.
2649 if (start_type == MIGRATE_MOVABLE) {
2650 alike_pages = movable_pages;
2653 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2654 * to MOVABLE pageblock, consider all non-movable pages as
2655 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2656 * vice versa, be conservative since we can't distinguish the
2657 * exact migratetype of non-movable pages.
2659 if (old_block_type == MIGRATE_MOVABLE)
2660 alike_pages = pageblock_nr_pages
2661 - (free_pages + movable_pages);
2666 /* moving whole block can fail due to zone boundary conditions */
2671 * If a sufficient number of pages in the block are either free or of
2672 * comparable migratability as our allocation, claim the whole block.
2674 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2675 page_group_by_mobility_disabled)
2676 set_pageblock_migratetype(page, start_type);
2681 move_to_free_list(page, zone, current_order, start_type);
2685 * Check whether there is a suitable fallback freepage with requested order.
2686 * If only_stealable is true, this function returns fallback_mt only if
2687 * we can steal other freepages all together. This would help to reduce
2688 * fragmentation due to mixed migratetype pages in one pageblock.
2690 int find_suitable_fallback(struct free_area *area, unsigned int order,
2691 int migratetype, bool only_stealable, bool *can_steal)
2696 if (area->nr_free == 0)
2701 fallback_mt = fallbacks[migratetype][i];
2702 if (fallback_mt == MIGRATE_TYPES)
2705 if (free_area_empty(area, fallback_mt))
2708 if (can_steal_fallback(order, migratetype))
2711 if (!only_stealable)
2722 * Reserve a pageblock for exclusive use of high-order atomic allocations if
2723 * there are no empty page blocks that contain a page with a suitable order
2725 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2726 unsigned int alloc_order)
2729 unsigned long max_managed, flags;
2732 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2733 * Check is race-prone but harmless.
2735 max_managed = (zone_managed_pages(zone) / 100) + pageblock_nr_pages;
2736 if (zone->nr_reserved_highatomic >= max_managed)
2739 spin_lock_irqsave(&zone->lock, flags);
2741 /* Recheck the nr_reserved_highatomic limit under the lock */
2742 if (zone->nr_reserved_highatomic >= max_managed)
2746 mt = get_pageblock_migratetype(page);
2747 if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
2748 && !is_migrate_cma(mt)) {
2749 zone->nr_reserved_highatomic += pageblock_nr_pages;
2750 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
2751 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
2755 spin_unlock_irqrestore(&zone->lock, flags);
2759 * Used when an allocation is about to fail under memory pressure. This
2760 * potentially hurts the reliability of high-order allocations when under
2761 * intense memory pressure but failed atomic allocations should be easier
2762 * to recover from than an OOM.
2764 * If @force is true, try to unreserve a pageblock even though highatomic
2765 * pageblock is exhausted.
2767 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2770 struct zonelist *zonelist = ac->zonelist;
2771 unsigned long flags;
2778 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->highest_zoneidx,
2781 * Preserve at least one pageblock unless memory pressure
2784 if (!force && zone->nr_reserved_highatomic <=
2788 spin_lock_irqsave(&zone->lock, flags);
2789 for (order = 0; order < MAX_ORDER; order++) {
2790 struct free_area *area = &(zone->free_area[order]);
2792 page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
2797 * In page freeing path, migratetype change is racy so
2798 * we can counter several free pages in a pageblock
2799 * in this loop although we changed the pageblock type
2800 * from highatomic to ac->migratetype. So we should
2801 * adjust the count once.
2803 if (is_migrate_highatomic_page(page)) {
2805 * It should never happen but changes to
2806 * locking could inadvertently allow a per-cpu
2807 * drain to add pages to MIGRATE_HIGHATOMIC
2808 * while unreserving so be safe and watch for
2811 zone->nr_reserved_highatomic -= min(
2813 zone->nr_reserved_highatomic);
2817 * Convert to ac->migratetype and avoid the normal
2818 * pageblock stealing heuristics. Minimally, the caller
2819 * is doing the work and needs the pages. More
2820 * importantly, if the block was always converted to
2821 * MIGRATE_UNMOVABLE or another type then the number
2822 * of pageblocks that cannot be completely freed
2825 set_pageblock_migratetype(page, ac->migratetype);
2826 ret = move_freepages_block(zone, page, ac->migratetype,
2829 spin_unlock_irqrestore(&zone->lock, flags);
2833 spin_unlock_irqrestore(&zone->lock, flags);
2840 * Try finding a free buddy page on the fallback list and put it on the free
2841 * list of requested migratetype, possibly along with other pages from the same
2842 * block, depending on fragmentation avoidance heuristics. Returns true if
2843 * fallback was found so that __rmqueue_smallest() can grab it.
2845 * The use of signed ints for order and current_order is a deliberate
2846 * deviation from the rest of this file, to make the for loop
2847 * condition simpler.
2849 static __always_inline bool
2850 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype,
2851 unsigned int alloc_flags)
2853 struct free_area *area;
2855 int min_order = order;
2861 * Do not steal pages from freelists belonging to other pageblocks
2862 * i.e. orders < pageblock_order. If there are no local zones free,
2863 * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2865 if (alloc_flags & ALLOC_NOFRAGMENT)
2866 min_order = pageblock_order;
2869 * Find the largest available free page in the other list. This roughly
2870 * approximates finding the pageblock with the most free pages, which
2871 * would be too costly to do exactly.
2873 for (current_order = MAX_ORDER - 1; current_order >= min_order;
2875 area = &(zone->free_area[current_order]);
2876 fallback_mt = find_suitable_fallback(area, current_order,
2877 start_migratetype, false, &can_steal);
2878 if (fallback_mt == -1)
2882 * We cannot steal all free pages from the pageblock and the
2883 * requested migratetype is movable. In that case it's better to
2884 * steal and split the smallest available page instead of the
2885 * largest available page, because even if the next movable
2886 * allocation falls back into a different pageblock than this
2887 * one, it won't cause permanent fragmentation.
2889 if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2890 && current_order > order)
2899 for (current_order = order; current_order < MAX_ORDER;
2901 area = &(zone->free_area[current_order]);
2902 fallback_mt = find_suitable_fallback(area, current_order,
2903 start_migratetype, false, &can_steal);
2904 if (fallback_mt != -1)
2909 * This should not happen - we already found a suitable fallback
2910 * when looking for the largest page.
2912 VM_BUG_ON(current_order == MAX_ORDER);
2915 page = get_page_from_free_area(area, fallback_mt);
2917 steal_suitable_fallback(zone, page, alloc_flags, start_migratetype,
2920 trace_mm_page_alloc_extfrag(page, order, current_order,
2921 start_migratetype, fallback_mt);
2928 * Do the hard work of removing an element from the buddy allocator.
2929 * Call me with the zone->lock already held.
2931 static __always_inline struct page *
2932 __rmqueue(struct zone *zone, unsigned int order, int migratetype,
2933 unsigned int alloc_flags)
2937 if (IS_ENABLED(CONFIG_CMA)) {
2939 * Balance movable allocations between regular and CMA areas by
2940 * allocating from CMA when over half of the zone's free memory
2941 * is in the CMA area.
2943 if (alloc_flags & ALLOC_CMA &&
2944 zone_page_state(zone, NR_FREE_CMA_PAGES) >
2945 zone_page_state(zone, NR_FREE_PAGES) / 2) {
2946 page = __rmqueue_cma_fallback(zone, order);
2952 page = __rmqueue_smallest(zone, order, migratetype);
2953 if (unlikely(!page)) {
2954 if (alloc_flags & ALLOC_CMA)
2955 page = __rmqueue_cma_fallback(zone, order);
2957 if (!page && __rmqueue_fallback(zone, order, migratetype,
2963 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2968 * Obtain a specified number of elements from the buddy allocator, all under
2969 * a single hold of the lock, for efficiency. Add them to the supplied list.
2970 * Returns the number of new pages which were placed at *list.
2972 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2973 unsigned long count, struct list_head *list,
2974 int migratetype, unsigned int alloc_flags)
2976 int i, allocated = 0;
2979 * local_lock_irq held so equivalent to spin_lock_irqsave for
2980 * both PREEMPT_RT and non-PREEMPT_RT configurations.
2982 spin_lock(&zone->lock);
2983 for (i = 0; i < count; ++i) {
2984 struct page *page = __rmqueue(zone, order, migratetype,
2986 if (unlikely(page == NULL))
2989 if (unlikely(check_pcp_refill(page)))
2993 * Split buddy pages returned by expand() are received here in
2994 * physical page order. The page is added to the tail of
2995 * caller's list. From the callers perspective, the linked list
2996 * is ordered by page number under some conditions. This is
2997 * useful for IO devices that can forward direction from the
2998 * head, thus also in the physical page order. This is useful
2999 * for IO devices that can merge IO requests if the physical
3000 * pages are ordered properly.
3002 list_add_tail(&page->lru, list);
3004 if (is_migrate_cma(get_pcppage_migratetype(page)))
3005 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
3010 * i pages were removed from the buddy list even if some leak due
3011 * to check_pcp_refill failing so adjust NR_FREE_PAGES based
3012 * on i. Do not confuse with 'allocated' which is the number of
3013 * pages added to the pcp list.
3015 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
3016 spin_unlock(&zone->lock);
3022 * Called from the vmstat counter updater to drain pagesets of this
3023 * currently executing processor on remote nodes after they have
3026 * Note that this function must be called with the thread pinned to
3027 * a single processor.
3029 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
3031 unsigned long flags;
3032 int to_drain, batch;
3034 local_lock_irqsave(&pagesets.lock, flags);
3035 batch = READ_ONCE(pcp->batch);
3036 to_drain = min(pcp->count, batch);
3038 free_pcppages_bulk(zone, to_drain, pcp);
3039 local_unlock_irqrestore(&pagesets.lock, flags);
3044 * Drain pcplists of the indicated processor and zone.
3046 * The processor must either be the current processor and the
3047 * thread pinned to the current processor or a processor that
3050 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
3052 unsigned long flags;
3053 struct per_cpu_pages *pcp;
3055 local_lock_irqsave(&pagesets.lock, flags);
3057 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
3059 free_pcppages_bulk(zone, pcp->count, pcp);
3061 local_unlock_irqrestore(&pagesets.lock, flags);
3065 * Drain pcplists of all zones on the indicated processor.
3067 * The processor must either be the current processor and the
3068 * thread pinned to the current processor or a processor that
3071 static void drain_pages(unsigned int cpu)
3075 for_each_populated_zone(zone) {
3076 drain_pages_zone(cpu, zone);
3081 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
3083 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
3084 * the single zone's pages.
3086 void drain_local_pages(struct zone *zone)
3088 int cpu = smp_processor_id();
3091 drain_pages_zone(cpu, zone);
3096 static void drain_local_pages_wq(struct work_struct *work)
3098 struct pcpu_drain *drain;
3100 drain = container_of(work, struct pcpu_drain, work);
3103 * drain_all_pages doesn't use proper cpu hotplug protection so
3104 * we can race with cpu offline when the WQ can move this from
3105 * a cpu pinned worker to an unbound one. We can operate on a different
3106 * cpu which is alright but we also have to make sure to not move to
3110 drain_local_pages(drain->zone);
3115 * The implementation of drain_all_pages(), exposing an extra parameter to
3116 * drain on all cpus.
3118 * drain_all_pages() is optimized to only execute on cpus where pcplists are
3119 * not empty. The check for non-emptiness can however race with a free to
3120 * pcplist that has not yet increased the pcp->count from 0 to 1. Callers
3121 * that need the guarantee that every CPU has drained can disable the
3122 * optimizing racy check.
3124 static void __drain_all_pages(struct zone *zone, bool force_all_cpus)
3129 * Allocate in the BSS so we wont require allocation in
3130 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
3132 static cpumask_t cpus_with_pcps;
3135 * Make sure nobody triggers this path before mm_percpu_wq is fully
3138 if (WARN_ON_ONCE(!mm_percpu_wq))
3142 * Do not drain if one is already in progress unless it's specific to
3143 * a zone. Such callers are primarily CMA and memory hotplug and need
3144 * the drain to be complete when the call returns.
3146 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
3149 mutex_lock(&pcpu_drain_mutex);
3153 * We don't care about racing with CPU hotplug event
3154 * as offline notification will cause the notified
3155 * cpu to drain that CPU pcps and on_each_cpu_mask
3156 * disables preemption as part of its processing
3158 for_each_online_cpu(cpu) {
3159 struct per_cpu_pages *pcp;
3161 bool has_pcps = false;
3163 if (force_all_cpus) {
3165 * The pcp.count check is racy, some callers need a
3166 * guarantee that no cpu is missed.
3170 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
3174 for_each_populated_zone(z) {
3175 pcp = per_cpu_ptr(z->per_cpu_pageset, cpu);
3184 cpumask_set_cpu(cpu, &cpus_with_pcps);
3186 cpumask_clear_cpu(cpu, &cpus_with_pcps);
3189 for_each_cpu(cpu, &cpus_with_pcps) {
3190 struct pcpu_drain *drain = per_cpu_ptr(&pcpu_drain, cpu);
3193 INIT_WORK(&drain->work, drain_local_pages_wq);
3194 queue_work_on(cpu, mm_percpu_wq, &drain->work);
3196 for_each_cpu(cpu, &cpus_with_pcps)
3197 flush_work(&per_cpu_ptr(&pcpu_drain, cpu)->work);
3199 mutex_unlock(&pcpu_drain_mutex);
3203 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
3205 * When zone parameter is non-NULL, spill just the single zone's pages.
3207 * Note that this can be extremely slow as the draining happens in a workqueue.
3209 void drain_all_pages(struct zone *zone)
3211 __drain_all_pages(zone, false);
3214 #ifdef CONFIG_HIBERNATION
3217 * Touch the watchdog for every WD_PAGE_COUNT pages.
3219 #define WD_PAGE_COUNT (128*1024)
3221 void mark_free_pages(struct zone *zone)
3223 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
3224 unsigned long flags;
3225 unsigned int order, t;
3228 if (zone_is_empty(zone))
3231 spin_lock_irqsave(&zone->lock, flags);
3233 max_zone_pfn = zone_end_pfn(zone);
3234 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
3235 if (pfn_valid(pfn)) {
3236 page = pfn_to_page(pfn);
3238 if (!--page_count) {
3239 touch_nmi_watchdog();
3240 page_count = WD_PAGE_COUNT;
3243 if (page_zone(page) != zone)
3246 if (!swsusp_page_is_forbidden(page))
3247 swsusp_unset_page_free(page);
3250 for_each_migratetype_order(order, t) {
3251 list_for_each_entry(page,
3252 &zone->free_area[order].free_list[t], lru) {
3255 pfn = page_to_pfn(page);
3256 for (i = 0; i < (1UL << order); i++) {
3257 if (!--page_count) {
3258 touch_nmi_watchdog();
3259 page_count = WD_PAGE_COUNT;
3261 swsusp_set_page_free(pfn_to_page(pfn + i));
3265 spin_unlock_irqrestore(&zone->lock, flags);
3267 #endif /* CONFIG_PM */
3269 static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
3273 if (!free_pcp_prepare(page))
3276 migratetype = get_pfnblock_migratetype(page, pfn);
3277 set_pcppage_migratetype(page, migratetype);
3281 static int nr_pcp_free(struct per_cpu_pages *pcp, int high, int batch)
3283 int min_nr_free, max_nr_free;
3285 /* Check for PCP disabled or boot pageset */
3286 if (unlikely(high < batch))
3289 /* Leave at least pcp->batch pages on the list */
3290 min_nr_free = batch;
3291 max_nr_free = high - batch;
3294 * Double the number of pages freed each time there is subsequent
3295 * freeing of pages without any allocation.
3297 batch <<= pcp->free_factor;
3298 if (batch < max_nr_free)
3300 batch = clamp(batch, min_nr_free, max_nr_free);
3305 static void free_unref_page_commit(struct page *page, unsigned long pfn,
3308 struct zone *zone = page_zone(page);
3309 struct per_cpu_pages *pcp;
3312 __count_vm_event(PGFREE);
3313 pcp = this_cpu_ptr(zone->per_cpu_pageset);
3314 list_add(&page->lru, &pcp->lists[migratetype]);
3316 high = READ_ONCE(pcp->high);
3317 if (pcp->count >= high) {
3318 int batch = READ_ONCE(pcp->batch);
3320 free_pcppages_bulk(zone, nr_pcp_free(pcp, high, batch), pcp);
3325 * Free a 0-order page
3327 void free_unref_page(struct page *page)
3329 unsigned long flags;
3330 unsigned long pfn = page_to_pfn(page);
3333 if (!free_unref_page_prepare(page, pfn))
3337 * We only track unmovable, reclaimable and movable on pcp lists.
3338 * Place ISOLATE pages on the isolated list because they are being
3339 * offlined but treat HIGHATOMIC as movable pages so we can get those
3340 * areas back if necessary. Otherwise, we may have to free
3341 * excessively into the page allocator
3343 migratetype = get_pcppage_migratetype(page);
3344 if (unlikely(migratetype >= MIGRATE_PCPTYPES)) {
3345 if (unlikely(is_migrate_isolate(migratetype))) {
3346 free_one_page(page_zone(page), page, pfn, 0, migratetype, FPI_NONE);
3349 migratetype = MIGRATE_MOVABLE;
3352 local_lock_irqsave(&pagesets.lock, flags);
3353 free_unref_page_commit(page, pfn, migratetype);
3354 local_unlock_irqrestore(&pagesets.lock, flags);
3358 * Free a list of 0-order pages
3360 void free_unref_page_list(struct list_head *list)
3362 struct page *page, *next;
3363 unsigned long flags, pfn;
3364 int batch_count = 0;
3367 /* Prepare pages for freeing */
3368 list_for_each_entry_safe(page, next, list, lru) {
3369 pfn = page_to_pfn(page);
3370 if (!free_unref_page_prepare(page, pfn))
3371 list_del(&page->lru);
3374 * Free isolated pages directly to the allocator, see
3375 * comment in free_unref_page.
3377 migratetype = get_pcppage_migratetype(page);
3378 if (unlikely(migratetype >= MIGRATE_PCPTYPES)) {
3379 if (unlikely(is_migrate_isolate(migratetype))) {
3380 list_del(&page->lru);
3381 free_one_page(page_zone(page), page, pfn, 0,
3382 migratetype, FPI_NONE);
3387 * Non-isolated types over MIGRATE_PCPTYPES get added
3388 * to the MIGRATE_MOVABLE pcp list.
3390 set_pcppage_migratetype(page, MIGRATE_MOVABLE);
3393 set_page_private(page, pfn);
3396 local_lock_irqsave(&pagesets.lock, flags);
3397 list_for_each_entry_safe(page, next, list, lru) {
3398 pfn = page_private(page);
3399 set_page_private(page, 0);
3400 migratetype = get_pcppage_migratetype(page);
3401 trace_mm_page_free_batched(page);
3402 free_unref_page_commit(page, pfn, migratetype);
3405 * Guard against excessive IRQ disabled times when we get
3406 * a large list of pages to free.
3408 if (++batch_count == SWAP_CLUSTER_MAX) {
3409 local_unlock_irqrestore(&pagesets.lock, flags);
3411 local_lock_irqsave(&pagesets.lock, flags);
3414 local_unlock_irqrestore(&pagesets.lock, flags);
3418 * split_page takes a non-compound higher-order page, and splits it into
3419 * n (1<<order) sub-pages: page[0..n]
3420 * Each sub-page must be freed individually.
3422 * Note: this is probably too low level an operation for use in drivers.
3423 * Please consult with lkml before using this in your driver.
3425 void split_page(struct page *page, unsigned int order)
3429 VM_BUG_ON_PAGE(PageCompound(page), page);
3430 VM_BUG_ON_PAGE(!page_count(page), page);
3432 for (i = 1; i < (1 << order); i++)
3433 set_page_refcounted(page + i);
3434 split_page_owner(page, 1 << order);
3435 split_page_memcg(page, 1 << order);
3437 EXPORT_SYMBOL_GPL(split_page);
3439 int __isolate_free_page(struct page *page, unsigned int order)
3441 unsigned long watermark;
3445 BUG_ON(!PageBuddy(page));
3447 zone = page_zone(page);
3448 mt = get_pageblock_migratetype(page);
3450 if (!is_migrate_isolate(mt)) {
3452 * Obey watermarks as if the page was being allocated. We can
3453 * emulate a high-order watermark check with a raised order-0
3454 * watermark, because we already know our high-order page
3457 watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
3458 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
3461 __mod_zone_freepage_state(zone, -(1UL << order), mt);
3464 /* Remove page from free list */
3466 del_page_from_free_list(page, zone, order);
3469 * Set the pageblock if the isolated page is at least half of a
3472 if (order >= pageblock_order - 1) {
3473 struct page *endpage = page + (1 << order) - 1;
3474 for (; page < endpage; page += pageblock_nr_pages) {
3475 int mt = get_pageblock_migratetype(page);
3476 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
3477 && !is_migrate_highatomic(mt))
3478 set_pageblock_migratetype(page,
3484 return 1UL << order;
3488 * __putback_isolated_page - Return a now-isolated page back where we got it
3489 * @page: Page that was isolated
3490 * @order: Order of the isolated page
3491 * @mt: The page's pageblock's migratetype
3493 * This function is meant to return a page pulled from the free lists via
3494 * __isolate_free_page back to the free lists they were pulled from.
3496 void __putback_isolated_page(struct page *page, unsigned int order, int mt)
3498 struct zone *zone = page_zone(page);
3500 /* zone lock should be held when this function is called */
3501 lockdep_assert_held(&zone->lock);
3503 /* Return isolated page to tail of freelist. */
3504 __free_one_page(page, page_to_pfn(page), zone, order, mt,
3505 FPI_SKIP_REPORT_NOTIFY | FPI_TO_TAIL);
3509 * Update NUMA hit/miss statistics
3511 * Must be called with interrupts disabled.
3513 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z,
3517 enum numa_stat_item local_stat = NUMA_LOCAL;
3519 /* skip numa counters update if numa stats is disabled */
3520 if (!static_branch_likely(&vm_numa_stat_key))
3523 if (zone_to_nid(z) != numa_node_id())
3524 local_stat = NUMA_OTHER;
3526 if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3527 __count_numa_events(z, NUMA_HIT, nr_account);
3529 __count_numa_events(z, NUMA_MISS, nr_account);
3530 __count_numa_events(preferred_zone, NUMA_FOREIGN, nr_account);
3532 __count_numa_events(z, local_stat, nr_account);
3536 /* Remove page from the per-cpu list, caller must protect the list */
3538 struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
3539 unsigned int alloc_flags,
3540 struct per_cpu_pages *pcp,
3541 struct list_head *list)
3546 if (list_empty(list)) {
3547 pcp->count += rmqueue_bulk(zone, 0,
3548 READ_ONCE(pcp->batch), list,
3549 migratetype, alloc_flags);
3550 if (unlikely(list_empty(list)))
3554 page = list_first_entry(list, struct page, lru);
3555 list_del(&page->lru);
3557 } while (check_new_pcp(page));
3562 /* Lock and remove page from the per-cpu list */
3563 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
3564 struct zone *zone, gfp_t gfp_flags,
3565 int migratetype, unsigned int alloc_flags)
3567 struct per_cpu_pages *pcp;
3568 struct list_head *list;
3570 unsigned long flags;
3572 local_lock_irqsave(&pagesets.lock, flags);
3575 * On allocation, reduce the number of pages that are batch freed.
3576 * See nr_pcp_free() where free_factor is increased for subsequent
3579 pcp = this_cpu_ptr(zone->per_cpu_pageset);
3580 pcp->free_factor >>= 1;
3581 list = &pcp->lists[migratetype];
3582 page = __rmqueue_pcplist(zone, migratetype, alloc_flags, pcp, list);
3583 local_unlock_irqrestore(&pagesets.lock, flags);
3585 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1);
3586 zone_statistics(preferred_zone, zone, 1);
3592 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
3595 struct page *rmqueue(struct zone *preferred_zone,
3596 struct zone *zone, unsigned int order,
3597 gfp_t gfp_flags, unsigned int alloc_flags,
3600 unsigned long flags;
3603 if (likely(order == 0)) {
3605 * MIGRATE_MOVABLE pcplist could have the pages on CMA area and
3606 * we need to skip it when CMA area isn't allowed.
3608 if (!IS_ENABLED(CONFIG_CMA) || alloc_flags & ALLOC_CMA ||
3609 migratetype != MIGRATE_MOVABLE) {
3610 page = rmqueue_pcplist(preferred_zone, zone, gfp_flags,
3611 migratetype, alloc_flags);
3617 * We most definitely don't want callers attempting to
3618 * allocate greater than order-1 page units with __GFP_NOFAIL.
3620 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
3621 spin_lock_irqsave(&zone->lock, flags);
3626 * order-0 request can reach here when the pcplist is skipped
3627 * due to non-CMA allocation context. HIGHATOMIC area is
3628 * reserved for high-order atomic allocation, so order-0
3629 * request should skip it.
3631 if (order > 0 && alloc_flags & ALLOC_HARDER) {
3632 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3634 trace_mm_page_alloc_zone_locked(page, order, migratetype);
3637 page = __rmqueue(zone, order, migratetype, alloc_flags);
3638 } while (page && check_new_pages(page, order));
3642 __mod_zone_freepage_state(zone, -(1 << order),
3643 get_pcppage_migratetype(page));
3644 spin_unlock_irqrestore(&zone->lock, flags);
3646 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3647 zone_statistics(preferred_zone, zone, 1);
3650 /* Separate test+clear to avoid unnecessary atomics */
3651 if (test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags)) {
3652 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3653 wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3656 VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3660 spin_unlock_irqrestore(&zone->lock, flags);
3664 #ifdef CONFIG_FAIL_PAGE_ALLOC
3667 struct fault_attr attr;
3669 bool ignore_gfp_highmem;
3670 bool ignore_gfp_reclaim;
3672 } fail_page_alloc = {
3673 .attr = FAULT_ATTR_INITIALIZER,
3674 .ignore_gfp_reclaim = true,
3675 .ignore_gfp_highmem = true,
3679 static int __init setup_fail_page_alloc(char *str)
3681 return setup_fault_attr(&fail_page_alloc.attr, str);
3683 __setup("fail_page_alloc=", setup_fail_page_alloc);
3685 static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3687 if (order < fail_page_alloc.min_order)
3689 if (gfp_mask & __GFP_NOFAIL)
3691 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3693 if (fail_page_alloc.ignore_gfp_reclaim &&
3694 (gfp_mask & __GFP_DIRECT_RECLAIM))
3697 return should_fail(&fail_page_alloc.attr, 1 << order);
3700 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3702 static int __init fail_page_alloc_debugfs(void)
3704 umode_t mode = S_IFREG | 0600;
3707 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3708 &fail_page_alloc.attr);
3710 debugfs_create_bool("ignore-gfp-wait", mode, dir,
3711 &fail_page_alloc.ignore_gfp_reclaim);
3712 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3713 &fail_page_alloc.ignore_gfp_highmem);
3714 debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order);
3719 late_initcall(fail_page_alloc_debugfs);
3721 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3723 #else /* CONFIG_FAIL_PAGE_ALLOC */
3725 static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3730 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3732 noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3734 return __should_fail_alloc_page(gfp_mask, order);
3736 ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE);
3738 static inline long __zone_watermark_unusable_free(struct zone *z,
3739 unsigned int order, unsigned int alloc_flags)
3741 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3742 long unusable_free = (1 << order) - 1;
3745 * If the caller does not have rights to ALLOC_HARDER then subtract
3746 * the high-atomic reserves. This will over-estimate the size of the
3747 * atomic reserve but it avoids a search.
3749 if (likely(!alloc_harder))
3750 unusable_free += z->nr_reserved_highatomic;
3753 /* If allocation can't use CMA areas don't use free CMA pages */
3754 if (!(alloc_flags & ALLOC_CMA))
3755 unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES);
3758 return unusable_free;
3762 * Return true if free base pages are above 'mark'. For high-order checks it
3763 * will return true of the order-0 watermark is reached and there is at least
3764 * one free page of a suitable size. Checking now avoids taking the zone lock
3765 * to check in the allocation paths if no pages are free.
3767 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3768 int highest_zoneidx, unsigned int alloc_flags,
3773 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3775 /* free_pages may go negative - that's OK */
3776 free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags);
3778 if (alloc_flags & ALLOC_HIGH)
3781 if (unlikely(alloc_harder)) {
3783 * OOM victims can try even harder than normal ALLOC_HARDER
3784 * users on the grounds that it's definitely going to be in
3785 * the exit path shortly and free memory. Any allocation it
3786 * makes during the free path will be small and short-lived.
3788 if (alloc_flags & ALLOC_OOM)
3795 * Check watermarks for an order-0 allocation request. If these
3796 * are not met, then a high-order request also cannot go ahead
3797 * even if a suitable page happened to be free.
3799 if (free_pages <= min + z->lowmem_reserve[highest_zoneidx])
3802 /* If this is an order-0 request then the watermark is fine */
3806 /* For a high-order request, check at least one suitable page is free */
3807 for (o = order; o < MAX_ORDER; o++) {
3808 struct free_area *area = &z->free_area[o];
3814 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3815 if (!free_area_empty(area, mt))
3820 if ((alloc_flags & ALLOC_CMA) &&
3821 !free_area_empty(area, MIGRATE_CMA)) {
3825 if (alloc_harder && !free_area_empty(area, MIGRATE_HIGHATOMIC))
3831 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3832 int highest_zoneidx, unsigned int alloc_flags)
3834 return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3835 zone_page_state(z, NR_FREE_PAGES));
3838 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3839 unsigned long mark, int highest_zoneidx,
3840 unsigned int alloc_flags, gfp_t gfp_mask)
3844 free_pages = zone_page_state(z, NR_FREE_PAGES);
3847 * Fast check for order-0 only. If this fails then the reserves
3848 * need to be calculated.
3853 fast_free = free_pages;
3854 fast_free -= __zone_watermark_unusable_free(z, 0, alloc_flags);
3855 if (fast_free > mark + z->lowmem_reserve[highest_zoneidx])
3859 if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3863 * Ignore watermark boosting for GFP_ATOMIC order-0 allocations
3864 * when checking the min watermark. The min watermark is the
3865 * point where boosting is ignored so that kswapd is woken up
3866 * when below the low watermark.
3868 if (unlikely(!order && (gfp_mask & __GFP_ATOMIC) && z->watermark_boost
3869 && ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) {
3870 mark = z->_watermark[WMARK_MIN];
3871 return __zone_watermark_ok(z, order, mark, highest_zoneidx,
3872 alloc_flags, free_pages);
3878 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3879 unsigned long mark, int highest_zoneidx)
3881 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3883 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3884 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3886 return __zone_watermark_ok(z, order, mark, highest_zoneidx, 0,
3891 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3893 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3894 node_reclaim_distance;
3896 #else /* CONFIG_NUMA */
3897 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3901 #endif /* CONFIG_NUMA */
3904 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3905 * fragmentation is subtle. If the preferred zone was HIGHMEM then
3906 * premature use of a lower zone may cause lowmem pressure problems that
3907 * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3908 * probably too small. It only makes sense to spread allocations to avoid
3909 * fragmentation between the Normal and DMA32 zones.
3911 static inline unsigned int
3912 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3914 unsigned int alloc_flags;
3917 * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
3920 alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
3922 #ifdef CONFIG_ZONE_DMA32
3926 if (zone_idx(zone) != ZONE_NORMAL)
3930 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3931 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3932 * on UMA that if Normal is populated then so is DMA32.
3934 BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3935 if (nr_online_nodes > 1 && !populated_zone(--zone))
3938 alloc_flags |= ALLOC_NOFRAGMENT;
3939 #endif /* CONFIG_ZONE_DMA32 */
3943 /* Must be called after current_gfp_context() which can change gfp_mask */
3944 static inline unsigned int gfp_to_alloc_flags_cma(gfp_t gfp_mask,
3945 unsigned int alloc_flags)
3948 if (gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE)
3949 alloc_flags |= ALLOC_CMA;
3955 * get_page_from_freelist goes through the zonelist trying to allocate
3958 static struct page *
3959 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3960 const struct alloc_context *ac)
3964 struct pglist_data *last_pgdat_dirty_limit = NULL;
3969 * Scan zonelist, looking for a zone with enough free.
3970 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3972 no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3973 z = ac->preferred_zoneref;
3974 for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx,
3979 if (cpusets_enabled() &&
3980 (alloc_flags & ALLOC_CPUSET) &&
3981 !__cpuset_zone_allowed(zone, gfp_mask))
3984 * When allocating a page cache page for writing, we
3985 * want to get it from a node that is within its dirty
3986 * limit, such that no single node holds more than its
3987 * proportional share of globally allowed dirty pages.
3988 * The dirty limits take into account the node's
3989 * lowmem reserves and high watermark so that kswapd
3990 * should be able to balance it without having to
3991 * write pages from its LRU list.
3993 * XXX: For now, allow allocations to potentially
3994 * exceed the per-node dirty limit in the slowpath
3995 * (spread_dirty_pages unset) before going into reclaim,
3996 * which is important when on a NUMA setup the allowed
3997 * nodes are together not big enough to reach the
3998 * global limit. The proper fix for these situations
3999 * will require awareness of nodes in the
4000 * dirty-throttling and the flusher threads.
4002 if (ac->spread_dirty_pages) {
4003 if (last_pgdat_dirty_limit == zone->zone_pgdat)
4006 if (!node_dirty_ok(zone->zone_pgdat)) {
4007 last_pgdat_dirty_limit = zone->zone_pgdat;
4012 if (no_fallback && nr_online_nodes > 1 &&
4013 zone != ac->preferred_zoneref->zone) {
4017 * If moving to a remote node, retry but allow
4018 * fragmenting fallbacks. Locality is more important
4019 * than fragmentation avoidance.
4021 local_nid = zone_to_nid(ac->preferred_zoneref->zone);
4022 if (zone_to_nid(zone) != local_nid) {
4023 alloc_flags &= ~ALLOC_NOFRAGMENT;
4028 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
4029 if (!zone_watermark_fast(zone, order, mark,
4030 ac->highest_zoneidx, alloc_flags,
4034 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
4036 * Watermark failed for this zone, but see if we can
4037 * grow this zone if it contains deferred pages.
4039 if (static_branch_unlikely(&deferred_pages)) {
4040 if (_deferred_grow_zone(zone, order))
4044 /* Checked here to keep the fast path fast */
4045 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
4046 if (alloc_flags & ALLOC_NO_WATERMARKS)
4049 if (!node_reclaim_enabled() ||
4050 !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
4053 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
4055 case NODE_RECLAIM_NOSCAN:
4058 case NODE_RECLAIM_FULL:
4059 /* scanned but unreclaimable */
4062 /* did we reclaim enough */
4063 if (zone_watermark_ok(zone, order, mark,
4064 ac->highest_zoneidx, alloc_flags))
4072 page = rmqueue(ac->preferred_zoneref->zone, zone, order,
4073 gfp_mask, alloc_flags, ac->migratetype);
4075 prep_new_page(page, order, gfp_mask, alloc_flags);
4078 * If this is a high-order atomic allocation then check
4079 * if the pageblock should be reserved for the future
4081 if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
4082 reserve_highatomic_pageblock(page, zone, order);
4086 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
4087 /* Try again if zone has deferred pages */
4088 if (static_branch_unlikely(&deferred_pages)) {
4089 if (_deferred_grow_zone(zone, order))
4097 * It's possible on a UMA machine to get through all zones that are
4098 * fragmented. If avoiding fragmentation, reset and try again.
4101 alloc_flags &= ~ALLOC_NOFRAGMENT;
4108 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
4110 unsigned int filter = SHOW_MEM_FILTER_NODES;
4113 * This documents exceptions given to allocations in certain
4114 * contexts that are allowed to allocate outside current's set
4117 if (!(gfp_mask & __GFP_NOMEMALLOC))
4118 if (tsk_is_oom_victim(current) ||
4119 (current->flags & (PF_MEMALLOC | PF_EXITING)))
4120 filter &= ~SHOW_MEM_FILTER_NODES;
4121 if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
4122 filter &= ~SHOW_MEM_FILTER_NODES;
4124 show_mem(filter, nodemask);
4127 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
4129 struct va_format vaf;
4131 static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
4133 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs))
4136 va_start(args, fmt);
4139 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
4140 current->comm, &vaf, gfp_mask, &gfp_mask,
4141 nodemask_pr_args(nodemask));
4144 cpuset_print_current_mems_allowed();
4147 warn_alloc_show_mem(gfp_mask, nodemask);
4150 static inline struct page *
4151 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
4152 unsigned int alloc_flags,
4153 const struct alloc_context *ac)
4157 page = get_page_from_freelist(gfp_mask, order,
4158 alloc_flags|ALLOC_CPUSET, ac);
4160 * fallback to ignore cpuset restriction if our nodes
4164 page = get_page_from_freelist(gfp_mask, order,
4170 static inline struct page *
4171 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
4172 const struct alloc_context *ac, unsigned long *did_some_progress)
4174 struct oom_control oc = {
4175 .zonelist = ac->zonelist,
4176 .nodemask = ac->nodemask,
4178 .gfp_mask = gfp_mask,
4183 *did_some_progress = 0;
4186 * Acquire the oom lock. If that fails, somebody else is
4187 * making progress for us.
4189 if (!mutex_trylock(&oom_lock)) {
4190 *did_some_progress = 1;
4191 schedule_timeout_uninterruptible(1);
4196 * Go through the zonelist yet one more time, keep very high watermark
4197 * here, this is only to catch a parallel oom killing, we must fail if
4198 * we're still under heavy pressure. But make sure that this reclaim
4199 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
4200 * allocation which will never fail due to oom_lock already held.
4202 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
4203 ~__GFP_DIRECT_RECLAIM, order,
4204 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
4208 /* Coredumps can quickly deplete all memory reserves */
4209 if (current->flags & PF_DUMPCORE)
4211 /* The OOM killer will not help higher order allocs */
4212 if (order > PAGE_ALLOC_COSTLY_ORDER)
4215 * We have already exhausted all our reclaim opportunities without any
4216 * success so it is time to admit defeat. We will skip the OOM killer
4217 * because it is very likely that the caller has a more reasonable
4218 * fallback than shooting a random task.
4220 * The OOM killer may not free memory on a specific node.
4222 if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE))
4224 /* The OOM killer does not needlessly kill tasks for lowmem */
4225 if (ac->highest_zoneidx < ZONE_NORMAL)
4227 if (pm_suspended_storage())
4230 * XXX: GFP_NOFS allocations should rather fail than rely on
4231 * other request to make a forward progress.
4232 * We are in an unfortunate situation where out_of_memory cannot
4233 * do much for this context but let's try it to at least get
4234 * access to memory reserved if the current task is killed (see
4235 * out_of_memory). Once filesystems are ready to handle allocation
4236 * failures more gracefully we should just bail out here.
4239 /* Exhausted what can be done so it's blame time */
4240 if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
4241 *did_some_progress = 1;
4244 * Help non-failing allocations by giving them access to memory
4247 if (gfp_mask & __GFP_NOFAIL)
4248 page = __alloc_pages_cpuset_fallback(gfp_mask, order,
4249 ALLOC_NO_WATERMARKS, ac);
4252 mutex_unlock(&oom_lock);
4257 * Maximum number of compaction retries with a progress before OOM
4258 * killer is consider as the only way to move forward.
4260 #define MAX_COMPACT_RETRIES 16
4262 #ifdef CONFIG_COMPACTION
4263 /* Try memory compaction for high-order allocations before reclaim */
4264 static struct page *
4265 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4266 unsigned int alloc_flags, const struct alloc_context *ac,
4267 enum compact_priority prio, enum compact_result *compact_result)
4269 struct page *page = NULL;
4270 unsigned long pflags;
4271 unsigned int noreclaim_flag;
4276 psi_memstall_enter(&pflags);
4277 noreclaim_flag = memalloc_noreclaim_save();
4279 *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
4282 memalloc_noreclaim_restore(noreclaim_flag);
4283 psi_memstall_leave(&pflags);
4285 if (*compact_result == COMPACT_SKIPPED)
4288 * At least in one zone compaction wasn't deferred or skipped, so let's
4289 * count a compaction stall
4291 count_vm_event(COMPACTSTALL);
4293 /* Prep a captured page if available */
4295 prep_new_page(page, order, gfp_mask, alloc_flags);
4297 /* Try get a page from the freelist if available */
4299 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4302 struct zone *zone = page_zone(page);
4304 zone->compact_blockskip_flush = false;
4305 compaction_defer_reset(zone, order, true);
4306 count_vm_event(COMPACTSUCCESS);
4311 * It's bad if compaction run occurs and fails. The most likely reason
4312 * is that pages exist, but not enough to satisfy watermarks.
4314 count_vm_event(COMPACTFAIL);
4322 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
4323 enum compact_result compact_result,
4324 enum compact_priority *compact_priority,
4325 int *compaction_retries)
4327 int max_retries = MAX_COMPACT_RETRIES;
4330 int retries = *compaction_retries;
4331 enum compact_priority priority = *compact_priority;
4336 if (fatal_signal_pending(current))
4339 if (compaction_made_progress(compact_result))
4340 (*compaction_retries)++;
4343 * compaction considers all the zone as desperately out of memory
4344 * so it doesn't really make much sense to retry except when the
4345 * failure could be caused by insufficient priority
4347 if (compaction_failed(compact_result))
4348 goto check_priority;
4351 * compaction was skipped because there are not enough order-0 pages
4352 * to work with, so we retry only if it looks like reclaim can help.
4354 if (compaction_needs_reclaim(compact_result)) {
4355 ret = compaction_zonelist_suitable(ac, order, alloc_flags);
4360 * make sure the compaction wasn't deferred or didn't bail out early
4361 * due to locks contention before we declare that we should give up.
4362 * But the next retry should use a higher priority if allowed, so
4363 * we don't just keep bailing out endlessly.
4365 if (compaction_withdrawn(compact_result)) {
4366 goto check_priority;
4370 * !costly requests are much more important than __GFP_RETRY_MAYFAIL
4371 * costly ones because they are de facto nofail and invoke OOM
4372 * killer to move on while costly can fail and users are ready
4373 * to cope with that. 1/4 retries is rather arbitrary but we
4374 * would need much more detailed feedback from compaction to
4375 * make a better decision.
4377 if (order > PAGE_ALLOC_COSTLY_ORDER)
4379 if (*compaction_retries <= max_retries) {
4385 * Make sure there are attempts at the highest priority if we exhausted
4386 * all retries or failed at the lower priorities.
4389 min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
4390 MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
4392 if (*compact_priority > min_priority) {
4393 (*compact_priority)--;
4394 *compaction_retries = 0;
4398 trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
4402 static inline struct page *
4403 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4404 unsigned int alloc_flags, const struct alloc_context *ac,
4405 enum compact_priority prio, enum compact_result *compact_result)
4407 *compact_result = COMPACT_SKIPPED;
4412 should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
4413 enum compact_result compact_result,
4414 enum compact_priority *compact_priority,
4415 int *compaction_retries)
4420 if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
4424 * There are setups with compaction disabled which would prefer to loop
4425 * inside the allocator rather than hit the oom killer prematurely.
4426 * Let's give them a good hope and keep retrying while the order-0
4427 * watermarks are OK.
4429 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4430 ac->highest_zoneidx, ac->nodemask) {
4431 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
4432 ac->highest_zoneidx, alloc_flags))
4437 #endif /* CONFIG_COMPACTION */
4439 #ifdef CONFIG_LOCKDEP
4440 static struct lockdep_map __fs_reclaim_map =
4441 STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
4443 static bool __need_reclaim(gfp_t gfp_mask)
4445 /* no reclaim without waiting on it */
4446 if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
4449 /* this guy won't enter reclaim */
4450 if (current->flags & PF_MEMALLOC)
4453 if (gfp_mask & __GFP_NOLOCKDEP)
4459 void __fs_reclaim_acquire(void)
4461 lock_map_acquire(&__fs_reclaim_map);
4464 void __fs_reclaim_release(void)
4466 lock_map_release(&__fs_reclaim_map);
4469 void fs_reclaim_acquire(gfp_t gfp_mask)
4471 gfp_mask = current_gfp_context(gfp_mask);
4473 if (__need_reclaim(gfp_mask)) {
4474 if (gfp_mask & __GFP_FS)
4475 __fs_reclaim_acquire();
4477 #ifdef CONFIG_MMU_NOTIFIER
4478 lock_map_acquire(&__mmu_notifier_invalidate_range_start_map);
4479 lock_map_release(&__mmu_notifier_invalidate_range_start_map);
4484 EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
4486 void fs_reclaim_release(gfp_t gfp_mask)
4488 gfp_mask = current_gfp_context(gfp_mask);
4490 if (__need_reclaim(gfp_mask)) {
4491 if (gfp_mask & __GFP_FS)
4492 __fs_reclaim_release();
4495 EXPORT_SYMBOL_GPL(fs_reclaim_release);
4498 /* Perform direct synchronous page reclaim */
4499 static unsigned long
4500 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
4501 const struct alloc_context *ac)
4503 unsigned int noreclaim_flag;
4504 unsigned long pflags, progress;
4508 /* We now go into synchronous reclaim */
4509 cpuset_memory_pressure_bump();
4510 psi_memstall_enter(&pflags);
4511 fs_reclaim_acquire(gfp_mask);
4512 noreclaim_flag = memalloc_noreclaim_save();
4514 progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
4517 memalloc_noreclaim_restore(noreclaim_flag);
4518 fs_reclaim_release(gfp_mask);
4519 psi_memstall_leave(&pflags);
4526 /* The really slow allocator path where we enter direct reclaim */
4527 static inline struct page *
4528 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
4529 unsigned int alloc_flags, const struct alloc_context *ac,
4530 unsigned long *did_some_progress)
4532 struct page *page = NULL;
4533 bool drained = false;
4535 *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
4536 if (unlikely(!(*did_some_progress)))
4540 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4543 * If an allocation failed after direct reclaim, it could be because
4544 * pages are pinned on the per-cpu lists or in high alloc reserves.
4545 * Shrink them and try again
4547 if (!page && !drained) {
4548 unreserve_highatomic_pageblock(ac, false);
4549 drain_all_pages(NULL);
4557 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
4558 const struct alloc_context *ac)
4562 pg_data_t *last_pgdat = NULL;
4563 enum zone_type highest_zoneidx = ac->highest_zoneidx;
4565 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx,
4567 if (last_pgdat != zone->zone_pgdat)
4568 wakeup_kswapd(zone, gfp_mask, order, highest_zoneidx);
4569 last_pgdat = zone->zone_pgdat;
4573 static inline unsigned int
4574 gfp_to_alloc_flags(gfp_t gfp_mask)
4576 unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
4579 * __GFP_HIGH is assumed to be the same as ALLOC_HIGH
4580 * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
4581 * to save two branches.
4583 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
4584 BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD);
4587 * The caller may dip into page reserves a bit more if the caller
4588 * cannot run direct reclaim, or if the caller has realtime scheduling
4589 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
4590 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
4592 alloc_flags |= (__force int)
4593 (gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM));
4595 if (gfp_mask & __GFP_ATOMIC) {
4597 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4598 * if it can't schedule.
4600 if (!(gfp_mask & __GFP_NOMEMALLOC))
4601 alloc_flags |= ALLOC_HARDER;
4603 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
4604 * comment for __cpuset_node_allowed().
4606 alloc_flags &= ~ALLOC_CPUSET;
4607 } else if (unlikely(rt_task(current)) && !in_interrupt())
4608 alloc_flags |= ALLOC_HARDER;
4610 alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, alloc_flags);
4615 static bool oom_reserves_allowed(struct task_struct *tsk)
4617 if (!tsk_is_oom_victim(tsk))
4621 * !MMU doesn't have oom reaper so give access to memory reserves
4622 * only to the thread with TIF_MEMDIE set
4624 if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
4631 * Distinguish requests which really need access to full memory
4632 * reserves from oom victims which can live with a portion of it
4634 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4636 if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4638 if (gfp_mask & __GFP_MEMALLOC)
4639 return ALLOC_NO_WATERMARKS;
4640 if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
4641 return ALLOC_NO_WATERMARKS;
4642 if (!in_interrupt()) {
4643 if (current->flags & PF_MEMALLOC)
4644 return ALLOC_NO_WATERMARKS;
4645 else if (oom_reserves_allowed(current))
4652 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4654 return !!__gfp_pfmemalloc_flags(gfp_mask);
4658 * Checks whether it makes sense to retry the reclaim to make a forward progress
4659 * for the given allocation request.
4661 * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4662 * without success, or when we couldn't even meet the watermark if we
4663 * reclaimed all remaining pages on the LRU lists.
4665 * Returns true if a retry is viable or false to enter the oom path.
4668 should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4669 struct alloc_context *ac, int alloc_flags,
4670 bool did_some_progress, int *no_progress_loops)
4677 * Costly allocations might have made a progress but this doesn't mean
4678 * their order will become available due to high fragmentation so
4679 * always increment the no progress counter for them
4681 if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4682 *no_progress_loops = 0;
4684 (*no_progress_loops)++;
4687 * Make sure we converge to OOM if we cannot make any progress
4688 * several times in the row.
4690 if (*no_progress_loops > MAX_RECLAIM_RETRIES) {
4691 /* Before OOM, exhaust highatomic_reserve */
4692 return unreserve_highatomic_pageblock(ac, true);
4696 * Keep reclaiming pages while there is a chance this will lead
4697 * somewhere. If none of the target zones can satisfy our allocation
4698 * request even if all reclaimable pages are considered then we are
4699 * screwed and have to go OOM.
4701 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4702 ac->highest_zoneidx, ac->nodemask) {
4703 unsigned long available;
4704 unsigned long reclaimable;
4705 unsigned long min_wmark = min_wmark_pages(zone);
4708 available = reclaimable = zone_reclaimable_pages(zone);
4709 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
4712 * Would the allocation succeed if we reclaimed all
4713 * reclaimable pages?
4715 wmark = __zone_watermark_ok(zone, order, min_wmark,
4716 ac->highest_zoneidx, alloc_flags, available);
4717 trace_reclaim_retry_zone(z, order, reclaimable,
4718 available, min_wmark, *no_progress_loops, wmark);
4721 * If we didn't make any progress and have a lot of
4722 * dirty + writeback pages then we should wait for
4723 * an IO to complete to slow down the reclaim and
4724 * prevent from pre mature OOM
4726 if (!did_some_progress) {
4727 unsigned long write_pending;
4729 write_pending = zone_page_state_snapshot(zone,
4730 NR_ZONE_WRITE_PENDING);
4732 if (2 * write_pending > reclaimable) {
4733 congestion_wait(BLK_RW_ASYNC, HZ/10);
4745 * Memory allocation/reclaim might be called from a WQ context and the
4746 * current implementation of the WQ concurrency control doesn't
4747 * recognize that a particular WQ is congested if the worker thread is
4748 * looping without ever sleeping. Therefore we have to do a short sleep
4749 * here rather than calling cond_resched().
4751 if (current->flags & PF_WQ_WORKER)
4752 schedule_timeout_uninterruptible(1);
4759 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4762 * It's possible that cpuset's mems_allowed and the nodemask from
4763 * mempolicy don't intersect. This should be normally dealt with by
4764 * policy_nodemask(), but it's possible to race with cpuset update in
4765 * such a way the check therein was true, and then it became false
4766 * before we got our cpuset_mems_cookie here.
4767 * This assumes that for all allocations, ac->nodemask can come only
4768 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4769 * when it does not intersect with the cpuset restrictions) or the
4770 * caller can deal with a violated nodemask.
4772 if (cpusets_enabled() && ac->nodemask &&
4773 !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4774 ac->nodemask = NULL;
4779 * When updating a task's mems_allowed or mempolicy nodemask, it is
4780 * possible to race with parallel threads in such a way that our
4781 * allocation can fail while the mask is being updated. If we are about
4782 * to fail, check if the cpuset changed during allocation and if so,
4785 if (read_mems_allowed_retry(cpuset_mems_cookie))
4791 static inline struct page *
4792 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
4793 struct alloc_context *ac)
4795 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
4796 const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
4797 struct page *page = NULL;
4798 unsigned int alloc_flags;
4799 unsigned long did_some_progress;
4800 enum compact_priority compact_priority;
4801 enum compact_result compact_result;
4802 int compaction_retries;
4803 int no_progress_loops;
4804 unsigned int cpuset_mems_cookie;
4808 * We also sanity check to catch abuse of atomic reserves being used by
4809 * callers that are not in atomic context.
4811 if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
4812 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
4813 gfp_mask &= ~__GFP_ATOMIC;
4816 compaction_retries = 0;
4817 no_progress_loops = 0;
4818 compact_priority = DEF_COMPACT_PRIORITY;
4819 cpuset_mems_cookie = read_mems_allowed_begin();
4822 * The fast path uses conservative alloc_flags to succeed only until
4823 * kswapd needs to be woken up, and to avoid the cost of setting up
4824 * alloc_flags precisely. So we do that now.
4826 alloc_flags = gfp_to_alloc_flags(gfp_mask);
4829 * We need to recalculate the starting point for the zonelist iterator
4830 * because we might have used different nodemask in the fast path, or
4831 * there was a cpuset modification and we are retrying - otherwise we
4832 * could end up iterating over non-eligible zones endlessly.
4834 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4835 ac->highest_zoneidx, ac->nodemask);
4836 if (!ac->preferred_zoneref->zone)
4839 if (alloc_flags & ALLOC_KSWAPD)
4840 wake_all_kswapds(order, gfp_mask, ac);
4843 * The adjusted alloc_flags might result in immediate success, so try
4846 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4851 * For costly allocations, try direct compaction first, as it's likely
4852 * that we have enough base pages and don't need to reclaim. For non-
4853 * movable high-order allocations, do that as well, as compaction will
4854 * try prevent permanent fragmentation by migrating from blocks of the
4856 * Don't try this for allocations that are allowed to ignore
4857 * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
4859 if (can_direct_reclaim &&
4861 (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
4862 && !gfp_pfmemalloc_allowed(gfp_mask)) {
4863 page = __alloc_pages_direct_compact(gfp_mask, order,
4865 INIT_COMPACT_PRIORITY,
4871 * Checks for costly allocations with __GFP_NORETRY, which
4872 * includes some THP page fault allocations
4874 if (costly_order && (gfp_mask & __GFP_NORETRY)) {
4876 * If allocating entire pageblock(s) and compaction
4877 * failed because all zones are below low watermarks
4878 * or is prohibited because it recently failed at this
4879 * order, fail immediately unless the allocator has
4880 * requested compaction and reclaim retry.
4883 * - potentially very expensive because zones are far
4884 * below their low watermarks or this is part of very
4885 * bursty high order allocations,
4886 * - not guaranteed to help because isolate_freepages()
4887 * may not iterate over freed pages as part of its
4889 * - unlikely to make entire pageblocks free on its
4892 if (compact_result == COMPACT_SKIPPED ||
4893 compact_result == COMPACT_DEFERRED)
4897 * Looks like reclaim/compaction is worth trying, but
4898 * sync compaction could be very expensive, so keep
4899 * using async compaction.
4901 compact_priority = INIT_COMPACT_PRIORITY;
4906 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4907 if (alloc_flags & ALLOC_KSWAPD)
4908 wake_all_kswapds(order, gfp_mask, ac);
4910 reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
4912 alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, reserve_flags);
4915 * Reset the nodemask and zonelist iterators if memory policies can be
4916 * ignored. These allocations are high priority and system rather than
4919 if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
4920 ac->nodemask = NULL;
4921 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4922 ac->highest_zoneidx, ac->nodemask);
4925 /* Attempt with potentially adjusted zonelist and alloc_flags */
4926 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4930 /* Caller is not willing to reclaim, we can't balance anything */
4931 if (!can_direct_reclaim)
4934 /* Avoid recursion of direct reclaim */
4935 if (current->flags & PF_MEMALLOC)
4938 /* Try direct reclaim and then allocating */
4939 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
4940 &did_some_progress);
4944 /* Try direct compaction and then allocating */
4945 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
4946 compact_priority, &compact_result);
4950 /* Do not loop if specifically requested */
4951 if (gfp_mask & __GFP_NORETRY)
4955 * Do not retry costly high order allocations unless they are
4956 * __GFP_RETRY_MAYFAIL
4958 if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL))
4961 if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
4962 did_some_progress > 0, &no_progress_loops))
4966 * It doesn't make any sense to retry for the compaction if the order-0
4967 * reclaim is not able to make any progress because the current
4968 * implementation of the compaction depends on the sufficient amount
4969 * of free memory (see __compaction_suitable)
4971 if (did_some_progress > 0 &&
4972 should_compact_retry(ac, order, alloc_flags,
4973 compact_result, &compact_priority,
4974 &compaction_retries))
4978 /* Deal with possible cpuset update races before we start OOM killing */
4979 if (check_retry_cpuset(cpuset_mems_cookie, ac))
4982 /* Reclaim has failed us, start killing things */
4983 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
4987 /* Avoid allocations with no watermarks from looping endlessly */
4988 if (tsk_is_oom_victim(current) &&
4989 (alloc_flags & ALLOC_OOM ||
4990 (gfp_mask & __GFP_NOMEMALLOC)))
4993 /* Retry as long as the OOM killer is making progress */
4994 if (did_some_progress) {
4995 no_progress_loops = 0;
5000 /* Deal with possible cpuset update races before we fail */
5001 if (check_retry_cpuset(cpuset_mems_cookie, ac))
5005 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
5008 if (gfp_mask & __GFP_NOFAIL) {
5010 * All existing users of the __GFP_NOFAIL are blockable, so warn
5011 * of any new users that actually require GFP_NOWAIT
5013 if (WARN_ON_ONCE(!can_direct_reclaim))
5017 * PF_MEMALLOC request from this context is rather bizarre
5018 * because we cannot reclaim anything and only can loop waiting
5019 * for somebody to do a work for us
5021 WARN_ON_ONCE(current->flags & PF_MEMALLOC);
5024 * non failing costly orders are a hard requirement which we
5025 * are not prepared for much so let's warn about these users
5026 * so that we can identify them and convert them to something
5029 WARN_ON_ONCE(order > PAGE_ALLOC_COSTLY_ORDER);
5032 * Help non-failing allocations by giving them access to memory
5033 * reserves but do not use ALLOC_NO_WATERMARKS because this
5034 * could deplete whole memory reserves which would just make
5035 * the situation worse
5037 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac);
5045 warn_alloc(gfp_mask, ac->nodemask,
5046 "page allocation failure: order:%u", order);
5051 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
5052 int preferred_nid, nodemask_t *nodemask,
5053 struct alloc_context *ac, gfp_t *alloc_gfp,
5054 unsigned int *alloc_flags)
5056 ac->highest_zoneidx = gfp_zone(gfp_mask);
5057 ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
5058 ac->nodemask = nodemask;
5059 ac->migratetype = gfp_migratetype(gfp_mask);
5061 if (cpusets_enabled()) {
5062 *alloc_gfp |= __GFP_HARDWALL;
5064 * When we are in the interrupt context, it is irrelevant
5065 * to the current task context. It means that any node ok.
5067 if (!in_interrupt() && !ac->nodemask)
5068 ac->nodemask = &cpuset_current_mems_allowed;
5070 *alloc_flags |= ALLOC_CPUSET;
5073 fs_reclaim_acquire(gfp_mask);
5074 fs_reclaim_release(gfp_mask);
5076 might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
5078 if (should_fail_alloc_page(gfp_mask, order))
5081 *alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, *alloc_flags);
5083 /* Dirty zone balancing only done in the fast path */
5084 ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
5087 * The preferred zone is used for statistics but crucially it is
5088 * also used as the starting point for the zonelist iterator. It
5089 * may get reset for allocations that ignore memory policies.
5091 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
5092 ac->highest_zoneidx, ac->nodemask);
5098 * __alloc_pages_bulk - Allocate a number of order-0 pages to a list or array
5099 * @gfp: GFP flags for the allocation
5100 * @preferred_nid: The preferred NUMA node ID to allocate from
5101 * @nodemask: Set of nodes to allocate from, may be NULL
5102 * @nr_pages: The number of pages desired on the list or array
5103 * @page_list: Optional list to store the allocated pages
5104 * @page_array: Optional array to store the pages
5106 * This is a batched version of the page allocator that attempts to
5107 * allocate nr_pages quickly. Pages are added to page_list if page_list
5108 * is not NULL, otherwise it is assumed that the page_array is valid.
5110 * For lists, nr_pages is the number of pages that should be allocated.
5112 * For arrays, only NULL elements are populated with pages and nr_pages
5113 * is the maximum number of pages that will be stored in the array.
5115 * Returns the number of pages on the list or array.
5117 unsigned long __alloc_pages_bulk(gfp_t gfp, int preferred_nid,
5118 nodemask_t *nodemask, int nr_pages,
5119 struct list_head *page_list,
5120 struct page **page_array)
5123 unsigned long flags;
5126 struct per_cpu_pages *pcp;
5127 struct list_head *pcp_list;
5128 struct alloc_context ac;
5130 unsigned int alloc_flags = ALLOC_WMARK_LOW;
5131 int nr_populated = 0, nr_account = 0;
5133 if (unlikely(nr_pages <= 0))
5137 * Skip populated array elements to determine if any pages need
5138 * to be allocated before disabling IRQs.
5140 while (page_array && nr_populated < nr_pages && page_array[nr_populated])
5143 /* Already populated array? */
5144 if (unlikely(page_array && nr_pages - nr_populated == 0))
5145 return nr_populated;
5147 /* Use the single page allocator for one page. */
5148 if (nr_pages - nr_populated == 1)
5151 /* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */
5152 gfp &= gfp_allowed_mask;
5154 if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &alloc_gfp, &alloc_flags))
5158 /* Find an allowed local zone that meets the low watermark. */
5159 for_each_zone_zonelist_nodemask(zone, z, ac.zonelist, ac.highest_zoneidx, ac.nodemask) {
5162 if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) &&
5163 !__cpuset_zone_allowed(zone, gfp)) {
5167 if (nr_online_nodes > 1 && zone != ac.preferred_zoneref->zone &&
5168 zone_to_nid(zone) != zone_to_nid(ac.preferred_zoneref->zone)) {
5172 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages;
5173 if (zone_watermark_fast(zone, 0, mark,
5174 zonelist_zone_idx(ac.preferred_zoneref),
5175 alloc_flags, gfp)) {
5181 * If there are no allowed local zones that meets the watermarks then
5182 * try to allocate a single page and reclaim if necessary.
5184 if (unlikely(!zone))
5187 /* Attempt the batch allocation */
5188 local_lock_irqsave(&pagesets.lock, flags);
5189 pcp = this_cpu_ptr(zone->per_cpu_pageset);
5190 pcp_list = &pcp->lists[ac.migratetype];
5192 while (nr_populated < nr_pages) {
5194 /* Skip existing pages */
5195 if (page_array && page_array[nr_populated]) {
5200 page = __rmqueue_pcplist(zone, ac.migratetype, alloc_flags,
5202 if (unlikely(!page)) {
5203 /* Try and get at least one page */
5210 prep_new_page(page, 0, gfp, 0);
5212 list_add(&page->lru, page_list);
5214 page_array[nr_populated] = page;
5218 local_unlock_irqrestore(&pagesets.lock, flags);
5220 __count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account);
5221 zone_statistics(ac.preferred_zoneref->zone, zone, nr_account);
5223 return nr_populated;
5226 local_unlock_irqrestore(&pagesets.lock, flags);
5229 page = __alloc_pages(gfp, 0, preferred_nid, nodemask);
5232 list_add(&page->lru, page_list);
5234 page_array[nr_populated] = page;
5238 return nr_populated;
5240 EXPORT_SYMBOL_GPL(__alloc_pages_bulk);
5243 * This is the 'heart' of the zoned buddy allocator.
5245 struct page *__alloc_pages(gfp_t gfp, unsigned int order, int preferred_nid,
5246 nodemask_t *nodemask)
5249 unsigned int alloc_flags = ALLOC_WMARK_LOW;
5250 gfp_t alloc_gfp; /* The gfp_t that was actually used for allocation */
5251 struct alloc_context ac = { };
5254 * There are several places where we assume that the order value is sane
5255 * so bail out early if the request is out of bound.
5257 if (unlikely(order >= MAX_ORDER)) {
5258 WARN_ON_ONCE(!(gfp & __GFP_NOWARN));
5262 gfp &= gfp_allowed_mask;
5264 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
5265 * resp. GFP_NOIO which has to be inherited for all allocation requests
5266 * from a particular context which has been marked by
5267 * memalloc_no{fs,io}_{save,restore}. And PF_MEMALLOC_PIN which ensures
5268 * movable zones are not used during allocation.
5270 gfp = current_gfp_context(gfp);
5272 if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac,
5273 &alloc_gfp, &alloc_flags))
5277 * Forbid the first pass from falling back to types that fragment
5278 * memory until all local zones are considered.
5280 alloc_flags |= alloc_flags_nofragment(ac.preferred_zoneref->zone, gfp);
5282 /* First allocation attempt */
5283 page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac);
5288 ac.spread_dirty_pages = false;
5291 * Restore the original nodemask if it was potentially replaced with
5292 * &cpuset_current_mems_allowed to optimize the fast-path attempt.
5294 ac.nodemask = nodemask;
5296 page = __alloc_pages_slowpath(alloc_gfp, order, &ac);
5299 if (memcg_kmem_enabled() && (gfp & __GFP_ACCOUNT) && page &&
5300 unlikely(__memcg_kmem_charge_page(page, gfp, order) != 0)) {
5301 __free_pages(page, order);
5305 trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype);
5309 EXPORT_SYMBOL(__alloc_pages);
5312 * Common helper functions. Never use with __GFP_HIGHMEM because the returned
5313 * address cannot represent highmem pages. Use alloc_pages and then kmap if
5314 * you need to access high mem.
5316 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
5320 page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order);
5323 return (unsigned long) page_address(page);
5325 EXPORT_SYMBOL(__get_free_pages);
5327 unsigned long get_zeroed_page(gfp_t gfp_mask)
5329 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
5331 EXPORT_SYMBOL(get_zeroed_page);
5333 static inline void free_the_page(struct page *page, unsigned int order)
5335 if (order == 0) /* Via pcp? */
5336 free_unref_page(page);
5338 __free_pages_ok(page, order, FPI_NONE);
5342 * __free_pages - Free pages allocated with alloc_pages().
5343 * @page: The page pointer returned from alloc_pages().
5344 * @order: The order of the allocation.
5346 * This function can free multi-page allocations that are not compound
5347 * pages. It does not check that the @order passed in matches that of
5348 * the allocation, so it is easy to leak memory. Freeing more memory
5349 * than was allocated will probably emit a warning.
5351 * If the last reference to this page is speculative, it will be released
5352 * by put_page() which only frees the first page of a non-compound
5353 * allocation. To prevent the remaining pages from being leaked, we free
5354 * the subsequent pages here. If you want to use the page's reference
5355 * count to decide when to free the allocation, you should allocate a
5356 * compound page, and use put_page() instead of __free_pages().
5358 * Context: May be called in interrupt context or while holding a normal
5359 * spinlock, but not in NMI context or while holding a raw spinlock.
5361 void __free_pages(struct page *page, unsigned int order)
5363 if (put_page_testzero(page))
5364 free_the_page(page, order);
5365 else if (!PageHead(page))
5367 free_the_page(page + (1 << order), order);
5369 EXPORT_SYMBOL(__free_pages);
5371 void free_pages(unsigned long addr, unsigned int order)
5374 VM_BUG_ON(!virt_addr_valid((void *)addr));
5375 __free_pages(virt_to_page((void *)addr), order);
5379 EXPORT_SYMBOL(free_pages);
5383 * An arbitrary-length arbitrary-offset area of memory which resides
5384 * within a 0 or higher order page. Multiple fragments within that page
5385 * are individually refcounted, in the page's reference counter.
5387 * The page_frag functions below provide a simple allocation framework for
5388 * page fragments. This is used by the network stack and network device
5389 * drivers to provide a backing region of memory for use as either an
5390 * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
5392 static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
5395 struct page *page = NULL;
5396 gfp_t gfp = gfp_mask;
5398 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5399 gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
5401 page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
5402 PAGE_FRAG_CACHE_MAX_ORDER);
5403 nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
5405 if (unlikely(!page))
5406 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
5408 nc->va = page ? page_address(page) : NULL;
5413 void __page_frag_cache_drain(struct page *page, unsigned int count)
5415 VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
5417 if (page_ref_sub_and_test(page, count))
5418 free_the_page(page, compound_order(page));
5420 EXPORT_SYMBOL(__page_frag_cache_drain);
5422 void *page_frag_alloc_align(struct page_frag_cache *nc,
5423 unsigned int fragsz, gfp_t gfp_mask,
5424 unsigned int align_mask)
5426 unsigned int size = PAGE_SIZE;
5430 if (unlikely(!nc->va)) {
5432 page = __page_frag_cache_refill(nc, gfp_mask);
5436 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5437 /* if size can vary use size else just use PAGE_SIZE */
5440 /* Even if we own the page, we do not use atomic_set().
5441 * This would break get_page_unless_zero() users.
5443 page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
5445 /* reset page count bias and offset to start of new frag */
5446 nc->pfmemalloc = page_is_pfmemalloc(page);
5447 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
5451 offset = nc->offset - fragsz;
5452 if (unlikely(offset < 0)) {
5453 page = virt_to_page(nc->va);
5455 if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
5458 if (unlikely(nc->pfmemalloc)) {
5459 free_the_page(page, compound_order(page));
5463 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5464 /* if size can vary use size else just use PAGE_SIZE */
5467 /* OK, page count is 0, we can safely set it */
5468 set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
5470 /* reset page count bias and offset to start of new frag */
5471 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
5472 offset = size - fragsz;
5476 offset &= align_mask;
5477 nc->offset = offset;
5479 return nc->va + offset;
5481 EXPORT_SYMBOL(page_frag_alloc_align);
5484 * Frees a page fragment allocated out of either a compound or order 0 page.
5486 void page_frag_free(void *addr)
5488 struct page *page = virt_to_head_page(addr);
5490 if (unlikely(put_page_testzero(page)))
5491 free_the_page(page, compound_order(page));
5493 EXPORT_SYMBOL(page_frag_free);
5495 static void *make_alloc_exact(unsigned long addr, unsigned int order,
5499 unsigned long alloc_end = addr + (PAGE_SIZE << order);
5500 unsigned long used = addr + PAGE_ALIGN(size);
5502 split_page(virt_to_page((void *)addr), order);
5503 while (used < alloc_end) {
5508 return (void *)addr;
5512 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
5513 * @size: the number of bytes to allocate
5514 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5516 * This function is similar to alloc_pages(), except that it allocates the
5517 * minimum number of pages to satisfy the request. alloc_pages() can only
5518 * allocate memory in power-of-two pages.
5520 * This function is also limited by MAX_ORDER.
5522 * Memory allocated by this function must be released by free_pages_exact().
5524 * Return: pointer to the allocated area or %NULL in case of error.
5526 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
5528 unsigned int order = get_order(size);
5531 if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
5532 gfp_mask &= ~__GFP_COMP;
5534 addr = __get_free_pages(gfp_mask, order);
5535 return make_alloc_exact(addr, order, size);
5537 EXPORT_SYMBOL(alloc_pages_exact);
5540 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
5542 * @nid: the preferred node ID where memory should be allocated
5543 * @size: the number of bytes to allocate
5544 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5546 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
5549 * Return: pointer to the allocated area or %NULL in case of error.
5551 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
5553 unsigned int order = get_order(size);
5556 if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
5557 gfp_mask &= ~__GFP_COMP;
5559 p = alloc_pages_node(nid, gfp_mask, order);
5562 return make_alloc_exact((unsigned long)page_address(p), order, size);
5566 * free_pages_exact - release memory allocated via alloc_pages_exact()
5567 * @virt: the value returned by alloc_pages_exact.
5568 * @size: size of allocation, same value as passed to alloc_pages_exact().
5570 * Release the memory allocated by a previous call to alloc_pages_exact.
5572 void free_pages_exact(void *virt, size_t size)
5574 unsigned long addr = (unsigned long)virt;
5575 unsigned long end = addr + PAGE_ALIGN(size);
5577 while (addr < end) {
5582 EXPORT_SYMBOL(free_pages_exact);
5585 * nr_free_zone_pages - count number of pages beyond high watermark
5586 * @offset: The zone index of the highest zone
5588 * nr_free_zone_pages() counts the number of pages which are beyond the
5589 * high watermark within all zones at or below a given zone index. For each
5590 * zone, the number of pages is calculated as:
5592 * nr_free_zone_pages = managed_pages - high_pages
5594 * Return: number of pages beyond high watermark.
5596 static unsigned long nr_free_zone_pages(int offset)
5601 /* Just pick one node, since fallback list is circular */
5602 unsigned long sum = 0;
5604 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
5606 for_each_zone_zonelist(zone, z, zonelist, offset) {
5607 unsigned long size = zone_managed_pages(zone);
5608 unsigned long high = high_wmark_pages(zone);
5617 * nr_free_buffer_pages - count number of pages beyond high watermark
5619 * nr_free_buffer_pages() counts the number of pages which are beyond the high
5620 * watermark within ZONE_DMA and ZONE_NORMAL.
5622 * Return: number of pages beyond high watermark within ZONE_DMA and
5625 unsigned long nr_free_buffer_pages(void)
5627 return nr_free_zone_pages(gfp_zone(GFP_USER));
5629 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
5631 static inline void show_node(struct zone *zone)
5633 if (IS_ENABLED(CONFIG_NUMA))
5634 printk("Node %d ", zone_to_nid(zone));
5637 long si_mem_available(void)
5640 unsigned long pagecache;
5641 unsigned long wmark_low = 0;
5642 unsigned long pages[NR_LRU_LISTS];
5643 unsigned long reclaimable;
5647 for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
5648 pages[lru] = global_node_page_state(NR_LRU_BASE + lru);
5651 wmark_low += low_wmark_pages(zone);
5654 * Estimate the amount of memory available for userspace allocations,
5655 * without causing swapping.
5657 available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages;
5660 * Not all the page cache can be freed, otherwise the system will
5661 * start swapping. Assume at least half of the page cache, or the
5662 * low watermark worth of cache, needs to stay.
5664 pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
5665 pagecache -= min(pagecache / 2, wmark_low);
5666 available += pagecache;
5669 * Part of the reclaimable slab and other kernel memory consists of
5670 * items that are in use, and cannot be freed. Cap this estimate at the
5673 reclaimable = global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B) +
5674 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE);
5675 available += reclaimable - min(reclaimable / 2, wmark_low);
5681 EXPORT_SYMBOL_GPL(si_mem_available);
5683 void si_meminfo(struct sysinfo *val)
5685 val->totalram = totalram_pages();
5686 val->sharedram = global_node_page_state(NR_SHMEM);
5687 val->freeram = global_zone_page_state(NR_FREE_PAGES);
5688 val->bufferram = nr_blockdev_pages();
5689 val->totalhigh = totalhigh_pages();
5690 val->freehigh = nr_free_highpages();
5691 val->mem_unit = PAGE_SIZE;
5694 EXPORT_SYMBOL(si_meminfo);
5697 void si_meminfo_node(struct sysinfo *val, int nid)
5699 int zone_type; /* needs to be signed */
5700 unsigned long managed_pages = 0;
5701 unsigned long managed_highpages = 0;
5702 unsigned long free_highpages = 0;
5703 pg_data_t *pgdat = NODE_DATA(nid);
5705 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
5706 managed_pages += zone_managed_pages(&pgdat->node_zones[zone_type]);
5707 val->totalram = managed_pages;
5708 val->sharedram = node_page_state(pgdat, NR_SHMEM);
5709 val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES);
5710 #ifdef CONFIG_HIGHMEM
5711 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
5712 struct zone *zone = &pgdat->node_zones[zone_type];
5714 if (is_highmem(zone)) {
5715 managed_highpages += zone_managed_pages(zone);
5716 free_highpages += zone_page_state(zone, NR_FREE_PAGES);
5719 val->totalhigh = managed_highpages;
5720 val->freehigh = free_highpages;
5722 val->totalhigh = managed_highpages;
5723 val->freehigh = free_highpages;
5725 val->mem_unit = PAGE_SIZE;
5730 * Determine whether the node should be displayed or not, depending on whether
5731 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
5733 static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask)
5735 if (!(flags & SHOW_MEM_FILTER_NODES))
5739 * no node mask - aka implicit memory numa policy. Do not bother with
5740 * the synchronization - read_mems_allowed_begin - because we do not
5741 * have to be precise here.
5744 nodemask = &cpuset_current_mems_allowed;
5746 return !node_isset(nid, *nodemask);
5749 #define K(x) ((x) << (PAGE_SHIFT-10))
5751 static void show_migration_types(unsigned char type)
5753 static const char types[MIGRATE_TYPES] = {
5754 [MIGRATE_UNMOVABLE] = 'U',
5755 [MIGRATE_MOVABLE] = 'M',
5756 [MIGRATE_RECLAIMABLE] = 'E',
5757 [MIGRATE_HIGHATOMIC] = 'H',
5759 [MIGRATE_CMA] = 'C',
5761 #ifdef CONFIG_MEMORY_ISOLATION
5762 [MIGRATE_ISOLATE] = 'I',
5765 char tmp[MIGRATE_TYPES + 1];
5769 for (i = 0; i < MIGRATE_TYPES; i++) {
5770 if (type & (1 << i))
5775 printk(KERN_CONT "(%s) ", tmp);
5779 * Show free area list (used inside shift_scroll-lock stuff)
5780 * We also calculate the percentage fragmentation. We do this by counting the
5781 * memory on each free list with the exception of the first item on the list.
5784 * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
5787 void show_free_areas(unsigned int filter, nodemask_t *nodemask)
5789 unsigned long free_pcp = 0;
5794 for_each_populated_zone(zone) {
5795 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5798 for_each_online_cpu(cpu)
5799 free_pcp += per_cpu_ptr(zone->per_cpu_pageset, cpu)->count;
5802 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
5803 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
5804 " unevictable:%lu dirty:%lu writeback:%lu\n"
5805 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
5806 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
5807 " free:%lu free_pcp:%lu free_cma:%lu\n",
5808 global_node_page_state(NR_ACTIVE_ANON),
5809 global_node_page_state(NR_INACTIVE_ANON),
5810 global_node_page_state(NR_ISOLATED_ANON),
5811 global_node_page_state(NR_ACTIVE_FILE),
5812 global_node_page_state(NR_INACTIVE_FILE),
5813 global_node_page_state(NR_ISOLATED_FILE),
5814 global_node_page_state(NR_UNEVICTABLE),
5815 global_node_page_state(NR_FILE_DIRTY),
5816 global_node_page_state(NR_WRITEBACK),
5817 global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B),
5818 global_node_page_state_pages(NR_SLAB_UNRECLAIMABLE_B),
5819 global_node_page_state(NR_FILE_MAPPED),
5820 global_node_page_state(NR_SHMEM),
5821 global_node_page_state(NR_PAGETABLE),
5822 global_zone_page_state(NR_BOUNCE),
5823 global_zone_page_state(NR_FREE_PAGES),
5825 global_zone_page_state(NR_FREE_CMA_PAGES));
5827 for_each_online_pgdat(pgdat) {
5828 if (show_mem_node_skip(filter, pgdat->node_id, nodemask))
5832 " active_anon:%lukB"
5833 " inactive_anon:%lukB"
5834 " active_file:%lukB"
5835 " inactive_file:%lukB"
5836 " unevictable:%lukB"
5837 " isolated(anon):%lukB"
5838 " isolated(file):%lukB"
5843 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5845 " shmem_pmdmapped: %lukB"
5848 " writeback_tmp:%lukB"
5849 " kernel_stack:%lukB"
5850 #ifdef CONFIG_SHADOW_CALL_STACK
5851 " shadow_call_stack:%lukB"
5854 " all_unreclaimable? %s"
5857 K(node_page_state(pgdat, NR_ACTIVE_ANON)),
5858 K(node_page_state(pgdat, NR_INACTIVE_ANON)),
5859 K(node_page_state(pgdat, NR_ACTIVE_FILE)),
5860 K(node_page_state(pgdat, NR_INACTIVE_FILE)),
5861 K(node_page_state(pgdat, NR_UNEVICTABLE)),
5862 K(node_page_state(pgdat, NR_ISOLATED_ANON)),
5863 K(node_page_state(pgdat, NR_ISOLATED_FILE)),
5864 K(node_page_state(pgdat, NR_FILE_MAPPED)),
5865 K(node_page_state(pgdat, NR_FILE_DIRTY)),
5866 K(node_page_state(pgdat, NR_WRITEBACK)),
5867 K(node_page_state(pgdat, NR_SHMEM)),
5868 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5869 K(node_page_state(pgdat, NR_SHMEM_THPS)),
5870 K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED)),
5871 K(node_page_state(pgdat, NR_ANON_THPS)),
5873 K(node_page_state(pgdat, NR_WRITEBACK_TEMP)),
5874 node_page_state(pgdat, NR_KERNEL_STACK_KB),
5875 #ifdef CONFIG_SHADOW_CALL_STACK
5876 node_page_state(pgdat, NR_KERNEL_SCS_KB),
5878 K(node_page_state(pgdat, NR_PAGETABLE)),
5879 pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ?
5883 for_each_populated_zone(zone) {
5886 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5890 for_each_online_cpu(cpu)
5891 free_pcp += per_cpu_ptr(zone->per_cpu_pageset, cpu)->count;
5900 " reserved_highatomic:%luKB"
5901 " active_anon:%lukB"
5902 " inactive_anon:%lukB"
5903 " active_file:%lukB"
5904 " inactive_file:%lukB"
5905 " unevictable:%lukB"
5906 " writepending:%lukB"
5916 K(zone_page_state(zone, NR_FREE_PAGES)),
5917 K(min_wmark_pages(zone)),
5918 K(low_wmark_pages(zone)),
5919 K(high_wmark_pages(zone)),
5920 K(zone->nr_reserved_highatomic),
5921 K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)),
5922 K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)),
5923 K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)),
5924 K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)),
5925 K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)),
5926 K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)),
5927 K(zone->present_pages),
5928 K(zone_managed_pages(zone)),
5929 K(zone_page_state(zone, NR_MLOCK)),
5930 K(zone_page_state(zone, NR_BOUNCE)),
5932 K(this_cpu_read(zone->per_cpu_pageset->count)),
5933 K(zone_page_state(zone, NR_FREE_CMA_PAGES)));
5934 printk("lowmem_reserve[]:");
5935 for (i = 0; i < MAX_NR_ZONES; i++)
5936 printk(KERN_CONT " %ld", zone->lowmem_reserve[i]);
5937 printk(KERN_CONT "\n");
5940 for_each_populated_zone(zone) {
5942 unsigned long nr[MAX_ORDER], flags, total = 0;
5943 unsigned char types[MAX_ORDER];
5945 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5948 printk(KERN_CONT "%s: ", zone->name);
5950 spin_lock_irqsave(&zone->lock, flags);
5951 for (order = 0; order < MAX_ORDER; order++) {
5952 struct free_area *area = &zone->free_area[order];
5955 nr[order] = area->nr_free;
5956 total += nr[order] << order;
5959 for (type = 0; type < MIGRATE_TYPES; type++) {
5960 if (!free_area_empty(area, type))
5961 types[order] |= 1 << type;
5964 spin_unlock_irqrestore(&zone->lock, flags);
5965 for (order = 0; order < MAX_ORDER; order++) {
5966 printk(KERN_CONT "%lu*%lukB ",
5967 nr[order], K(1UL) << order);
5969 show_migration_types(types[order]);
5971 printk(KERN_CONT "= %lukB\n", K(total));
5974 hugetlb_show_meminfo();
5976 printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES));
5978 show_swap_cache_info();
5981 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
5983 zoneref->zone = zone;
5984 zoneref->zone_idx = zone_idx(zone);
5988 * Builds allocation fallback zone lists.
5990 * Add all populated zones of a node to the zonelist.
5992 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
5995 enum zone_type zone_type = MAX_NR_ZONES;
6000 zone = pgdat->node_zones + zone_type;
6001 if (managed_zone(zone)) {
6002 zoneref_set_zone(zone, &zonerefs[nr_zones++]);
6003 check_highest_zone(zone_type);
6005 } while (zone_type);
6012 static int __parse_numa_zonelist_order(char *s)
6015 * We used to support different zonelists modes but they turned
6016 * out to be just not useful. Let's keep the warning in place
6017 * if somebody still use the cmd line parameter so that we do
6018 * not fail it silently
6020 if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
6021 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s);
6027 char numa_zonelist_order[] = "Node";
6030 * sysctl handler for numa_zonelist_order
6032 int numa_zonelist_order_handler(struct ctl_table *table, int write,
6033 void *buffer, size_t *length, loff_t *ppos)
6036 return __parse_numa_zonelist_order(buffer);
6037 return proc_dostring(table, write, buffer, length, ppos);
6041 #define MAX_NODE_LOAD (nr_online_nodes)
6042 static int node_load[MAX_NUMNODES];
6045 * find_next_best_node - find the next node that should appear in a given node's fallback list
6046 * @node: node whose fallback list we're appending
6047 * @used_node_mask: nodemask_t of already used nodes
6049 * We use a number of factors to determine which is the next node that should
6050 * appear on a given node's fallback list. The node should not have appeared
6051 * already in @node's fallback list, and it should be the next closest node
6052 * according to the distance array (which contains arbitrary distance values
6053 * from each node to each node in the system), and should also prefer nodes
6054 * with no CPUs, since presumably they'll have very little allocation pressure
6055 * on them otherwise.
6057 * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
6059 static int find_next_best_node(int node, nodemask_t *used_node_mask)
6062 int min_val = INT_MAX;
6063 int best_node = NUMA_NO_NODE;
6065 /* Use the local node if we haven't already */
6066 if (!node_isset(node, *used_node_mask)) {
6067 node_set(node, *used_node_mask);
6071 for_each_node_state(n, N_MEMORY) {
6073 /* Don't want a node to appear more than once */
6074 if (node_isset(n, *used_node_mask))
6077 /* Use the distance array to find the distance */
6078 val = node_distance(node, n);
6080 /* Penalize nodes under us ("prefer the next node") */
6083 /* Give preference to headless and unused nodes */
6084 if (!cpumask_empty(cpumask_of_node(n)))
6085 val += PENALTY_FOR_NODE_WITH_CPUS;
6087 /* Slight preference for less loaded node */
6088 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
6089 val += node_load[n];
6091 if (val < min_val) {
6098 node_set(best_node, *used_node_mask);
6105 * Build zonelists ordered by node and zones within node.
6106 * This results in maximum locality--normal zone overflows into local
6107 * DMA zone, if any--but risks exhausting DMA zone.
6109 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
6112 struct zoneref *zonerefs;
6115 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
6117 for (i = 0; i < nr_nodes; i++) {
6120 pg_data_t *node = NODE_DATA(node_order[i]);
6122 nr_zones = build_zonerefs_node(node, zonerefs);
6123 zonerefs += nr_zones;
6125 zonerefs->zone = NULL;
6126 zonerefs->zone_idx = 0;
6130 * Build gfp_thisnode zonelists
6132 static void build_thisnode_zonelists(pg_data_t *pgdat)
6134 struct zoneref *zonerefs;
6137 zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
6138 nr_zones = build_zonerefs_node(pgdat, zonerefs);
6139 zonerefs += nr_zones;
6140 zonerefs->zone = NULL;
6141 zonerefs->zone_idx = 0;
6145 * Build zonelists ordered by zone and nodes within zones.
6146 * This results in conserving DMA zone[s] until all Normal memory is
6147 * exhausted, but results in overflowing to remote node while memory
6148 * may still exist in local DMA zone.
6151 static void build_zonelists(pg_data_t *pgdat)
6153 static int node_order[MAX_NUMNODES];
6154 int node, load, nr_nodes = 0;
6155 nodemask_t used_mask = NODE_MASK_NONE;
6156 int local_node, prev_node;
6158 /* NUMA-aware ordering of nodes */
6159 local_node = pgdat->node_id;
6160 load = nr_online_nodes;
6161 prev_node = local_node;
6163 memset(node_order, 0, sizeof(node_order));
6164 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
6166 * We don't want to pressure a particular node.
6167 * So adding penalty to the first node in same
6168 * distance group to make it round-robin.
6170 if (node_distance(local_node, node) !=
6171 node_distance(local_node, prev_node))
6172 node_load[node] = load;
6174 node_order[nr_nodes++] = node;
6179 build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
6180 build_thisnode_zonelists(pgdat);
6183 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
6185 * Return node id of node used for "local" allocations.
6186 * I.e., first node id of first zone in arg node's generic zonelist.
6187 * Used for initializing percpu 'numa_mem', which is used primarily
6188 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
6190 int local_memory_node(int node)
6194 z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
6195 gfp_zone(GFP_KERNEL),
6197 return zone_to_nid(z->zone);
6201 static void setup_min_unmapped_ratio(void);
6202 static void setup_min_slab_ratio(void);
6203 #else /* CONFIG_NUMA */
6205 static void build_zonelists(pg_data_t *pgdat)
6207 int node, local_node;
6208 struct zoneref *zonerefs;
6211 local_node = pgdat->node_id;
6213 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
6214 nr_zones = build_zonerefs_node(pgdat, zonerefs);
6215 zonerefs += nr_zones;
6218 * Now we build the zonelist so that it contains the zones
6219 * of all the other nodes.
6220 * We don't want to pressure a particular node, so when
6221 * building the zones for node N, we make sure that the
6222 * zones coming right after the local ones are those from
6223 * node N+1 (modulo N)
6225 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
6226 if (!node_online(node))
6228 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
6229 zonerefs += nr_zones;
6231 for (node = 0; node < local_node; node++) {
6232 if (!node_online(node))
6234 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
6235 zonerefs += nr_zones;
6238 zonerefs->zone = NULL;
6239 zonerefs->zone_idx = 0;
6242 #endif /* CONFIG_NUMA */
6245 * Boot pageset table. One per cpu which is going to be used for all
6246 * zones and all nodes. The parameters will be set in such a way
6247 * that an item put on a list will immediately be handed over to
6248 * the buddy list. This is safe since pageset manipulation is done
6249 * with interrupts disabled.
6251 * The boot_pagesets must be kept even after bootup is complete for
6252 * unused processors and/or zones. They do play a role for bootstrapping
6253 * hotplugged processors.
6255 * zoneinfo_show() and maybe other functions do
6256 * not check if the processor is online before following the pageset pointer.
6257 * Other parts of the kernel may not check if the zone is available.
6259 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats);
6260 /* These effectively disable the pcplists in the boot pageset completely */
6261 #define BOOT_PAGESET_HIGH 0
6262 #define BOOT_PAGESET_BATCH 1
6263 static DEFINE_PER_CPU(struct per_cpu_pages, boot_pageset);
6264 static DEFINE_PER_CPU(struct per_cpu_zonestat, boot_zonestats);
6265 static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
6267 static void __build_all_zonelists(void *data)
6270 int __maybe_unused cpu;
6271 pg_data_t *self = data;
6272 static DEFINE_SPINLOCK(lock);
6277 memset(node_load, 0, sizeof(node_load));
6281 * This node is hotadded and no memory is yet present. So just
6282 * building zonelists is fine - no need to touch other nodes.
6284 if (self && !node_online(self->node_id)) {
6285 build_zonelists(self);
6287 for_each_online_node(nid) {
6288 pg_data_t *pgdat = NODE_DATA(nid);
6290 build_zonelists(pgdat);
6293 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
6295 * We now know the "local memory node" for each node--
6296 * i.e., the node of the first zone in the generic zonelist.
6297 * Set up numa_mem percpu variable for on-line cpus. During
6298 * boot, only the boot cpu should be on-line; we'll init the
6299 * secondary cpus' numa_mem as they come on-line. During
6300 * node/memory hotplug, we'll fixup all on-line cpus.
6302 for_each_online_cpu(cpu)
6303 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
6310 static noinline void __init
6311 build_all_zonelists_init(void)
6315 __build_all_zonelists(NULL);
6318 * Initialize the boot_pagesets that are going to be used
6319 * for bootstrapping processors. The real pagesets for
6320 * each zone will be allocated later when the per cpu
6321 * allocator is available.
6323 * boot_pagesets are used also for bootstrapping offline
6324 * cpus if the system is already booted because the pagesets
6325 * are needed to initialize allocators on a specific cpu too.
6326 * F.e. the percpu allocator needs the page allocator which
6327 * needs the percpu allocator in order to allocate its pagesets
6328 * (a chicken-egg dilemma).
6330 for_each_possible_cpu(cpu)
6331 per_cpu_pages_init(&per_cpu(boot_pageset, cpu), &per_cpu(boot_zonestats, cpu));
6333 mminit_verify_zonelist();
6334 cpuset_init_current_mems_allowed();
6338 * unless system_state == SYSTEM_BOOTING.
6340 * __ref due to call of __init annotated helper build_all_zonelists_init
6341 * [protected by SYSTEM_BOOTING].
6343 void __ref build_all_zonelists(pg_data_t *pgdat)
6345 unsigned long vm_total_pages;
6347 if (system_state == SYSTEM_BOOTING) {
6348 build_all_zonelists_init();
6350 __build_all_zonelists(pgdat);
6351 /* cpuset refresh routine should be here */
6353 /* Get the number of free pages beyond high watermark in all zones. */
6354 vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
6356 * Disable grouping by mobility if the number of pages in the
6357 * system is too low to allow the mechanism to work. It would be
6358 * more accurate, but expensive to check per-zone. This check is
6359 * made on memory-hotadd so a system can start with mobility
6360 * disabled and enable it later
6362 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
6363 page_group_by_mobility_disabled = 1;
6365 page_group_by_mobility_disabled = 0;
6367 pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n",
6369 page_group_by_mobility_disabled ? "off" : "on",
6372 pr_info("Policy zone: %s\n", zone_names[policy_zone]);
6376 /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
6377 static bool __meminit
6378 overlap_memmap_init(unsigned long zone, unsigned long *pfn)
6380 static struct memblock_region *r;
6382 if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
6383 if (!r || *pfn >= memblock_region_memory_end_pfn(r)) {
6384 for_each_mem_region(r) {
6385 if (*pfn < memblock_region_memory_end_pfn(r))
6389 if (*pfn >= memblock_region_memory_base_pfn(r) &&
6390 memblock_is_mirror(r)) {
6391 *pfn = memblock_region_memory_end_pfn(r);
6399 * Initially all pages are reserved - free ones are freed
6400 * up by memblock_free_all() once the early boot process is
6401 * done. Non-atomic initialization, single-pass.
6403 * All aligned pageblocks are initialized to the specified migratetype
6404 * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
6405 * zone stats (e.g., nr_isolate_pageblock) are touched.
6407 void __meminit memmap_init_range(unsigned long size, int nid, unsigned long zone,
6408 unsigned long start_pfn, unsigned long zone_end_pfn,
6409 enum meminit_context context,
6410 struct vmem_altmap *altmap, int migratetype)
6412 unsigned long pfn, end_pfn = start_pfn + size;
6415 if (highest_memmap_pfn < end_pfn - 1)
6416 highest_memmap_pfn = end_pfn - 1;
6418 #ifdef CONFIG_ZONE_DEVICE
6420 * Honor reservation requested by the driver for this ZONE_DEVICE
6421 * memory. We limit the total number of pages to initialize to just
6422 * those that might contain the memory mapping. We will defer the
6423 * ZONE_DEVICE page initialization until after we have released
6426 if (zone == ZONE_DEVICE) {
6430 if (start_pfn == altmap->base_pfn)
6431 start_pfn += altmap->reserve;
6432 end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
6436 for (pfn = start_pfn; pfn < end_pfn; ) {
6438 * There can be holes in boot-time mem_map[]s handed to this
6439 * function. They do not exist on hotplugged memory.
6441 if (context == MEMINIT_EARLY) {
6442 if (overlap_memmap_init(zone, &pfn))
6444 if (defer_init(nid, pfn, zone_end_pfn))
6448 page = pfn_to_page(pfn);
6449 __init_single_page(page, pfn, zone, nid);
6450 if (context == MEMINIT_HOTPLUG)
6451 __SetPageReserved(page);
6454 * Usually, we want to mark the pageblock MIGRATE_MOVABLE,
6455 * such that unmovable allocations won't be scattered all
6456 * over the place during system boot.
6458 if (IS_ALIGNED(pfn, pageblock_nr_pages)) {
6459 set_pageblock_migratetype(page, migratetype);
6466 #ifdef CONFIG_ZONE_DEVICE
6467 void __ref memmap_init_zone_device(struct zone *zone,
6468 unsigned long start_pfn,
6469 unsigned long nr_pages,
6470 struct dev_pagemap *pgmap)
6472 unsigned long pfn, end_pfn = start_pfn + nr_pages;
6473 struct pglist_data *pgdat = zone->zone_pgdat;
6474 struct vmem_altmap *altmap = pgmap_altmap(pgmap);
6475 unsigned long zone_idx = zone_idx(zone);
6476 unsigned long start = jiffies;
6477 int nid = pgdat->node_id;
6479 if (WARN_ON_ONCE(!pgmap || zone_idx(zone) != ZONE_DEVICE))
6483 * The call to memmap_init should have already taken care
6484 * of the pages reserved for the memmap, so we can just jump to
6485 * the end of that region and start processing the device pages.
6488 start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
6489 nr_pages = end_pfn - start_pfn;
6492 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
6493 struct page *page = pfn_to_page(pfn);
6495 __init_single_page(page, pfn, zone_idx, nid);
6498 * Mark page reserved as it will need to wait for onlining
6499 * phase for it to be fully associated with a zone.
6501 * We can use the non-atomic __set_bit operation for setting
6502 * the flag as we are still initializing the pages.
6504 __SetPageReserved(page);
6507 * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer
6508 * and zone_device_data. It is a bug if a ZONE_DEVICE page is
6509 * ever freed or placed on a driver-private list.
6511 page->pgmap = pgmap;
6512 page->zone_device_data = NULL;
6515 * Mark the block movable so that blocks are reserved for
6516 * movable at startup. This will force kernel allocations
6517 * to reserve their blocks rather than leaking throughout
6518 * the address space during boot when many long-lived
6519 * kernel allocations are made.
6521 * Please note that MEMINIT_HOTPLUG path doesn't clear memmap
6522 * because this is done early in section_activate()
6524 if (IS_ALIGNED(pfn, pageblock_nr_pages)) {
6525 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
6530 pr_info("%s initialised %lu pages in %ums\n", __func__,
6531 nr_pages, jiffies_to_msecs(jiffies - start));
6535 static void __meminit zone_init_free_lists(struct zone *zone)
6537 unsigned int order, t;
6538 for_each_migratetype_order(order, t) {
6539 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
6540 zone->free_area[order].nr_free = 0;
6544 #if !defined(CONFIG_FLAT_NODE_MEM_MAP)
6546 * Only struct pages that correspond to ranges defined by memblock.memory
6547 * are zeroed and initialized by going through __init_single_page() during
6548 * memmap_init_zone_range().
6550 * But, there could be struct pages that correspond to holes in
6551 * memblock.memory. This can happen because of the following reasons:
6552 * - physical memory bank size is not necessarily the exact multiple of the
6553 * arbitrary section size
6554 * - early reserved memory may not be listed in memblock.memory
6555 * - memory layouts defined with memmap= kernel parameter may not align
6556 * nicely with memmap sections
6558 * Explicitly initialize those struct pages so that:
6559 * - PG_Reserved is set
6560 * - zone and node links point to zone and node that span the page if the
6561 * hole is in the middle of a zone
6562 * - zone and node links point to adjacent zone/node if the hole falls on
6563 * the zone boundary; the pages in such holes will be prepended to the
6564 * zone/node above the hole except for the trailing pages in the last
6565 * section that will be appended to the zone/node below.
6567 static void __init init_unavailable_range(unsigned long spfn,
6574 for (pfn = spfn; pfn < epfn; pfn++) {
6575 if (!pfn_valid(ALIGN_DOWN(pfn, pageblock_nr_pages))) {
6576 pfn = ALIGN_DOWN(pfn, pageblock_nr_pages)
6577 + pageblock_nr_pages - 1;
6580 __init_single_page(pfn_to_page(pfn), pfn, zone, node);
6581 __SetPageReserved(pfn_to_page(pfn));
6586 pr_info("On node %d, zone %s: %lld pages in unavailable ranges",
6587 node, zone_names[zone], pgcnt);
6590 static inline void init_unavailable_range(unsigned long spfn,
6597 static void __init memmap_init_zone_range(struct zone *zone,
6598 unsigned long start_pfn,
6599 unsigned long end_pfn,
6600 unsigned long *hole_pfn)
6602 unsigned long zone_start_pfn = zone->zone_start_pfn;
6603 unsigned long zone_end_pfn = zone_start_pfn + zone->spanned_pages;
6604 int nid = zone_to_nid(zone), zone_id = zone_idx(zone);
6606 start_pfn = clamp(start_pfn, zone_start_pfn, zone_end_pfn);
6607 end_pfn = clamp(end_pfn, zone_start_pfn, zone_end_pfn);
6609 if (start_pfn >= end_pfn)
6612 memmap_init_range(end_pfn - start_pfn, nid, zone_id, start_pfn,
6613 zone_end_pfn, MEMINIT_EARLY, NULL, MIGRATE_MOVABLE);
6615 if (*hole_pfn < start_pfn)
6616 init_unavailable_range(*hole_pfn, start_pfn, zone_id, nid);
6618 *hole_pfn = end_pfn;
6621 static void __init memmap_init(void)
6623 unsigned long start_pfn, end_pfn;
6624 unsigned long hole_pfn = 0;
6625 int i, j, zone_id, nid;
6627 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
6628 struct pglist_data *node = NODE_DATA(nid);
6630 for (j = 0; j < MAX_NR_ZONES; j++) {
6631 struct zone *zone = node->node_zones + j;
6633 if (!populated_zone(zone))
6636 memmap_init_zone_range(zone, start_pfn, end_pfn,
6642 #ifdef CONFIG_SPARSEMEM
6644 * Initialize the memory map for hole in the range [memory_end,
6646 * Append the pages in this hole to the highest zone in the last
6648 * The call to init_unavailable_range() is outside the ifdef to
6649 * silence the compiler warining about zone_id set but not used;
6650 * for FLATMEM it is a nop anyway
6652 end_pfn = round_up(end_pfn, PAGES_PER_SECTION);
6653 if (hole_pfn < end_pfn)
6655 init_unavailable_range(hole_pfn, end_pfn, zone_id, nid);
6658 static int zone_batchsize(struct zone *zone)
6664 * The number of pages to batch allocate is either ~0.1%
6665 * of the zone or 1MB, whichever is smaller. The batch
6666 * size is striking a balance between allocation latency
6667 * and zone lock contention.
6669 batch = min(zone_managed_pages(zone) >> 10, (1024 * 1024) / PAGE_SIZE);
6670 batch /= 4; /* We effectively *= 4 below */
6675 * Clamp the batch to a 2^n - 1 value. Having a power
6676 * of 2 value was found to be more likely to have
6677 * suboptimal cache aliasing properties in some cases.
6679 * For example if 2 tasks are alternately allocating
6680 * batches of pages, one task can end up with a lot
6681 * of pages of one half of the possible page colors
6682 * and the other with pages of the other colors.
6684 batch = rounddown_pow_of_two(batch + batch/2) - 1;
6689 /* The deferral and batching of frees should be suppressed under NOMMU
6692 * The problem is that NOMMU needs to be able to allocate large chunks
6693 * of contiguous memory as there's no hardware page translation to
6694 * assemble apparent contiguous memory from discontiguous pages.
6696 * Queueing large contiguous runs of pages for batching, however,
6697 * causes the pages to actually be freed in smaller chunks. As there
6698 * can be a significant delay between the individual batches being
6699 * recycled, this leads to the once large chunks of space being
6700 * fragmented and becoming unavailable for high-order allocations.
6706 static int zone_highsize(struct zone *zone, int batch, int cpu_online)
6713 * The high value of the pcp is based on the zone low watermark
6714 * so that if they are full then background reclaim will not be
6715 * started prematurely. The value is split across all online CPUs
6716 * local to the zone. Note that early in boot that CPUs may not be
6717 * online yet and that during CPU hotplug that the cpumask is not
6718 * yet updated when a CPU is being onlined.
6720 nr_local_cpus = max(1U, cpumask_weight(cpumask_of_node(zone_to_nid(zone)))) + cpu_online;
6721 high = low_wmark_pages(zone) / nr_local_cpus;
6724 * Ensure high is at least batch*4. The multiple is based on the
6725 * historical relationship between high and batch.
6727 high = max(high, batch << 2);
6736 * pcp->high and pcp->batch values are related and generally batch is lower
6737 * than high. They are also related to pcp->count such that count is lower
6738 * than high, and as soon as it reaches high, the pcplist is flushed.
6740 * However, guaranteeing these relations at all times would require e.g. write
6741 * barriers here but also careful usage of read barriers at the read side, and
6742 * thus be prone to error and bad for performance. Thus the update only prevents
6743 * store tearing. Any new users of pcp->batch and pcp->high should ensure they
6744 * can cope with those fields changing asynchronously, and fully trust only the
6745 * pcp->count field on the local CPU with interrupts disabled.
6747 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
6748 * outside of boot time (or some other assurance that no concurrent updaters
6751 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
6752 unsigned long batch)
6754 WRITE_ONCE(pcp->batch, batch);
6755 WRITE_ONCE(pcp->high, high);
6758 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats)
6762 memset(pcp, 0, sizeof(*pcp));
6763 memset(pzstats, 0, sizeof(*pzstats));
6765 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
6766 INIT_LIST_HEAD(&pcp->lists[migratetype]);
6769 * Set batch and high values safe for a boot pageset. A true percpu
6770 * pageset's initialization will update them subsequently. Here we don't
6771 * need to be as careful as pageset_update() as nobody can access the
6774 pcp->high = BOOT_PAGESET_HIGH;
6775 pcp->batch = BOOT_PAGESET_BATCH;
6776 pcp->free_factor = 0;
6779 static void __zone_set_pageset_high_and_batch(struct zone *zone, unsigned long high,
6780 unsigned long batch)
6782 struct per_cpu_pages *pcp;
6785 for_each_possible_cpu(cpu) {
6786 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
6787 pageset_update(pcp, high, batch);
6792 * Calculate and set new high and batch values for all per-cpu pagesets of a
6793 * zone based on the zone's size.
6795 static void zone_set_pageset_high_and_batch(struct zone *zone, int cpu_online)
6797 int new_high, new_batch;
6799 new_batch = max(1, zone_batchsize(zone));
6800 new_high = zone_highsize(zone, new_batch, cpu_online);
6802 if (zone->pageset_high == new_high &&
6803 zone->pageset_batch == new_batch)
6806 zone->pageset_high = new_high;
6807 zone->pageset_batch = new_batch;
6809 __zone_set_pageset_high_and_batch(zone, new_high, new_batch);
6812 void __meminit setup_zone_pageset(struct zone *zone)
6816 /* Size may be 0 on !SMP && !NUMA */
6817 if (sizeof(struct per_cpu_zonestat) > 0)
6818 zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat);
6820 zone->per_cpu_pageset = alloc_percpu(struct per_cpu_pages);
6821 for_each_possible_cpu(cpu) {
6822 struct per_cpu_pages *pcp;
6823 struct per_cpu_zonestat *pzstats;
6825 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
6826 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
6827 per_cpu_pages_init(pcp, pzstats);
6830 zone_set_pageset_high_and_batch(zone, 0);
6834 * Allocate per cpu pagesets and initialize them.
6835 * Before this call only boot pagesets were available.
6837 void __init setup_per_cpu_pageset(void)
6839 struct pglist_data *pgdat;
6841 int __maybe_unused cpu;
6843 for_each_populated_zone(zone)
6844 setup_zone_pageset(zone);
6848 * Unpopulated zones continue using the boot pagesets.
6849 * The numa stats for these pagesets need to be reset.
6850 * Otherwise, they will end up skewing the stats of
6851 * the nodes these zones are associated with.
6853 for_each_possible_cpu(cpu) {
6854 struct per_cpu_zonestat *pzstats = &per_cpu(boot_zonestats, cpu);
6855 memset(pzstats->vm_numa_event, 0,
6856 sizeof(pzstats->vm_numa_event));
6860 for_each_online_pgdat(pgdat)
6861 pgdat->per_cpu_nodestats =
6862 alloc_percpu(struct per_cpu_nodestat);
6865 static __meminit void zone_pcp_init(struct zone *zone)
6868 * per cpu subsystem is not up at this point. The following code
6869 * relies on the ability of the linker to provide the
6870 * offset of a (static) per cpu variable into the per cpu area.
6872 zone->per_cpu_pageset = &boot_pageset;
6873 zone->per_cpu_zonestats = &boot_zonestats;
6874 zone->pageset_high = BOOT_PAGESET_HIGH;
6875 zone->pageset_batch = BOOT_PAGESET_BATCH;
6877 if (populated_zone(zone))
6878 pr_debug(" %s zone: %lu pages, LIFO batch:%u\n", zone->name,
6879 zone->present_pages, zone_batchsize(zone));
6882 void __meminit init_currently_empty_zone(struct zone *zone,
6883 unsigned long zone_start_pfn,
6886 struct pglist_data *pgdat = zone->zone_pgdat;
6887 int zone_idx = zone_idx(zone) + 1;
6889 if (zone_idx > pgdat->nr_zones)
6890 pgdat->nr_zones = zone_idx;
6892 zone->zone_start_pfn = zone_start_pfn;
6894 mminit_dprintk(MMINIT_TRACE, "memmap_init",
6895 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
6897 (unsigned long)zone_idx(zone),
6898 zone_start_pfn, (zone_start_pfn + size));
6900 zone_init_free_lists(zone);
6901 zone->initialized = 1;
6905 * get_pfn_range_for_nid - Return the start and end page frames for a node
6906 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
6907 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
6908 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
6910 * It returns the start and end page frame of a node based on information
6911 * provided by memblock_set_node(). If called for a node
6912 * with no available memory, a warning is printed and the start and end
6915 void __init get_pfn_range_for_nid(unsigned int nid,
6916 unsigned long *start_pfn, unsigned long *end_pfn)
6918 unsigned long this_start_pfn, this_end_pfn;
6924 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
6925 *start_pfn = min(*start_pfn, this_start_pfn);
6926 *end_pfn = max(*end_pfn, this_end_pfn);
6929 if (*start_pfn == -1UL)
6934 * This finds a zone that can be used for ZONE_MOVABLE pages. The
6935 * assumption is made that zones within a node are ordered in monotonic
6936 * increasing memory addresses so that the "highest" populated zone is used
6938 static void __init find_usable_zone_for_movable(void)
6941 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
6942 if (zone_index == ZONE_MOVABLE)
6945 if (arch_zone_highest_possible_pfn[zone_index] >
6946 arch_zone_lowest_possible_pfn[zone_index])
6950 VM_BUG_ON(zone_index == -1);
6951 movable_zone = zone_index;
6955 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
6956 * because it is sized independent of architecture. Unlike the other zones,
6957 * the starting point for ZONE_MOVABLE is not fixed. It may be different
6958 * in each node depending on the size of each node and how evenly kernelcore
6959 * is distributed. This helper function adjusts the zone ranges
6960 * provided by the architecture for a given node by using the end of the
6961 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
6962 * zones within a node are in order of monotonic increases memory addresses
6964 static void __init adjust_zone_range_for_zone_movable(int nid,
6965 unsigned long zone_type,
6966 unsigned long node_start_pfn,
6967 unsigned long node_end_pfn,
6968 unsigned long *zone_start_pfn,
6969 unsigned long *zone_end_pfn)
6971 /* Only adjust if ZONE_MOVABLE is on this node */
6972 if (zone_movable_pfn[nid]) {
6973 /* Size ZONE_MOVABLE */
6974 if (zone_type == ZONE_MOVABLE) {
6975 *zone_start_pfn = zone_movable_pfn[nid];
6976 *zone_end_pfn = min(node_end_pfn,
6977 arch_zone_highest_possible_pfn[movable_zone]);
6979 /* Adjust for ZONE_MOVABLE starting within this range */
6980 } else if (!mirrored_kernelcore &&
6981 *zone_start_pfn < zone_movable_pfn[nid] &&
6982 *zone_end_pfn > zone_movable_pfn[nid]) {
6983 *zone_end_pfn = zone_movable_pfn[nid];
6985 /* Check if this whole range is within ZONE_MOVABLE */
6986 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
6987 *zone_start_pfn = *zone_end_pfn;
6992 * Return the number of pages a zone spans in a node, including holes
6993 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
6995 static unsigned long __init zone_spanned_pages_in_node(int nid,
6996 unsigned long zone_type,
6997 unsigned long node_start_pfn,
6998 unsigned long node_end_pfn,
6999 unsigned long *zone_start_pfn,
7000 unsigned long *zone_end_pfn)
7002 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
7003 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
7004 /* When hotadd a new node from cpu_up(), the node should be empty */
7005 if (!node_start_pfn && !node_end_pfn)
7008 /* Get the start and end of the zone */
7009 *zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
7010 *zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
7011 adjust_zone_range_for_zone_movable(nid, zone_type,
7012 node_start_pfn, node_end_pfn,
7013 zone_start_pfn, zone_end_pfn);
7015 /* Check that this node has pages within the zone's required range */
7016 if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
7019 /* Move the zone boundaries inside the node if necessary */
7020 *zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
7021 *zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
7023 /* Return the spanned pages */
7024 return *zone_end_pfn - *zone_start_pfn;
7028 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
7029 * then all holes in the requested range will be accounted for.
7031 unsigned long __init __absent_pages_in_range(int nid,
7032 unsigned long range_start_pfn,
7033 unsigned long range_end_pfn)
7035 unsigned long nr_absent = range_end_pfn - range_start_pfn;
7036 unsigned long start_pfn, end_pfn;
7039 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
7040 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
7041 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
7042 nr_absent -= end_pfn - start_pfn;
7048 * absent_pages_in_range - Return number of page frames in holes within a range
7049 * @start_pfn: The start PFN to start searching for holes
7050 * @end_pfn: The end PFN to stop searching for holes
7052 * Return: the number of pages frames in memory holes within a range.
7054 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
7055 unsigned long end_pfn)
7057 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
7060 /* Return the number of page frames in holes in a zone on a node */
7061 static unsigned long __init zone_absent_pages_in_node(int nid,
7062 unsigned long zone_type,
7063 unsigned long node_start_pfn,
7064 unsigned long node_end_pfn)
7066 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
7067 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
7068 unsigned long zone_start_pfn, zone_end_pfn;
7069 unsigned long nr_absent;
7071 /* When hotadd a new node from cpu_up(), the node should be empty */
7072 if (!node_start_pfn && !node_end_pfn)
7075 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
7076 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
7078 adjust_zone_range_for_zone_movable(nid, zone_type,
7079 node_start_pfn, node_end_pfn,
7080 &zone_start_pfn, &zone_end_pfn);
7081 nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
7084 * ZONE_MOVABLE handling.
7085 * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
7088 if (mirrored_kernelcore && zone_movable_pfn[nid]) {
7089 unsigned long start_pfn, end_pfn;
7090 struct memblock_region *r;
7092 for_each_mem_region(r) {
7093 start_pfn = clamp(memblock_region_memory_base_pfn(r),
7094 zone_start_pfn, zone_end_pfn);
7095 end_pfn = clamp(memblock_region_memory_end_pfn(r),
7096 zone_start_pfn, zone_end_pfn);
7098 if (zone_type == ZONE_MOVABLE &&
7099 memblock_is_mirror(r))
7100 nr_absent += end_pfn - start_pfn;
7102 if (zone_type == ZONE_NORMAL &&
7103 !memblock_is_mirror(r))
7104 nr_absent += end_pfn - start_pfn;
7111 static void __init calculate_node_totalpages(struct pglist_data *pgdat,
7112 unsigned long node_start_pfn,
7113 unsigned long node_end_pfn)
7115 unsigned long realtotalpages = 0, totalpages = 0;
7118 for (i = 0; i < MAX_NR_ZONES; i++) {
7119 struct zone *zone = pgdat->node_zones + i;
7120 unsigned long zone_start_pfn, zone_end_pfn;
7121 unsigned long spanned, absent;
7122 unsigned long size, real_size;
7124 spanned = zone_spanned_pages_in_node(pgdat->node_id, i,
7129 absent = zone_absent_pages_in_node(pgdat->node_id, i,
7134 real_size = size - absent;
7137 zone->zone_start_pfn = zone_start_pfn;
7139 zone->zone_start_pfn = 0;
7140 zone->spanned_pages = size;
7141 zone->present_pages = real_size;
7144 realtotalpages += real_size;
7147 pgdat->node_spanned_pages = totalpages;
7148 pgdat->node_present_pages = realtotalpages;
7149 pr_debug("On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
7152 #ifndef CONFIG_SPARSEMEM
7154 * Calculate the size of the zone->blockflags rounded to an unsigned long
7155 * Start by making sure zonesize is a multiple of pageblock_order by rounding
7156 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
7157 * round what is now in bits to nearest long in bits, then return it in
7160 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
7162 unsigned long usemapsize;
7164 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
7165 usemapsize = roundup(zonesize, pageblock_nr_pages);
7166 usemapsize = usemapsize >> pageblock_order;
7167 usemapsize *= NR_PAGEBLOCK_BITS;
7168 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
7170 return usemapsize / 8;
7173 static void __ref setup_usemap(struct zone *zone)
7175 unsigned long usemapsize = usemap_size(zone->zone_start_pfn,
7176 zone->spanned_pages);
7177 zone->pageblock_flags = NULL;
7179 zone->pageblock_flags =
7180 memblock_alloc_node(usemapsize, SMP_CACHE_BYTES,
7182 if (!zone->pageblock_flags)
7183 panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n",
7184 usemapsize, zone->name, zone_to_nid(zone));
7188 static inline void setup_usemap(struct zone *zone) {}
7189 #endif /* CONFIG_SPARSEMEM */
7191 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
7193 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
7194 void __init set_pageblock_order(void)
7198 /* Check that pageblock_nr_pages has not already been setup */
7199 if (pageblock_order)
7202 if (HPAGE_SHIFT > PAGE_SHIFT)
7203 order = HUGETLB_PAGE_ORDER;
7205 order = MAX_ORDER - 1;
7208 * Assume the largest contiguous order of interest is a huge page.
7209 * This value may be variable depending on boot parameters on IA64 and
7212 pageblock_order = order;
7214 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
7217 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
7218 * is unused as pageblock_order is set at compile-time. See
7219 * include/linux/pageblock-flags.h for the values of pageblock_order based on
7222 void __init set_pageblock_order(void)
7226 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
7228 static unsigned long __init calc_memmap_size(unsigned long spanned_pages,
7229 unsigned long present_pages)
7231 unsigned long pages = spanned_pages;
7234 * Provide a more accurate estimation if there are holes within
7235 * the zone and SPARSEMEM is in use. If there are holes within the
7236 * zone, each populated memory region may cost us one or two extra
7237 * memmap pages due to alignment because memmap pages for each
7238 * populated regions may not be naturally aligned on page boundary.
7239 * So the (present_pages >> 4) heuristic is a tradeoff for that.
7241 if (spanned_pages > present_pages + (present_pages >> 4) &&
7242 IS_ENABLED(CONFIG_SPARSEMEM))
7243 pages = present_pages;
7245 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
7248 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
7249 static void pgdat_init_split_queue(struct pglist_data *pgdat)
7251 struct deferred_split *ds_queue = &pgdat->deferred_split_queue;
7253 spin_lock_init(&ds_queue->split_queue_lock);
7254 INIT_LIST_HEAD(&ds_queue->split_queue);
7255 ds_queue->split_queue_len = 0;
7258 static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
7261 #ifdef CONFIG_COMPACTION
7262 static void pgdat_init_kcompactd(struct pglist_data *pgdat)
7264 init_waitqueue_head(&pgdat->kcompactd_wait);
7267 static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
7270 static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
7272 pgdat_resize_init(pgdat);
7274 pgdat_init_split_queue(pgdat);
7275 pgdat_init_kcompactd(pgdat);
7277 init_waitqueue_head(&pgdat->kswapd_wait);
7278 init_waitqueue_head(&pgdat->pfmemalloc_wait);
7280 pgdat_page_ext_init(pgdat);
7281 lruvec_init(&pgdat->__lruvec);
7284 static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
7285 unsigned long remaining_pages)
7287 atomic_long_set(&zone->managed_pages, remaining_pages);
7288 zone_set_nid(zone, nid);
7289 zone->name = zone_names[idx];
7290 zone->zone_pgdat = NODE_DATA(nid);
7291 spin_lock_init(&zone->lock);
7292 zone_seqlock_init(zone);
7293 zone_pcp_init(zone);
7297 * Set up the zone data structures
7298 * - init pgdat internals
7299 * - init all zones belonging to this node
7301 * NOTE: this function is only called during memory hotplug
7303 #ifdef CONFIG_MEMORY_HOTPLUG
7304 void __ref free_area_init_core_hotplug(int nid)
7307 pg_data_t *pgdat = NODE_DATA(nid);
7309 pgdat_init_internals(pgdat);
7310 for (z = 0; z < MAX_NR_ZONES; z++)
7311 zone_init_internals(&pgdat->node_zones[z], z, nid, 0);
7316 * Set up the zone data structures:
7317 * - mark all pages reserved
7318 * - mark all memory queues empty
7319 * - clear the memory bitmaps
7321 * NOTE: pgdat should get zeroed by caller.
7322 * NOTE: this function is only called during early init.
7324 static void __init free_area_init_core(struct pglist_data *pgdat)
7327 int nid = pgdat->node_id;
7329 pgdat_init_internals(pgdat);
7330 pgdat->per_cpu_nodestats = &boot_nodestats;
7332 for (j = 0; j < MAX_NR_ZONES; j++) {
7333 struct zone *zone = pgdat->node_zones + j;
7334 unsigned long size, freesize, memmap_pages;
7336 size = zone->spanned_pages;
7337 freesize = zone->present_pages;
7340 * Adjust freesize so that it accounts for how much memory
7341 * is used by this zone for memmap. This affects the watermark
7342 * and per-cpu initialisations
7344 memmap_pages = calc_memmap_size(size, freesize);
7345 if (!is_highmem_idx(j)) {
7346 if (freesize >= memmap_pages) {
7347 freesize -= memmap_pages;
7349 pr_debug(" %s zone: %lu pages used for memmap\n",
7350 zone_names[j], memmap_pages);
7352 pr_warn(" %s zone: %lu pages exceeds freesize %lu\n",
7353 zone_names[j], memmap_pages, freesize);
7356 /* Account for reserved pages */
7357 if (j == 0 && freesize > dma_reserve) {
7358 freesize -= dma_reserve;
7359 pr_debug(" %s zone: %lu pages reserved\n", zone_names[0], dma_reserve);
7362 if (!is_highmem_idx(j))
7363 nr_kernel_pages += freesize;
7364 /* Charge for highmem memmap if there are enough kernel pages */
7365 else if (nr_kernel_pages > memmap_pages * 2)
7366 nr_kernel_pages -= memmap_pages;
7367 nr_all_pages += freesize;
7370 * Set an approximate value for lowmem here, it will be adjusted
7371 * when the bootmem allocator frees pages into the buddy system.
7372 * And all highmem pages will be managed by the buddy system.
7374 zone_init_internals(zone, j, nid, freesize);
7379 set_pageblock_order();
7381 init_currently_empty_zone(zone, zone->zone_start_pfn, size);
7385 #ifdef CONFIG_FLAT_NODE_MEM_MAP
7386 static void __ref alloc_node_mem_map(struct pglist_data *pgdat)
7388 unsigned long __maybe_unused start = 0;
7389 unsigned long __maybe_unused offset = 0;
7391 /* Skip empty nodes */
7392 if (!pgdat->node_spanned_pages)
7395 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
7396 offset = pgdat->node_start_pfn - start;
7397 /* ia64 gets its own node_mem_map, before this, without bootmem */
7398 if (!pgdat->node_mem_map) {
7399 unsigned long size, end;
7403 * The zone's endpoints aren't required to be MAX_ORDER
7404 * aligned but the node_mem_map endpoints must be in order
7405 * for the buddy allocator to function correctly.
7407 end = pgdat_end_pfn(pgdat);
7408 end = ALIGN(end, MAX_ORDER_NR_PAGES);
7409 size = (end - start) * sizeof(struct page);
7410 map = memblock_alloc_node(size, SMP_CACHE_BYTES,
7413 panic("Failed to allocate %ld bytes for node %d memory map\n",
7414 size, pgdat->node_id);
7415 pgdat->node_mem_map = map + offset;
7417 pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
7418 __func__, pgdat->node_id, (unsigned long)pgdat,
7419 (unsigned long)pgdat->node_mem_map);
7420 #ifndef CONFIG_NEED_MULTIPLE_NODES
7422 * With no DISCONTIG, the global mem_map is just set as node 0's
7424 if (pgdat == NODE_DATA(0)) {
7425 mem_map = NODE_DATA(0)->node_mem_map;
7426 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
7432 static void __ref alloc_node_mem_map(struct pglist_data *pgdat) { }
7433 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
7435 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
7436 static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
7438 pgdat->first_deferred_pfn = ULONG_MAX;
7441 static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
7444 static void __init free_area_init_node(int nid)
7446 pg_data_t *pgdat = NODE_DATA(nid);
7447 unsigned long start_pfn = 0;
7448 unsigned long end_pfn = 0;
7450 /* pg_data_t should be reset to zero when it's allocated */
7451 WARN_ON(pgdat->nr_zones || pgdat->kswapd_highest_zoneidx);
7453 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
7455 pgdat->node_id = nid;
7456 pgdat->node_start_pfn = start_pfn;
7457 pgdat->per_cpu_nodestats = NULL;
7459 pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
7460 (u64)start_pfn << PAGE_SHIFT,
7461 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
7462 calculate_node_totalpages(pgdat, start_pfn, end_pfn);
7464 alloc_node_mem_map(pgdat);
7465 pgdat_set_deferred_range(pgdat);
7467 free_area_init_core(pgdat);
7470 void __init free_area_init_memoryless_node(int nid)
7472 free_area_init_node(nid);
7475 #if MAX_NUMNODES > 1
7477 * Figure out the number of possible node ids.
7479 void __init setup_nr_node_ids(void)
7481 unsigned int highest;
7483 highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
7484 nr_node_ids = highest + 1;
7489 * node_map_pfn_alignment - determine the maximum internode alignment
7491 * This function should be called after node map is populated and sorted.
7492 * It calculates the maximum power of two alignment which can distinguish
7495 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
7496 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
7497 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
7498 * shifted, 1GiB is enough and this function will indicate so.
7500 * This is used to test whether pfn -> nid mapping of the chosen memory
7501 * model has fine enough granularity to avoid incorrect mapping for the
7502 * populated node map.
7504 * Return: the determined alignment in pfn's. 0 if there is no alignment
7505 * requirement (single node).
7507 unsigned long __init node_map_pfn_alignment(void)
7509 unsigned long accl_mask = 0, last_end = 0;
7510 unsigned long start, end, mask;
7511 int last_nid = NUMA_NO_NODE;
7514 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
7515 if (!start || last_nid < 0 || last_nid == nid) {
7522 * Start with a mask granular enough to pin-point to the
7523 * start pfn and tick off bits one-by-one until it becomes
7524 * too coarse to separate the current node from the last.
7526 mask = ~((1 << __ffs(start)) - 1);
7527 while (mask && last_end <= (start & (mask << 1)))
7530 /* accumulate all internode masks */
7534 /* convert mask to number of pages */
7535 return ~accl_mask + 1;
7539 * find_min_pfn_with_active_regions - Find the minimum PFN registered
7541 * Return: the minimum PFN based on information provided via
7542 * memblock_set_node().
7544 unsigned long __init find_min_pfn_with_active_regions(void)
7546 return PHYS_PFN(memblock_start_of_DRAM());
7550 * early_calculate_totalpages()
7551 * Sum pages in active regions for movable zone.
7552 * Populate N_MEMORY for calculating usable_nodes.
7554 static unsigned long __init early_calculate_totalpages(void)
7556 unsigned long totalpages = 0;
7557 unsigned long start_pfn, end_pfn;
7560 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7561 unsigned long pages = end_pfn - start_pfn;
7563 totalpages += pages;
7565 node_set_state(nid, N_MEMORY);
7571 * Find the PFN the Movable zone begins in each node. Kernel memory
7572 * is spread evenly between nodes as long as the nodes have enough
7573 * memory. When they don't, some nodes will have more kernelcore than
7576 static void __init find_zone_movable_pfns_for_nodes(void)
7579 unsigned long usable_startpfn;
7580 unsigned long kernelcore_node, kernelcore_remaining;
7581 /* save the state before borrow the nodemask */
7582 nodemask_t saved_node_state = node_states[N_MEMORY];
7583 unsigned long totalpages = early_calculate_totalpages();
7584 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
7585 struct memblock_region *r;
7587 /* Need to find movable_zone earlier when movable_node is specified. */
7588 find_usable_zone_for_movable();
7591 * If movable_node is specified, ignore kernelcore and movablecore
7594 if (movable_node_is_enabled()) {
7595 for_each_mem_region(r) {
7596 if (!memblock_is_hotpluggable(r))
7599 nid = memblock_get_region_node(r);
7601 usable_startpfn = PFN_DOWN(r->base);
7602 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7603 min(usable_startpfn, zone_movable_pfn[nid]) :
7611 * If kernelcore=mirror is specified, ignore movablecore option
7613 if (mirrored_kernelcore) {
7614 bool mem_below_4gb_not_mirrored = false;
7616 for_each_mem_region(r) {
7617 if (memblock_is_mirror(r))
7620 nid = memblock_get_region_node(r);
7622 usable_startpfn = memblock_region_memory_base_pfn(r);
7624 if (usable_startpfn < 0x100000) {
7625 mem_below_4gb_not_mirrored = true;
7629 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7630 min(usable_startpfn, zone_movable_pfn[nid]) :
7634 if (mem_below_4gb_not_mirrored)
7635 pr_warn("This configuration results in unmirrored kernel memory.\n");
7641 * If kernelcore=nn% or movablecore=nn% was specified, calculate the
7642 * amount of necessary memory.
7644 if (required_kernelcore_percent)
7645 required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
7647 if (required_movablecore_percent)
7648 required_movablecore = (totalpages * 100 * required_movablecore_percent) /
7652 * If movablecore= was specified, calculate what size of
7653 * kernelcore that corresponds so that memory usable for
7654 * any allocation type is evenly spread. If both kernelcore
7655 * and movablecore are specified, then the value of kernelcore
7656 * will be used for required_kernelcore if it's greater than
7657 * what movablecore would have allowed.
7659 if (required_movablecore) {
7660 unsigned long corepages;
7663 * Round-up so that ZONE_MOVABLE is at least as large as what
7664 * was requested by the user
7666 required_movablecore =
7667 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
7668 required_movablecore = min(totalpages, required_movablecore);
7669 corepages = totalpages - required_movablecore;
7671 required_kernelcore = max(required_kernelcore, corepages);
7675 * If kernelcore was not specified or kernelcore size is larger
7676 * than totalpages, there is no ZONE_MOVABLE.
7678 if (!required_kernelcore || required_kernelcore >= totalpages)
7681 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
7682 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
7685 /* Spread kernelcore memory as evenly as possible throughout nodes */
7686 kernelcore_node = required_kernelcore / usable_nodes;
7687 for_each_node_state(nid, N_MEMORY) {
7688 unsigned long start_pfn, end_pfn;
7691 * Recalculate kernelcore_node if the division per node
7692 * now exceeds what is necessary to satisfy the requested
7693 * amount of memory for the kernel
7695 if (required_kernelcore < kernelcore_node)
7696 kernelcore_node = required_kernelcore / usable_nodes;
7699 * As the map is walked, we track how much memory is usable
7700 * by the kernel using kernelcore_remaining. When it is
7701 * 0, the rest of the node is usable by ZONE_MOVABLE
7703 kernelcore_remaining = kernelcore_node;
7705 /* Go through each range of PFNs within this node */
7706 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
7707 unsigned long size_pages;
7709 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
7710 if (start_pfn >= end_pfn)
7713 /* Account for what is only usable for kernelcore */
7714 if (start_pfn < usable_startpfn) {
7715 unsigned long kernel_pages;
7716 kernel_pages = min(end_pfn, usable_startpfn)
7719 kernelcore_remaining -= min(kernel_pages,
7720 kernelcore_remaining);
7721 required_kernelcore -= min(kernel_pages,
7722 required_kernelcore);
7724 /* Continue if range is now fully accounted */
7725 if (end_pfn <= usable_startpfn) {
7728 * Push zone_movable_pfn to the end so
7729 * that if we have to rebalance
7730 * kernelcore across nodes, we will
7731 * not double account here
7733 zone_movable_pfn[nid] = end_pfn;
7736 start_pfn = usable_startpfn;
7740 * The usable PFN range for ZONE_MOVABLE is from
7741 * start_pfn->end_pfn. Calculate size_pages as the
7742 * number of pages used as kernelcore
7744 size_pages = end_pfn - start_pfn;
7745 if (size_pages > kernelcore_remaining)
7746 size_pages = kernelcore_remaining;
7747 zone_movable_pfn[nid] = start_pfn + size_pages;
7750 * Some kernelcore has been met, update counts and
7751 * break if the kernelcore for this node has been
7754 required_kernelcore -= min(required_kernelcore,
7756 kernelcore_remaining -= size_pages;
7757 if (!kernelcore_remaining)
7763 * If there is still required_kernelcore, we do another pass with one
7764 * less node in the count. This will push zone_movable_pfn[nid] further
7765 * along on the nodes that still have memory until kernelcore is
7769 if (usable_nodes && required_kernelcore > usable_nodes)
7773 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
7774 for (nid = 0; nid < MAX_NUMNODES; nid++)
7775 zone_movable_pfn[nid] =
7776 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
7779 /* restore the node_state */
7780 node_states[N_MEMORY] = saved_node_state;
7783 /* Any regular or high memory on that node ? */
7784 static void check_for_memory(pg_data_t *pgdat, int nid)
7786 enum zone_type zone_type;
7788 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
7789 struct zone *zone = &pgdat->node_zones[zone_type];
7790 if (populated_zone(zone)) {
7791 if (IS_ENABLED(CONFIG_HIGHMEM))
7792 node_set_state(nid, N_HIGH_MEMORY);
7793 if (zone_type <= ZONE_NORMAL)
7794 node_set_state(nid, N_NORMAL_MEMORY);
7801 * Some architectures, e.g. ARC may have ZONE_HIGHMEM below ZONE_NORMAL. For
7802 * such cases we allow max_zone_pfn sorted in the descending order
7804 bool __weak arch_has_descending_max_zone_pfns(void)
7810 * free_area_init - Initialise all pg_data_t and zone data
7811 * @max_zone_pfn: an array of max PFNs for each zone
7813 * This will call free_area_init_node() for each active node in the system.
7814 * Using the page ranges provided by memblock_set_node(), the size of each
7815 * zone in each node and their holes is calculated. If the maximum PFN
7816 * between two adjacent zones match, it is assumed that the zone is empty.
7817 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
7818 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
7819 * starts where the previous one ended. For example, ZONE_DMA32 starts
7820 * at arch_max_dma_pfn.
7822 void __init free_area_init(unsigned long *max_zone_pfn)
7824 unsigned long start_pfn, end_pfn;
7828 /* Record where the zone boundaries are */
7829 memset(arch_zone_lowest_possible_pfn, 0,
7830 sizeof(arch_zone_lowest_possible_pfn));
7831 memset(arch_zone_highest_possible_pfn, 0,
7832 sizeof(arch_zone_highest_possible_pfn));
7834 start_pfn = find_min_pfn_with_active_regions();
7835 descending = arch_has_descending_max_zone_pfns();
7837 for (i = 0; i < MAX_NR_ZONES; i++) {
7839 zone = MAX_NR_ZONES - i - 1;
7843 if (zone == ZONE_MOVABLE)
7846 end_pfn = max(max_zone_pfn[zone], start_pfn);
7847 arch_zone_lowest_possible_pfn[zone] = start_pfn;
7848 arch_zone_highest_possible_pfn[zone] = end_pfn;
7850 start_pfn = end_pfn;
7853 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
7854 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
7855 find_zone_movable_pfns_for_nodes();
7857 /* Print out the zone ranges */
7858 pr_info("Zone ranges:\n");
7859 for (i = 0; i < MAX_NR_ZONES; i++) {
7860 if (i == ZONE_MOVABLE)
7862 pr_info(" %-8s ", zone_names[i]);
7863 if (arch_zone_lowest_possible_pfn[i] ==
7864 arch_zone_highest_possible_pfn[i])
7867 pr_cont("[mem %#018Lx-%#018Lx]\n",
7868 (u64)arch_zone_lowest_possible_pfn[i]
7870 ((u64)arch_zone_highest_possible_pfn[i]
7871 << PAGE_SHIFT) - 1);
7874 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
7875 pr_info("Movable zone start for each node\n");
7876 for (i = 0; i < MAX_NUMNODES; i++) {
7877 if (zone_movable_pfn[i])
7878 pr_info(" Node %d: %#018Lx\n", i,
7879 (u64)zone_movable_pfn[i] << PAGE_SHIFT);
7883 * Print out the early node map, and initialize the
7884 * subsection-map relative to active online memory ranges to
7885 * enable future "sub-section" extensions of the memory map.
7887 pr_info("Early memory node ranges\n");
7888 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7889 pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid,
7890 (u64)start_pfn << PAGE_SHIFT,
7891 ((u64)end_pfn << PAGE_SHIFT) - 1);
7892 subsection_map_init(start_pfn, end_pfn - start_pfn);
7895 /* Initialise every node */
7896 mminit_verify_pageflags_layout();
7897 setup_nr_node_ids();
7898 for_each_online_node(nid) {
7899 pg_data_t *pgdat = NODE_DATA(nid);
7900 free_area_init_node(nid);
7902 /* Any memory on that node */
7903 if (pgdat->node_present_pages)
7904 node_set_state(nid, N_MEMORY);
7905 check_for_memory(pgdat, nid);
7911 static int __init cmdline_parse_core(char *p, unsigned long *core,
7912 unsigned long *percent)
7914 unsigned long long coremem;
7920 /* Value may be a percentage of total memory, otherwise bytes */
7921 coremem = simple_strtoull(p, &endptr, 0);
7922 if (*endptr == '%') {
7923 /* Paranoid check for percent values greater than 100 */
7924 WARN_ON(coremem > 100);
7928 coremem = memparse(p, &p);
7929 /* Paranoid check that UL is enough for the coremem value */
7930 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
7932 *core = coremem >> PAGE_SHIFT;
7939 * kernelcore=size sets the amount of memory for use for allocations that
7940 * cannot be reclaimed or migrated.
7942 static int __init cmdline_parse_kernelcore(char *p)
7944 /* parse kernelcore=mirror */
7945 if (parse_option_str(p, "mirror")) {
7946 mirrored_kernelcore = true;
7950 return cmdline_parse_core(p, &required_kernelcore,
7951 &required_kernelcore_percent);
7955 * movablecore=size sets the amount of memory for use for allocations that
7956 * can be reclaimed or migrated.
7958 static int __init cmdline_parse_movablecore(char *p)
7960 return cmdline_parse_core(p, &required_movablecore,
7961 &required_movablecore_percent);
7964 early_param("kernelcore", cmdline_parse_kernelcore);
7965 early_param("movablecore", cmdline_parse_movablecore);
7967 void adjust_managed_page_count(struct page *page, long count)
7969 atomic_long_add(count, &page_zone(page)->managed_pages);
7970 totalram_pages_add(count);
7971 #ifdef CONFIG_HIGHMEM
7972 if (PageHighMem(page))
7973 totalhigh_pages_add(count);
7976 EXPORT_SYMBOL(adjust_managed_page_count);
7978 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
7981 unsigned long pages = 0;
7983 start = (void *)PAGE_ALIGN((unsigned long)start);
7984 end = (void *)((unsigned long)end & PAGE_MASK);
7985 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
7986 struct page *page = virt_to_page(pos);
7987 void *direct_map_addr;
7990 * 'direct_map_addr' might be different from 'pos'
7991 * because some architectures' virt_to_page()
7992 * work with aliases. Getting the direct map
7993 * address ensures that we get a _writeable_
7994 * alias for the memset().
7996 direct_map_addr = page_address(page);
7998 * Perform a kasan-unchecked memset() since this memory
7999 * has not been initialized.
8001 direct_map_addr = kasan_reset_tag(direct_map_addr);
8002 if ((unsigned int)poison <= 0xFF)
8003 memset(direct_map_addr, poison, PAGE_SIZE);
8005 free_reserved_page(page);
8009 pr_info("Freeing %s memory: %ldK\n",
8010 s, pages << (PAGE_SHIFT - 10));
8015 void __init mem_init_print_info(void)
8017 unsigned long physpages, codesize, datasize, rosize, bss_size;
8018 unsigned long init_code_size, init_data_size;
8020 physpages = get_num_physpages();
8021 codesize = _etext - _stext;
8022 datasize = _edata - _sdata;
8023 rosize = __end_rodata - __start_rodata;
8024 bss_size = __bss_stop - __bss_start;
8025 init_data_size = __init_end - __init_begin;
8026 init_code_size = _einittext - _sinittext;
8029 * Detect special cases and adjust section sizes accordingly:
8030 * 1) .init.* may be embedded into .data sections
8031 * 2) .init.text.* may be out of [__init_begin, __init_end],
8032 * please refer to arch/tile/kernel/vmlinux.lds.S.
8033 * 3) .rodata.* may be embedded into .text or .data sections.
8035 #define adj_init_size(start, end, size, pos, adj) \
8037 if (start <= pos && pos < end && size > adj) \
8041 adj_init_size(__init_begin, __init_end, init_data_size,
8042 _sinittext, init_code_size);
8043 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
8044 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
8045 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
8046 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
8048 #undef adj_init_size
8050 pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
8051 #ifdef CONFIG_HIGHMEM
8055 nr_free_pages() << (PAGE_SHIFT - 10),
8056 physpages << (PAGE_SHIFT - 10),
8057 codesize >> 10, datasize >> 10, rosize >> 10,
8058 (init_data_size + init_code_size) >> 10, bss_size >> 10,
8059 (physpages - totalram_pages() - totalcma_pages) << (PAGE_SHIFT - 10),
8060 totalcma_pages << (PAGE_SHIFT - 10)
8061 #ifdef CONFIG_HIGHMEM
8062 , totalhigh_pages() << (PAGE_SHIFT - 10)
8068 * set_dma_reserve - set the specified number of pages reserved in the first zone
8069 * @new_dma_reserve: The number of pages to mark reserved
8071 * The per-cpu batchsize and zone watermarks are determined by managed_pages.
8072 * In the DMA zone, a significant percentage may be consumed by kernel image
8073 * and other unfreeable allocations which can skew the watermarks badly. This
8074 * function may optionally be used to account for unfreeable pages in the
8075 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
8076 * smaller per-cpu batchsize.
8078 void __init set_dma_reserve(unsigned long new_dma_reserve)
8080 dma_reserve = new_dma_reserve;
8083 static int page_alloc_cpu_dead(unsigned int cpu)
8087 lru_add_drain_cpu(cpu);
8091 * Spill the event counters of the dead processor
8092 * into the current processors event counters.
8093 * This artificially elevates the count of the current
8096 vm_events_fold_cpu(cpu);
8099 * Zero the differential counters of the dead processor
8100 * so that the vm statistics are consistent.
8102 * This is only okay since the processor is dead and cannot
8103 * race with what we are doing.
8105 cpu_vm_stats_fold(cpu);
8107 for_each_populated_zone(zone)
8108 zone_pcp_update(zone, 0);
8113 static int page_alloc_cpu_online(unsigned int cpu)
8117 for_each_populated_zone(zone)
8118 zone_pcp_update(zone, 1);
8123 int hashdist = HASHDIST_DEFAULT;
8125 static int __init set_hashdist(char *str)
8129 hashdist = simple_strtoul(str, &str, 0);
8132 __setup("hashdist=", set_hashdist);
8135 void __init page_alloc_init(void)
8140 if (num_node_state(N_MEMORY) == 1)
8144 ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC,
8145 "mm/page_alloc:pcp",
8146 page_alloc_cpu_online,
8147 page_alloc_cpu_dead);
8152 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
8153 * or min_free_kbytes changes.
8155 static void calculate_totalreserve_pages(void)
8157 struct pglist_data *pgdat;
8158 unsigned long reserve_pages = 0;
8159 enum zone_type i, j;
8161 for_each_online_pgdat(pgdat) {
8163 pgdat->totalreserve_pages = 0;
8165 for (i = 0; i < MAX_NR_ZONES; i++) {
8166 struct zone *zone = pgdat->node_zones + i;
8168 unsigned long managed_pages = zone_managed_pages(zone);
8170 /* Find valid and maximum lowmem_reserve in the zone */
8171 for (j = i; j < MAX_NR_ZONES; j++) {
8172 if (zone->lowmem_reserve[j] > max)
8173 max = zone->lowmem_reserve[j];
8176 /* we treat the high watermark as reserved pages. */
8177 max += high_wmark_pages(zone);
8179 if (max > managed_pages)
8180 max = managed_pages;
8182 pgdat->totalreserve_pages += max;
8184 reserve_pages += max;
8187 totalreserve_pages = reserve_pages;
8191 * setup_per_zone_lowmem_reserve - called whenever
8192 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
8193 * has a correct pages reserved value, so an adequate number of
8194 * pages are left in the zone after a successful __alloc_pages().
8196 static void setup_per_zone_lowmem_reserve(void)
8198 struct pglist_data *pgdat;
8199 enum zone_type i, j;
8201 for_each_online_pgdat(pgdat) {
8202 for (i = 0; i < MAX_NR_ZONES - 1; i++) {
8203 struct zone *zone = &pgdat->node_zones[i];
8204 int ratio = sysctl_lowmem_reserve_ratio[i];
8205 bool clear = !ratio || !zone_managed_pages(zone);
8206 unsigned long managed_pages = 0;
8208 for (j = i + 1; j < MAX_NR_ZONES; j++) {
8210 zone->lowmem_reserve[j] = 0;
8212 struct zone *upper_zone = &pgdat->node_zones[j];
8214 managed_pages += zone_managed_pages(upper_zone);
8215 zone->lowmem_reserve[j] = managed_pages / ratio;
8221 /* update totalreserve_pages */
8222 calculate_totalreserve_pages();
8225 static void __setup_per_zone_wmarks(void)
8227 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
8228 unsigned long lowmem_pages = 0;
8230 unsigned long flags;
8232 /* Calculate total number of !ZONE_HIGHMEM pages */
8233 for_each_zone(zone) {
8234 if (!is_highmem(zone))
8235 lowmem_pages += zone_managed_pages(zone);
8238 for_each_zone(zone) {
8241 spin_lock_irqsave(&zone->lock, flags);
8242 tmp = (u64)pages_min * zone_managed_pages(zone);
8243 do_div(tmp, lowmem_pages);
8244 if (is_highmem(zone)) {
8246 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
8247 * need highmem pages, so cap pages_min to a small
8250 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
8251 * deltas control async page reclaim, and so should
8252 * not be capped for highmem.
8254 unsigned long min_pages;
8256 min_pages = zone_managed_pages(zone) / 1024;
8257 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
8258 zone->_watermark[WMARK_MIN] = min_pages;
8261 * If it's a lowmem zone, reserve a number of pages
8262 * proportionate to the zone's size.
8264 zone->_watermark[WMARK_MIN] = tmp;
8268 * Set the kswapd watermarks distance according to the
8269 * scale factor in proportion to available memory, but
8270 * ensure a minimum size on small systems.
8272 tmp = max_t(u64, tmp >> 2,
8273 mult_frac(zone_managed_pages(zone),
8274 watermark_scale_factor, 10000));
8276 zone->watermark_boost = 0;
8277 zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp;
8278 zone->_watermark[WMARK_HIGH] = min_wmark_pages(zone) + tmp * 2;
8280 spin_unlock_irqrestore(&zone->lock, flags);
8283 /* update totalreserve_pages */
8284 calculate_totalreserve_pages();
8288 * setup_per_zone_wmarks - called when min_free_kbytes changes
8289 * or when memory is hot-{added|removed}
8291 * Ensures that the watermark[min,low,high] values for each zone are set
8292 * correctly with respect to min_free_kbytes.
8294 void setup_per_zone_wmarks(void)
8297 static DEFINE_SPINLOCK(lock);
8300 __setup_per_zone_wmarks();
8304 * The watermark size have changed so update the pcpu batch
8305 * and high limits or the limits may be inappropriate.
8308 zone_pcp_update(zone, 0);
8312 * Initialise min_free_kbytes.
8314 * For small machines we want it small (128k min). For large machines
8315 * we want it large (256MB max). But it is not linear, because network
8316 * bandwidth does not increase linearly with machine size. We use
8318 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
8319 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
8335 int __meminit init_per_zone_wmark_min(void)
8337 unsigned long lowmem_kbytes;
8338 int new_min_free_kbytes;
8340 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
8341 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
8343 if (new_min_free_kbytes > user_min_free_kbytes) {
8344 min_free_kbytes = new_min_free_kbytes;
8345 if (min_free_kbytes < 128)
8346 min_free_kbytes = 128;
8347 if (min_free_kbytes > 262144)
8348 min_free_kbytes = 262144;
8350 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
8351 new_min_free_kbytes, user_min_free_kbytes);
8353 setup_per_zone_wmarks();
8354 refresh_zone_stat_thresholds();
8355 setup_per_zone_lowmem_reserve();
8358 setup_min_unmapped_ratio();
8359 setup_min_slab_ratio();
8362 khugepaged_min_free_kbytes_update();
8366 postcore_initcall(init_per_zone_wmark_min)
8369 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
8370 * that we can call two helper functions whenever min_free_kbytes
8373 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
8374 void *buffer, size_t *length, loff_t *ppos)
8378 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8383 user_min_free_kbytes = min_free_kbytes;
8384 setup_per_zone_wmarks();
8389 int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write,
8390 void *buffer, size_t *length, loff_t *ppos)
8394 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8399 setup_per_zone_wmarks();
8405 static void setup_min_unmapped_ratio(void)
8410 for_each_online_pgdat(pgdat)
8411 pgdat->min_unmapped_pages = 0;
8414 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
8415 sysctl_min_unmapped_ratio) / 100;
8419 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
8420 void *buffer, size_t *length, loff_t *ppos)
8424 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8428 setup_min_unmapped_ratio();
8433 static void setup_min_slab_ratio(void)
8438 for_each_online_pgdat(pgdat)
8439 pgdat->min_slab_pages = 0;
8442 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
8443 sysctl_min_slab_ratio) / 100;
8446 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
8447 void *buffer, size_t *length, loff_t *ppos)
8451 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8455 setup_min_slab_ratio();
8462 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
8463 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
8464 * whenever sysctl_lowmem_reserve_ratio changes.
8466 * The reserve ratio obviously has absolutely no relation with the
8467 * minimum watermarks. The lowmem reserve ratio can only make sense
8468 * if in function of the boot time zone sizes.
8470 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
8471 void *buffer, size_t *length, loff_t *ppos)
8475 proc_dointvec_minmax(table, write, buffer, length, ppos);
8477 for (i = 0; i < MAX_NR_ZONES; i++) {
8478 if (sysctl_lowmem_reserve_ratio[i] < 1)
8479 sysctl_lowmem_reserve_ratio[i] = 0;
8482 setup_per_zone_lowmem_reserve();
8486 #ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES
8488 * Returns the number of pages that arch has reserved but
8489 * is not known to alloc_large_system_hash().
8491 static unsigned long __init arch_reserved_kernel_pages(void)
8498 * Adaptive scale is meant to reduce sizes of hash tables on large memory
8499 * machines. As memory size is increased the scale is also increased but at
8500 * slower pace. Starting from ADAPT_SCALE_BASE (64G), every time memory
8501 * quadruples the scale is increased by one, which means the size of hash table
8502 * only doubles, instead of quadrupling as well.
8503 * Because 32-bit systems cannot have large physical memory, where this scaling
8504 * makes sense, it is disabled on such platforms.
8506 #if __BITS_PER_LONG > 32
8507 #define ADAPT_SCALE_BASE (64ul << 30)
8508 #define ADAPT_SCALE_SHIFT 2
8509 #define ADAPT_SCALE_NPAGES (ADAPT_SCALE_BASE >> PAGE_SHIFT)
8513 * allocate a large system hash table from bootmem
8514 * - it is assumed that the hash table must contain an exact power-of-2
8515 * quantity of entries
8516 * - limit is the number of hash buckets, not the total allocation size
8518 void *__init alloc_large_system_hash(const char *tablename,
8519 unsigned long bucketsize,
8520 unsigned long numentries,
8523 unsigned int *_hash_shift,
8524 unsigned int *_hash_mask,
8525 unsigned long low_limit,
8526 unsigned long high_limit)
8528 unsigned long long max = high_limit;
8529 unsigned long log2qty, size;
8535 /* allow the kernel cmdline to have a say */
8537 /* round applicable memory size up to nearest megabyte */
8538 numentries = nr_kernel_pages;
8539 numentries -= arch_reserved_kernel_pages();
8541 /* It isn't necessary when PAGE_SIZE >= 1MB */
8542 if (PAGE_SHIFT < 20)
8543 numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
8545 #if __BITS_PER_LONG > 32
8547 unsigned long adapt;
8549 for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
8550 adapt <<= ADAPT_SCALE_SHIFT)
8555 /* limit to 1 bucket per 2^scale bytes of low memory */
8556 if (scale > PAGE_SHIFT)
8557 numentries >>= (scale - PAGE_SHIFT);
8559 numentries <<= (PAGE_SHIFT - scale);
8561 /* Make sure we've got at least a 0-order allocation.. */
8562 if (unlikely(flags & HASH_SMALL)) {
8563 /* Makes no sense without HASH_EARLY */
8564 WARN_ON(!(flags & HASH_EARLY));
8565 if (!(numentries >> *_hash_shift)) {
8566 numentries = 1UL << *_hash_shift;
8567 BUG_ON(!numentries);
8569 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
8570 numentries = PAGE_SIZE / bucketsize;
8572 numentries = roundup_pow_of_two(numentries);
8574 /* limit allocation size to 1/16 total memory by default */
8576 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
8577 do_div(max, bucketsize);
8579 max = min(max, 0x80000000ULL);
8581 if (numentries < low_limit)
8582 numentries = low_limit;
8583 if (numentries > max)
8586 log2qty = ilog2(numentries);
8588 gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
8591 size = bucketsize << log2qty;
8592 if (flags & HASH_EARLY) {
8593 if (flags & HASH_ZERO)
8594 table = memblock_alloc(size, SMP_CACHE_BYTES);
8596 table = memblock_alloc_raw(size,
8598 } else if (get_order(size) >= MAX_ORDER || hashdist) {
8599 table = __vmalloc(size, gfp_flags);
8601 huge = is_vm_area_hugepages(table);
8604 * If bucketsize is not a power-of-two, we may free
8605 * some pages at the end of hash table which
8606 * alloc_pages_exact() automatically does
8608 table = alloc_pages_exact(size, gfp_flags);
8609 kmemleak_alloc(table, size, 1, gfp_flags);
8611 } while (!table && size > PAGE_SIZE && --log2qty);
8614 panic("Failed to allocate %s hash table\n", tablename);
8616 pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n",
8617 tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size,
8618 virt ? (huge ? "vmalloc hugepage" : "vmalloc") : "linear");
8621 *_hash_shift = log2qty;
8623 *_hash_mask = (1 << log2qty) - 1;
8629 * This function checks whether pageblock includes unmovable pages or not.
8631 * PageLRU check without isolation or lru_lock could race so that
8632 * MIGRATE_MOVABLE block might include unmovable pages. And __PageMovable
8633 * check without lock_page also may miss some movable non-lru pages at
8634 * race condition. So you can't expect this function should be exact.
8636 * Returns a page without holding a reference. If the caller wants to
8637 * dereference that page (e.g., dumping), it has to make sure that it
8638 * cannot get removed (e.g., via memory unplug) concurrently.
8641 struct page *has_unmovable_pages(struct zone *zone, struct page *page,
8642 int migratetype, int flags)
8644 unsigned long iter = 0;
8645 unsigned long pfn = page_to_pfn(page);
8646 unsigned long offset = pfn % pageblock_nr_pages;
8648 if (is_migrate_cma_page(page)) {
8650 * CMA allocations (alloc_contig_range) really need to mark
8651 * isolate CMA pageblocks even when they are not movable in fact
8652 * so consider them movable here.
8654 if (is_migrate_cma(migratetype))
8660 for (; iter < pageblock_nr_pages - offset; iter++) {
8661 if (!pfn_valid_within(pfn + iter))
8664 page = pfn_to_page(pfn + iter);
8667 * Both, bootmem allocations and memory holes are marked
8668 * PG_reserved and are unmovable. We can even have unmovable
8669 * allocations inside ZONE_MOVABLE, for example when
8670 * specifying "movablecore".
8672 if (PageReserved(page))
8676 * If the zone is movable and we have ruled out all reserved
8677 * pages then it should be reasonably safe to assume the rest
8680 if (zone_idx(zone) == ZONE_MOVABLE)
8684 * Hugepages are not in LRU lists, but they're movable.
8685 * THPs are on the LRU, but need to be counted as #small pages.
8686 * We need not scan over tail pages because we don't
8687 * handle each tail page individually in migration.
8689 if (PageHuge(page) || PageTransCompound(page)) {
8690 struct page *head = compound_head(page);
8691 unsigned int skip_pages;
8693 if (PageHuge(page)) {
8694 if (!hugepage_migration_supported(page_hstate(head)))
8696 } else if (!PageLRU(head) && !__PageMovable(head)) {
8700 skip_pages = compound_nr(head) - (page - head);
8701 iter += skip_pages - 1;
8706 * We can't use page_count without pin a page
8707 * because another CPU can free compound page.
8708 * This check already skips compound tails of THP
8709 * because their page->_refcount is zero at all time.
8711 if (!page_ref_count(page)) {
8712 if (PageBuddy(page))
8713 iter += (1 << buddy_order(page)) - 1;
8718 * The HWPoisoned page may be not in buddy system, and
8719 * page_count() is not 0.
8721 if ((flags & MEMORY_OFFLINE) && PageHWPoison(page))
8725 * We treat all PageOffline() pages as movable when offlining
8726 * to give drivers a chance to decrement their reference count
8727 * in MEM_GOING_OFFLINE in order to indicate that these pages
8728 * can be offlined as there are no direct references anymore.
8729 * For actually unmovable PageOffline() where the driver does
8730 * not support this, we will fail later when trying to actually
8731 * move these pages that still have a reference count > 0.
8732 * (false negatives in this function only)
8734 if ((flags & MEMORY_OFFLINE) && PageOffline(page))
8737 if (__PageMovable(page) || PageLRU(page))
8741 * If there are RECLAIMABLE pages, we need to check
8742 * it. But now, memory offline itself doesn't call
8743 * shrink_node_slabs() and it still to be fixed.
8750 #ifdef CONFIG_CONTIG_ALLOC
8751 static unsigned long pfn_max_align_down(unsigned long pfn)
8753 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
8754 pageblock_nr_pages) - 1);
8757 static unsigned long pfn_max_align_up(unsigned long pfn)
8759 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
8760 pageblock_nr_pages));
8763 #if defined(CONFIG_DYNAMIC_DEBUG) || \
8764 (defined(CONFIG_DYNAMIC_DEBUG_CORE) && defined(DYNAMIC_DEBUG_MODULE))
8765 /* Usage: See admin-guide/dynamic-debug-howto.rst */
8766 static void alloc_contig_dump_pages(struct list_head *page_list)
8768 DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure");
8770 if (DYNAMIC_DEBUG_BRANCH(descriptor)) {
8774 list_for_each_entry(page, page_list, lru)
8775 dump_page(page, "migration failure");
8779 static inline void alloc_contig_dump_pages(struct list_head *page_list)
8784 /* [start, end) must belong to a single zone. */
8785 static int __alloc_contig_migrate_range(struct compact_control *cc,
8786 unsigned long start, unsigned long end)
8788 /* This function is based on compact_zone() from compaction.c. */
8789 unsigned int nr_reclaimed;
8790 unsigned long pfn = start;
8791 unsigned int tries = 0;
8793 struct migration_target_control mtc = {
8794 .nid = zone_to_nid(cc->zone),
8795 .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
8798 lru_cache_disable();
8800 while (pfn < end || !list_empty(&cc->migratepages)) {
8801 if (fatal_signal_pending(current)) {
8806 if (list_empty(&cc->migratepages)) {
8807 cc->nr_migratepages = 0;
8808 ret = isolate_migratepages_range(cc, pfn, end);
8809 if (ret && ret != -EAGAIN)
8811 pfn = cc->migrate_pfn;
8813 } else if (++tries == 5) {
8818 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
8820 cc->nr_migratepages -= nr_reclaimed;
8822 ret = migrate_pages(&cc->migratepages, alloc_migration_target,
8823 NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE);
8826 * On -ENOMEM, migrate_pages() bails out right away. It is pointless
8827 * to retry again over this error, so do the same here.
8836 alloc_contig_dump_pages(&cc->migratepages);
8837 putback_movable_pages(&cc->migratepages);
8844 * alloc_contig_range() -- tries to allocate given range of pages
8845 * @start: start PFN to allocate
8846 * @end: one-past-the-last PFN to allocate
8847 * @migratetype: migratetype of the underlying pageblocks (either
8848 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
8849 * in range must have the same migratetype and it must
8850 * be either of the two.
8851 * @gfp_mask: GFP mask to use during compaction
8853 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
8854 * aligned. The PFN range must belong to a single zone.
8856 * The first thing this routine does is attempt to MIGRATE_ISOLATE all
8857 * pageblocks in the range. Once isolated, the pageblocks should not
8858 * be modified by others.
8860 * Return: zero on success or negative error code. On success all
8861 * pages which PFN is in [start, end) are allocated for the caller and
8862 * need to be freed with free_contig_range().
8864 int alloc_contig_range(unsigned long start, unsigned long end,
8865 unsigned migratetype, gfp_t gfp_mask)
8867 unsigned long outer_start, outer_end;
8871 struct compact_control cc = {
8872 .nr_migratepages = 0,
8874 .zone = page_zone(pfn_to_page(start)),
8875 .mode = MIGRATE_SYNC,
8876 .ignore_skip_hint = true,
8877 .no_set_skip_hint = true,
8878 .gfp_mask = current_gfp_context(gfp_mask),
8879 .alloc_contig = true,
8881 INIT_LIST_HEAD(&cc.migratepages);
8884 * What we do here is we mark all pageblocks in range as
8885 * MIGRATE_ISOLATE. Because pageblock and max order pages may
8886 * have different sizes, and due to the way page allocator
8887 * work, we align the range to biggest of the two pages so
8888 * that page allocator won't try to merge buddies from
8889 * different pageblocks and change MIGRATE_ISOLATE to some
8890 * other migration type.
8892 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
8893 * migrate the pages from an unaligned range (ie. pages that
8894 * we are interested in). This will put all the pages in
8895 * range back to page allocator as MIGRATE_ISOLATE.
8897 * When this is done, we take the pages in range from page
8898 * allocator removing them from the buddy system. This way
8899 * page allocator will never consider using them.
8901 * This lets us mark the pageblocks back as
8902 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
8903 * aligned range but not in the unaligned, original range are
8904 * put back to page allocator so that buddy can use them.
8907 ret = start_isolate_page_range(pfn_max_align_down(start),
8908 pfn_max_align_up(end), migratetype, 0);
8912 drain_all_pages(cc.zone);
8915 * In case of -EBUSY, we'd like to know which page causes problem.
8916 * So, just fall through. test_pages_isolated() has a tracepoint
8917 * which will report the busy page.
8919 * It is possible that busy pages could become available before
8920 * the call to test_pages_isolated, and the range will actually be
8921 * allocated. So, if we fall through be sure to clear ret so that
8922 * -EBUSY is not accidentally used or returned to caller.
8924 ret = __alloc_contig_migrate_range(&cc, start, end);
8925 if (ret && ret != -EBUSY)
8930 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
8931 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
8932 * more, all pages in [start, end) are free in page allocator.
8933 * What we are going to do is to allocate all pages from
8934 * [start, end) (that is remove them from page allocator).
8936 * The only problem is that pages at the beginning and at the
8937 * end of interesting range may be not aligned with pages that
8938 * page allocator holds, ie. they can be part of higher order
8939 * pages. Because of this, we reserve the bigger range and
8940 * once this is done free the pages we are not interested in.
8942 * We don't have to hold zone->lock here because the pages are
8943 * isolated thus they won't get removed from buddy.
8947 outer_start = start;
8948 while (!PageBuddy(pfn_to_page(outer_start))) {
8949 if (++order >= MAX_ORDER) {
8950 outer_start = start;
8953 outer_start &= ~0UL << order;
8956 if (outer_start != start) {
8957 order = buddy_order(pfn_to_page(outer_start));
8960 * outer_start page could be small order buddy page and
8961 * it doesn't include start page. Adjust outer_start
8962 * in this case to report failed page properly
8963 * on tracepoint in test_pages_isolated()
8965 if (outer_start + (1UL << order) <= start)
8966 outer_start = start;
8969 /* Make sure the range is really isolated. */
8970 if (test_pages_isolated(outer_start, end, 0)) {
8975 /* Grab isolated pages from freelists. */
8976 outer_end = isolate_freepages_range(&cc, outer_start, end);
8982 /* Free head and tail (if any) */
8983 if (start != outer_start)
8984 free_contig_range(outer_start, start - outer_start);
8985 if (end != outer_end)
8986 free_contig_range(end, outer_end - end);
8989 undo_isolate_page_range(pfn_max_align_down(start),
8990 pfn_max_align_up(end), migratetype);
8993 EXPORT_SYMBOL(alloc_contig_range);
8995 static int __alloc_contig_pages(unsigned long start_pfn,
8996 unsigned long nr_pages, gfp_t gfp_mask)
8998 unsigned long end_pfn = start_pfn + nr_pages;
9000 return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE,
9004 static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn,
9005 unsigned long nr_pages)
9007 unsigned long i, end_pfn = start_pfn + nr_pages;
9010 for (i = start_pfn; i < end_pfn; i++) {
9011 page = pfn_to_online_page(i);
9015 if (page_zone(page) != z)
9018 if (PageReserved(page))
9024 static bool zone_spans_last_pfn(const struct zone *zone,
9025 unsigned long start_pfn, unsigned long nr_pages)
9027 unsigned long last_pfn = start_pfn + nr_pages - 1;
9029 return zone_spans_pfn(zone, last_pfn);
9033 * alloc_contig_pages() -- tries to find and allocate contiguous range of pages
9034 * @nr_pages: Number of contiguous pages to allocate
9035 * @gfp_mask: GFP mask to limit search and used during compaction
9037 * @nodemask: Mask for other possible nodes
9039 * This routine is a wrapper around alloc_contig_range(). It scans over zones
9040 * on an applicable zonelist to find a contiguous pfn range which can then be
9041 * tried for allocation with alloc_contig_range(). This routine is intended
9042 * for allocation requests which can not be fulfilled with the buddy allocator.
9044 * The allocated memory is always aligned to a page boundary. If nr_pages is a
9045 * power of two then the alignment is guaranteed to be to the given nr_pages
9046 * (e.g. 1GB request would be aligned to 1GB).
9048 * Allocated pages can be freed with free_contig_range() or by manually calling
9049 * __free_page() on each allocated page.
9051 * Return: pointer to contiguous pages on success, or NULL if not successful.
9053 struct page *alloc_contig_pages(unsigned long nr_pages, gfp_t gfp_mask,
9054 int nid, nodemask_t *nodemask)
9056 unsigned long ret, pfn, flags;
9057 struct zonelist *zonelist;
9061 zonelist = node_zonelist(nid, gfp_mask);
9062 for_each_zone_zonelist_nodemask(zone, z, zonelist,
9063 gfp_zone(gfp_mask), nodemask) {
9064 spin_lock_irqsave(&zone->lock, flags);
9066 pfn = ALIGN(zone->zone_start_pfn, nr_pages);
9067 while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
9068 if (pfn_range_valid_contig(zone, pfn, nr_pages)) {
9070 * We release the zone lock here because
9071 * alloc_contig_range() will also lock the zone
9072 * at some point. If there's an allocation
9073 * spinning on this lock, it may win the race
9074 * and cause alloc_contig_range() to fail...
9076 spin_unlock_irqrestore(&zone->lock, flags);
9077 ret = __alloc_contig_pages(pfn, nr_pages,
9080 return pfn_to_page(pfn);
9081 spin_lock_irqsave(&zone->lock, flags);
9085 spin_unlock_irqrestore(&zone->lock, flags);
9089 #endif /* CONFIG_CONTIG_ALLOC */
9091 void free_contig_range(unsigned long pfn, unsigned long nr_pages)
9093 unsigned long count = 0;
9095 for (; nr_pages--; pfn++) {
9096 struct page *page = pfn_to_page(pfn);
9098 count += page_count(page) != 1;
9101 WARN(count != 0, "%lu pages are still in use!\n", count);
9103 EXPORT_SYMBOL(free_contig_range);
9106 * The zone indicated has a new number of managed_pages; batch sizes and percpu
9107 * page high values need to be recalculated.
9109 void zone_pcp_update(struct zone *zone, int cpu_online)
9111 mutex_lock(&pcp_batch_high_lock);
9112 zone_set_pageset_high_and_batch(zone, cpu_online);
9113 mutex_unlock(&pcp_batch_high_lock);
9117 * Effectively disable pcplists for the zone by setting the high limit to 0
9118 * and draining all cpus. A concurrent page freeing on another CPU that's about
9119 * to put the page on pcplist will either finish before the drain and the page
9120 * will be drained, or observe the new high limit and skip the pcplist.
9122 * Must be paired with a call to zone_pcp_enable().
9124 void zone_pcp_disable(struct zone *zone)
9126 mutex_lock(&pcp_batch_high_lock);
9127 __zone_set_pageset_high_and_batch(zone, 0, 1);
9128 __drain_all_pages(zone, true);
9131 void zone_pcp_enable(struct zone *zone)
9133 __zone_set_pageset_high_and_batch(zone, zone->pageset_high, zone->pageset_batch);
9134 mutex_unlock(&pcp_batch_high_lock);
9137 void zone_pcp_reset(struct zone *zone)
9140 struct per_cpu_zonestat *pzstats;
9142 if (zone->per_cpu_pageset != &boot_pageset) {
9143 for_each_online_cpu(cpu) {
9144 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
9145 drain_zonestat(zone, pzstats);
9147 free_percpu(zone->per_cpu_pageset);
9148 free_percpu(zone->per_cpu_zonestats);
9149 zone->per_cpu_pageset = &boot_pageset;
9150 zone->per_cpu_zonestats = &boot_zonestats;
9154 #ifdef CONFIG_MEMORY_HOTREMOVE
9156 * All pages in the range must be in a single zone, must not contain holes,
9157 * must span full sections, and must be isolated before calling this function.
9159 void __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
9161 unsigned long pfn = start_pfn;
9165 unsigned long flags;
9167 offline_mem_sections(pfn, end_pfn);
9168 zone = page_zone(pfn_to_page(pfn));
9169 spin_lock_irqsave(&zone->lock, flags);
9170 while (pfn < end_pfn) {
9171 page = pfn_to_page(pfn);
9173 * The HWPoisoned page may be not in buddy system, and
9174 * page_count() is not 0.
9176 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
9181 * At this point all remaining PageOffline() pages have a
9182 * reference count of 0 and can simply be skipped.
9184 if (PageOffline(page)) {
9185 BUG_ON(page_count(page));
9186 BUG_ON(PageBuddy(page));
9191 BUG_ON(page_count(page));
9192 BUG_ON(!PageBuddy(page));
9193 order = buddy_order(page);
9194 del_page_from_free_list(page, zone, order);
9195 pfn += (1 << order);
9197 spin_unlock_irqrestore(&zone->lock, flags);
9201 bool is_free_buddy_page(struct page *page)
9203 struct zone *zone = page_zone(page);
9204 unsigned long pfn = page_to_pfn(page);
9205 unsigned long flags;
9208 spin_lock_irqsave(&zone->lock, flags);
9209 for (order = 0; order < MAX_ORDER; order++) {
9210 struct page *page_head = page - (pfn & ((1 << order) - 1));
9212 if (PageBuddy(page_head) && buddy_order(page_head) >= order)
9215 spin_unlock_irqrestore(&zone->lock, flags);
9217 return order < MAX_ORDER;
9220 #ifdef CONFIG_MEMORY_FAILURE
9222 * Break down a higher-order page in sub-pages, and keep our target out of
9225 static void break_down_buddy_pages(struct zone *zone, struct page *page,
9226 struct page *target, int low, int high,
9229 unsigned long size = 1 << high;
9230 struct page *current_buddy, *next_page;
9232 while (high > low) {
9236 if (target >= &page[size]) {
9237 next_page = page + size;
9238 current_buddy = page;
9241 current_buddy = page + size;
9244 if (set_page_guard(zone, current_buddy, high, migratetype))
9247 if (current_buddy != target) {
9248 add_to_free_list(current_buddy, zone, high, migratetype);
9249 set_buddy_order(current_buddy, high);
9256 * Take a page that will be marked as poisoned off the buddy allocator.
9258 bool take_page_off_buddy(struct page *page)
9260 struct zone *zone = page_zone(page);
9261 unsigned long pfn = page_to_pfn(page);
9262 unsigned long flags;
9266 spin_lock_irqsave(&zone->lock, flags);
9267 for (order = 0; order < MAX_ORDER; order++) {
9268 struct page *page_head = page - (pfn & ((1 << order) - 1));
9269 int page_order = buddy_order(page_head);
9271 if (PageBuddy(page_head) && page_order >= order) {
9272 unsigned long pfn_head = page_to_pfn(page_head);
9273 int migratetype = get_pfnblock_migratetype(page_head,
9276 del_page_from_free_list(page_head, zone, page_order);
9277 break_down_buddy_pages(zone, page_head, page, 0,
9278 page_order, migratetype);
9279 if (!is_migrate_isolate(migratetype))
9280 __mod_zone_freepage_state(zone, -1, migratetype);
9284 if (page_count(page_head) > 0)
9287 spin_unlock_irqrestore(&zone->lock, flags);