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/migrate.h>
61 #include <linux/hugetlb.h>
62 #include <linux/sched/rt.h>
63 #include <linux/sched/mm.h>
64 #include <linux/page_owner.h>
65 #include <linux/kthread.h>
66 #include <linux/memcontrol.h>
67 #include <linux/ftrace.h>
68 #include <linux/lockdep.h>
69 #include <linux/nmi.h>
70 #include <linux/psi.h>
72 #include <asm/sections.h>
73 #include <asm/tlbflush.h>
74 #include <asm/div64.h>
78 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
79 static DEFINE_MUTEX(pcp_batch_high_lock);
80 #define MIN_PERCPU_PAGELIST_FRACTION (8)
82 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
83 DEFINE_PER_CPU(int, numa_node);
84 EXPORT_PER_CPU_SYMBOL(numa_node);
87 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
89 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
91 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
92 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
93 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
94 * defined in <linux/topology.h>.
96 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
97 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
98 int _node_numa_mem_[MAX_NUMNODES];
101 /* work_structs for global per-cpu drains */
104 struct work_struct work;
106 DEFINE_MUTEX(pcpu_drain_mutex);
107 DEFINE_PER_CPU(struct pcpu_drain, pcpu_drain);
109 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
110 volatile unsigned long latent_entropy __latent_entropy;
111 EXPORT_SYMBOL(latent_entropy);
115 * Array of node states.
117 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
118 [N_POSSIBLE] = NODE_MASK_ALL,
119 [N_ONLINE] = { { [0] = 1UL } },
121 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
122 #ifdef CONFIG_HIGHMEM
123 [N_HIGH_MEMORY] = { { [0] = 1UL } },
125 [N_MEMORY] = { { [0] = 1UL } },
126 [N_CPU] = { { [0] = 1UL } },
129 EXPORT_SYMBOL(node_states);
131 atomic_long_t _totalram_pages __read_mostly;
132 EXPORT_SYMBOL(_totalram_pages);
133 unsigned long totalreserve_pages __read_mostly;
134 unsigned long totalcma_pages __read_mostly;
136 int percpu_pagelist_fraction;
137 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
138 #ifdef CONFIG_INIT_ON_ALLOC_DEFAULT_ON
139 DEFINE_STATIC_KEY_TRUE(init_on_alloc);
141 DEFINE_STATIC_KEY_FALSE(init_on_alloc);
143 EXPORT_SYMBOL(init_on_alloc);
145 #ifdef CONFIG_INIT_ON_FREE_DEFAULT_ON
146 DEFINE_STATIC_KEY_TRUE(init_on_free);
148 DEFINE_STATIC_KEY_FALSE(init_on_free);
150 EXPORT_SYMBOL(init_on_free);
152 static int __init early_init_on_alloc(char *buf)
159 ret = kstrtobool(buf, &bool_result);
160 if (bool_result && page_poisoning_enabled())
161 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, will take precedence over init_on_alloc\n");
163 static_branch_enable(&init_on_alloc);
165 static_branch_disable(&init_on_alloc);
168 early_param("init_on_alloc", early_init_on_alloc);
170 static int __init early_init_on_free(char *buf)
177 ret = kstrtobool(buf, &bool_result);
178 if (bool_result && page_poisoning_enabled())
179 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, will take precedence over init_on_free\n");
181 static_branch_enable(&init_on_free);
183 static_branch_disable(&init_on_free);
186 early_param("init_on_free", early_init_on_free);
189 * A cached value of the page's pageblock's migratetype, used when the page is
190 * put on a pcplist. Used to avoid the pageblock migratetype lookup when
191 * freeing from pcplists in most cases, at the cost of possibly becoming stale.
192 * Also the migratetype set in the page does not necessarily match the pcplist
193 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
194 * other index - this ensures that it will be put on the correct CMA freelist.
196 static inline int get_pcppage_migratetype(struct page *page)
201 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
203 page->index = migratetype;
206 #ifdef CONFIG_PM_SLEEP
208 * The following functions are used by the suspend/hibernate code to temporarily
209 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
210 * while devices are suspended. To avoid races with the suspend/hibernate code,
211 * they should always be called with system_transition_mutex held
212 * (gfp_allowed_mask also should only be modified with system_transition_mutex
213 * held, unless the suspend/hibernate code is guaranteed not to run in parallel
214 * with that modification).
217 static gfp_t saved_gfp_mask;
219 void pm_restore_gfp_mask(void)
221 WARN_ON(!mutex_is_locked(&system_transition_mutex));
222 if (saved_gfp_mask) {
223 gfp_allowed_mask = saved_gfp_mask;
228 void pm_restrict_gfp_mask(void)
230 WARN_ON(!mutex_is_locked(&system_transition_mutex));
231 WARN_ON(saved_gfp_mask);
232 saved_gfp_mask = gfp_allowed_mask;
233 gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
236 bool pm_suspended_storage(void)
238 if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
242 #endif /* CONFIG_PM_SLEEP */
244 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
245 unsigned int pageblock_order __read_mostly;
248 static void __free_pages_ok(struct page *page, unsigned int order);
251 * results with 256, 32 in the lowmem_reserve sysctl:
252 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
253 * 1G machine -> (16M dma, 784M normal, 224M high)
254 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
255 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
256 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
258 * TBD: should special case ZONE_DMA32 machines here - in those we normally
259 * don't need any ZONE_NORMAL reservation
261 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
262 #ifdef CONFIG_ZONE_DMA
265 #ifdef CONFIG_ZONE_DMA32
269 #ifdef CONFIG_HIGHMEM
275 static char * const zone_names[MAX_NR_ZONES] = {
276 #ifdef CONFIG_ZONE_DMA
279 #ifdef CONFIG_ZONE_DMA32
283 #ifdef CONFIG_HIGHMEM
287 #ifdef CONFIG_ZONE_DEVICE
292 const char * const migratetype_names[MIGRATE_TYPES] = {
300 #ifdef CONFIG_MEMORY_ISOLATION
305 compound_page_dtor * const compound_page_dtors[] = {
308 #ifdef CONFIG_HUGETLB_PAGE
311 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
316 int min_free_kbytes = 1024;
317 int user_min_free_kbytes = -1;
318 #ifdef CONFIG_DISCONTIGMEM
320 * DiscontigMem defines memory ranges as separate pg_data_t even if the ranges
321 * are not on separate NUMA nodes. Functionally this works but with
322 * watermark_boost_factor, it can reclaim prematurely as the ranges can be
323 * quite small. By default, do not boost watermarks on discontigmem as in
324 * many cases very high-order allocations like THP are likely to be
325 * unsupported and the premature reclaim offsets the advantage of long-term
326 * fragmentation avoidance.
328 int watermark_boost_factor __read_mostly;
330 int watermark_boost_factor __read_mostly = 15000;
332 int watermark_scale_factor = 10;
334 static unsigned long nr_kernel_pages __initdata;
335 static unsigned long nr_all_pages __initdata;
336 static unsigned long dma_reserve __initdata;
338 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
339 static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata;
340 static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata;
341 static unsigned long required_kernelcore __initdata;
342 static unsigned long required_kernelcore_percent __initdata;
343 static unsigned long required_movablecore __initdata;
344 static unsigned long required_movablecore_percent __initdata;
345 static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata;
346 static bool mirrored_kernelcore __meminitdata;
348 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
350 EXPORT_SYMBOL(movable_zone);
351 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
354 unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
355 unsigned int nr_online_nodes __read_mostly = 1;
356 EXPORT_SYMBOL(nr_node_ids);
357 EXPORT_SYMBOL(nr_online_nodes);
360 int page_group_by_mobility_disabled __read_mostly;
362 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
364 * During boot we initialize deferred pages on-demand, as needed, but once
365 * page_alloc_init_late() has finished, the deferred pages are all initialized,
366 * and we can permanently disable that path.
368 static DEFINE_STATIC_KEY_TRUE(deferred_pages);
371 * Calling kasan_free_pages() only after deferred memory initialization
372 * has completed. Poisoning pages during deferred memory init will greatly
373 * lengthen the process and cause problem in large memory systems as the
374 * deferred pages initialization is done with interrupt disabled.
376 * Assuming that there will be no reference to those newly initialized
377 * pages before they are ever allocated, this should have no effect on
378 * KASAN memory tracking as the poison will be properly inserted at page
379 * allocation time. The only corner case is when pages are allocated by
380 * on-demand allocation and then freed again before the deferred pages
381 * initialization is done, but this is not likely to happen.
383 static inline void kasan_free_nondeferred_pages(struct page *page, int order)
385 if (!static_branch_unlikely(&deferred_pages))
386 kasan_free_pages(page, order);
389 /* Returns true if the struct page for the pfn is uninitialised */
390 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
392 int nid = early_pfn_to_nid(pfn);
394 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
401 * Returns true when the remaining initialisation should be deferred until
402 * later in the boot cycle when it can be parallelised.
404 static bool __meminit
405 defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
407 static unsigned long prev_end_pfn, nr_initialised;
410 * prev_end_pfn static that contains the end of previous zone
411 * No need to protect because called very early in boot before smp_init.
413 if (prev_end_pfn != end_pfn) {
414 prev_end_pfn = end_pfn;
418 /* Always populate low zones for address-constrained allocations */
419 if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
423 * We start only with one section of pages, more pages are added as
424 * needed until the rest of deferred pages are initialized.
427 if ((nr_initialised > PAGES_PER_SECTION) &&
428 (pfn & (PAGES_PER_SECTION - 1)) == 0) {
429 NODE_DATA(nid)->first_deferred_pfn = pfn;
435 #define kasan_free_nondeferred_pages(p, o) kasan_free_pages(p, o)
437 static inline bool early_page_uninitialised(unsigned long pfn)
442 static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
448 /* Return a pointer to the bitmap storing bits affecting a block of pages */
449 static inline unsigned long *get_pageblock_bitmap(struct page *page,
452 #ifdef CONFIG_SPARSEMEM
453 return section_to_usemap(__pfn_to_section(pfn));
455 return page_zone(page)->pageblock_flags;
456 #endif /* CONFIG_SPARSEMEM */
459 static inline int pfn_to_bitidx(struct page *page, unsigned long pfn)
461 #ifdef CONFIG_SPARSEMEM
462 pfn &= (PAGES_PER_SECTION-1);
463 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
465 pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
466 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
467 #endif /* CONFIG_SPARSEMEM */
471 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
472 * @page: The page within the block of interest
473 * @pfn: The target page frame number
474 * @end_bitidx: The last bit of interest to retrieve
475 * @mask: mask of bits that the caller is interested in
477 * Return: pageblock_bits flags
479 static __always_inline unsigned long __get_pfnblock_flags_mask(struct page *page,
481 unsigned long end_bitidx,
484 unsigned long *bitmap;
485 unsigned long bitidx, word_bitidx;
488 bitmap = get_pageblock_bitmap(page, pfn);
489 bitidx = pfn_to_bitidx(page, pfn);
490 word_bitidx = bitidx / BITS_PER_LONG;
491 bitidx &= (BITS_PER_LONG-1);
493 word = bitmap[word_bitidx];
494 bitidx += end_bitidx;
495 return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
498 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
499 unsigned long end_bitidx,
502 return __get_pfnblock_flags_mask(page, pfn, end_bitidx, mask);
505 static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn)
507 return __get_pfnblock_flags_mask(page, pfn, PB_migrate_end, MIGRATETYPE_MASK);
511 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
512 * @page: The page within the block of interest
513 * @flags: The flags to set
514 * @pfn: The target page frame number
515 * @end_bitidx: The last bit of interest
516 * @mask: mask of bits that the caller is interested in
518 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
520 unsigned long end_bitidx,
523 unsigned long *bitmap;
524 unsigned long bitidx, word_bitidx;
525 unsigned long old_word, word;
527 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
528 BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits));
530 bitmap = get_pageblock_bitmap(page, pfn);
531 bitidx = pfn_to_bitidx(page, pfn);
532 word_bitidx = bitidx / BITS_PER_LONG;
533 bitidx &= (BITS_PER_LONG-1);
535 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
537 bitidx += end_bitidx;
538 mask <<= (BITS_PER_LONG - bitidx - 1);
539 flags <<= (BITS_PER_LONG - bitidx - 1);
541 word = READ_ONCE(bitmap[word_bitidx]);
543 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
544 if (word == old_word)
550 void set_pageblock_migratetype(struct page *page, int migratetype)
552 if (unlikely(page_group_by_mobility_disabled &&
553 migratetype < MIGRATE_PCPTYPES))
554 migratetype = MIGRATE_UNMOVABLE;
556 set_pageblock_flags_group(page, (unsigned long)migratetype,
557 PB_migrate, PB_migrate_end);
560 #ifdef CONFIG_DEBUG_VM
561 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
565 unsigned long pfn = page_to_pfn(page);
566 unsigned long sp, start_pfn;
569 seq = zone_span_seqbegin(zone);
570 start_pfn = zone->zone_start_pfn;
571 sp = zone->spanned_pages;
572 if (!zone_spans_pfn(zone, pfn))
574 } while (zone_span_seqretry(zone, seq));
577 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
578 pfn, zone_to_nid(zone), zone->name,
579 start_pfn, start_pfn + sp);
584 static int page_is_consistent(struct zone *zone, struct page *page)
586 if (!pfn_valid_within(page_to_pfn(page)))
588 if (zone != page_zone(page))
594 * Temporary debugging check for pages not lying within a given zone.
596 static int __maybe_unused bad_range(struct zone *zone, struct page *page)
598 if (page_outside_zone_boundaries(zone, page))
600 if (!page_is_consistent(zone, page))
606 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
612 static void bad_page(struct page *page, const char *reason,
613 unsigned long bad_flags)
615 static unsigned long resume;
616 static unsigned long nr_shown;
617 static unsigned long nr_unshown;
620 * Allow a burst of 60 reports, then keep quiet for that minute;
621 * or allow a steady drip of one report per second.
623 if (nr_shown == 60) {
624 if (time_before(jiffies, resume)) {
630 "BUG: Bad page state: %lu messages suppressed\n",
637 resume = jiffies + 60 * HZ;
639 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
640 current->comm, page_to_pfn(page));
641 __dump_page(page, reason);
642 bad_flags &= page->flags;
644 pr_alert("bad because of flags: %#lx(%pGp)\n",
645 bad_flags, &bad_flags);
646 dump_page_owner(page);
651 /* Leave bad fields for debug, except PageBuddy could make trouble */
652 page_mapcount_reset(page); /* remove PageBuddy */
653 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
657 * Higher-order pages are called "compound pages". They are structured thusly:
659 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
661 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
662 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
664 * The first tail page's ->compound_dtor holds the offset in array of compound
665 * page destructors. See compound_page_dtors.
667 * The first tail page's ->compound_order holds the order of allocation.
668 * This usage means that zero-order pages may not be compound.
671 void free_compound_page(struct page *page)
673 __free_pages_ok(page, compound_order(page));
676 void prep_compound_page(struct page *page, unsigned int order)
679 int nr_pages = 1 << order;
681 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
682 set_compound_order(page, order);
684 for (i = 1; i < nr_pages; i++) {
685 struct page *p = page + i;
686 set_page_count(p, 0);
687 p->mapping = TAIL_MAPPING;
688 set_compound_head(p, page);
690 atomic_set(compound_mapcount_ptr(page), -1);
693 #ifdef CONFIG_DEBUG_PAGEALLOC
694 unsigned int _debug_guardpage_minorder;
696 #ifdef CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT
697 DEFINE_STATIC_KEY_TRUE(_debug_pagealloc_enabled);
699 DEFINE_STATIC_KEY_FALSE(_debug_pagealloc_enabled);
701 EXPORT_SYMBOL(_debug_pagealloc_enabled);
703 DEFINE_STATIC_KEY_FALSE(_debug_guardpage_enabled);
705 static int __init early_debug_pagealloc(char *buf)
709 if (kstrtobool(buf, &enable))
713 static_branch_enable(&_debug_pagealloc_enabled);
717 early_param("debug_pagealloc", early_debug_pagealloc);
719 static void init_debug_guardpage(void)
721 if (!debug_pagealloc_enabled())
724 if (!debug_guardpage_minorder())
727 static_branch_enable(&_debug_guardpage_enabled);
730 static int __init debug_guardpage_minorder_setup(char *buf)
734 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
735 pr_err("Bad debug_guardpage_minorder value\n");
738 _debug_guardpage_minorder = res;
739 pr_info("Setting debug_guardpage_minorder to %lu\n", res);
742 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
744 static inline bool set_page_guard(struct zone *zone, struct page *page,
745 unsigned int order, int migratetype)
747 if (!debug_guardpage_enabled())
750 if (order >= debug_guardpage_minorder())
753 __SetPageGuard(page);
754 INIT_LIST_HEAD(&page->lru);
755 set_page_private(page, order);
756 /* Guard pages are not available for any usage */
757 __mod_zone_freepage_state(zone, -(1 << order), migratetype);
762 static inline void clear_page_guard(struct zone *zone, struct page *page,
763 unsigned int order, int migratetype)
765 if (!debug_guardpage_enabled())
768 __ClearPageGuard(page);
770 set_page_private(page, 0);
771 if (!is_migrate_isolate(migratetype))
772 __mod_zone_freepage_state(zone, (1 << order), migratetype);
775 static inline bool set_page_guard(struct zone *zone, struct page *page,
776 unsigned int order, int migratetype) { return false; }
777 static inline void clear_page_guard(struct zone *zone, struct page *page,
778 unsigned int order, int migratetype) {}
781 static inline void set_page_order(struct page *page, unsigned int order)
783 set_page_private(page, order);
784 __SetPageBuddy(page);
788 * This function checks whether a page is free && is the buddy
789 * we can coalesce a page and its buddy if
790 * (a) the buddy is not in a hole (check before calling!) &&
791 * (b) the buddy is in the buddy system &&
792 * (c) a page and its buddy have the same order &&
793 * (d) a page and its buddy are in the same zone.
795 * For recording whether a page is in the buddy system, we set PageBuddy.
796 * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
798 * For recording page's order, we use page_private(page).
800 static inline int page_is_buddy(struct page *page, struct page *buddy,
803 if (page_is_guard(buddy) && page_order(buddy) == order) {
804 if (page_zone_id(page) != page_zone_id(buddy))
807 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
812 if (PageBuddy(buddy) && page_order(buddy) == order) {
814 * zone check is done late to avoid uselessly
815 * calculating zone/node ids for pages that could
818 if (page_zone_id(page) != page_zone_id(buddy))
821 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
828 #ifdef CONFIG_COMPACTION
829 static inline struct capture_control *task_capc(struct zone *zone)
831 struct capture_control *capc = current->capture_control;
834 !(current->flags & PF_KTHREAD) &&
836 capc->cc->zone == zone &&
837 capc->cc->direct_compaction ? capc : NULL;
841 compaction_capture(struct capture_control *capc, struct page *page,
842 int order, int migratetype)
844 if (!capc || order != capc->cc->order)
847 /* Do not accidentally pollute CMA or isolated regions*/
848 if (is_migrate_cma(migratetype) ||
849 is_migrate_isolate(migratetype))
853 * Do not let lower order allocations polluate a movable pageblock.
854 * This might let an unmovable request use a reclaimable pageblock
855 * and vice-versa but no more than normal fallback logic which can
856 * have trouble finding a high-order free page.
858 if (order < pageblock_order && migratetype == MIGRATE_MOVABLE)
866 static inline struct capture_control *task_capc(struct zone *zone)
872 compaction_capture(struct capture_control *capc, struct page *page,
873 int order, int migratetype)
877 #endif /* CONFIG_COMPACTION */
880 * Freeing function for a buddy system allocator.
882 * The concept of a buddy system is to maintain direct-mapped table
883 * (containing bit values) for memory blocks of various "orders".
884 * The bottom level table contains the map for the smallest allocatable
885 * units of memory (here, pages), and each level above it describes
886 * pairs of units from the levels below, hence, "buddies".
887 * At a high level, all that happens here is marking the table entry
888 * at the bottom level available, and propagating the changes upward
889 * as necessary, plus some accounting needed to play nicely with other
890 * parts of the VM system.
891 * At each level, we keep a list of pages, which are heads of continuous
892 * free pages of length of (1 << order) and marked with PageBuddy.
893 * Page's order is recorded in page_private(page) field.
894 * So when we are allocating or freeing one, we can derive the state of the
895 * other. That is, if we allocate a small block, and both were
896 * free, the remainder of the region must be split into blocks.
897 * If a block is freed, and its buddy is also free, then this
898 * triggers coalescing into a block of larger size.
903 static inline void __free_one_page(struct page *page,
905 struct zone *zone, unsigned int order,
908 unsigned long combined_pfn;
909 unsigned long uninitialized_var(buddy_pfn);
911 unsigned int max_order;
912 struct capture_control *capc = task_capc(zone);
914 max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
916 VM_BUG_ON(!zone_is_initialized(zone));
917 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
919 VM_BUG_ON(migratetype == -1);
920 if (likely(!is_migrate_isolate(migratetype)))
921 __mod_zone_freepage_state(zone, 1 << order, migratetype);
923 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
924 VM_BUG_ON_PAGE(bad_range(zone, page), page);
927 while (order < max_order - 1) {
928 if (compaction_capture(capc, page, order, migratetype)) {
929 __mod_zone_freepage_state(zone, -(1 << order),
933 buddy_pfn = __find_buddy_pfn(pfn, order);
934 buddy = page + (buddy_pfn - pfn);
936 if (!pfn_valid_within(buddy_pfn))
938 if (!page_is_buddy(page, buddy, order))
941 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
942 * merge with it and move up one order.
944 if (page_is_guard(buddy))
945 clear_page_guard(zone, buddy, order, migratetype);
947 del_page_from_free_area(buddy, &zone->free_area[order]);
948 combined_pfn = buddy_pfn & pfn;
949 page = page + (combined_pfn - pfn);
953 if (max_order < MAX_ORDER) {
954 /* If we are here, it means order is >= pageblock_order.
955 * We want to prevent merge between freepages on isolate
956 * pageblock and normal pageblock. Without this, pageblock
957 * isolation could cause incorrect freepage or CMA accounting.
959 * We don't want to hit this code for the more frequent
962 if (unlikely(has_isolate_pageblock(zone))) {
965 buddy_pfn = __find_buddy_pfn(pfn, order);
966 buddy = page + (buddy_pfn - pfn);
967 buddy_mt = get_pageblock_migratetype(buddy);
969 if (migratetype != buddy_mt
970 && (is_migrate_isolate(migratetype) ||
971 is_migrate_isolate(buddy_mt)))
975 goto continue_merging;
979 set_page_order(page, order);
982 * If this is not the largest possible page, check if the buddy
983 * of the next-highest order is free. If it is, it's possible
984 * that pages are being freed that will coalesce soon. In case,
985 * that is happening, add the free page to the tail of the list
986 * so it's less likely to be used soon and more likely to be merged
987 * as a higher order page
989 if ((order < MAX_ORDER-2) && pfn_valid_within(buddy_pfn)
990 && !is_shuffle_order(order)) {
991 struct page *higher_page, *higher_buddy;
992 combined_pfn = buddy_pfn & pfn;
993 higher_page = page + (combined_pfn - pfn);
994 buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
995 higher_buddy = higher_page + (buddy_pfn - combined_pfn);
996 if (pfn_valid_within(buddy_pfn) &&
997 page_is_buddy(higher_page, higher_buddy, order + 1)) {
998 add_to_free_area_tail(page, &zone->free_area[order],
1004 if (is_shuffle_order(order))
1005 add_to_free_area_random(page, &zone->free_area[order],
1008 add_to_free_area(page, &zone->free_area[order], migratetype);
1013 * A bad page could be due to a number of fields. Instead of multiple branches,
1014 * try and check multiple fields with one check. The caller must do a detailed
1015 * check if necessary.
1017 static inline bool page_expected_state(struct page *page,
1018 unsigned long check_flags)
1020 if (unlikely(atomic_read(&page->_mapcount) != -1))
1023 if (unlikely((unsigned long)page->mapping |
1024 page_ref_count(page) |
1026 (unsigned long)page->mem_cgroup |
1028 (page->flags & check_flags)))
1034 static void free_pages_check_bad(struct page *page)
1036 const char *bad_reason;
1037 unsigned long bad_flags;
1042 if (unlikely(atomic_read(&page->_mapcount) != -1))
1043 bad_reason = "nonzero mapcount";
1044 if (unlikely(page->mapping != NULL))
1045 bad_reason = "non-NULL mapping";
1046 if (unlikely(page_ref_count(page) != 0))
1047 bad_reason = "nonzero _refcount";
1048 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
1049 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
1050 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
1053 if (unlikely(page->mem_cgroup))
1054 bad_reason = "page still charged to cgroup";
1056 bad_page(page, bad_reason, bad_flags);
1059 static inline int free_pages_check(struct page *page)
1061 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
1064 /* Something has gone sideways, find it */
1065 free_pages_check_bad(page);
1069 static int free_tail_pages_check(struct page *head_page, struct page *page)
1074 * We rely page->lru.next never has bit 0 set, unless the page
1075 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
1077 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
1079 if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
1083 switch (page - head_page) {
1085 /* the first tail page: ->mapping may be compound_mapcount() */
1086 if (unlikely(compound_mapcount(page))) {
1087 bad_page(page, "nonzero compound_mapcount", 0);
1093 * the second tail page: ->mapping is
1094 * deferred_list.next -- ignore value.
1098 if (page->mapping != TAIL_MAPPING) {
1099 bad_page(page, "corrupted mapping in tail page", 0);
1104 if (unlikely(!PageTail(page))) {
1105 bad_page(page, "PageTail not set", 0);
1108 if (unlikely(compound_head(page) != head_page)) {
1109 bad_page(page, "compound_head not consistent", 0);
1114 page->mapping = NULL;
1115 clear_compound_head(page);
1119 static void kernel_init_free_pages(struct page *page, int numpages)
1123 for (i = 0; i < numpages; i++)
1124 clear_highpage(page + i);
1127 static __always_inline bool free_pages_prepare(struct page *page,
1128 unsigned int order, bool check_free)
1132 VM_BUG_ON_PAGE(PageTail(page), page);
1134 trace_mm_page_free(page, order);
1137 * Check tail pages before head page information is cleared to
1138 * avoid checking PageCompound for order-0 pages.
1140 if (unlikely(order)) {
1141 bool compound = PageCompound(page);
1144 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1147 ClearPageDoubleMap(page);
1148 for (i = 1; i < (1 << order); i++) {
1150 bad += free_tail_pages_check(page, page + i);
1151 if (unlikely(free_pages_check(page + i))) {
1155 (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1158 if (PageMappingFlags(page))
1159 page->mapping = NULL;
1160 if (memcg_kmem_enabled() && PageKmemcg(page))
1161 __memcg_kmem_uncharge(page, order);
1163 bad += free_pages_check(page);
1167 page_cpupid_reset_last(page);
1168 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1169 reset_page_owner(page, order);
1171 if (!PageHighMem(page)) {
1172 debug_check_no_locks_freed(page_address(page),
1173 PAGE_SIZE << order);
1174 debug_check_no_obj_freed(page_address(page),
1175 PAGE_SIZE << order);
1177 if (want_init_on_free())
1178 kernel_init_free_pages(page, 1 << order);
1180 kernel_poison_pages(page, 1 << order, 0);
1182 * arch_free_page() can make the page's contents inaccessible. s390
1183 * does this. So nothing which can access the page's contents should
1184 * happen after this.
1186 arch_free_page(page, order);
1188 if (debug_pagealloc_enabled())
1189 kernel_map_pages(page, 1 << order, 0);
1191 kasan_free_nondeferred_pages(page, order);
1196 #ifdef CONFIG_DEBUG_VM
1198 * With DEBUG_VM enabled, order-0 pages are checked immediately when being freed
1199 * to pcp lists. With debug_pagealloc also enabled, they are also rechecked when
1200 * moved from pcp lists to free lists.
1202 static bool free_pcp_prepare(struct page *page)
1204 return free_pages_prepare(page, 0, true);
1207 static bool bulkfree_pcp_prepare(struct page *page)
1209 if (debug_pagealloc_enabled())
1210 return free_pages_check(page);
1216 * With DEBUG_VM disabled, order-0 pages being freed are checked only when
1217 * moving from pcp lists to free list in order to reduce overhead. With
1218 * debug_pagealloc enabled, they are checked also immediately when being freed
1221 static bool free_pcp_prepare(struct page *page)
1223 if (debug_pagealloc_enabled())
1224 return free_pages_prepare(page, 0, true);
1226 return free_pages_prepare(page, 0, false);
1229 static bool bulkfree_pcp_prepare(struct page *page)
1231 return free_pages_check(page);
1233 #endif /* CONFIG_DEBUG_VM */
1235 static inline void prefetch_buddy(struct page *page)
1237 unsigned long pfn = page_to_pfn(page);
1238 unsigned long buddy_pfn = __find_buddy_pfn(pfn, 0);
1239 struct page *buddy = page + (buddy_pfn - pfn);
1245 * Frees a number of pages from the PCP lists
1246 * Assumes all pages on list are in same zone, and of same order.
1247 * count is the number of pages to free.
1249 * If the zone was previously in an "all pages pinned" state then look to
1250 * see if this freeing clears that state.
1252 * And clear the zone's pages_scanned counter, to hold off the "all pages are
1253 * pinned" detection logic.
1255 static void free_pcppages_bulk(struct zone *zone, int count,
1256 struct per_cpu_pages *pcp)
1258 int migratetype = 0;
1260 int prefetch_nr = 0;
1261 bool isolated_pageblocks;
1262 struct page *page, *tmp;
1266 struct list_head *list;
1269 * Remove pages from lists in a round-robin fashion. A
1270 * batch_free count is maintained that is incremented when an
1271 * empty list is encountered. This is so more pages are freed
1272 * off fuller lists instead of spinning excessively around empty
1277 if (++migratetype == MIGRATE_PCPTYPES)
1279 list = &pcp->lists[migratetype];
1280 } while (list_empty(list));
1282 /* This is the only non-empty list. Free them all. */
1283 if (batch_free == MIGRATE_PCPTYPES)
1287 page = list_last_entry(list, struct page, lru);
1288 /* must delete to avoid corrupting pcp list */
1289 list_del(&page->lru);
1292 if (bulkfree_pcp_prepare(page))
1295 list_add_tail(&page->lru, &head);
1298 * We are going to put the page back to the global
1299 * pool, prefetch its buddy to speed up later access
1300 * under zone->lock. It is believed the overhead of
1301 * an additional test and calculating buddy_pfn here
1302 * can be offset by reduced memory latency later. To
1303 * avoid excessive prefetching due to large count, only
1304 * prefetch buddy for the first pcp->batch nr of pages.
1306 if (prefetch_nr++ < pcp->batch)
1307 prefetch_buddy(page);
1308 } while (--count && --batch_free && !list_empty(list));
1311 spin_lock(&zone->lock);
1312 isolated_pageblocks = has_isolate_pageblock(zone);
1315 * Use safe version since after __free_one_page(),
1316 * page->lru.next will not point to original list.
1318 list_for_each_entry_safe(page, tmp, &head, lru) {
1319 int mt = get_pcppage_migratetype(page);
1320 /* MIGRATE_ISOLATE page should not go to pcplists */
1321 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1322 /* Pageblock could have been isolated meanwhile */
1323 if (unlikely(isolated_pageblocks))
1324 mt = get_pageblock_migratetype(page);
1326 __free_one_page(page, page_to_pfn(page), zone, 0, mt);
1327 trace_mm_page_pcpu_drain(page, 0, mt);
1329 spin_unlock(&zone->lock);
1332 static void free_one_page(struct zone *zone,
1333 struct page *page, unsigned long pfn,
1337 spin_lock(&zone->lock);
1338 if (unlikely(has_isolate_pageblock(zone) ||
1339 is_migrate_isolate(migratetype))) {
1340 migratetype = get_pfnblock_migratetype(page, pfn);
1342 __free_one_page(page, pfn, zone, order, migratetype);
1343 spin_unlock(&zone->lock);
1346 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
1347 unsigned long zone, int nid)
1349 mm_zero_struct_page(page);
1350 set_page_links(page, zone, nid, pfn);
1351 init_page_count(page);
1352 page_mapcount_reset(page);
1353 page_cpupid_reset_last(page);
1354 page_kasan_tag_reset(page);
1356 INIT_LIST_HEAD(&page->lru);
1357 #ifdef WANT_PAGE_VIRTUAL
1358 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1359 if (!is_highmem_idx(zone))
1360 set_page_address(page, __va(pfn << PAGE_SHIFT));
1364 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1365 static void __meminit init_reserved_page(unsigned long pfn)
1370 if (!early_page_uninitialised(pfn))
1373 nid = early_pfn_to_nid(pfn);
1374 pgdat = NODE_DATA(nid);
1376 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1377 struct zone *zone = &pgdat->node_zones[zid];
1379 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
1382 __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
1385 static inline void init_reserved_page(unsigned long pfn)
1388 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1391 * Initialised pages do not have PageReserved set. This function is
1392 * called for each range allocated by the bootmem allocator and
1393 * marks the pages PageReserved. The remaining valid pages are later
1394 * sent to the buddy page allocator.
1396 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1398 unsigned long start_pfn = PFN_DOWN(start);
1399 unsigned long end_pfn = PFN_UP(end);
1401 for (; start_pfn < end_pfn; start_pfn++) {
1402 if (pfn_valid(start_pfn)) {
1403 struct page *page = pfn_to_page(start_pfn);
1405 init_reserved_page(start_pfn);
1407 /* Avoid false-positive PageTail() */
1408 INIT_LIST_HEAD(&page->lru);
1411 * no need for atomic set_bit because the struct
1412 * page is not visible yet so nobody should
1415 __SetPageReserved(page);
1420 static void __free_pages_ok(struct page *page, unsigned int order)
1422 unsigned long flags;
1424 unsigned long pfn = page_to_pfn(page);
1426 if (!free_pages_prepare(page, order, true))
1429 migratetype = get_pfnblock_migratetype(page, pfn);
1430 local_irq_save(flags);
1431 __count_vm_events(PGFREE, 1 << order);
1432 free_one_page(page_zone(page), page, pfn, order, migratetype);
1433 local_irq_restore(flags);
1436 void __free_pages_core(struct page *page, unsigned int order)
1438 unsigned int nr_pages = 1 << order;
1439 struct page *p = page;
1443 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1445 __ClearPageReserved(p);
1446 set_page_count(p, 0);
1448 __ClearPageReserved(p);
1449 set_page_count(p, 0);
1451 atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
1452 set_page_refcounted(page);
1453 __free_pages(page, order);
1456 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1457 defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1459 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1461 int __meminit early_pfn_to_nid(unsigned long pfn)
1463 static DEFINE_SPINLOCK(early_pfn_lock);
1466 spin_lock(&early_pfn_lock);
1467 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1469 nid = first_online_node;
1470 spin_unlock(&early_pfn_lock);
1476 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1477 /* Only safe to use early in boot when initialisation is single-threaded */
1478 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1482 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1483 if (nid >= 0 && nid != node)
1489 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1496 void __init memblock_free_pages(struct page *page, unsigned long pfn,
1499 if (early_page_uninitialised(pfn))
1501 __free_pages_core(page, order);
1505 * Check that the whole (or subset of) a pageblock given by the interval of
1506 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1507 * with the migration of free compaction scanner. The scanners then need to
1508 * use only pfn_valid_within() check for arches that allow holes within
1511 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1513 * It's possible on some configurations to have a setup like node0 node1 node0
1514 * i.e. it's possible that all pages within a zones range of pages do not
1515 * belong to a single zone. We assume that a border between node0 and node1
1516 * can occur within a single pageblock, but not a node0 node1 node0
1517 * interleaving within a single pageblock. It is therefore sufficient to check
1518 * the first and last page of a pageblock and avoid checking each individual
1519 * page in a pageblock.
1521 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1522 unsigned long end_pfn, struct zone *zone)
1524 struct page *start_page;
1525 struct page *end_page;
1527 /* end_pfn is one past the range we are checking */
1530 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1533 start_page = pfn_to_online_page(start_pfn);
1537 if (page_zone(start_page) != zone)
1540 end_page = pfn_to_page(end_pfn);
1542 /* This gives a shorter code than deriving page_zone(end_page) */
1543 if (page_zone_id(start_page) != page_zone_id(end_page))
1549 void set_zone_contiguous(struct zone *zone)
1551 unsigned long block_start_pfn = zone->zone_start_pfn;
1552 unsigned long block_end_pfn;
1554 block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1555 for (; block_start_pfn < zone_end_pfn(zone);
1556 block_start_pfn = block_end_pfn,
1557 block_end_pfn += pageblock_nr_pages) {
1559 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1561 if (!__pageblock_pfn_to_page(block_start_pfn,
1562 block_end_pfn, zone))
1566 /* We confirm that there is no hole */
1567 zone->contiguous = true;
1570 void clear_zone_contiguous(struct zone *zone)
1572 zone->contiguous = false;
1575 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1576 static void __init deferred_free_range(unsigned long pfn,
1577 unsigned long nr_pages)
1585 page = pfn_to_page(pfn);
1587 /* Free a large naturally-aligned chunk if possible */
1588 if (nr_pages == pageblock_nr_pages &&
1589 (pfn & (pageblock_nr_pages - 1)) == 0) {
1590 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1591 __free_pages_core(page, pageblock_order);
1595 for (i = 0; i < nr_pages; i++, page++, pfn++) {
1596 if ((pfn & (pageblock_nr_pages - 1)) == 0)
1597 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1598 __free_pages_core(page, 0);
1602 /* Completion tracking for deferred_init_memmap() threads */
1603 static atomic_t pgdat_init_n_undone __initdata;
1604 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1606 static inline void __init pgdat_init_report_one_done(void)
1608 if (atomic_dec_and_test(&pgdat_init_n_undone))
1609 complete(&pgdat_init_all_done_comp);
1613 * Returns true if page needs to be initialized or freed to buddy allocator.
1615 * First we check if pfn is valid on architectures where it is possible to have
1616 * holes within pageblock_nr_pages. On systems where it is not possible, this
1617 * function is optimized out.
1619 * Then, we check if a current large page is valid by only checking the validity
1622 static inline bool __init deferred_pfn_valid(unsigned long pfn)
1624 if (!pfn_valid_within(pfn))
1626 if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1632 * Free pages to buddy allocator. Try to free aligned pages in
1633 * pageblock_nr_pages sizes.
1635 static void __init deferred_free_pages(unsigned long pfn,
1636 unsigned long end_pfn)
1638 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1639 unsigned long nr_free = 0;
1641 for (; pfn < end_pfn; pfn++) {
1642 if (!deferred_pfn_valid(pfn)) {
1643 deferred_free_range(pfn - nr_free, nr_free);
1645 } else if (!(pfn & nr_pgmask)) {
1646 deferred_free_range(pfn - nr_free, nr_free);
1648 touch_nmi_watchdog();
1653 /* Free the last block of pages to allocator */
1654 deferred_free_range(pfn - nr_free, nr_free);
1658 * Initialize struct pages. We minimize pfn page lookups and scheduler checks
1659 * by performing it only once every pageblock_nr_pages.
1660 * Return number of pages initialized.
1662 static unsigned long __init deferred_init_pages(struct zone *zone,
1664 unsigned long end_pfn)
1666 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1667 int nid = zone_to_nid(zone);
1668 unsigned long nr_pages = 0;
1669 int zid = zone_idx(zone);
1670 struct page *page = NULL;
1672 for (; pfn < end_pfn; pfn++) {
1673 if (!deferred_pfn_valid(pfn)) {
1676 } else if (!page || !(pfn & nr_pgmask)) {
1677 page = pfn_to_page(pfn);
1678 touch_nmi_watchdog();
1682 __init_single_page(page, pfn, zid, nid);
1689 * This function is meant to pre-load the iterator for the zone init.
1690 * Specifically it walks through the ranges until we are caught up to the
1691 * first_init_pfn value and exits there. If we never encounter the value we
1692 * return false indicating there are no valid ranges left.
1695 deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone,
1696 unsigned long *spfn, unsigned long *epfn,
1697 unsigned long first_init_pfn)
1702 * Start out by walking through the ranges in this zone that have
1703 * already been initialized. We don't need to do anything with them
1704 * so we just need to flush them out of the system.
1706 for_each_free_mem_pfn_range_in_zone(j, zone, spfn, epfn) {
1707 if (*epfn <= first_init_pfn)
1709 if (*spfn < first_init_pfn)
1710 *spfn = first_init_pfn;
1719 * Initialize and free pages. We do it in two loops: first we initialize
1720 * struct page, then free to buddy allocator, because while we are
1721 * freeing pages we can access pages that are ahead (computing buddy
1722 * page in __free_one_page()).
1724 * In order to try and keep some memory in the cache we have the loop
1725 * broken along max page order boundaries. This way we will not cause
1726 * any issues with the buddy page computation.
1728 static unsigned long __init
1729 deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn,
1730 unsigned long *end_pfn)
1732 unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES);
1733 unsigned long spfn = *start_pfn, epfn = *end_pfn;
1734 unsigned long nr_pages = 0;
1737 /* First we loop through and initialize the page values */
1738 for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) {
1741 if (mo_pfn <= *start_pfn)
1744 t = min(mo_pfn, *end_pfn);
1745 nr_pages += deferred_init_pages(zone, *start_pfn, t);
1747 if (mo_pfn < *end_pfn) {
1748 *start_pfn = mo_pfn;
1753 /* Reset values and now loop through freeing pages as needed */
1756 for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) {
1762 t = min(mo_pfn, epfn);
1763 deferred_free_pages(spfn, t);
1772 /* Initialise remaining memory on a node */
1773 static int __init deferred_init_memmap(void *data)
1775 pg_data_t *pgdat = data;
1776 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1777 unsigned long spfn = 0, epfn = 0, nr_pages = 0;
1778 unsigned long first_init_pfn, flags;
1779 unsigned long start = jiffies;
1784 /* Bind memory initialisation thread to a local node if possible */
1785 if (!cpumask_empty(cpumask))
1786 set_cpus_allowed_ptr(current, cpumask);
1788 pgdat_resize_lock(pgdat, &flags);
1789 first_init_pfn = pgdat->first_deferred_pfn;
1790 if (first_init_pfn == ULONG_MAX) {
1791 pgdat_resize_unlock(pgdat, &flags);
1792 pgdat_init_report_one_done();
1796 /* Sanity check boundaries */
1797 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1798 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1799 pgdat->first_deferred_pfn = ULONG_MAX;
1801 /* Only the highest zone is deferred so find it */
1802 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1803 zone = pgdat->node_zones + zid;
1804 if (first_init_pfn < zone_end_pfn(zone))
1808 /* If the zone is empty somebody else may have cleared out the zone */
1809 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
1814 * Initialize and free pages in MAX_ORDER sized increments so
1815 * that we can avoid introducing any issues with the buddy
1819 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
1821 pgdat_resize_unlock(pgdat, &flags);
1823 /* Sanity check that the next zone really is unpopulated */
1824 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1826 pr_info("node %d initialised, %lu pages in %ums\n",
1827 pgdat->node_id, nr_pages, jiffies_to_msecs(jiffies - start));
1829 pgdat_init_report_one_done();
1834 * If this zone has deferred pages, try to grow it by initializing enough
1835 * deferred pages to satisfy the allocation specified by order, rounded up to
1836 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
1837 * of SECTION_SIZE bytes by initializing struct pages in increments of
1838 * PAGES_PER_SECTION * sizeof(struct page) bytes.
1840 * Return true when zone was grown, otherwise return false. We return true even
1841 * when we grow less than requested, to let the caller decide if there are
1842 * enough pages to satisfy the allocation.
1844 * Note: We use noinline because this function is needed only during boot, and
1845 * it is called from a __ref function _deferred_grow_zone. This way we are
1846 * making sure that it is not inlined into permanent text section.
1848 static noinline bool __init
1849 deferred_grow_zone(struct zone *zone, unsigned int order)
1851 unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
1852 pg_data_t *pgdat = zone->zone_pgdat;
1853 unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
1854 unsigned long spfn, epfn, flags;
1855 unsigned long nr_pages = 0;
1858 /* Only the last zone may have deferred pages */
1859 if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
1862 pgdat_resize_lock(pgdat, &flags);
1865 * If deferred pages have been initialized while we were waiting for
1866 * the lock, return true, as the zone was grown. The caller will retry
1867 * this zone. We won't return to this function since the caller also
1868 * has this static branch.
1870 if (!static_branch_unlikely(&deferred_pages)) {
1871 pgdat_resize_unlock(pgdat, &flags);
1876 * If someone grew this zone while we were waiting for spinlock, return
1877 * true, as there might be enough pages already.
1879 if (first_deferred_pfn != pgdat->first_deferred_pfn) {
1880 pgdat_resize_unlock(pgdat, &flags);
1884 /* If the zone is empty somebody else may have cleared out the zone */
1885 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
1886 first_deferred_pfn)) {
1887 pgdat->first_deferred_pfn = ULONG_MAX;
1888 pgdat_resize_unlock(pgdat, &flags);
1889 /* Retry only once. */
1890 return first_deferred_pfn != ULONG_MAX;
1894 * Initialize and free pages in MAX_ORDER sized increments so
1895 * that we can avoid introducing any issues with the buddy
1898 while (spfn < epfn) {
1899 /* update our first deferred PFN for this section */
1900 first_deferred_pfn = spfn;
1902 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
1904 /* We should only stop along section boundaries */
1905 if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION)
1908 /* If our quota has been met we can stop here */
1909 if (nr_pages >= nr_pages_needed)
1913 pgdat->first_deferred_pfn = spfn;
1914 pgdat_resize_unlock(pgdat, &flags);
1916 return nr_pages > 0;
1920 * deferred_grow_zone() is __init, but it is called from
1921 * get_page_from_freelist() during early boot until deferred_pages permanently
1922 * disables this call. This is why we have refdata wrapper to avoid warning,
1923 * and to ensure that the function body gets unloaded.
1926 _deferred_grow_zone(struct zone *zone, unsigned int order)
1928 return deferred_grow_zone(zone, order);
1931 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1933 void __init page_alloc_init_late(void)
1938 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1940 /* There will be num_node_state(N_MEMORY) threads */
1941 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1942 for_each_node_state(nid, N_MEMORY) {
1943 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1946 /* Block until all are initialised */
1947 wait_for_completion(&pgdat_init_all_done_comp);
1950 * The number of managed pages has changed due to the initialisation
1951 * so the pcpu batch and high limits needs to be updated or the limits
1952 * will be artificially small.
1954 for_each_populated_zone(zone)
1955 zone_pcp_update(zone);
1958 * We initialized the rest of the deferred pages. Permanently disable
1959 * on-demand struct page initialization.
1961 static_branch_disable(&deferred_pages);
1963 /* Reinit limits that are based on free pages after the kernel is up */
1964 files_maxfiles_init();
1967 /* Discard memblock private memory */
1970 for_each_node_state(nid, N_MEMORY)
1971 shuffle_free_memory(NODE_DATA(nid));
1973 for_each_populated_zone(zone)
1974 set_zone_contiguous(zone);
1976 #ifdef CONFIG_DEBUG_PAGEALLOC
1977 init_debug_guardpage();
1982 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
1983 void __init init_cma_reserved_pageblock(struct page *page)
1985 unsigned i = pageblock_nr_pages;
1986 struct page *p = page;
1989 __ClearPageReserved(p);
1990 set_page_count(p, 0);
1993 set_pageblock_migratetype(page, MIGRATE_CMA);
1995 if (pageblock_order >= MAX_ORDER) {
1996 i = pageblock_nr_pages;
1999 set_page_refcounted(p);
2000 __free_pages(p, MAX_ORDER - 1);
2001 p += MAX_ORDER_NR_PAGES;
2002 } while (i -= MAX_ORDER_NR_PAGES);
2004 set_page_refcounted(page);
2005 __free_pages(page, pageblock_order);
2008 adjust_managed_page_count(page, pageblock_nr_pages);
2013 * The order of subdivision here is critical for the IO subsystem.
2014 * Please do not alter this order without good reasons and regression
2015 * testing. Specifically, as large blocks of memory are subdivided,
2016 * the order in which smaller blocks are delivered depends on the order
2017 * they're subdivided in this function. This is the primary factor
2018 * influencing the order in which pages are delivered to the IO
2019 * subsystem according to empirical testing, and this is also justified
2020 * by considering the behavior of a buddy system containing a single
2021 * large block of memory acted on by a series of small allocations.
2022 * This behavior is a critical factor in sglist merging's success.
2026 static inline void expand(struct zone *zone, struct page *page,
2027 int low, int high, struct free_area *area,
2030 unsigned long size = 1 << high;
2032 while (high > low) {
2036 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
2039 * Mark as guard pages (or page), that will allow to
2040 * merge back to allocator when buddy will be freed.
2041 * Corresponding page table entries will not be touched,
2042 * pages will stay not present in virtual address space
2044 if (set_page_guard(zone, &page[size], high, migratetype))
2047 add_to_free_area(&page[size], area, migratetype);
2048 set_page_order(&page[size], high);
2052 static void check_new_page_bad(struct page *page)
2054 const char *bad_reason = NULL;
2055 unsigned long bad_flags = 0;
2057 if (unlikely(atomic_read(&page->_mapcount) != -1))
2058 bad_reason = "nonzero mapcount";
2059 if (unlikely(page->mapping != NULL))
2060 bad_reason = "non-NULL mapping";
2061 if (unlikely(page_ref_count(page) != 0))
2062 bad_reason = "nonzero _refcount";
2063 if (unlikely(page->flags & __PG_HWPOISON)) {
2064 bad_reason = "HWPoisoned (hardware-corrupted)";
2065 bad_flags = __PG_HWPOISON;
2066 /* Don't complain about hwpoisoned pages */
2067 page_mapcount_reset(page); /* remove PageBuddy */
2070 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
2071 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
2072 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
2075 if (unlikely(page->mem_cgroup))
2076 bad_reason = "page still charged to cgroup";
2078 bad_page(page, bad_reason, bad_flags);
2082 * This page is about to be returned from the page allocator
2084 static inline int check_new_page(struct page *page)
2086 if (likely(page_expected_state(page,
2087 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
2090 check_new_page_bad(page);
2094 static inline bool free_pages_prezeroed(void)
2096 return (IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) &&
2097 page_poisoning_enabled()) || want_init_on_free();
2100 #ifdef CONFIG_DEBUG_VM
2102 * With DEBUG_VM enabled, order-0 pages are checked for expected state when
2103 * being allocated from pcp lists. With debug_pagealloc also enabled, they are
2104 * also checked when pcp lists are refilled from the free lists.
2106 static inline bool check_pcp_refill(struct page *page)
2108 if (debug_pagealloc_enabled())
2109 return check_new_page(page);
2114 static inline bool check_new_pcp(struct page *page)
2116 return check_new_page(page);
2120 * With DEBUG_VM disabled, free order-0 pages are checked for expected state
2121 * when pcp lists are being refilled from the free lists. With debug_pagealloc
2122 * enabled, they are also checked when being allocated from the pcp lists.
2124 static inline bool check_pcp_refill(struct page *page)
2126 return check_new_page(page);
2128 static inline bool check_new_pcp(struct page *page)
2130 if (debug_pagealloc_enabled())
2131 return check_new_page(page);
2135 #endif /* CONFIG_DEBUG_VM */
2137 static bool check_new_pages(struct page *page, unsigned int order)
2140 for (i = 0; i < (1 << order); i++) {
2141 struct page *p = page + i;
2143 if (unlikely(check_new_page(p)))
2150 inline void post_alloc_hook(struct page *page, unsigned int order,
2153 set_page_private(page, 0);
2154 set_page_refcounted(page);
2156 arch_alloc_page(page, order);
2157 if (debug_pagealloc_enabled())
2158 kernel_map_pages(page, 1 << order, 1);
2159 kasan_alloc_pages(page, order);
2160 kernel_poison_pages(page, 1 << order, 1);
2161 set_page_owner(page, order, gfp_flags);
2164 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
2165 unsigned int alloc_flags)
2167 post_alloc_hook(page, order, gfp_flags);
2169 if (!free_pages_prezeroed() && want_init_on_alloc(gfp_flags))
2170 kernel_init_free_pages(page, 1 << order);
2172 if (order && (gfp_flags & __GFP_COMP))
2173 prep_compound_page(page, order);
2176 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
2177 * allocate the page. The expectation is that the caller is taking
2178 * steps that will free more memory. The caller should avoid the page
2179 * being used for !PFMEMALLOC purposes.
2181 if (alloc_flags & ALLOC_NO_WATERMARKS)
2182 set_page_pfmemalloc(page);
2184 clear_page_pfmemalloc(page);
2188 * Go through the free lists for the given migratetype and remove
2189 * the smallest available page from the freelists
2191 static __always_inline
2192 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
2195 unsigned int current_order;
2196 struct free_area *area;
2199 /* Find a page of the appropriate size in the preferred list */
2200 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
2201 area = &(zone->free_area[current_order]);
2202 page = get_page_from_free_area(area, migratetype);
2205 del_page_from_free_area(page, area);
2206 expand(zone, page, order, current_order, area, migratetype);
2207 set_pcppage_migratetype(page, migratetype);
2216 * This array describes the order lists are fallen back to when
2217 * the free lists for the desirable migrate type are depleted
2219 static int fallbacks[MIGRATE_TYPES][4] = {
2220 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2221 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
2222 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2224 [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */
2226 #ifdef CONFIG_MEMORY_ISOLATION
2227 [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */
2232 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2235 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
2238 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2239 unsigned int order) { return NULL; }
2243 * Move the free pages in a range to the free lists of the requested type.
2244 * Note that start_page and end_pages are not aligned on a pageblock
2245 * boundary. If alignment is required, use move_freepages_block()
2247 static int move_freepages(struct zone *zone,
2248 struct page *start_page, struct page *end_page,
2249 int migratetype, int *num_movable)
2253 int pages_moved = 0;
2255 for (page = start_page; page <= end_page;) {
2256 if (!pfn_valid_within(page_to_pfn(page))) {
2261 if (!PageBuddy(page)) {
2263 * We assume that pages that could be isolated for
2264 * migration are movable. But we don't actually try
2265 * isolating, as that would be expensive.
2268 (PageLRU(page) || __PageMovable(page)))
2275 /* Make sure we are not inadvertently changing nodes */
2276 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2277 VM_BUG_ON_PAGE(page_zone(page) != zone, page);
2279 order = page_order(page);
2280 move_to_free_area(page, &zone->free_area[order], migratetype);
2282 pages_moved += 1 << order;
2288 int move_freepages_block(struct zone *zone, struct page *page,
2289 int migratetype, int *num_movable)
2291 unsigned long start_pfn, end_pfn;
2292 struct page *start_page, *end_page;
2297 start_pfn = page_to_pfn(page);
2298 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
2299 start_page = pfn_to_page(start_pfn);
2300 end_page = start_page + pageblock_nr_pages - 1;
2301 end_pfn = start_pfn + pageblock_nr_pages - 1;
2303 /* Do not cross zone boundaries */
2304 if (!zone_spans_pfn(zone, start_pfn))
2306 if (!zone_spans_pfn(zone, end_pfn))
2309 return move_freepages(zone, start_page, end_page, migratetype,
2313 static void change_pageblock_range(struct page *pageblock_page,
2314 int start_order, int migratetype)
2316 int nr_pageblocks = 1 << (start_order - pageblock_order);
2318 while (nr_pageblocks--) {
2319 set_pageblock_migratetype(pageblock_page, migratetype);
2320 pageblock_page += pageblock_nr_pages;
2325 * When we are falling back to another migratetype during allocation, try to
2326 * steal extra free pages from the same pageblocks to satisfy further
2327 * allocations, instead of polluting multiple pageblocks.
2329 * If we are stealing a relatively large buddy page, it is likely there will
2330 * be more free pages in the pageblock, so try to steal them all. For
2331 * reclaimable and unmovable allocations, we steal regardless of page size,
2332 * as fragmentation caused by those allocations polluting movable pageblocks
2333 * is worse than movable allocations stealing from unmovable and reclaimable
2336 static bool can_steal_fallback(unsigned int order, int start_mt)
2339 * Leaving this order check is intended, although there is
2340 * relaxed order check in next check. The reason is that
2341 * we can actually steal whole pageblock if this condition met,
2342 * but, below check doesn't guarantee it and that is just heuristic
2343 * so could be changed anytime.
2345 if (order >= pageblock_order)
2348 if (order >= pageblock_order / 2 ||
2349 start_mt == MIGRATE_RECLAIMABLE ||
2350 start_mt == MIGRATE_UNMOVABLE ||
2351 page_group_by_mobility_disabled)
2357 static inline void boost_watermark(struct zone *zone)
2359 unsigned long max_boost;
2361 if (!watermark_boost_factor)
2364 max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
2365 watermark_boost_factor, 10000);
2368 * high watermark may be uninitialised if fragmentation occurs
2369 * very early in boot so do not boost. We do not fall
2370 * through and boost by pageblock_nr_pages as failing
2371 * allocations that early means that reclaim is not going
2372 * to help and it may even be impossible to reclaim the
2373 * boosted watermark resulting in a hang.
2378 max_boost = max(pageblock_nr_pages, max_boost);
2380 zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
2385 * This function implements actual steal behaviour. If order is large enough,
2386 * we can steal whole pageblock. If not, we first move freepages in this
2387 * pageblock to our migratetype and determine how many already-allocated pages
2388 * are there in the pageblock with a compatible migratetype. If at least half
2389 * of pages are free or compatible, we can change migratetype of the pageblock
2390 * itself, so pages freed in the future will be put on the correct free list.
2392 static void steal_suitable_fallback(struct zone *zone, struct page *page,
2393 unsigned int alloc_flags, int start_type, bool whole_block)
2395 unsigned int current_order = page_order(page);
2396 struct free_area *area;
2397 int free_pages, movable_pages, alike_pages;
2400 old_block_type = get_pageblock_migratetype(page);
2403 * This can happen due to races and we want to prevent broken
2404 * highatomic accounting.
2406 if (is_migrate_highatomic(old_block_type))
2409 /* Take ownership for orders >= pageblock_order */
2410 if (current_order >= pageblock_order) {
2411 change_pageblock_range(page, current_order, start_type);
2416 * Boost watermarks to increase reclaim pressure to reduce the
2417 * likelihood of future fallbacks. Wake kswapd now as the node
2418 * may be balanced overall and kswapd will not wake naturally.
2420 boost_watermark(zone);
2421 if (alloc_flags & ALLOC_KSWAPD)
2422 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
2424 /* We are not allowed to try stealing from the whole block */
2428 free_pages = move_freepages_block(zone, page, start_type,
2431 * Determine how many pages are compatible with our allocation.
2432 * For movable allocation, it's the number of movable pages which
2433 * we just obtained. For other types it's a bit more tricky.
2435 if (start_type == MIGRATE_MOVABLE) {
2436 alike_pages = movable_pages;
2439 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2440 * to MOVABLE pageblock, consider all non-movable pages as
2441 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2442 * vice versa, be conservative since we can't distinguish the
2443 * exact migratetype of non-movable pages.
2445 if (old_block_type == MIGRATE_MOVABLE)
2446 alike_pages = pageblock_nr_pages
2447 - (free_pages + movable_pages);
2452 /* moving whole block can fail due to zone boundary conditions */
2457 * If a sufficient number of pages in the block are either free or of
2458 * comparable migratability as our allocation, claim the whole block.
2460 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2461 page_group_by_mobility_disabled)
2462 set_pageblock_migratetype(page, start_type);
2467 area = &zone->free_area[current_order];
2468 move_to_free_area(page, area, start_type);
2472 * Check whether there is a suitable fallback freepage with requested order.
2473 * If only_stealable is true, this function returns fallback_mt only if
2474 * we can steal other freepages all together. This would help to reduce
2475 * fragmentation due to mixed migratetype pages in one pageblock.
2477 int find_suitable_fallback(struct free_area *area, unsigned int order,
2478 int migratetype, bool only_stealable, bool *can_steal)
2483 if (area->nr_free == 0)
2488 fallback_mt = fallbacks[migratetype][i];
2489 if (fallback_mt == MIGRATE_TYPES)
2492 if (free_area_empty(area, fallback_mt))
2495 if (can_steal_fallback(order, migratetype))
2498 if (!only_stealable)
2509 * Reserve a pageblock for exclusive use of high-order atomic allocations if
2510 * there are no empty page blocks that contain a page with a suitable order
2512 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2513 unsigned int alloc_order)
2516 unsigned long max_managed, flags;
2519 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2520 * Check is race-prone but harmless.
2522 max_managed = (zone_managed_pages(zone) / 100) + pageblock_nr_pages;
2523 if (zone->nr_reserved_highatomic >= max_managed)
2526 spin_lock_irqsave(&zone->lock, flags);
2528 /* Recheck the nr_reserved_highatomic limit under the lock */
2529 if (zone->nr_reserved_highatomic >= max_managed)
2533 mt = get_pageblock_migratetype(page);
2534 if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
2535 && !is_migrate_cma(mt)) {
2536 zone->nr_reserved_highatomic += pageblock_nr_pages;
2537 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
2538 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
2542 spin_unlock_irqrestore(&zone->lock, flags);
2546 * Used when an allocation is about to fail under memory pressure. This
2547 * potentially hurts the reliability of high-order allocations when under
2548 * intense memory pressure but failed atomic allocations should be easier
2549 * to recover from than an OOM.
2551 * If @force is true, try to unreserve a pageblock even though highatomic
2552 * pageblock is exhausted.
2554 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2557 struct zonelist *zonelist = ac->zonelist;
2558 unsigned long flags;
2565 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2568 * Preserve at least one pageblock unless memory pressure
2571 if (!force && zone->nr_reserved_highatomic <=
2575 spin_lock_irqsave(&zone->lock, flags);
2576 for (order = 0; order < MAX_ORDER; order++) {
2577 struct free_area *area = &(zone->free_area[order]);
2579 page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
2584 * In page freeing path, migratetype change is racy so
2585 * we can counter several free pages in a pageblock
2586 * in this loop althoug we changed the pageblock type
2587 * from highatomic to ac->migratetype. So we should
2588 * adjust the count once.
2590 if (is_migrate_highatomic_page(page)) {
2592 * It should never happen but changes to
2593 * locking could inadvertently allow a per-cpu
2594 * drain to add pages to MIGRATE_HIGHATOMIC
2595 * while unreserving so be safe and watch for
2598 zone->nr_reserved_highatomic -= min(
2600 zone->nr_reserved_highatomic);
2604 * Convert to ac->migratetype and avoid the normal
2605 * pageblock stealing heuristics. Minimally, the caller
2606 * is doing the work and needs the pages. More
2607 * importantly, if the block was always converted to
2608 * MIGRATE_UNMOVABLE or another type then the number
2609 * of pageblocks that cannot be completely freed
2612 set_pageblock_migratetype(page, ac->migratetype);
2613 ret = move_freepages_block(zone, page, ac->migratetype,
2616 spin_unlock_irqrestore(&zone->lock, flags);
2620 spin_unlock_irqrestore(&zone->lock, flags);
2627 * Try finding a free buddy page on the fallback list and put it on the free
2628 * list of requested migratetype, possibly along with other pages from the same
2629 * block, depending on fragmentation avoidance heuristics. Returns true if
2630 * fallback was found so that __rmqueue_smallest() can grab it.
2632 * The use of signed ints for order and current_order is a deliberate
2633 * deviation from the rest of this file, to make the for loop
2634 * condition simpler.
2636 static __always_inline bool
2637 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype,
2638 unsigned int alloc_flags)
2640 struct free_area *area;
2642 int min_order = order;
2648 * Do not steal pages from freelists belonging to other pageblocks
2649 * i.e. orders < pageblock_order. If there are no local zones free,
2650 * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2652 if (alloc_flags & ALLOC_NOFRAGMENT)
2653 min_order = pageblock_order;
2656 * Find the largest available free page in the other list. This roughly
2657 * approximates finding the pageblock with the most free pages, which
2658 * would be too costly to do exactly.
2660 for (current_order = MAX_ORDER - 1; current_order >= min_order;
2662 area = &(zone->free_area[current_order]);
2663 fallback_mt = find_suitable_fallback(area, current_order,
2664 start_migratetype, false, &can_steal);
2665 if (fallback_mt == -1)
2669 * We cannot steal all free pages from the pageblock and the
2670 * requested migratetype is movable. In that case it's better to
2671 * steal and split the smallest available page instead of the
2672 * largest available page, because even if the next movable
2673 * allocation falls back into a different pageblock than this
2674 * one, it won't cause permanent fragmentation.
2676 if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2677 && current_order > order)
2686 for (current_order = order; current_order < MAX_ORDER;
2688 area = &(zone->free_area[current_order]);
2689 fallback_mt = find_suitable_fallback(area, current_order,
2690 start_migratetype, false, &can_steal);
2691 if (fallback_mt != -1)
2696 * This should not happen - we already found a suitable fallback
2697 * when looking for the largest page.
2699 VM_BUG_ON(current_order == MAX_ORDER);
2702 page = get_page_from_free_area(area, fallback_mt);
2704 steal_suitable_fallback(zone, page, alloc_flags, start_migratetype,
2707 trace_mm_page_alloc_extfrag(page, order, current_order,
2708 start_migratetype, fallback_mt);
2715 * Do the hard work of removing an element from the buddy allocator.
2716 * Call me with the zone->lock already held.
2718 static __always_inline struct page *
2719 __rmqueue(struct zone *zone, unsigned int order, int migratetype,
2720 unsigned int alloc_flags)
2725 page = __rmqueue_smallest(zone, order, migratetype);
2726 if (unlikely(!page)) {
2727 if (migratetype == MIGRATE_MOVABLE)
2728 page = __rmqueue_cma_fallback(zone, order);
2730 if (!page && __rmqueue_fallback(zone, order, migratetype,
2735 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2740 * Obtain a specified number of elements from the buddy allocator, all under
2741 * a single hold of the lock, for efficiency. Add them to the supplied list.
2742 * Returns the number of new pages which were placed at *list.
2744 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2745 unsigned long count, struct list_head *list,
2746 int migratetype, unsigned int alloc_flags)
2750 spin_lock(&zone->lock);
2751 for (i = 0; i < count; ++i) {
2752 struct page *page = __rmqueue(zone, order, migratetype,
2754 if (unlikely(page == NULL))
2757 if (unlikely(check_pcp_refill(page)))
2761 * Split buddy pages returned by expand() are received here in
2762 * physical page order. The page is added to the tail of
2763 * caller's list. From the callers perspective, the linked list
2764 * is ordered by page number under some conditions. This is
2765 * useful for IO devices that can forward direction from the
2766 * head, thus also in the physical page order. This is useful
2767 * for IO devices that can merge IO requests if the physical
2768 * pages are ordered properly.
2770 list_add_tail(&page->lru, list);
2772 if (is_migrate_cma(get_pcppage_migratetype(page)))
2773 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
2778 * i pages were removed from the buddy list even if some leak due
2779 * to check_pcp_refill failing so adjust NR_FREE_PAGES based
2780 * on i. Do not confuse with 'alloced' which is the number of
2781 * pages added to the pcp list.
2783 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
2784 spin_unlock(&zone->lock);
2790 * Called from the vmstat counter updater to drain pagesets of this
2791 * currently executing processor on remote nodes after they have
2794 * Note that this function must be called with the thread pinned to
2795 * a single processor.
2797 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2799 unsigned long flags;
2800 int to_drain, batch;
2802 local_irq_save(flags);
2803 batch = READ_ONCE(pcp->batch);
2804 to_drain = min(pcp->count, batch);
2806 free_pcppages_bulk(zone, to_drain, pcp);
2807 local_irq_restore(flags);
2812 * Drain pcplists of the indicated processor and zone.
2814 * The processor must either be the current processor and the
2815 * thread pinned to the current processor or a processor that
2818 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2820 unsigned long flags;
2821 struct per_cpu_pageset *pset;
2822 struct per_cpu_pages *pcp;
2824 local_irq_save(flags);
2825 pset = per_cpu_ptr(zone->pageset, cpu);
2829 free_pcppages_bulk(zone, pcp->count, pcp);
2830 local_irq_restore(flags);
2834 * Drain pcplists of all zones on the indicated processor.
2836 * The processor must either be the current processor and the
2837 * thread pinned to the current processor or a processor that
2840 static void drain_pages(unsigned int cpu)
2844 for_each_populated_zone(zone) {
2845 drain_pages_zone(cpu, zone);
2850 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2852 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2853 * the single zone's pages.
2855 void drain_local_pages(struct zone *zone)
2857 int cpu = smp_processor_id();
2860 drain_pages_zone(cpu, zone);
2865 static void drain_local_pages_wq(struct work_struct *work)
2867 struct pcpu_drain *drain;
2869 drain = container_of(work, struct pcpu_drain, work);
2872 * drain_all_pages doesn't use proper cpu hotplug protection so
2873 * we can race with cpu offline when the WQ can move this from
2874 * a cpu pinned worker to an unbound one. We can operate on a different
2875 * cpu which is allright but we also have to make sure to not move to
2879 drain_local_pages(drain->zone);
2884 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2886 * When zone parameter is non-NULL, spill just the single zone's pages.
2888 * Note that this can be extremely slow as the draining happens in a workqueue.
2890 void drain_all_pages(struct zone *zone)
2895 * Allocate in the BSS so we wont require allocation in
2896 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2898 static cpumask_t cpus_with_pcps;
2901 * Make sure nobody triggers this path before mm_percpu_wq is fully
2904 if (WARN_ON_ONCE(!mm_percpu_wq))
2908 * Do not drain if one is already in progress unless it's specific to
2909 * a zone. Such callers are primarily CMA and memory hotplug and need
2910 * the drain to be complete when the call returns.
2912 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
2915 mutex_lock(&pcpu_drain_mutex);
2919 * We don't care about racing with CPU hotplug event
2920 * as offline notification will cause the notified
2921 * cpu to drain that CPU pcps and on_each_cpu_mask
2922 * disables preemption as part of its processing
2924 for_each_online_cpu(cpu) {
2925 struct per_cpu_pageset *pcp;
2927 bool has_pcps = false;
2930 pcp = per_cpu_ptr(zone->pageset, cpu);
2934 for_each_populated_zone(z) {
2935 pcp = per_cpu_ptr(z->pageset, cpu);
2936 if (pcp->pcp.count) {
2944 cpumask_set_cpu(cpu, &cpus_with_pcps);
2946 cpumask_clear_cpu(cpu, &cpus_with_pcps);
2949 for_each_cpu(cpu, &cpus_with_pcps) {
2950 struct pcpu_drain *drain = per_cpu_ptr(&pcpu_drain, cpu);
2953 INIT_WORK(&drain->work, drain_local_pages_wq);
2954 queue_work_on(cpu, mm_percpu_wq, &drain->work);
2956 for_each_cpu(cpu, &cpus_with_pcps)
2957 flush_work(&per_cpu_ptr(&pcpu_drain, cpu)->work);
2959 mutex_unlock(&pcpu_drain_mutex);
2962 #ifdef CONFIG_HIBERNATION
2965 * Touch the watchdog for every WD_PAGE_COUNT pages.
2967 #define WD_PAGE_COUNT (128*1024)
2969 void mark_free_pages(struct zone *zone)
2971 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
2972 unsigned long flags;
2973 unsigned int order, t;
2976 if (zone_is_empty(zone))
2979 spin_lock_irqsave(&zone->lock, flags);
2981 max_zone_pfn = zone_end_pfn(zone);
2982 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
2983 if (pfn_valid(pfn)) {
2984 page = pfn_to_page(pfn);
2986 if (!--page_count) {
2987 touch_nmi_watchdog();
2988 page_count = WD_PAGE_COUNT;
2991 if (page_zone(page) != zone)
2994 if (!swsusp_page_is_forbidden(page))
2995 swsusp_unset_page_free(page);
2998 for_each_migratetype_order(order, t) {
2999 list_for_each_entry(page,
3000 &zone->free_area[order].free_list[t], lru) {
3003 pfn = page_to_pfn(page);
3004 for (i = 0; i < (1UL << order); i++) {
3005 if (!--page_count) {
3006 touch_nmi_watchdog();
3007 page_count = WD_PAGE_COUNT;
3009 swsusp_set_page_free(pfn_to_page(pfn + i));
3013 spin_unlock_irqrestore(&zone->lock, flags);
3015 #endif /* CONFIG_PM */
3017 static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
3021 if (!free_pcp_prepare(page))
3024 migratetype = get_pfnblock_migratetype(page, pfn);
3025 set_pcppage_migratetype(page, migratetype);
3029 static void free_unref_page_commit(struct page *page, unsigned long pfn)
3031 struct zone *zone = page_zone(page);
3032 struct per_cpu_pages *pcp;
3035 migratetype = get_pcppage_migratetype(page);
3036 __count_vm_event(PGFREE);
3039 * We only track unmovable, reclaimable and movable on pcp lists.
3040 * Free ISOLATE pages back to the allocator because they are being
3041 * offlined but treat HIGHATOMIC as movable pages so we can get those
3042 * areas back if necessary. Otherwise, we may have to free
3043 * excessively into the page allocator
3045 if (migratetype >= MIGRATE_PCPTYPES) {
3046 if (unlikely(is_migrate_isolate(migratetype))) {
3047 free_one_page(zone, page, pfn, 0, migratetype);
3050 migratetype = MIGRATE_MOVABLE;
3053 pcp = &this_cpu_ptr(zone->pageset)->pcp;
3054 list_add(&page->lru, &pcp->lists[migratetype]);
3056 if (pcp->count >= pcp->high) {
3057 unsigned long batch = READ_ONCE(pcp->batch);
3058 free_pcppages_bulk(zone, batch, pcp);
3063 * Free a 0-order page
3065 void free_unref_page(struct page *page)
3067 unsigned long flags;
3068 unsigned long pfn = page_to_pfn(page);
3070 if (!free_unref_page_prepare(page, pfn))
3073 local_irq_save(flags);
3074 free_unref_page_commit(page, pfn);
3075 local_irq_restore(flags);
3079 * Free a list of 0-order pages
3081 void free_unref_page_list(struct list_head *list)
3083 struct page *page, *next;
3084 unsigned long flags, pfn;
3085 int batch_count = 0;
3087 /* Prepare pages for freeing */
3088 list_for_each_entry_safe(page, next, list, lru) {
3089 pfn = page_to_pfn(page);
3090 if (!free_unref_page_prepare(page, pfn))
3091 list_del(&page->lru);
3092 set_page_private(page, pfn);
3095 local_irq_save(flags);
3096 list_for_each_entry_safe(page, next, list, lru) {
3097 unsigned long pfn = page_private(page);
3099 set_page_private(page, 0);
3100 trace_mm_page_free_batched(page);
3101 free_unref_page_commit(page, pfn);
3104 * Guard against excessive IRQ disabled times when we get
3105 * a large list of pages to free.
3107 if (++batch_count == SWAP_CLUSTER_MAX) {
3108 local_irq_restore(flags);
3110 local_irq_save(flags);
3113 local_irq_restore(flags);
3117 * split_page takes a non-compound higher-order page, and splits it into
3118 * n (1<<order) sub-pages: page[0..n]
3119 * Each sub-page must be freed individually.
3121 * Note: this is probably too low level an operation for use in drivers.
3122 * Please consult with lkml before using this in your driver.
3124 void split_page(struct page *page, unsigned int order)
3128 VM_BUG_ON_PAGE(PageCompound(page), page);
3129 VM_BUG_ON_PAGE(!page_count(page), page);
3131 for (i = 1; i < (1 << order); i++)
3132 set_page_refcounted(page + i);
3133 split_page_owner(page, order);
3135 EXPORT_SYMBOL_GPL(split_page);
3137 int __isolate_free_page(struct page *page, unsigned int order)
3139 struct free_area *area = &page_zone(page)->free_area[order];
3140 unsigned long watermark;
3144 BUG_ON(!PageBuddy(page));
3146 zone = page_zone(page);
3147 mt = get_pageblock_migratetype(page);
3149 if (!is_migrate_isolate(mt)) {
3151 * Obey watermarks as if the page was being allocated. We can
3152 * emulate a high-order watermark check with a raised order-0
3153 * watermark, because we already know our high-order page
3156 watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
3157 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
3160 __mod_zone_freepage_state(zone, -(1UL << order), mt);
3163 /* Remove page from free list */
3165 del_page_from_free_area(page, area);
3168 * Set the pageblock if the isolated page is at least half of a
3171 if (order >= pageblock_order - 1) {
3172 struct page *endpage = page + (1 << order) - 1;
3173 for (; page < endpage; page += pageblock_nr_pages) {
3174 int mt = get_pageblock_migratetype(page);
3175 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
3176 && !is_migrate_highatomic(mt))
3177 set_pageblock_migratetype(page,
3183 return 1UL << order;
3187 * Update NUMA hit/miss statistics
3189 * Must be called with interrupts disabled.
3191 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z)
3194 enum numa_stat_item local_stat = NUMA_LOCAL;
3196 /* skip numa counters update if numa stats is disabled */
3197 if (!static_branch_likely(&vm_numa_stat_key))
3200 if (zone_to_nid(z) != numa_node_id())
3201 local_stat = NUMA_OTHER;
3203 if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3204 __inc_numa_state(z, NUMA_HIT);
3206 __inc_numa_state(z, NUMA_MISS);
3207 __inc_numa_state(preferred_zone, NUMA_FOREIGN);
3209 __inc_numa_state(z, local_stat);
3213 /* Remove page from the per-cpu list, caller must protect the list */
3214 static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
3215 unsigned int alloc_flags,
3216 struct per_cpu_pages *pcp,
3217 struct list_head *list)
3222 if (list_empty(list)) {
3223 pcp->count += rmqueue_bulk(zone, 0,
3225 migratetype, alloc_flags);
3226 if (unlikely(list_empty(list)))
3230 page = list_first_entry(list, struct page, lru);
3231 list_del(&page->lru);
3233 } while (check_new_pcp(page));
3238 /* Lock and remove page from the per-cpu list */
3239 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
3240 struct zone *zone, gfp_t gfp_flags,
3241 int migratetype, unsigned int alloc_flags)
3243 struct per_cpu_pages *pcp;
3244 struct list_head *list;
3246 unsigned long flags;
3248 local_irq_save(flags);
3249 pcp = &this_cpu_ptr(zone->pageset)->pcp;
3250 list = &pcp->lists[migratetype];
3251 page = __rmqueue_pcplist(zone, migratetype, alloc_flags, pcp, list);
3253 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1);
3254 zone_statistics(preferred_zone, zone);
3256 local_irq_restore(flags);
3261 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
3264 struct page *rmqueue(struct zone *preferred_zone,
3265 struct zone *zone, unsigned int order,
3266 gfp_t gfp_flags, unsigned int alloc_flags,
3269 unsigned long flags;
3272 if (likely(order == 0)) {
3273 page = rmqueue_pcplist(preferred_zone, zone, gfp_flags,
3274 migratetype, alloc_flags);
3279 * We most definitely don't want callers attempting to
3280 * allocate greater than order-1 page units with __GFP_NOFAIL.
3282 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
3283 spin_lock_irqsave(&zone->lock, flags);
3287 if (alloc_flags & ALLOC_HARDER) {
3288 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3290 trace_mm_page_alloc_zone_locked(page, order, migratetype);
3293 page = __rmqueue(zone, order, migratetype, alloc_flags);
3294 } while (page && check_new_pages(page, order));
3295 spin_unlock(&zone->lock);
3298 __mod_zone_freepage_state(zone, -(1 << order),
3299 get_pcppage_migratetype(page));
3301 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3302 zone_statistics(preferred_zone, zone);
3303 local_irq_restore(flags);
3306 /* Separate test+clear to avoid unnecessary atomics */
3307 if (test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags)) {
3308 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3309 wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3312 VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3316 local_irq_restore(flags);
3320 #ifdef CONFIG_FAIL_PAGE_ALLOC
3323 struct fault_attr attr;
3325 bool ignore_gfp_highmem;
3326 bool ignore_gfp_reclaim;
3328 } fail_page_alloc = {
3329 .attr = FAULT_ATTR_INITIALIZER,
3330 .ignore_gfp_reclaim = true,
3331 .ignore_gfp_highmem = true,
3335 static int __init setup_fail_page_alloc(char *str)
3337 return setup_fault_attr(&fail_page_alloc.attr, str);
3339 __setup("fail_page_alloc=", setup_fail_page_alloc);
3341 static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3343 if (order < fail_page_alloc.min_order)
3345 if (gfp_mask & __GFP_NOFAIL)
3347 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3349 if (fail_page_alloc.ignore_gfp_reclaim &&
3350 (gfp_mask & __GFP_DIRECT_RECLAIM))
3353 return should_fail(&fail_page_alloc.attr, 1 << order);
3356 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3358 static int __init fail_page_alloc_debugfs(void)
3360 umode_t mode = S_IFREG | 0600;
3363 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3364 &fail_page_alloc.attr);
3366 debugfs_create_bool("ignore-gfp-wait", mode, dir,
3367 &fail_page_alloc.ignore_gfp_reclaim);
3368 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3369 &fail_page_alloc.ignore_gfp_highmem);
3370 debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order);
3375 late_initcall(fail_page_alloc_debugfs);
3377 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3379 #else /* CONFIG_FAIL_PAGE_ALLOC */
3381 static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3386 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3388 static noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3390 return __should_fail_alloc_page(gfp_mask, order);
3392 ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE);
3395 * Return true if free base pages are above 'mark'. For high-order checks it
3396 * will return true of the order-0 watermark is reached and there is at least
3397 * one free page of a suitable size. Checking now avoids taking the zone lock
3398 * to check in the allocation paths if no pages are free.
3400 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3401 int classzone_idx, unsigned int alloc_flags,
3406 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3408 /* free_pages may go negative - that's OK */
3409 free_pages -= (1 << order) - 1;
3411 if (alloc_flags & ALLOC_HIGH)
3415 * If the caller does not have rights to ALLOC_HARDER then subtract
3416 * the high-atomic reserves. This will over-estimate the size of the
3417 * atomic reserve but it avoids a search.
3419 if (likely(!alloc_harder)) {
3420 free_pages -= z->nr_reserved_highatomic;
3423 * OOM victims can try even harder than normal ALLOC_HARDER
3424 * users on the grounds that it's definitely going to be in
3425 * the exit path shortly and free memory. Any allocation it
3426 * makes during the free path will be small and short-lived.
3428 if (alloc_flags & ALLOC_OOM)
3436 /* If allocation can't use CMA areas don't use free CMA pages */
3437 if (!(alloc_flags & ALLOC_CMA))
3438 free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
3442 * Check watermarks for an order-0 allocation request. If these
3443 * are not met, then a high-order request also cannot go ahead
3444 * even if a suitable page happened to be free.
3446 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
3449 /* If this is an order-0 request then the watermark is fine */
3453 /* For a high-order request, check at least one suitable page is free */
3454 for (o = order; o < MAX_ORDER; o++) {
3455 struct free_area *area = &z->free_area[o];
3461 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3462 if (!free_area_empty(area, mt))
3467 if ((alloc_flags & ALLOC_CMA) &&
3468 !free_area_empty(area, MIGRATE_CMA)) {
3473 !list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
3479 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3480 int classzone_idx, unsigned int alloc_flags)
3482 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3483 zone_page_state(z, NR_FREE_PAGES));
3486 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3487 unsigned long mark, int classzone_idx, unsigned int alloc_flags)
3489 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3493 /* If allocation can't use CMA areas don't use free CMA pages */
3494 if (!(alloc_flags & ALLOC_CMA))
3495 cma_pages = zone_page_state(z, NR_FREE_CMA_PAGES);
3499 * Fast check for order-0 only. If this fails then the reserves
3500 * need to be calculated. There is a corner case where the check
3501 * passes but only the high-order atomic reserve are free. If
3502 * the caller is !atomic then it'll uselessly search the free
3503 * list. That corner case is then slower but it is harmless.
3505 if (!order && (free_pages - cma_pages) > mark + z->lowmem_reserve[classzone_idx])
3508 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3512 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3513 unsigned long mark, int classzone_idx)
3515 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3517 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3518 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3520 return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
3525 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3527 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3530 #else /* CONFIG_NUMA */
3531 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3535 #endif /* CONFIG_NUMA */
3538 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3539 * fragmentation is subtle. If the preferred zone was HIGHMEM then
3540 * premature use of a lower zone may cause lowmem pressure problems that
3541 * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3542 * probably too small. It only makes sense to spread allocations to avoid
3543 * fragmentation between the Normal and DMA32 zones.
3545 static inline unsigned int
3546 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3548 unsigned int alloc_flags = 0;
3550 if (gfp_mask & __GFP_KSWAPD_RECLAIM)
3551 alloc_flags |= ALLOC_KSWAPD;
3553 #ifdef CONFIG_ZONE_DMA32
3557 if (zone_idx(zone) != ZONE_NORMAL)
3561 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3562 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3563 * on UMA that if Normal is populated then so is DMA32.
3565 BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3566 if (nr_online_nodes > 1 && !populated_zone(--zone))
3569 alloc_flags |= ALLOC_NOFRAGMENT;
3570 #endif /* CONFIG_ZONE_DMA32 */
3575 * get_page_from_freelist goes through the zonelist trying to allocate
3578 static struct page *
3579 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3580 const struct alloc_context *ac)
3584 struct pglist_data *last_pgdat_dirty_limit = NULL;
3589 * Scan zonelist, looking for a zone with enough free.
3590 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3592 no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3593 z = ac->preferred_zoneref;
3594 for_next_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
3599 if (cpusets_enabled() &&
3600 (alloc_flags & ALLOC_CPUSET) &&
3601 !__cpuset_zone_allowed(zone, gfp_mask))
3604 * When allocating a page cache page for writing, we
3605 * want to get it from a node that is within its dirty
3606 * limit, such that no single node holds more than its
3607 * proportional share of globally allowed dirty pages.
3608 * The dirty limits take into account the node's
3609 * lowmem reserves and high watermark so that kswapd
3610 * should be able to balance it without having to
3611 * write pages from its LRU list.
3613 * XXX: For now, allow allocations to potentially
3614 * exceed the per-node dirty limit in the slowpath
3615 * (spread_dirty_pages unset) before going into reclaim,
3616 * which is important when on a NUMA setup the allowed
3617 * nodes are together not big enough to reach the
3618 * global limit. The proper fix for these situations
3619 * will require awareness of nodes in the
3620 * dirty-throttling and the flusher threads.
3622 if (ac->spread_dirty_pages) {
3623 if (last_pgdat_dirty_limit == zone->zone_pgdat)
3626 if (!node_dirty_ok(zone->zone_pgdat)) {
3627 last_pgdat_dirty_limit = zone->zone_pgdat;
3632 if (no_fallback && nr_online_nodes > 1 &&
3633 zone != ac->preferred_zoneref->zone) {
3637 * If moving to a remote node, retry but allow
3638 * fragmenting fallbacks. Locality is more important
3639 * than fragmentation avoidance.
3641 local_nid = zone_to_nid(ac->preferred_zoneref->zone);
3642 if (zone_to_nid(zone) != local_nid) {
3643 alloc_flags &= ~ALLOC_NOFRAGMENT;
3648 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
3649 if (!zone_watermark_fast(zone, order, mark,
3650 ac_classzone_idx(ac), alloc_flags)) {
3653 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3655 * Watermark failed for this zone, but see if we can
3656 * grow this zone if it contains deferred pages.
3658 if (static_branch_unlikely(&deferred_pages)) {
3659 if (_deferred_grow_zone(zone, order))
3663 /* Checked here to keep the fast path fast */
3664 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3665 if (alloc_flags & ALLOC_NO_WATERMARKS)
3668 if (node_reclaim_mode == 0 ||
3669 !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
3672 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3674 case NODE_RECLAIM_NOSCAN:
3677 case NODE_RECLAIM_FULL:
3678 /* scanned but unreclaimable */
3681 /* did we reclaim enough */
3682 if (zone_watermark_ok(zone, order, mark,
3683 ac_classzone_idx(ac), alloc_flags))
3691 page = rmqueue(ac->preferred_zoneref->zone, zone, order,
3692 gfp_mask, alloc_flags, ac->migratetype);
3694 prep_new_page(page, order, gfp_mask, alloc_flags);
3697 * If this is a high-order atomic allocation then check
3698 * if the pageblock should be reserved for the future
3700 if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
3701 reserve_highatomic_pageblock(page, zone, order);
3705 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3706 /* Try again if zone has deferred pages */
3707 if (static_branch_unlikely(&deferred_pages)) {
3708 if (_deferred_grow_zone(zone, order))
3716 * It's possible on a UMA machine to get through all zones that are
3717 * fragmented. If avoiding fragmentation, reset and try again.
3720 alloc_flags &= ~ALLOC_NOFRAGMENT;
3727 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
3729 unsigned int filter = SHOW_MEM_FILTER_NODES;
3730 static DEFINE_RATELIMIT_STATE(show_mem_rs, HZ, 1);
3732 if (!__ratelimit(&show_mem_rs))
3736 * This documents exceptions given to allocations in certain
3737 * contexts that are allowed to allocate outside current's set
3740 if (!(gfp_mask & __GFP_NOMEMALLOC))
3741 if (tsk_is_oom_victim(current) ||
3742 (current->flags & (PF_MEMALLOC | PF_EXITING)))
3743 filter &= ~SHOW_MEM_FILTER_NODES;
3744 if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
3745 filter &= ~SHOW_MEM_FILTER_NODES;
3747 show_mem(filter, nodemask);
3750 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
3752 struct va_format vaf;
3754 static DEFINE_RATELIMIT_STATE(nopage_rs, DEFAULT_RATELIMIT_INTERVAL,
3755 DEFAULT_RATELIMIT_BURST);
3757 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs))
3760 va_start(args, fmt);
3763 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
3764 current->comm, &vaf, gfp_mask, &gfp_mask,
3765 nodemask_pr_args(nodemask));
3768 cpuset_print_current_mems_allowed();
3771 warn_alloc_show_mem(gfp_mask, nodemask);
3774 static inline struct page *
3775 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
3776 unsigned int alloc_flags,
3777 const struct alloc_context *ac)
3781 page = get_page_from_freelist(gfp_mask, order,
3782 alloc_flags|ALLOC_CPUSET, ac);
3784 * fallback to ignore cpuset restriction if our nodes
3788 page = get_page_from_freelist(gfp_mask, order,
3794 static inline struct page *
3795 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
3796 const struct alloc_context *ac, unsigned long *did_some_progress)
3798 struct oom_control oc = {
3799 .zonelist = ac->zonelist,
3800 .nodemask = ac->nodemask,
3802 .gfp_mask = gfp_mask,
3807 *did_some_progress = 0;
3810 * Acquire the oom lock. If that fails, somebody else is
3811 * making progress for us.
3813 if (!mutex_trylock(&oom_lock)) {
3814 *did_some_progress = 1;
3815 schedule_timeout_uninterruptible(1);
3820 * Go through the zonelist yet one more time, keep very high watermark
3821 * here, this is only to catch a parallel oom killing, we must fail if
3822 * we're still under heavy pressure. But make sure that this reclaim
3823 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
3824 * allocation which will never fail due to oom_lock already held.
3826 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
3827 ~__GFP_DIRECT_RECLAIM, order,
3828 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
3832 /* Coredumps can quickly deplete all memory reserves */
3833 if (current->flags & PF_DUMPCORE)
3835 /* The OOM killer will not help higher order allocs */
3836 if (order > PAGE_ALLOC_COSTLY_ORDER)
3839 * We have already exhausted all our reclaim opportunities without any
3840 * success so it is time to admit defeat. We will skip the OOM killer
3841 * because it is very likely that the caller has a more reasonable
3842 * fallback than shooting a random task.
3844 if (gfp_mask & __GFP_RETRY_MAYFAIL)
3846 /* The OOM killer does not needlessly kill tasks for lowmem */
3847 if (ac->high_zoneidx < ZONE_NORMAL)
3849 if (pm_suspended_storage())
3852 * XXX: GFP_NOFS allocations should rather fail than rely on
3853 * other request to make a forward progress.
3854 * We are in an unfortunate situation where out_of_memory cannot
3855 * do much for this context but let's try it to at least get
3856 * access to memory reserved if the current task is killed (see
3857 * out_of_memory). Once filesystems are ready to handle allocation
3858 * failures more gracefully we should just bail out here.
3861 /* The OOM killer may not free memory on a specific node */
3862 if (gfp_mask & __GFP_THISNODE)
3865 /* Exhausted what can be done so it's blame time */
3866 if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
3867 *did_some_progress = 1;
3870 * Help non-failing allocations by giving them access to memory
3873 if (gfp_mask & __GFP_NOFAIL)
3874 page = __alloc_pages_cpuset_fallback(gfp_mask, order,
3875 ALLOC_NO_WATERMARKS, ac);
3878 mutex_unlock(&oom_lock);
3883 * Maximum number of compaction retries wit a progress before OOM
3884 * killer is consider as the only way to move forward.
3886 #define MAX_COMPACT_RETRIES 16
3888 #ifdef CONFIG_COMPACTION
3889 /* Try memory compaction for high-order allocations before reclaim */
3890 static struct page *
3891 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
3892 unsigned int alloc_flags, const struct alloc_context *ac,
3893 enum compact_priority prio, enum compact_result *compact_result)
3895 struct page *page = NULL;
3896 unsigned long pflags;
3897 unsigned int noreclaim_flag;
3902 psi_memstall_enter(&pflags);
3903 noreclaim_flag = memalloc_noreclaim_save();
3905 *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
3908 memalloc_noreclaim_restore(noreclaim_flag);
3909 psi_memstall_leave(&pflags);
3912 * At least in one zone compaction wasn't deferred or skipped, so let's
3913 * count a compaction stall
3915 count_vm_event(COMPACTSTALL);
3917 /* Prep a captured page if available */
3919 prep_new_page(page, order, gfp_mask, alloc_flags);
3921 /* Try get a page from the freelist if available */
3923 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
3926 struct zone *zone = page_zone(page);
3928 zone->compact_blockskip_flush = false;
3929 compaction_defer_reset(zone, order, true);
3930 count_vm_event(COMPACTSUCCESS);
3935 * It's bad if compaction run occurs and fails. The most likely reason
3936 * is that pages exist, but not enough to satisfy watermarks.
3938 count_vm_event(COMPACTFAIL);
3946 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
3947 enum compact_result compact_result,
3948 enum compact_priority *compact_priority,
3949 int *compaction_retries)
3951 int max_retries = MAX_COMPACT_RETRIES;
3954 int retries = *compaction_retries;
3955 enum compact_priority priority = *compact_priority;
3960 if (compaction_made_progress(compact_result))
3961 (*compaction_retries)++;
3964 * compaction considers all the zone as desperately out of memory
3965 * so it doesn't really make much sense to retry except when the
3966 * failure could be caused by insufficient priority
3968 if (compaction_failed(compact_result))
3969 goto check_priority;
3972 * make sure the compaction wasn't deferred or didn't bail out early
3973 * due to locks contention before we declare that we should give up.
3974 * But do not retry if the given zonelist is not suitable for
3977 if (compaction_withdrawn(compact_result)) {
3978 ret = compaction_zonelist_suitable(ac, order, alloc_flags);
3983 * !costly requests are much more important than __GFP_RETRY_MAYFAIL
3984 * costly ones because they are de facto nofail and invoke OOM
3985 * killer to move on while costly can fail and users are ready
3986 * to cope with that. 1/4 retries is rather arbitrary but we
3987 * would need much more detailed feedback from compaction to
3988 * make a better decision.
3990 if (order > PAGE_ALLOC_COSTLY_ORDER)
3992 if (*compaction_retries <= max_retries) {
3998 * Make sure there are attempts at the highest priority if we exhausted
3999 * all retries or failed at the lower priorities.
4002 min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
4003 MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
4005 if (*compact_priority > min_priority) {
4006 (*compact_priority)--;
4007 *compaction_retries = 0;
4011 trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
4015 static inline struct page *
4016 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4017 unsigned int alloc_flags, const struct alloc_context *ac,
4018 enum compact_priority prio, enum compact_result *compact_result)
4020 *compact_result = COMPACT_SKIPPED;
4025 should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
4026 enum compact_result compact_result,
4027 enum compact_priority *compact_priority,
4028 int *compaction_retries)
4033 if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
4037 * There are setups with compaction disabled which would prefer to loop
4038 * inside the allocator rather than hit the oom killer prematurely.
4039 * Let's give them a good hope and keep retrying while the order-0
4040 * watermarks are OK.
4042 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
4044 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
4045 ac_classzone_idx(ac), alloc_flags))
4050 #endif /* CONFIG_COMPACTION */
4052 #ifdef CONFIG_LOCKDEP
4053 static struct lockdep_map __fs_reclaim_map =
4054 STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
4056 static bool __need_fs_reclaim(gfp_t gfp_mask)
4058 gfp_mask = current_gfp_context(gfp_mask);
4060 /* no reclaim without waiting on it */
4061 if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
4064 /* this guy won't enter reclaim */
4065 if (current->flags & PF_MEMALLOC)
4068 /* We're only interested __GFP_FS allocations for now */
4069 if (!(gfp_mask & __GFP_FS))
4072 if (gfp_mask & __GFP_NOLOCKDEP)
4078 void __fs_reclaim_acquire(void)
4080 lock_map_acquire(&__fs_reclaim_map);
4083 void __fs_reclaim_release(void)
4085 lock_map_release(&__fs_reclaim_map);
4088 void fs_reclaim_acquire(gfp_t gfp_mask)
4090 if (__need_fs_reclaim(gfp_mask))
4091 __fs_reclaim_acquire();
4093 EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
4095 void fs_reclaim_release(gfp_t gfp_mask)
4097 if (__need_fs_reclaim(gfp_mask))
4098 __fs_reclaim_release();
4100 EXPORT_SYMBOL_GPL(fs_reclaim_release);
4103 /* Perform direct synchronous page reclaim */
4105 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
4106 const struct alloc_context *ac)
4109 unsigned int noreclaim_flag;
4110 unsigned long pflags;
4114 /* We now go into synchronous reclaim */
4115 cpuset_memory_pressure_bump();
4116 psi_memstall_enter(&pflags);
4117 fs_reclaim_acquire(gfp_mask);
4118 noreclaim_flag = memalloc_noreclaim_save();
4120 progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
4123 memalloc_noreclaim_restore(noreclaim_flag);
4124 fs_reclaim_release(gfp_mask);
4125 psi_memstall_leave(&pflags);
4132 /* The really slow allocator path where we enter direct reclaim */
4133 static inline struct page *
4134 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
4135 unsigned int alloc_flags, const struct alloc_context *ac,
4136 unsigned long *did_some_progress)
4138 struct page *page = NULL;
4139 bool drained = false;
4141 *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
4142 if (unlikely(!(*did_some_progress)))
4146 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4149 * If an allocation failed after direct reclaim, it could be because
4150 * pages are pinned on the per-cpu lists or in high alloc reserves.
4151 * Shrink them them and try again
4153 if (!page && !drained) {
4154 unreserve_highatomic_pageblock(ac, false);
4155 drain_all_pages(NULL);
4163 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
4164 const struct alloc_context *ac)
4168 pg_data_t *last_pgdat = NULL;
4169 enum zone_type high_zoneidx = ac->high_zoneidx;
4171 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, high_zoneidx,
4173 if (last_pgdat != zone->zone_pgdat)
4174 wakeup_kswapd(zone, gfp_mask, order, high_zoneidx);
4175 last_pgdat = zone->zone_pgdat;
4179 static inline unsigned int
4180 gfp_to_alloc_flags(gfp_t gfp_mask)
4182 unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
4184 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
4185 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
4188 * The caller may dip into page reserves a bit more if the caller
4189 * cannot run direct reclaim, or if the caller has realtime scheduling
4190 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
4191 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
4193 alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
4195 if (gfp_mask & __GFP_ATOMIC) {
4197 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4198 * if it can't schedule.
4200 if (!(gfp_mask & __GFP_NOMEMALLOC))
4201 alloc_flags |= ALLOC_HARDER;
4203 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
4204 * comment for __cpuset_node_allowed().
4206 alloc_flags &= ~ALLOC_CPUSET;
4207 } else if (unlikely(rt_task(current)) && !in_interrupt())
4208 alloc_flags |= ALLOC_HARDER;
4210 if (gfp_mask & __GFP_KSWAPD_RECLAIM)
4211 alloc_flags |= ALLOC_KSWAPD;
4214 if (gfpflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
4215 alloc_flags |= ALLOC_CMA;
4220 static bool oom_reserves_allowed(struct task_struct *tsk)
4222 if (!tsk_is_oom_victim(tsk))
4226 * !MMU doesn't have oom reaper so give access to memory reserves
4227 * only to the thread with TIF_MEMDIE set
4229 if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
4236 * Distinguish requests which really need access to full memory
4237 * reserves from oom victims which can live with a portion of it
4239 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4241 if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4243 if (gfp_mask & __GFP_MEMALLOC)
4244 return ALLOC_NO_WATERMARKS;
4245 if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
4246 return ALLOC_NO_WATERMARKS;
4247 if (!in_interrupt()) {
4248 if (current->flags & PF_MEMALLOC)
4249 return ALLOC_NO_WATERMARKS;
4250 else if (oom_reserves_allowed(current))
4257 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4259 return !!__gfp_pfmemalloc_flags(gfp_mask);
4263 * Checks whether it makes sense to retry the reclaim to make a forward progress
4264 * for the given allocation request.
4266 * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4267 * without success, or when we couldn't even meet the watermark if we
4268 * reclaimed all remaining pages on the LRU lists.
4270 * Returns true if a retry is viable or false to enter the oom path.
4273 should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4274 struct alloc_context *ac, int alloc_flags,
4275 bool did_some_progress, int *no_progress_loops)
4282 * Costly allocations might have made a progress but this doesn't mean
4283 * their order will become available due to high fragmentation so
4284 * always increment the no progress counter for them
4286 if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4287 *no_progress_loops = 0;
4289 (*no_progress_loops)++;
4292 * Make sure we converge to OOM if we cannot make any progress
4293 * several times in the row.
4295 if (*no_progress_loops > MAX_RECLAIM_RETRIES) {
4296 /* Before OOM, exhaust highatomic_reserve */
4297 return unreserve_highatomic_pageblock(ac, true);
4301 * Keep reclaiming pages while there is a chance this will lead
4302 * somewhere. If none of the target zones can satisfy our allocation
4303 * request even if all reclaimable pages are considered then we are
4304 * screwed and have to go OOM.
4306 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
4308 unsigned long available;
4309 unsigned long reclaimable;
4310 unsigned long min_wmark = min_wmark_pages(zone);
4313 available = reclaimable = zone_reclaimable_pages(zone);
4314 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
4317 * Would the allocation succeed if we reclaimed all
4318 * reclaimable pages?
4320 wmark = __zone_watermark_ok(zone, order, min_wmark,
4321 ac_classzone_idx(ac), alloc_flags, available);
4322 trace_reclaim_retry_zone(z, order, reclaimable,
4323 available, min_wmark, *no_progress_loops, wmark);
4326 * If we didn't make any progress and have a lot of
4327 * dirty + writeback pages then we should wait for
4328 * an IO to complete to slow down the reclaim and
4329 * prevent from pre mature OOM
4331 if (!did_some_progress) {
4332 unsigned long write_pending;
4334 write_pending = zone_page_state_snapshot(zone,
4335 NR_ZONE_WRITE_PENDING);
4337 if (2 * write_pending > reclaimable) {
4338 congestion_wait(BLK_RW_ASYNC, HZ/10);
4350 * Memory allocation/reclaim might be called from a WQ context and the
4351 * current implementation of the WQ concurrency control doesn't
4352 * recognize that a particular WQ is congested if the worker thread is
4353 * looping without ever sleeping. Therefore we have to do a short sleep
4354 * here rather than calling cond_resched().
4356 if (current->flags & PF_WQ_WORKER)
4357 schedule_timeout_uninterruptible(1);
4364 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4367 * It's possible that cpuset's mems_allowed and the nodemask from
4368 * mempolicy don't intersect. This should be normally dealt with by
4369 * policy_nodemask(), but it's possible to race with cpuset update in
4370 * such a way the check therein was true, and then it became false
4371 * before we got our cpuset_mems_cookie here.
4372 * This assumes that for all allocations, ac->nodemask can come only
4373 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4374 * when it does not intersect with the cpuset restrictions) or the
4375 * caller can deal with a violated nodemask.
4377 if (cpusets_enabled() && ac->nodemask &&
4378 !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4379 ac->nodemask = NULL;
4384 * When updating a task's mems_allowed or mempolicy nodemask, it is
4385 * possible to race with parallel threads in such a way that our
4386 * allocation can fail while the mask is being updated. If we are about
4387 * to fail, check if the cpuset changed during allocation and if so,
4390 if (read_mems_allowed_retry(cpuset_mems_cookie))
4396 static inline struct page *
4397 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
4398 struct alloc_context *ac)
4400 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
4401 const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
4402 struct page *page = NULL;
4403 unsigned int alloc_flags;
4404 unsigned long did_some_progress;
4405 enum compact_priority compact_priority;
4406 enum compact_result compact_result;
4407 int compaction_retries;
4408 int no_progress_loops;
4409 unsigned int cpuset_mems_cookie;
4413 * We also sanity check to catch abuse of atomic reserves being used by
4414 * callers that are not in atomic context.
4416 if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
4417 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
4418 gfp_mask &= ~__GFP_ATOMIC;
4421 compaction_retries = 0;
4422 no_progress_loops = 0;
4423 compact_priority = DEF_COMPACT_PRIORITY;
4424 cpuset_mems_cookie = read_mems_allowed_begin();
4427 * The fast path uses conservative alloc_flags to succeed only until
4428 * kswapd needs to be woken up, and to avoid the cost of setting up
4429 * alloc_flags precisely. So we do that now.
4431 alloc_flags = gfp_to_alloc_flags(gfp_mask);
4434 * We need to recalculate the starting point for the zonelist iterator
4435 * because we might have used different nodemask in the fast path, or
4436 * there was a cpuset modification and we are retrying - otherwise we
4437 * could end up iterating over non-eligible zones endlessly.
4439 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4440 ac->high_zoneidx, ac->nodemask);
4441 if (!ac->preferred_zoneref->zone)
4444 if (alloc_flags & ALLOC_KSWAPD)
4445 wake_all_kswapds(order, gfp_mask, ac);
4448 * The adjusted alloc_flags might result in immediate success, so try
4451 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4456 * For costly allocations, try direct compaction first, as it's likely
4457 * that we have enough base pages and don't need to reclaim. For non-
4458 * movable high-order allocations, do that as well, as compaction will
4459 * try prevent permanent fragmentation by migrating from blocks of the
4461 * Don't try this for allocations that are allowed to ignore
4462 * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
4464 if (can_direct_reclaim &&
4466 (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
4467 && !gfp_pfmemalloc_allowed(gfp_mask)) {
4468 page = __alloc_pages_direct_compact(gfp_mask, order,
4470 INIT_COMPACT_PRIORITY,
4476 * Checks for costly allocations with __GFP_NORETRY, which
4477 * includes THP page fault allocations
4479 if (costly_order && (gfp_mask & __GFP_NORETRY)) {
4481 * If compaction is deferred for high-order allocations,
4482 * it is because sync compaction recently failed. If
4483 * this is the case and the caller requested a THP
4484 * allocation, we do not want to heavily disrupt the
4485 * system, so we fail the allocation instead of entering
4488 if (compact_result == COMPACT_DEFERRED)
4492 * Looks like reclaim/compaction is worth trying, but
4493 * sync compaction could be very expensive, so keep
4494 * using async compaction.
4496 compact_priority = INIT_COMPACT_PRIORITY;
4501 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4502 if (alloc_flags & ALLOC_KSWAPD)
4503 wake_all_kswapds(order, gfp_mask, ac);
4505 reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
4507 alloc_flags = reserve_flags;
4510 * Reset the nodemask and zonelist iterators if memory policies can be
4511 * ignored. These allocations are high priority and system rather than
4514 if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
4515 ac->nodemask = NULL;
4516 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4517 ac->high_zoneidx, ac->nodemask);
4520 /* Attempt with potentially adjusted zonelist and alloc_flags */
4521 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4525 /* Caller is not willing to reclaim, we can't balance anything */
4526 if (!can_direct_reclaim)
4529 /* Avoid recursion of direct reclaim */
4530 if (current->flags & PF_MEMALLOC)
4533 /* Try direct reclaim and then allocating */
4534 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
4535 &did_some_progress);
4539 /* Try direct compaction and then allocating */
4540 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
4541 compact_priority, &compact_result);
4545 /* Do not loop if specifically requested */
4546 if (gfp_mask & __GFP_NORETRY)
4550 * Do not retry costly high order allocations unless they are
4551 * __GFP_RETRY_MAYFAIL
4553 if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL))
4556 if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
4557 did_some_progress > 0, &no_progress_loops))
4561 * It doesn't make any sense to retry for the compaction if the order-0
4562 * reclaim is not able to make any progress because the current
4563 * implementation of the compaction depends on the sufficient amount
4564 * of free memory (see __compaction_suitable)
4566 if (did_some_progress > 0 &&
4567 should_compact_retry(ac, order, alloc_flags,
4568 compact_result, &compact_priority,
4569 &compaction_retries))
4573 /* Deal with possible cpuset update races before we start OOM killing */
4574 if (check_retry_cpuset(cpuset_mems_cookie, ac))
4577 /* Reclaim has failed us, start killing things */
4578 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
4582 /* Avoid allocations with no watermarks from looping endlessly */
4583 if (tsk_is_oom_victim(current) &&
4584 (alloc_flags == ALLOC_OOM ||
4585 (gfp_mask & __GFP_NOMEMALLOC)))
4588 /* Retry as long as the OOM killer is making progress */
4589 if (did_some_progress) {
4590 no_progress_loops = 0;
4595 /* Deal with possible cpuset update races before we fail */
4596 if (check_retry_cpuset(cpuset_mems_cookie, ac))
4600 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
4603 if (gfp_mask & __GFP_NOFAIL) {
4605 * All existing users of the __GFP_NOFAIL are blockable, so warn
4606 * of any new users that actually require GFP_NOWAIT
4608 if (WARN_ON_ONCE(!can_direct_reclaim))
4612 * PF_MEMALLOC request from this context is rather bizarre
4613 * because we cannot reclaim anything and only can loop waiting
4614 * for somebody to do a work for us
4616 WARN_ON_ONCE(current->flags & PF_MEMALLOC);
4619 * non failing costly orders are a hard requirement which we
4620 * are not prepared for much so let's warn about these users
4621 * so that we can identify them and convert them to something
4624 WARN_ON_ONCE(order > PAGE_ALLOC_COSTLY_ORDER);
4627 * Help non-failing allocations by giving them access to memory
4628 * reserves but do not use ALLOC_NO_WATERMARKS because this
4629 * could deplete whole memory reserves which would just make
4630 * the situation worse
4632 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac);
4640 warn_alloc(gfp_mask, ac->nodemask,
4641 "page allocation failure: order:%u", order);
4646 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
4647 int preferred_nid, nodemask_t *nodemask,
4648 struct alloc_context *ac, gfp_t *alloc_mask,
4649 unsigned int *alloc_flags)
4651 ac->high_zoneidx = gfp_zone(gfp_mask);
4652 ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
4653 ac->nodemask = nodemask;
4654 ac->migratetype = gfpflags_to_migratetype(gfp_mask);
4656 if (cpusets_enabled()) {
4657 *alloc_mask |= __GFP_HARDWALL;
4659 ac->nodemask = &cpuset_current_mems_allowed;
4661 *alloc_flags |= ALLOC_CPUSET;
4664 fs_reclaim_acquire(gfp_mask);
4665 fs_reclaim_release(gfp_mask);
4667 might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
4669 if (should_fail_alloc_page(gfp_mask, order))
4672 if (IS_ENABLED(CONFIG_CMA) && ac->migratetype == MIGRATE_MOVABLE)
4673 *alloc_flags |= ALLOC_CMA;
4678 /* Determine whether to spread dirty pages and what the first usable zone */
4679 static inline void finalise_ac(gfp_t gfp_mask, struct alloc_context *ac)
4681 /* Dirty zone balancing only done in the fast path */
4682 ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
4685 * The preferred zone is used for statistics but crucially it is
4686 * also used as the starting point for the zonelist iterator. It
4687 * may get reset for allocations that ignore memory policies.
4689 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4690 ac->high_zoneidx, ac->nodemask);
4694 * This is the 'heart' of the zoned buddy allocator.
4697 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order, int preferred_nid,
4698 nodemask_t *nodemask)
4701 unsigned int alloc_flags = ALLOC_WMARK_LOW;
4702 gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
4703 struct alloc_context ac = { };
4706 * There are several places where we assume that the order value is sane
4707 * so bail out early if the request is out of bound.
4709 if (unlikely(order >= MAX_ORDER)) {
4710 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
4714 gfp_mask &= gfp_allowed_mask;
4715 alloc_mask = gfp_mask;
4716 if (!prepare_alloc_pages(gfp_mask, order, preferred_nid, nodemask, &ac, &alloc_mask, &alloc_flags))
4719 finalise_ac(gfp_mask, &ac);
4722 * Forbid the first pass from falling back to types that fragment
4723 * memory until all local zones are considered.
4725 alloc_flags |= alloc_flags_nofragment(ac.preferred_zoneref->zone, gfp_mask);
4727 /* First allocation attempt */
4728 page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
4733 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
4734 * resp. GFP_NOIO which has to be inherited for all allocation requests
4735 * from a particular context which has been marked by
4736 * memalloc_no{fs,io}_{save,restore}.
4738 alloc_mask = current_gfp_context(gfp_mask);
4739 ac.spread_dirty_pages = false;
4742 * Restore the original nodemask if it was potentially replaced with
4743 * &cpuset_current_mems_allowed to optimize the fast-path attempt.
4745 if (unlikely(ac.nodemask != nodemask))
4746 ac.nodemask = nodemask;
4748 page = __alloc_pages_slowpath(alloc_mask, order, &ac);
4751 if (memcg_kmem_enabled() && (gfp_mask & __GFP_ACCOUNT) && page &&
4752 unlikely(__memcg_kmem_charge(page, gfp_mask, order) != 0)) {
4753 __free_pages(page, order);
4757 trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
4761 EXPORT_SYMBOL(__alloc_pages_nodemask);
4764 * Common helper functions. Never use with __GFP_HIGHMEM because the returned
4765 * address cannot represent highmem pages. Use alloc_pages and then kmap if
4766 * you need to access high mem.
4768 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
4772 page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order);
4775 return (unsigned long) page_address(page);
4777 EXPORT_SYMBOL(__get_free_pages);
4779 unsigned long get_zeroed_page(gfp_t gfp_mask)
4781 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
4783 EXPORT_SYMBOL(get_zeroed_page);
4785 static inline void free_the_page(struct page *page, unsigned int order)
4787 if (order == 0) /* Via pcp? */
4788 free_unref_page(page);
4790 __free_pages_ok(page, order);
4793 void __free_pages(struct page *page, unsigned int order)
4795 if (put_page_testzero(page))
4796 free_the_page(page, order);
4798 EXPORT_SYMBOL(__free_pages);
4800 void free_pages(unsigned long addr, unsigned int order)
4803 VM_BUG_ON(!virt_addr_valid((void *)addr));
4804 __free_pages(virt_to_page((void *)addr), order);
4808 EXPORT_SYMBOL(free_pages);
4812 * An arbitrary-length arbitrary-offset area of memory which resides
4813 * within a 0 or higher order page. Multiple fragments within that page
4814 * are individually refcounted, in the page's reference counter.
4816 * The page_frag functions below provide a simple allocation framework for
4817 * page fragments. This is used by the network stack and network device
4818 * drivers to provide a backing region of memory for use as either an
4819 * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
4821 static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
4824 struct page *page = NULL;
4825 gfp_t gfp = gfp_mask;
4827 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4828 gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
4830 page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
4831 PAGE_FRAG_CACHE_MAX_ORDER);
4832 nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
4834 if (unlikely(!page))
4835 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
4837 nc->va = page ? page_address(page) : NULL;
4842 void __page_frag_cache_drain(struct page *page, unsigned int count)
4844 VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
4846 if (page_ref_sub_and_test(page, count))
4847 free_the_page(page, compound_order(page));
4849 EXPORT_SYMBOL(__page_frag_cache_drain);
4851 void *page_frag_alloc(struct page_frag_cache *nc,
4852 unsigned int fragsz, gfp_t gfp_mask)
4854 unsigned int size = PAGE_SIZE;
4858 if (unlikely(!nc->va)) {
4860 page = __page_frag_cache_refill(nc, gfp_mask);
4864 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4865 /* if size can vary use size else just use PAGE_SIZE */
4868 /* Even if we own the page, we do not use atomic_set().
4869 * This would break get_page_unless_zero() users.
4871 page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
4873 /* reset page count bias and offset to start of new frag */
4874 nc->pfmemalloc = page_is_pfmemalloc(page);
4875 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
4879 offset = nc->offset - fragsz;
4880 if (unlikely(offset < 0)) {
4881 page = virt_to_page(nc->va);
4883 if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
4886 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4887 /* if size can vary use size else just use PAGE_SIZE */
4890 /* OK, page count is 0, we can safely set it */
4891 set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
4893 /* reset page count bias and offset to start of new frag */
4894 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
4895 offset = size - fragsz;
4899 nc->offset = offset;
4901 return nc->va + offset;
4903 EXPORT_SYMBOL(page_frag_alloc);
4906 * Frees a page fragment allocated out of either a compound or order 0 page.
4908 void page_frag_free(void *addr)
4910 struct page *page = virt_to_head_page(addr);
4912 if (unlikely(put_page_testzero(page)))
4913 free_the_page(page, compound_order(page));
4915 EXPORT_SYMBOL(page_frag_free);
4917 static void *make_alloc_exact(unsigned long addr, unsigned int order,
4921 unsigned long alloc_end = addr + (PAGE_SIZE << order);
4922 unsigned long used = addr + PAGE_ALIGN(size);
4924 split_page(virt_to_page((void *)addr), order);
4925 while (used < alloc_end) {
4930 return (void *)addr;
4934 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
4935 * @size: the number of bytes to allocate
4936 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
4938 * This function is similar to alloc_pages(), except that it allocates the
4939 * minimum number of pages to satisfy the request. alloc_pages() can only
4940 * allocate memory in power-of-two pages.
4942 * This function is also limited by MAX_ORDER.
4944 * Memory allocated by this function must be released by free_pages_exact().
4946 * Return: pointer to the allocated area or %NULL in case of error.
4948 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
4950 unsigned int order = get_order(size);
4953 if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
4954 gfp_mask &= ~__GFP_COMP;
4956 addr = __get_free_pages(gfp_mask, order);
4957 return make_alloc_exact(addr, order, size);
4959 EXPORT_SYMBOL(alloc_pages_exact);
4962 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
4964 * @nid: the preferred node ID where memory should be allocated
4965 * @size: the number of bytes to allocate
4966 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
4968 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
4971 * Return: pointer to the allocated area or %NULL in case of error.
4973 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
4975 unsigned int order = get_order(size);
4978 if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
4979 gfp_mask &= ~__GFP_COMP;
4981 p = alloc_pages_node(nid, gfp_mask, order);
4984 return make_alloc_exact((unsigned long)page_address(p), order, size);
4988 * free_pages_exact - release memory allocated via alloc_pages_exact()
4989 * @virt: the value returned by alloc_pages_exact.
4990 * @size: size of allocation, same value as passed to alloc_pages_exact().
4992 * Release the memory allocated by a previous call to alloc_pages_exact.
4994 void free_pages_exact(void *virt, size_t size)
4996 unsigned long addr = (unsigned long)virt;
4997 unsigned long end = addr + PAGE_ALIGN(size);
4999 while (addr < end) {
5004 EXPORT_SYMBOL(free_pages_exact);
5007 * nr_free_zone_pages - count number of pages beyond high watermark
5008 * @offset: The zone index of the highest zone
5010 * nr_free_zone_pages() counts the number of pages which are beyond the
5011 * high watermark within all zones at or below a given zone index. For each
5012 * zone, the number of pages is calculated as:
5014 * nr_free_zone_pages = managed_pages - high_pages
5016 * Return: number of pages beyond high watermark.
5018 static unsigned long nr_free_zone_pages(int offset)
5023 /* Just pick one node, since fallback list is circular */
5024 unsigned long sum = 0;
5026 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
5028 for_each_zone_zonelist(zone, z, zonelist, offset) {
5029 unsigned long size = zone_managed_pages(zone);
5030 unsigned long high = high_wmark_pages(zone);
5039 * nr_free_buffer_pages - count number of pages beyond high watermark
5041 * nr_free_buffer_pages() counts the number of pages which are beyond the high
5042 * watermark within ZONE_DMA and ZONE_NORMAL.
5044 * Return: number of pages beyond high watermark within ZONE_DMA and
5047 unsigned long nr_free_buffer_pages(void)
5049 return nr_free_zone_pages(gfp_zone(GFP_USER));
5051 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
5054 * nr_free_pagecache_pages - count number of pages beyond high watermark
5056 * nr_free_pagecache_pages() counts the number of pages which are beyond the
5057 * high watermark within all zones.
5059 * Return: number of pages beyond high watermark within all zones.
5061 unsigned long nr_free_pagecache_pages(void)
5063 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
5066 static inline void show_node(struct zone *zone)
5068 if (IS_ENABLED(CONFIG_NUMA))
5069 printk("Node %d ", zone_to_nid(zone));
5072 long si_mem_available(void)
5075 unsigned long pagecache;
5076 unsigned long wmark_low = 0;
5077 unsigned long pages[NR_LRU_LISTS];
5078 unsigned long reclaimable;
5082 for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
5083 pages[lru] = global_node_page_state(NR_LRU_BASE + lru);
5086 wmark_low += low_wmark_pages(zone);
5089 * Estimate the amount of memory available for userspace allocations,
5090 * without causing swapping.
5092 available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages;
5095 * Not all the page cache can be freed, otherwise the system will
5096 * start swapping. Assume at least half of the page cache, or the
5097 * low watermark worth of cache, needs to stay.
5099 pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
5100 pagecache -= min(pagecache / 2, wmark_low);
5101 available += pagecache;
5104 * Part of the reclaimable slab and other kernel memory consists of
5105 * items that are in use, and cannot be freed. Cap this estimate at the
5108 reclaimable = global_node_page_state(NR_SLAB_RECLAIMABLE) +
5109 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE);
5110 available += reclaimable - min(reclaimable / 2, wmark_low);
5116 EXPORT_SYMBOL_GPL(si_mem_available);
5118 void si_meminfo(struct sysinfo *val)
5120 val->totalram = totalram_pages();
5121 val->sharedram = global_node_page_state(NR_SHMEM);
5122 val->freeram = global_zone_page_state(NR_FREE_PAGES);
5123 val->bufferram = nr_blockdev_pages();
5124 val->totalhigh = totalhigh_pages();
5125 val->freehigh = nr_free_highpages();
5126 val->mem_unit = PAGE_SIZE;
5129 EXPORT_SYMBOL(si_meminfo);
5132 void si_meminfo_node(struct sysinfo *val, int nid)
5134 int zone_type; /* needs to be signed */
5135 unsigned long managed_pages = 0;
5136 unsigned long managed_highpages = 0;
5137 unsigned long free_highpages = 0;
5138 pg_data_t *pgdat = NODE_DATA(nid);
5140 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
5141 managed_pages += zone_managed_pages(&pgdat->node_zones[zone_type]);
5142 val->totalram = managed_pages;
5143 val->sharedram = node_page_state(pgdat, NR_SHMEM);
5144 val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES);
5145 #ifdef CONFIG_HIGHMEM
5146 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
5147 struct zone *zone = &pgdat->node_zones[zone_type];
5149 if (is_highmem(zone)) {
5150 managed_highpages += zone_managed_pages(zone);
5151 free_highpages += zone_page_state(zone, NR_FREE_PAGES);
5154 val->totalhigh = managed_highpages;
5155 val->freehigh = free_highpages;
5157 val->totalhigh = managed_highpages;
5158 val->freehigh = free_highpages;
5160 val->mem_unit = PAGE_SIZE;
5165 * Determine whether the node should be displayed or not, depending on whether
5166 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
5168 static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask)
5170 if (!(flags & SHOW_MEM_FILTER_NODES))
5174 * no node mask - aka implicit memory numa policy. Do not bother with
5175 * the synchronization - read_mems_allowed_begin - because we do not
5176 * have to be precise here.
5179 nodemask = &cpuset_current_mems_allowed;
5181 return !node_isset(nid, *nodemask);
5184 #define K(x) ((x) << (PAGE_SHIFT-10))
5186 static void show_migration_types(unsigned char type)
5188 static const char types[MIGRATE_TYPES] = {
5189 [MIGRATE_UNMOVABLE] = 'U',
5190 [MIGRATE_MOVABLE] = 'M',
5191 [MIGRATE_RECLAIMABLE] = 'E',
5192 [MIGRATE_HIGHATOMIC] = 'H',
5194 [MIGRATE_CMA] = 'C',
5196 #ifdef CONFIG_MEMORY_ISOLATION
5197 [MIGRATE_ISOLATE] = 'I',
5200 char tmp[MIGRATE_TYPES + 1];
5204 for (i = 0; i < MIGRATE_TYPES; i++) {
5205 if (type & (1 << i))
5210 printk(KERN_CONT "(%s) ", tmp);
5214 * Show free area list (used inside shift_scroll-lock stuff)
5215 * We also calculate the percentage fragmentation. We do this by counting the
5216 * memory on each free list with the exception of the first item on the list.
5219 * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
5222 void show_free_areas(unsigned int filter, nodemask_t *nodemask)
5224 unsigned long free_pcp = 0;
5229 for_each_populated_zone(zone) {
5230 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5233 for_each_online_cpu(cpu)
5234 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5237 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
5238 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
5239 " unevictable:%lu dirty:%lu writeback:%lu unstable:%lu\n"
5240 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
5241 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
5242 " free:%lu free_pcp:%lu free_cma:%lu\n",
5243 global_node_page_state(NR_ACTIVE_ANON),
5244 global_node_page_state(NR_INACTIVE_ANON),
5245 global_node_page_state(NR_ISOLATED_ANON),
5246 global_node_page_state(NR_ACTIVE_FILE),
5247 global_node_page_state(NR_INACTIVE_FILE),
5248 global_node_page_state(NR_ISOLATED_FILE),
5249 global_node_page_state(NR_UNEVICTABLE),
5250 global_node_page_state(NR_FILE_DIRTY),
5251 global_node_page_state(NR_WRITEBACK),
5252 global_node_page_state(NR_UNSTABLE_NFS),
5253 global_node_page_state(NR_SLAB_RECLAIMABLE),
5254 global_node_page_state(NR_SLAB_UNRECLAIMABLE),
5255 global_node_page_state(NR_FILE_MAPPED),
5256 global_node_page_state(NR_SHMEM),
5257 global_zone_page_state(NR_PAGETABLE),
5258 global_zone_page_state(NR_BOUNCE),
5259 global_zone_page_state(NR_FREE_PAGES),
5261 global_zone_page_state(NR_FREE_CMA_PAGES));
5263 for_each_online_pgdat(pgdat) {
5264 if (show_mem_node_skip(filter, pgdat->node_id, nodemask))
5268 " active_anon:%lukB"
5269 " inactive_anon:%lukB"
5270 " active_file:%lukB"
5271 " inactive_file:%lukB"
5272 " unevictable:%lukB"
5273 " isolated(anon):%lukB"
5274 " isolated(file):%lukB"
5279 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5281 " shmem_pmdmapped: %lukB"
5284 " writeback_tmp:%lukB"
5286 " all_unreclaimable? %s"
5289 K(node_page_state(pgdat, NR_ACTIVE_ANON)),
5290 K(node_page_state(pgdat, NR_INACTIVE_ANON)),
5291 K(node_page_state(pgdat, NR_ACTIVE_FILE)),
5292 K(node_page_state(pgdat, NR_INACTIVE_FILE)),
5293 K(node_page_state(pgdat, NR_UNEVICTABLE)),
5294 K(node_page_state(pgdat, NR_ISOLATED_ANON)),
5295 K(node_page_state(pgdat, NR_ISOLATED_FILE)),
5296 K(node_page_state(pgdat, NR_FILE_MAPPED)),
5297 K(node_page_state(pgdat, NR_FILE_DIRTY)),
5298 K(node_page_state(pgdat, NR_WRITEBACK)),
5299 K(node_page_state(pgdat, NR_SHMEM)),
5300 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5301 K(node_page_state(pgdat, NR_SHMEM_THPS) * HPAGE_PMD_NR),
5302 K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED)
5304 K(node_page_state(pgdat, NR_ANON_THPS) * HPAGE_PMD_NR),
5306 K(node_page_state(pgdat, NR_WRITEBACK_TEMP)),
5307 K(node_page_state(pgdat, NR_UNSTABLE_NFS)),
5308 pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ?
5312 for_each_populated_zone(zone) {
5315 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5319 for_each_online_cpu(cpu)
5320 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5329 " active_anon:%lukB"
5330 " inactive_anon:%lukB"
5331 " active_file:%lukB"
5332 " inactive_file:%lukB"
5333 " unevictable:%lukB"
5334 " writepending:%lukB"
5338 " kernel_stack:%lukB"
5346 K(zone_page_state(zone, NR_FREE_PAGES)),
5347 K(min_wmark_pages(zone)),
5348 K(low_wmark_pages(zone)),
5349 K(high_wmark_pages(zone)),
5350 K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)),
5351 K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)),
5352 K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)),
5353 K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)),
5354 K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)),
5355 K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)),
5356 K(zone->present_pages),
5357 K(zone_managed_pages(zone)),
5358 K(zone_page_state(zone, NR_MLOCK)),
5359 zone_page_state(zone, NR_KERNEL_STACK_KB),
5360 K(zone_page_state(zone, NR_PAGETABLE)),
5361 K(zone_page_state(zone, NR_BOUNCE)),
5363 K(this_cpu_read(zone->pageset->pcp.count)),
5364 K(zone_page_state(zone, NR_FREE_CMA_PAGES)));
5365 printk("lowmem_reserve[]:");
5366 for (i = 0; i < MAX_NR_ZONES; i++)
5367 printk(KERN_CONT " %ld", zone->lowmem_reserve[i]);
5368 printk(KERN_CONT "\n");
5371 for_each_populated_zone(zone) {
5373 unsigned long nr[MAX_ORDER], flags, total = 0;
5374 unsigned char types[MAX_ORDER];
5376 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5379 printk(KERN_CONT "%s: ", zone->name);
5381 spin_lock_irqsave(&zone->lock, flags);
5382 for (order = 0; order < MAX_ORDER; order++) {
5383 struct free_area *area = &zone->free_area[order];
5386 nr[order] = area->nr_free;
5387 total += nr[order] << order;
5390 for (type = 0; type < MIGRATE_TYPES; type++) {
5391 if (!free_area_empty(area, type))
5392 types[order] |= 1 << type;
5395 spin_unlock_irqrestore(&zone->lock, flags);
5396 for (order = 0; order < MAX_ORDER; order++) {
5397 printk(KERN_CONT "%lu*%lukB ",
5398 nr[order], K(1UL) << order);
5400 show_migration_types(types[order]);
5402 printk(KERN_CONT "= %lukB\n", K(total));
5405 hugetlb_show_meminfo();
5407 printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES));
5409 show_swap_cache_info();
5412 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
5414 zoneref->zone = zone;
5415 zoneref->zone_idx = zone_idx(zone);
5419 * Builds allocation fallback zone lists.
5421 * Add all populated zones of a node to the zonelist.
5423 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
5426 enum zone_type zone_type = MAX_NR_ZONES;
5431 zone = pgdat->node_zones + zone_type;
5432 if (managed_zone(zone)) {
5433 zoneref_set_zone(zone, &zonerefs[nr_zones++]);
5434 check_highest_zone(zone_type);
5436 } while (zone_type);
5443 static int __parse_numa_zonelist_order(char *s)
5446 * We used to support different zonlists modes but they turned
5447 * out to be just not useful. Let's keep the warning in place
5448 * if somebody still use the cmd line parameter so that we do
5449 * not fail it silently
5451 if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
5452 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s);
5458 static __init int setup_numa_zonelist_order(char *s)
5463 return __parse_numa_zonelist_order(s);
5465 early_param("numa_zonelist_order", setup_numa_zonelist_order);
5467 char numa_zonelist_order[] = "Node";
5470 * sysctl handler for numa_zonelist_order
5472 int numa_zonelist_order_handler(struct ctl_table *table, int write,
5473 void __user *buffer, size_t *length,
5480 return proc_dostring(table, write, buffer, length, ppos);
5481 str = memdup_user_nul(buffer, 16);
5483 return PTR_ERR(str);
5485 ret = __parse_numa_zonelist_order(str);
5491 #define MAX_NODE_LOAD (nr_online_nodes)
5492 static int node_load[MAX_NUMNODES];
5495 * find_next_best_node - find the next node that should appear in a given node's fallback list
5496 * @node: node whose fallback list we're appending
5497 * @used_node_mask: nodemask_t of already used nodes
5499 * We use a number of factors to determine which is the next node that should
5500 * appear on a given node's fallback list. The node should not have appeared
5501 * already in @node's fallback list, and it should be the next closest node
5502 * according to the distance array (which contains arbitrary distance values
5503 * from each node to each node in the system), and should also prefer nodes
5504 * with no CPUs, since presumably they'll have very little allocation pressure
5505 * on them otherwise.
5507 * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
5509 static int find_next_best_node(int node, nodemask_t *used_node_mask)
5512 int min_val = INT_MAX;
5513 int best_node = NUMA_NO_NODE;
5514 const struct cpumask *tmp = cpumask_of_node(0);
5516 /* Use the local node if we haven't already */
5517 if (!node_isset(node, *used_node_mask)) {
5518 node_set(node, *used_node_mask);
5522 for_each_node_state(n, N_MEMORY) {
5524 /* Don't want a node to appear more than once */
5525 if (node_isset(n, *used_node_mask))
5528 /* Use the distance array to find the distance */
5529 val = node_distance(node, n);
5531 /* Penalize nodes under us ("prefer the next node") */
5534 /* Give preference to headless and unused nodes */
5535 tmp = cpumask_of_node(n);
5536 if (!cpumask_empty(tmp))
5537 val += PENALTY_FOR_NODE_WITH_CPUS;
5539 /* Slight preference for less loaded node */
5540 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
5541 val += node_load[n];
5543 if (val < min_val) {
5550 node_set(best_node, *used_node_mask);
5557 * Build zonelists ordered by node and zones within node.
5558 * This results in maximum locality--normal zone overflows into local
5559 * DMA zone, if any--but risks exhausting DMA zone.
5561 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
5564 struct zoneref *zonerefs;
5567 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5569 for (i = 0; i < nr_nodes; i++) {
5572 pg_data_t *node = NODE_DATA(node_order[i]);
5574 nr_zones = build_zonerefs_node(node, zonerefs);
5575 zonerefs += nr_zones;
5577 zonerefs->zone = NULL;
5578 zonerefs->zone_idx = 0;
5582 * Build gfp_thisnode zonelists
5584 static void build_thisnode_zonelists(pg_data_t *pgdat)
5586 struct zoneref *zonerefs;
5589 zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
5590 nr_zones = build_zonerefs_node(pgdat, zonerefs);
5591 zonerefs += nr_zones;
5592 zonerefs->zone = NULL;
5593 zonerefs->zone_idx = 0;
5597 * Build zonelists ordered by zone and nodes within zones.
5598 * This results in conserving DMA zone[s] until all Normal memory is
5599 * exhausted, but results in overflowing to remote node while memory
5600 * may still exist in local DMA zone.
5603 static void build_zonelists(pg_data_t *pgdat)
5605 static int node_order[MAX_NUMNODES];
5606 int node, load, nr_nodes = 0;
5607 nodemask_t used_mask;
5608 int local_node, prev_node;
5610 /* NUMA-aware ordering of nodes */
5611 local_node = pgdat->node_id;
5612 load = nr_online_nodes;
5613 prev_node = local_node;
5614 nodes_clear(used_mask);
5616 memset(node_order, 0, sizeof(node_order));
5617 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
5619 * We don't want to pressure a particular node.
5620 * So adding penalty to the first node in same
5621 * distance group to make it round-robin.
5623 if (node_distance(local_node, node) !=
5624 node_distance(local_node, prev_node))
5625 node_load[node] = load;
5627 node_order[nr_nodes++] = node;
5632 build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
5633 build_thisnode_zonelists(pgdat);
5636 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5638 * Return node id of node used for "local" allocations.
5639 * I.e., first node id of first zone in arg node's generic zonelist.
5640 * Used for initializing percpu 'numa_mem', which is used primarily
5641 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
5643 int local_memory_node(int node)
5647 z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
5648 gfp_zone(GFP_KERNEL),
5650 return zone_to_nid(z->zone);
5654 static void setup_min_unmapped_ratio(void);
5655 static void setup_min_slab_ratio(void);
5656 #else /* CONFIG_NUMA */
5658 static void build_zonelists(pg_data_t *pgdat)
5660 int node, local_node;
5661 struct zoneref *zonerefs;
5664 local_node = pgdat->node_id;
5666 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5667 nr_zones = build_zonerefs_node(pgdat, zonerefs);
5668 zonerefs += nr_zones;
5671 * Now we build the zonelist so that it contains the zones
5672 * of all the other nodes.
5673 * We don't want to pressure a particular node, so when
5674 * building the zones for node N, we make sure that the
5675 * zones coming right after the local ones are those from
5676 * node N+1 (modulo N)
5678 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
5679 if (!node_online(node))
5681 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
5682 zonerefs += nr_zones;
5684 for (node = 0; node < local_node; node++) {
5685 if (!node_online(node))
5687 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
5688 zonerefs += nr_zones;
5691 zonerefs->zone = NULL;
5692 zonerefs->zone_idx = 0;
5695 #endif /* CONFIG_NUMA */
5698 * Boot pageset table. One per cpu which is going to be used for all
5699 * zones and all nodes. The parameters will be set in such a way
5700 * that an item put on a list will immediately be handed over to
5701 * the buddy list. This is safe since pageset manipulation is done
5702 * with interrupts disabled.
5704 * The boot_pagesets must be kept even after bootup is complete for
5705 * unused processors and/or zones. They do play a role for bootstrapping
5706 * hotplugged processors.
5708 * zoneinfo_show() and maybe other functions do
5709 * not check if the processor is online before following the pageset pointer.
5710 * Other parts of the kernel may not check if the zone is available.
5712 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
5713 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
5714 static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
5716 static void __build_all_zonelists(void *data)
5719 int __maybe_unused cpu;
5720 pg_data_t *self = data;
5721 static DEFINE_SPINLOCK(lock);
5726 memset(node_load, 0, sizeof(node_load));
5730 * This node is hotadded and no memory is yet present. So just
5731 * building zonelists is fine - no need to touch other nodes.
5733 if (self && !node_online(self->node_id)) {
5734 build_zonelists(self);
5736 for_each_online_node(nid) {
5737 pg_data_t *pgdat = NODE_DATA(nid);
5739 build_zonelists(pgdat);
5742 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5744 * We now know the "local memory node" for each node--
5745 * i.e., the node of the first zone in the generic zonelist.
5746 * Set up numa_mem percpu variable for on-line cpus. During
5747 * boot, only the boot cpu should be on-line; we'll init the
5748 * secondary cpus' numa_mem as they come on-line. During
5749 * node/memory hotplug, we'll fixup all on-line cpus.
5751 for_each_online_cpu(cpu)
5752 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
5759 static noinline void __init
5760 build_all_zonelists_init(void)
5764 __build_all_zonelists(NULL);
5767 * Initialize the boot_pagesets that are going to be used
5768 * for bootstrapping processors. The real pagesets for
5769 * each zone will be allocated later when the per cpu
5770 * allocator is available.
5772 * boot_pagesets are used also for bootstrapping offline
5773 * cpus if the system is already booted because the pagesets
5774 * are needed to initialize allocators on a specific cpu too.
5775 * F.e. the percpu allocator needs the page allocator which
5776 * needs the percpu allocator in order to allocate its pagesets
5777 * (a chicken-egg dilemma).
5779 for_each_possible_cpu(cpu)
5780 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
5782 mminit_verify_zonelist();
5783 cpuset_init_current_mems_allowed();
5787 * unless system_state == SYSTEM_BOOTING.
5789 * __ref due to call of __init annotated helper build_all_zonelists_init
5790 * [protected by SYSTEM_BOOTING].
5792 void __ref build_all_zonelists(pg_data_t *pgdat)
5794 if (system_state == SYSTEM_BOOTING) {
5795 build_all_zonelists_init();
5797 __build_all_zonelists(pgdat);
5798 /* cpuset refresh routine should be here */
5800 vm_total_pages = nr_free_pagecache_pages();
5802 * Disable grouping by mobility if the number of pages in the
5803 * system is too low to allow the mechanism to work. It would be
5804 * more accurate, but expensive to check per-zone. This check is
5805 * made on memory-hotadd so a system can start with mobility
5806 * disabled and enable it later
5808 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
5809 page_group_by_mobility_disabled = 1;
5811 page_group_by_mobility_disabled = 0;
5813 pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n",
5815 page_group_by_mobility_disabled ? "off" : "on",
5818 pr_info("Policy zone: %s\n", zone_names[policy_zone]);
5822 /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
5823 static bool __meminit
5824 overlap_memmap_init(unsigned long zone, unsigned long *pfn)
5826 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5827 static struct memblock_region *r;
5829 if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
5830 if (!r || *pfn >= memblock_region_memory_end_pfn(r)) {
5831 for_each_memblock(memory, r) {
5832 if (*pfn < memblock_region_memory_end_pfn(r))
5836 if (*pfn >= memblock_region_memory_base_pfn(r) &&
5837 memblock_is_mirror(r)) {
5838 *pfn = memblock_region_memory_end_pfn(r);
5847 * Initially all pages are reserved - free ones are freed
5848 * up by memblock_free_all() once the early boot process is
5849 * done. Non-atomic initialization, single-pass.
5851 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
5852 unsigned long start_pfn, enum memmap_context context,
5853 struct vmem_altmap *altmap)
5855 unsigned long pfn, end_pfn = start_pfn + size;
5858 if (highest_memmap_pfn < end_pfn - 1)
5859 highest_memmap_pfn = end_pfn - 1;
5861 #ifdef CONFIG_ZONE_DEVICE
5863 * Honor reservation requested by the driver for this ZONE_DEVICE
5864 * memory. We limit the total number of pages to initialize to just
5865 * those that might contain the memory mapping. We will defer the
5866 * ZONE_DEVICE page initialization until after we have released
5869 if (zone == ZONE_DEVICE) {
5873 if (start_pfn == altmap->base_pfn)
5874 start_pfn += altmap->reserve;
5875 end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
5879 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
5881 * There can be holes in boot-time mem_map[]s handed to this
5882 * function. They do not exist on hotplugged memory.
5884 if (context == MEMMAP_EARLY) {
5885 if (!early_pfn_valid(pfn))
5887 if (!early_pfn_in_nid(pfn, nid))
5889 if (overlap_memmap_init(zone, &pfn))
5891 if (defer_init(nid, pfn, end_pfn))
5895 page = pfn_to_page(pfn);
5896 __init_single_page(page, pfn, zone, nid);
5897 if (context == MEMMAP_HOTPLUG)
5898 __SetPageReserved(page);
5901 * Mark the block movable so that blocks are reserved for
5902 * movable at startup. This will force kernel allocations
5903 * to reserve their blocks rather than leaking throughout
5904 * the address space during boot when many long-lived
5905 * kernel allocations are made.
5907 * bitmap is created for zone's valid pfn range. but memmap
5908 * can be created for invalid pages (for alignment)
5909 * check here not to call set_pageblock_migratetype() against
5912 if (!(pfn & (pageblock_nr_pages - 1))) {
5913 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
5919 #ifdef CONFIG_ZONE_DEVICE
5920 void __ref memmap_init_zone_device(struct zone *zone,
5921 unsigned long start_pfn,
5923 struct dev_pagemap *pgmap)
5925 unsigned long pfn, end_pfn = start_pfn + size;
5926 struct pglist_data *pgdat = zone->zone_pgdat;
5927 struct vmem_altmap *altmap = pgmap_altmap(pgmap);
5928 unsigned long zone_idx = zone_idx(zone);
5929 unsigned long start = jiffies;
5930 int nid = pgdat->node_id;
5932 if (WARN_ON_ONCE(!pgmap || zone_idx(zone) != ZONE_DEVICE))
5936 * The call to memmap_init_zone should have already taken care
5937 * of the pages reserved for the memmap, so we can just jump to
5938 * the end of that region and start processing the device pages.
5941 start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
5942 size = end_pfn - start_pfn;
5945 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
5946 struct page *page = pfn_to_page(pfn);
5948 __init_single_page(page, pfn, zone_idx, nid);
5951 * Mark page reserved as it will need to wait for onlining
5952 * phase for it to be fully associated with a zone.
5954 * We can use the non-atomic __set_bit operation for setting
5955 * the flag as we are still initializing the pages.
5957 __SetPageReserved(page);
5960 * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer
5961 * and zone_device_data. It is a bug if a ZONE_DEVICE page is
5962 * ever freed or placed on a driver-private list.
5964 page->pgmap = pgmap;
5965 page->zone_device_data = NULL;
5968 * Mark the block movable so that blocks are reserved for
5969 * movable at startup. This will force kernel allocations
5970 * to reserve their blocks rather than leaking throughout
5971 * the address space during boot when many long-lived
5972 * kernel allocations are made.
5974 * bitmap is created for zone's valid pfn range. but memmap
5975 * can be created for invalid pages (for alignment)
5976 * check here not to call set_pageblock_migratetype() against
5979 * Please note that MEMMAP_HOTPLUG path doesn't clear memmap
5980 * because this is done early in section_activate()
5982 if (!(pfn & (pageblock_nr_pages - 1))) {
5983 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
5988 pr_info("%s initialised, %lu pages in %ums\n", dev_name(pgmap->dev),
5989 size, jiffies_to_msecs(jiffies - start));
5993 static void __meminit zone_init_free_lists(struct zone *zone)
5995 unsigned int order, t;
5996 for_each_migratetype_order(order, t) {
5997 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
5998 zone->free_area[order].nr_free = 0;
6002 void __meminit __weak memmap_init(unsigned long size, int nid,
6003 unsigned long zone, unsigned long start_pfn)
6005 memmap_init_zone(size, nid, zone, start_pfn, MEMMAP_EARLY, NULL);
6008 static int zone_batchsize(struct zone *zone)
6014 * The per-cpu-pages pools are set to around 1000th of the
6017 batch = zone_managed_pages(zone) / 1024;
6018 /* But no more than a meg. */
6019 if (batch * PAGE_SIZE > 1024 * 1024)
6020 batch = (1024 * 1024) / PAGE_SIZE;
6021 batch /= 4; /* We effectively *= 4 below */
6026 * Clamp the batch to a 2^n - 1 value. Having a power
6027 * of 2 value was found to be more likely to have
6028 * suboptimal cache aliasing properties in some cases.
6030 * For example if 2 tasks are alternately allocating
6031 * batches of pages, one task can end up with a lot
6032 * of pages of one half of the possible page colors
6033 * and the other with pages of the other colors.
6035 batch = rounddown_pow_of_two(batch + batch/2) - 1;
6040 /* The deferral and batching of frees should be suppressed under NOMMU
6043 * The problem is that NOMMU needs to be able to allocate large chunks
6044 * of contiguous memory as there's no hardware page translation to
6045 * assemble apparent contiguous memory from discontiguous pages.
6047 * Queueing large contiguous runs of pages for batching, however,
6048 * causes the pages to actually be freed in smaller chunks. As there
6049 * can be a significant delay between the individual batches being
6050 * recycled, this leads to the once large chunks of space being
6051 * fragmented and becoming unavailable for high-order allocations.
6058 * pcp->high and pcp->batch values are related and dependent on one another:
6059 * ->batch must never be higher then ->high.
6060 * The following function updates them in a safe manner without read side
6063 * Any new users of pcp->batch and pcp->high should ensure they can cope with
6064 * those fields changing asynchronously (acording the the above rule).
6066 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
6067 * outside of boot time (or some other assurance that no concurrent updaters
6070 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
6071 unsigned long batch)
6073 /* start with a fail safe value for batch */
6077 /* Update high, then batch, in order */
6084 /* a companion to pageset_set_high() */
6085 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
6087 pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
6090 static void pageset_init(struct per_cpu_pageset *p)
6092 struct per_cpu_pages *pcp;
6095 memset(p, 0, sizeof(*p));
6098 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
6099 INIT_LIST_HEAD(&pcp->lists[migratetype]);
6102 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
6105 pageset_set_batch(p, batch);
6109 * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
6110 * to the value high for the pageset p.
6112 static void pageset_set_high(struct per_cpu_pageset *p,
6115 unsigned long batch = max(1UL, high / 4);
6116 if ((high / 4) > (PAGE_SHIFT * 8))
6117 batch = PAGE_SHIFT * 8;
6119 pageset_update(&p->pcp, high, batch);
6122 static void pageset_set_high_and_batch(struct zone *zone,
6123 struct per_cpu_pageset *pcp)
6125 if (percpu_pagelist_fraction)
6126 pageset_set_high(pcp,
6127 (zone_managed_pages(zone) /
6128 percpu_pagelist_fraction));
6130 pageset_set_batch(pcp, zone_batchsize(zone));
6133 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
6135 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
6138 pageset_set_high_and_batch(zone, pcp);
6141 void __meminit setup_zone_pageset(struct zone *zone)
6144 zone->pageset = alloc_percpu(struct per_cpu_pageset);
6145 for_each_possible_cpu(cpu)
6146 zone_pageset_init(zone, cpu);
6150 * Allocate per cpu pagesets and initialize them.
6151 * Before this call only boot pagesets were available.
6153 void __init setup_per_cpu_pageset(void)
6155 struct pglist_data *pgdat;
6158 for_each_populated_zone(zone)
6159 setup_zone_pageset(zone);
6161 for_each_online_pgdat(pgdat)
6162 pgdat->per_cpu_nodestats =
6163 alloc_percpu(struct per_cpu_nodestat);
6166 static __meminit void zone_pcp_init(struct zone *zone)
6169 * per cpu subsystem is not up at this point. The following code
6170 * relies on the ability of the linker to provide the
6171 * offset of a (static) per cpu variable into the per cpu area.
6173 zone->pageset = &boot_pageset;
6175 if (populated_zone(zone))
6176 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
6177 zone->name, zone->present_pages,
6178 zone_batchsize(zone));
6181 void __meminit init_currently_empty_zone(struct zone *zone,
6182 unsigned long zone_start_pfn,
6185 struct pglist_data *pgdat = zone->zone_pgdat;
6186 int zone_idx = zone_idx(zone) + 1;
6188 if (zone_idx > pgdat->nr_zones)
6189 pgdat->nr_zones = zone_idx;
6191 zone->zone_start_pfn = zone_start_pfn;
6193 mminit_dprintk(MMINIT_TRACE, "memmap_init",
6194 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
6196 (unsigned long)zone_idx(zone),
6197 zone_start_pfn, (zone_start_pfn + size));
6199 zone_init_free_lists(zone);
6200 zone->initialized = 1;
6203 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6204 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
6207 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
6209 int __meminit __early_pfn_to_nid(unsigned long pfn,
6210 struct mminit_pfnnid_cache *state)
6212 unsigned long start_pfn, end_pfn;
6215 if (state->last_start <= pfn && pfn < state->last_end)
6216 return state->last_nid;
6218 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
6219 if (nid != NUMA_NO_NODE) {
6220 state->last_start = start_pfn;
6221 state->last_end = end_pfn;
6222 state->last_nid = nid;
6227 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
6230 * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
6231 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
6232 * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
6234 * If an architecture guarantees that all ranges registered contain no holes
6235 * and may be freed, this this function may be used instead of calling
6236 * memblock_free_early_nid() manually.
6238 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
6240 unsigned long start_pfn, end_pfn;
6243 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
6244 start_pfn = min(start_pfn, max_low_pfn);
6245 end_pfn = min(end_pfn, max_low_pfn);
6247 if (start_pfn < end_pfn)
6248 memblock_free_early_nid(PFN_PHYS(start_pfn),
6249 (end_pfn - start_pfn) << PAGE_SHIFT,
6255 * sparse_memory_present_with_active_regions - Call memory_present for each active range
6256 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
6258 * If an architecture guarantees that all ranges registered contain no holes and may
6259 * be freed, this function may be used instead of calling memory_present() manually.
6261 void __init sparse_memory_present_with_active_regions(int nid)
6263 unsigned long start_pfn, end_pfn;
6266 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
6267 memory_present(this_nid, start_pfn, end_pfn);
6271 * get_pfn_range_for_nid - Return the start and end page frames for a node
6272 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
6273 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
6274 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
6276 * It returns the start and end page frame of a node based on information
6277 * provided by memblock_set_node(). If called for a node
6278 * with no available memory, a warning is printed and the start and end
6281 void __init get_pfn_range_for_nid(unsigned int nid,
6282 unsigned long *start_pfn, unsigned long *end_pfn)
6284 unsigned long this_start_pfn, this_end_pfn;
6290 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
6291 *start_pfn = min(*start_pfn, this_start_pfn);
6292 *end_pfn = max(*end_pfn, this_end_pfn);
6295 if (*start_pfn == -1UL)
6300 * This finds a zone that can be used for ZONE_MOVABLE pages. The
6301 * assumption is made that zones within a node are ordered in monotonic
6302 * increasing memory addresses so that the "highest" populated zone is used
6304 static void __init find_usable_zone_for_movable(void)
6307 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
6308 if (zone_index == ZONE_MOVABLE)
6311 if (arch_zone_highest_possible_pfn[zone_index] >
6312 arch_zone_lowest_possible_pfn[zone_index])
6316 VM_BUG_ON(zone_index == -1);
6317 movable_zone = zone_index;
6321 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
6322 * because it is sized independent of architecture. Unlike the other zones,
6323 * the starting point for ZONE_MOVABLE is not fixed. It may be different
6324 * in each node depending on the size of each node and how evenly kernelcore
6325 * is distributed. This helper function adjusts the zone ranges
6326 * provided by the architecture for a given node by using the end of the
6327 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
6328 * zones within a node are in order of monotonic increases memory addresses
6330 static void __init adjust_zone_range_for_zone_movable(int nid,
6331 unsigned long zone_type,
6332 unsigned long node_start_pfn,
6333 unsigned long node_end_pfn,
6334 unsigned long *zone_start_pfn,
6335 unsigned long *zone_end_pfn)
6337 /* Only adjust if ZONE_MOVABLE is on this node */
6338 if (zone_movable_pfn[nid]) {
6339 /* Size ZONE_MOVABLE */
6340 if (zone_type == ZONE_MOVABLE) {
6341 *zone_start_pfn = zone_movable_pfn[nid];
6342 *zone_end_pfn = min(node_end_pfn,
6343 arch_zone_highest_possible_pfn[movable_zone]);
6345 /* Adjust for ZONE_MOVABLE starting within this range */
6346 } else if (!mirrored_kernelcore &&
6347 *zone_start_pfn < zone_movable_pfn[nid] &&
6348 *zone_end_pfn > zone_movable_pfn[nid]) {
6349 *zone_end_pfn = zone_movable_pfn[nid];
6351 /* Check if this whole range is within ZONE_MOVABLE */
6352 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
6353 *zone_start_pfn = *zone_end_pfn;
6358 * Return the number of pages a zone spans in a node, including holes
6359 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
6361 static unsigned long __init zone_spanned_pages_in_node(int nid,
6362 unsigned long zone_type,
6363 unsigned long node_start_pfn,
6364 unsigned long node_end_pfn,
6365 unsigned long *zone_start_pfn,
6366 unsigned long *zone_end_pfn,
6367 unsigned long *ignored)
6369 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
6370 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
6371 /* When hotadd a new node from cpu_up(), the node should be empty */
6372 if (!node_start_pfn && !node_end_pfn)
6375 /* Get the start and end of the zone */
6376 *zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
6377 *zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
6378 adjust_zone_range_for_zone_movable(nid, zone_type,
6379 node_start_pfn, node_end_pfn,
6380 zone_start_pfn, zone_end_pfn);
6382 /* Check that this node has pages within the zone's required range */
6383 if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
6386 /* Move the zone boundaries inside the node if necessary */
6387 *zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
6388 *zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
6390 /* Return the spanned pages */
6391 return *zone_end_pfn - *zone_start_pfn;
6395 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
6396 * then all holes in the requested range will be accounted for.
6398 unsigned long __init __absent_pages_in_range(int nid,
6399 unsigned long range_start_pfn,
6400 unsigned long range_end_pfn)
6402 unsigned long nr_absent = range_end_pfn - range_start_pfn;
6403 unsigned long start_pfn, end_pfn;
6406 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
6407 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
6408 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
6409 nr_absent -= end_pfn - start_pfn;
6415 * absent_pages_in_range - Return number of page frames in holes within a range
6416 * @start_pfn: The start PFN to start searching for holes
6417 * @end_pfn: The end PFN to stop searching for holes
6419 * Return: the number of pages frames in memory holes within a range.
6421 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
6422 unsigned long end_pfn)
6424 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
6427 /* Return the number of page frames in holes in a zone on a node */
6428 static unsigned long __init zone_absent_pages_in_node(int nid,
6429 unsigned long zone_type,
6430 unsigned long node_start_pfn,
6431 unsigned long node_end_pfn,
6432 unsigned long *ignored)
6434 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
6435 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
6436 unsigned long zone_start_pfn, zone_end_pfn;
6437 unsigned long nr_absent;
6439 /* When hotadd a new node from cpu_up(), the node should be empty */
6440 if (!node_start_pfn && !node_end_pfn)
6443 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
6444 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
6446 adjust_zone_range_for_zone_movable(nid, zone_type,
6447 node_start_pfn, node_end_pfn,
6448 &zone_start_pfn, &zone_end_pfn);
6449 nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
6452 * ZONE_MOVABLE handling.
6453 * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
6456 if (mirrored_kernelcore && zone_movable_pfn[nid]) {
6457 unsigned long start_pfn, end_pfn;
6458 struct memblock_region *r;
6460 for_each_memblock(memory, r) {
6461 start_pfn = clamp(memblock_region_memory_base_pfn(r),
6462 zone_start_pfn, zone_end_pfn);
6463 end_pfn = clamp(memblock_region_memory_end_pfn(r),
6464 zone_start_pfn, zone_end_pfn);
6466 if (zone_type == ZONE_MOVABLE &&
6467 memblock_is_mirror(r))
6468 nr_absent += end_pfn - start_pfn;
6470 if (zone_type == ZONE_NORMAL &&
6471 !memblock_is_mirror(r))
6472 nr_absent += end_pfn - start_pfn;
6479 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6480 static inline unsigned long __init zone_spanned_pages_in_node(int nid,
6481 unsigned long zone_type,
6482 unsigned long node_start_pfn,
6483 unsigned long node_end_pfn,
6484 unsigned long *zone_start_pfn,
6485 unsigned long *zone_end_pfn,
6486 unsigned long *zones_size)
6490 *zone_start_pfn = node_start_pfn;
6491 for (zone = 0; zone < zone_type; zone++)
6492 *zone_start_pfn += zones_size[zone];
6494 *zone_end_pfn = *zone_start_pfn + zones_size[zone_type];
6496 return zones_size[zone_type];
6499 static inline unsigned long __init zone_absent_pages_in_node(int nid,
6500 unsigned long zone_type,
6501 unsigned long node_start_pfn,
6502 unsigned long node_end_pfn,
6503 unsigned long *zholes_size)
6508 return zholes_size[zone_type];
6511 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6513 static void __init calculate_node_totalpages(struct pglist_data *pgdat,
6514 unsigned long node_start_pfn,
6515 unsigned long node_end_pfn,
6516 unsigned long *zones_size,
6517 unsigned long *zholes_size)
6519 unsigned long realtotalpages = 0, totalpages = 0;
6522 for (i = 0; i < MAX_NR_ZONES; i++) {
6523 struct zone *zone = pgdat->node_zones + i;
6524 unsigned long zone_start_pfn, zone_end_pfn;
6525 unsigned long size, real_size;
6527 size = zone_spanned_pages_in_node(pgdat->node_id, i,
6533 real_size = size - zone_absent_pages_in_node(pgdat->node_id, i,
6534 node_start_pfn, node_end_pfn,
6537 zone->zone_start_pfn = zone_start_pfn;
6539 zone->zone_start_pfn = 0;
6540 zone->spanned_pages = size;
6541 zone->present_pages = real_size;
6544 realtotalpages += real_size;
6547 pgdat->node_spanned_pages = totalpages;
6548 pgdat->node_present_pages = realtotalpages;
6549 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
6553 #ifndef CONFIG_SPARSEMEM
6555 * Calculate the size of the zone->blockflags rounded to an unsigned long
6556 * Start by making sure zonesize is a multiple of pageblock_order by rounding
6557 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
6558 * round what is now in bits to nearest long in bits, then return it in
6561 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
6563 unsigned long usemapsize;
6565 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
6566 usemapsize = roundup(zonesize, pageblock_nr_pages);
6567 usemapsize = usemapsize >> pageblock_order;
6568 usemapsize *= NR_PAGEBLOCK_BITS;
6569 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
6571 return usemapsize / 8;
6574 static void __ref setup_usemap(struct pglist_data *pgdat,
6576 unsigned long zone_start_pfn,
6577 unsigned long zonesize)
6579 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
6580 zone->pageblock_flags = NULL;
6582 zone->pageblock_flags =
6583 memblock_alloc_node(usemapsize, SMP_CACHE_BYTES,
6585 if (!zone->pageblock_flags)
6586 panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n",
6587 usemapsize, zone->name, pgdat->node_id);
6591 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
6592 unsigned long zone_start_pfn, unsigned long zonesize) {}
6593 #endif /* CONFIG_SPARSEMEM */
6595 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
6597 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
6598 void __init set_pageblock_order(void)
6602 /* Check that pageblock_nr_pages has not already been setup */
6603 if (pageblock_order)
6606 if (HPAGE_SHIFT > PAGE_SHIFT)
6607 order = HUGETLB_PAGE_ORDER;
6609 order = MAX_ORDER - 1;
6612 * Assume the largest contiguous order of interest is a huge page.
6613 * This value may be variable depending on boot parameters on IA64 and
6616 pageblock_order = order;
6618 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6621 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
6622 * is unused as pageblock_order is set at compile-time. See
6623 * include/linux/pageblock-flags.h for the values of pageblock_order based on
6626 void __init set_pageblock_order(void)
6630 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6632 static unsigned long __init calc_memmap_size(unsigned long spanned_pages,
6633 unsigned long present_pages)
6635 unsigned long pages = spanned_pages;
6638 * Provide a more accurate estimation if there are holes within
6639 * the zone and SPARSEMEM is in use. If there are holes within the
6640 * zone, each populated memory region may cost us one or two extra
6641 * memmap pages due to alignment because memmap pages for each
6642 * populated regions may not be naturally aligned on page boundary.
6643 * So the (present_pages >> 4) heuristic is a tradeoff for that.
6645 if (spanned_pages > present_pages + (present_pages >> 4) &&
6646 IS_ENABLED(CONFIG_SPARSEMEM))
6647 pages = present_pages;
6649 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
6652 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6653 static void pgdat_init_split_queue(struct pglist_data *pgdat)
6655 spin_lock_init(&pgdat->split_queue_lock);
6656 INIT_LIST_HEAD(&pgdat->split_queue);
6657 pgdat->split_queue_len = 0;
6660 static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
6663 #ifdef CONFIG_COMPACTION
6664 static void pgdat_init_kcompactd(struct pglist_data *pgdat)
6666 init_waitqueue_head(&pgdat->kcompactd_wait);
6669 static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
6672 static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
6674 pgdat_resize_init(pgdat);
6676 pgdat_init_split_queue(pgdat);
6677 pgdat_init_kcompactd(pgdat);
6679 init_waitqueue_head(&pgdat->kswapd_wait);
6680 init_waitqueue_head(&pgdat->pfmemalloc_wait);
6682 pgdat_page_ext_init(pgdat);
6683 spin_lock_init(&pgdat->lru_lock);
6684 lruvec_init(node_lruvec(pgdat));
6687 static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
6688 unsigned long remaining_pages)
6690 atomic_long_set(&zone->managed_pages, remaining_pages);
6691 zone_set_nid(zone, nid);
6692 zone->name = zone_names[idx];
6693 zone->zone_pgdat = NODE_DATA(nid);
6694 spin_lock_init(&zone->lock);
6695 zone_seqlock_init(zone);
6696 zone_pcp_init(zone);
6700 * Set up the zone data structures
6701 * - init pgdat internals
6702 * - init all zones belonging to this node
6704 * NOTE: this function is only called during memory hotplug
6706 #ifdef CONFIG_MEMORY_HOTPLUG
6707 void __ref free_area_init_core_hotplug(int nid)
6710 pg_data_t *pgdat = NODE_DATA(nid);
6712 pgdat_init_internals(pgdat);
6713 for (z = 0; z < MAX_NR_ZONES; z++)
6714 zone_init_internals(&pgdat->node_zones[z], z, nid, 0);
6719 * Set up the zone data structures:
6720 * - mark all pages reserved
6721 * - mark all memory queues empty
6722 * - clear the memory bitmaps
6724 * NOTE: pgdat should get zeroed by caller.
6725 * NOTE: this function is only called during early init.
6727 static void __init free_area_init_core(struct pglist_data *pgdat)
6730 int nid = pgdat->node_id;
6732 pgdat_init_internals(pgdat);
6733 pgdat->per_cpu_nodestats = &boot_nodestats;
6735 for (j = 0; j < MAX_NR_ZONES; j++) {
6736 struct zone *zone = pgdat->node_zones + j;
6737 unsigned long size, freesize, memmap_pages;
6738 unsigned long zone_start_pfn = zone->zone_start_pfn;
6740 size = zone->spanned_pages;
6741 freesize = zone->present_pages;
6744 * Adjust freesize so that it accounts for how much memory
6745 * is used by this zone for memmap. This affects the watermark
6746 * and per-cpu initialisations
6748 memmap_pages = calc_memmap_size(size, freesize);
6749 if (!is_highmem_idx(j)) {
6750 if (freesize >= memmap_pages) {
6751 freesize -= memmap_pages;
6754 " %s zone: %lu pages used for memmap\n",
6755 zone_names[j], memmap_pages);
6757 pr_warn(" %s zone: %lu pages exceeds freesize %lu\n",
6758 zone_names[j], memmap_pages, freesize);
6761 /* Account for reserved pages */
6762 if (j == 0 && freesize > dma_reserve) {
6763 freesize -= dma_reserve;
6764 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
6765 zone_names[0], dma_reserve);
6768 if (!is_highmem_idx(j))
6769 nr_kernel_pages += freesize;
6770 /* Charge for highmem memmap if there are enough kernel pages */
6771 else if (nr_kernel_pages > memmap_pages * 2)
6772 nr_kernel_pages -= memmap_pages;
6773 nr_all_pages += freesize;
6776 * Set an approximate value for lowmem here, it will be adjusted
6777 * when the bootmem allocator frees pages into the buddy system.
6778 * And all highmem pages will be managed by the buddy system.
6780 zone_init_internals(zone, j, nid, freesize);
6785 set_pageblock_order();
6786 setup_usemap(pgdat, zone, zone_start_pfn, size);
6787 init_currently_empty_zone(zone, zone_start_pfn, size);
6788 memmap_init(size, nid, j, zone_start_pfn);
6792 #ifdef CONFIG_FLAT_NODE_MEM_MAP
6793 static void __ref alloc_node_mem_map(struct pglist_data *pgdat)
6795 unsigned long __maybe_unused start = 0;
6796 unsigned long __maybe_unused offset = 0;
6798 /* Skip empty nodes */
6799 if (!pgdat->node_spanned_pages)
6802 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
6803 offset = pgdat->node_start_pfn - start;
6804 /* ia64 gets its own node_mem_map, before this, without bootmem */
6805 if (!pgdat->node_mem_map) {
6806 unsigned long size, end;
6810 * The zone's endpoints aren't required to be MAX_ORDER
6811 * aligned but the node_mem_map endpoints must be in order
6812 * for the buddy allocator to function correctly.
6814 end = pgdat_end_pfn(pgdat);
6815 end = ALIGN(end, MAX_ORDER_NR_PAGES);
6816 size = (end - start) * sizeof(struct page);
6817 map = memblock_alloc_node(size, SMP_CACHE_BYTES,
6820 panic("Failed to allocate %ld bytes for node %d memory map\n",
6821 size, pgdat->node_id);
6822 pgdat->node_mem_map = map + offset;
6824 pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
6825 __func__, pgdat->node_id, (unsigned long)pgdat,
6826 (unsigned long)pgdat->node_mem_map);
6827 #ifndef CONFIG_NEED_MULTIPLE_NODES
6829 * With no DISCONTIG, the global mem_map is just set as node 0's
6831 if (pgdat == NODE_DATA(0)) {
6832 mem_map = NODE_DATA(0)->node_mem_map;
6833 #if defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) || defined(CONFIG_FLATMEM)
6834 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
6836 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6841 static void __ref alloc_node_mem_map(struct pglist_data *pgdat) { }
6842 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
6844 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
6845 static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
6847 pgdat->first_deferred_pfn = ULONG_MAX;
6850 static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
6853 void __init free_area_init_node(int nid, unsigned long *zones_size,
6854 unsigned long node_start_pfn,
6855 unsigned long *zholes_size)
6857 pg_data_t *pgdat = NODE_DATA(nid);
6858 unsigned long start_pfn = 0;
6859 unsigned long end_pfn = 0;
6861 /* pg_data_t should be reset to zero when it's allocated */
6862 WARN_ON(pgdat->nr_zones || pgdat->kswapd_classzone_idx);
6864 pgdat->node_id = nid;
6865 pgdat->node_start_pfn = node_start_pfn;
6866 pgdat->per_cpu_nodestats = NULL;
6867 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6868 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
6869 pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
6870 (u64)start_pfn << PAGE_SHIFT,
6871 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
6873 start_pfn = node_start_pfn;
6875 calculate_node_totalpages(pgdat, start_pfn, end_pfn,
6876 zones_size, zholes_size);
6878 alloc_node_mem_map(pgdat);
6879 pgdat_set_deferred_range(pgdat);
6881 free_area_init_core(pgdat);
6884 #if !defined(CONFIG_FLAT_NODE_MEM_MAP)
6886 * Zero all valid struct pages in range [spfn, epfn), return number of struct
6889 static u64 zero_pfn_range(unsigned long spfn, unsigned long epfn)
6894 for (pfn = spfn; pfn < epfn; pfn++) {
6895 if (!pfn_valid(ALIGN_DOWN(pfn, pageblock_nr_pages))) {
6896 pfn = ALIGN_DOWN(pfn, pageblock_nr_pages)
6897 + pageblock_nr_pages - 1;
6900 mm_zero_struct_page(pfn_to_page(pfn));
6908 * Only struct pages that are backed by physical memory are zeroed and
6909 * initialized by going through __init_single_page(). But, there are some
6910 * struct pages which are reserved in memblock allocator and their fields
6911 * may be accessed (for example page_to_pfn() on some configuration accesses
6912 * flags). We must explicitly zero those struct pages.
6914 * This function also addresses a similar issue where struct pages are left
6915 * uninitialized because the physical address range is not covered by
6916 * memblock.memory or memblock.reserved. That could happen when memblock
6917 * layout is manually configured via memmap=.
6919 void __init zero_resv_unavail(void)
6921 phys_addr_t start, end;
6923 phys_addr_t next = 0;
6926 * Loop through unavailable ranges not covered by memblock.memory.
6929 for_each_mem_range(i, &memblock.memory, NULL,
6930 NUMA_NO_NODE, MEMBLOCK_NONE, &start, &end, NULL) {
6932 pgcnt += zero_pfn_range(PFN_DOWN(next), PFN_UP(start));
6935 pgcnt += zero_pfn_range(PFN_DOWN(next), max_pfn);
6938 * Struct pages that do not have backing memory. This could be because
6939 * firmware is using some of this memory, or for some other reasons.
6942 pr_info("Zeroed struct page in unavailable ranges: %lld pages", pgcnt);
6944 #endif /* !CONFIG_FLAT_NODE_MEM_MAP */
6946 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6948 #if MAX_NUMNODES > 1
6950 * Figure out the number of possible node ids.
6952 void __init setup_nr_node_ids(void)
6954 unsigned int highest;
6956 highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
6957 nr_node_ids = highest + 1;
6962 * node_map_pfn_alignment - determine the maximum internode alignment
6964 * This function should be called after node map is populated and sorted.
6965 * It calculates the maximum power of two alignment which can distinguish
6968 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
6969 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
6970 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
6971 * shifted, 1GiB is enough and this function will indicate so.
6973 * This is used to test whether pfn -> nid mapping of the chosen memory
6974 * model has fine enough granularity to avoid incorrect mapping for the
6975 * populated node map.
6977 * Return: the determined alignment in pfn's. 0 if there is no alignment
6978 * requirement (single node).
6980 unsigned long __init node_map_pfn_alignment(void)
6982 unsigned long accl_mask = 0, last_end = 0;
6983 unsigned long start, end, mask;
6984 int last_nid = NUMA_NO_NODE;
6987 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
6988 if (!start || last_nid < 0 || last_nid == nid) {
6995 * Start with a mask granular enough to pin-point to the
6996 * start pfn and tick off bits one-by-one until it becomes
6997 * too coarse to separate the current node from the last.
6999 mask = ~((1 << __ffs(start)) - 1);
7000 while (mask && last_end <= (start & (mask << 1)))
7003 /* accumulate all internode masks */
7007 /* convert mask to number of pages */
7008 return ~accl_mask + 1;
7011 /* Find the lowest pfn for a node */
7012 static unsigned long __init find_min_pfn_for_node(int nid)
7014 unsigned long min_pfn = ULONG_MAX;
7015 unsigned long start_pfn;
7018 for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
7019 min_pfn = min(min_pfn, start_pfn);
7021 if (min_pfn == ULONG_MAX) {
7022 pr_warn("Could not find start_pfn for node %d\n", nid);
7030 * find_min_pfn_with_active_regions - Find the minimum PFN registered
7032 * Return: the minimum PFN based on information provided via
7033 * memblock_set_node().
7035 unsigned long __init find_min_pfn_with_active_regions(void)
7037 return find_min_pfn_for_node(MAX_NUMNODES);
7041 * early_calculate_totalpages()
7042 * Sum pages in active regions for movable zone.
7043 * Populate N_MEMORY for calculating usable_nodes.
7045 static unsigned long __init early_calculate_totalpages(void)
7047 unsigned long totalpages = 0;
7048 unsigned long start_pfn, end_pfn;
7051 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7052 unsigned long pages = end_pfn - start_pfn;
7054 totalpages += pages;
7056 node_set_state(nid, N_MEMORY);
7062 * Find the PFN the Movable zone begins in each node. Kernel memory
7063 * is spread evenly between nodes as long as the nodes have enough
7064 * memory. When they don't, some nodes will have more kernelcore than
7067 static void __init find_zone_movable_pfns_for_nodes(void)
7070 unsigned long usable_startpfn;
7071 unsigned long kernelcore_node, kernelcore_remaining;
7072 /* save the state before borrow the nodemask */
7073 nodemask_t saved_node_state = node_states[N_MEMORY];
7074 unsigned long totalpages = early_calculate_totalpages();
7075 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
7076 struct memblock_region *r;
7078 /* Need to find movable_zone earlier when movable_node is specified. */
7079 find_usable_zone_for_movable();
7082 * If movable_node is specified, ignore kernelcore and movablecore
7085 if (movable_node_is_enabled()) {
7086 for_each_memblock(memory, r) {
7087 if (!memblock_is_hotpluggable(r))
7092 usable_startpfn = PFN_DOWN(r->base);
7093 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7094 min(usable_startpfn, zone_movable_pfn[nid]) :
7102 * If kernelcore=mirror is specified, ignore movablecore option
7104 if (mirrored_kernelcore) {
7105 bool mem_below_4gb_not_mirrored = false;
7107 for_each_memblock(memory, r) {
7108 if (memblock_is_mirror(r))
7113 usable_startpfn = memblock_region_memory_base_pfn(r);
7115 if (usable_startpfn < 0x100000) {
7116 mem_below_4gb_not_mirrored = true;
7120 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7121 min(usable_startpfn, zone_movable_pfn[nid]) :
7125 if (mem_below_4gb_not_mirrored)
7126 pr_warn("This configuration results in unmirrored kernel memory.");
7132 * If kernelcore=nn% or movablecore=nn% was specified, calculate the
7133 * amount of necessary memory.
7135 if (required_kernelcore_percent)
7136 required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
7138 if (required_movablecore_percent)
7139 required_movablecore = (totalpages * 100 * required_movablecore_percent) /
7143 * If movablecore= was specified, calculate what size of
7144 * kernelcore that corresponds so that memory usable for
7145 * any allocation type is evenly spread. If both kernelcore
7146 * and movablecore are specified, then the value of kernelcore
7147 * will be used for required_kernelcore if it's greater than
7148 * what movablecore would have allowed.
7150 if (required_movablecore) {
7151 unsigned long corepages;
7154 * Round-up so that ZONE_MOVABLE is at least as large as what
7155 * was requested by the user
7157 required_movablecore =
7158 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
7159 required_movablecore = min(totalpages, required_movablecore);
7160 corepages = totalpages - required_movablecore;
7162 required_kernelcore = max(required_kernelcore, corepages);
7166 * If kernelcore was not specified or kernelcore size is larger
7167 * than totalpages, there is no ZONE_MOVABLE.
7169 if (!required_kernelcore || required_kernelcore >= totalpages)
7172 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
7173 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
7176 /* Spread kernelcore memory as evenly as possible throughout nodes */
7177 kernelcore_node = required_kernelcore / usable_nodes;
7178 for_each_node_state(nid, N_MEMORY) {
7179 unsigned long start_pfn, end_pfn;
7182 * Recalculate kernelcore_node if the division per node
7183 * now exceeds what is necessary to satisfy the requested
7184 * amount of memory for the kernel
7186 if (required_kernelcore < kernelcore_node)
7187 kernelcore_node = required_kernelcore / usable_nodes;
7190 * As the map is walked, we track how much memory is usable
7191 * by the kernel using kernelcore_remaining. When it is
7192 * 0, the rest of the node is usable by ZONE_MOVABLE
7194 kernelcore_remaining = kernelcore_node;
7196 /* Go through each range of PFNs within this node */
7197 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
7198 unsigned long size_pages;
7200 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
7201 if (start_pfn >= end_pfn)
7204 /* Account for what is only usable for kernelcore */
7205 if (start_pfn < usable_startpfn) {
7206 unsigned long kernel_pages;
7207 kernel_pages = min(end_pfn, usable_startpfn)
7210 kernelcore_remaining -= min(kernel_pages,
7211 kernelcore_remaining);
7212 required_kernelcore -= min(kernel_pages,
7213 required_kernelcore);
7215 /* Continue if range is now fully accounted */
7216 if (end_pfn <= usable_startpfn) {
7219 * Push zone_movable_pfn to the end so
7220 * that if we have to rebalance
7221 * kernelcore across nodes, we will
7222 * not double account here
7224 zone_movable_pfn[nid] = end_pfn;
7227 start_pfn = usable_startpfn;
7231 * The usable PFN range for ZONE_MOVABLE is from
7232 * start_pfn->end_pfn. Calculate size_pages as the
7233 * number of pages used as kernelcore
7235 size_pages = end_pfn - start_pfn;
7236 if (size_pages > kernelcore_remaining)
7237 size_pages = kernelcore_remaining;
7238 zone_movable_pfn[nid] = start_pfn + size_pages;
7241 * Some kernelcore has been met, update counts and
7242 * break if the kernelcore for this node has been
7245 required_kernelcore -= min(required_kernelcore,
7247 kernelcore_remaining -= size_pages;
7248 if (!kernelcore_remaining)
7254 * If there is still required_kernelcore, we do another pass with one
7255 * less node in the count. This will push zone_movable_pfn[nid] further
7256 * along on the nodes that still have memory until kernelcore is
7260 if (usable_nodes && required_kernelcore > usable_nodes)
7264 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
7265 for (nid = 0; nid < MAX_NUMNODES; nid++)
7266 zone_movable_pfn[nid] =
7267 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
7270 /* restore the node_state */
7271 node_states[N_MEMORY] = saved_node_state;
7274 /* Any regular or high memory on that node ? */
7275 static void check_for_memory(pg_data_t *pgdat, int nid)
7277 enum zone_type zone_type;
7279 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
7280 struct zone *zone = &pgdat->node_zones[zone_type];
7281 if (populated_zone(zone)) {
7282 if (IS_ENABLED(CONFIG_HIGHMEM))
7283 node_set_state(nid, N_HIGH_MEMORY);
7284 if (zone_type <= ZONE_NORMAL)
7285 node_set_state(nid, N_NORMAL_MEMORY);
7292 * free_area_init_nodes - Initialise all pg_data_t and zone data
7293 * @max_zone_pfn: an array of max PFNs for each zone
7295 * This will call free_area_init_node() for each active node in the system.
7296 * Using the page ranges provided by memblock_set_node(), the size of each
7297 * zone in each node and their holes is calculated. If the maximum PFN
7298 * between two adjacent zones match, it is assumed that the zone is empty.
7299 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
7300 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
7301 * starts where the previous one ended. For example, ZONE_DMA32 starts
7302 * at arch_max_dma_pfn.
7304 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
7306 unsigned long start_pfn, end_pfn;
7309 /* Record where the zone boundaries are */
7310 memset(arch_zone_lowest_possible_pfn, 0,
7311 sizeof(arch_zone_lowest_possible_pfn));
7312 memset(arch_zone_highest_possible_pfn, 0,
7313 sizeof(arch_zone_highest_possible_pfn));
7315 start_pfn = find_min_pfn_with_active_regions();
7317 for (i = 0; i < MAX_NR_ZONES; i++) {
7318 if (i == ZONE_MOVABLE)
7321 end_pfn = max(max_zone_pfn[i], start_pfn);
7322 arch_zone_lowest_possible_pfn[i] = start_pfn;
7323 arch_zone_highest_possible_pfn[i] = end_pfn;
7325 start_pfn = end_pfn;
7328 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
7329 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
7330 find_zone_movable_pfns_for_nodes();
7332 /* Print out the zone ranges */
7333 pr_info("Zone ranges:\n");
7334 for (i = 0; i < MAX_NR_ZONES; i++) {
7335 if (i == ZONE_MOVABLE)
7337 pr_info(" %-8s ", zone_names[i]);
7338 if (arch_zone_lowest_possible_pfn[i] ==
7339 arch_zone_highest_possible_pfn[i])
7342 pr_cont("[mem %#018Lx-%#018Lx]\n",
7343 (u64)arch_zone_lowest_possible_pfn[i]
7345 ((u64)arch_zone_highest_possible_pfn[i]
7346 << PAGE_SHIFT) - 1);
7349 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
7350 pr_info("Movable zone start for each node\n");
7351 for (i = 0; i < MAX_NUMNODES; i++) {
7352 if (zone_movable_pfn[i])
7353 pr_info(" Node %d: %#018Lx\n", i,
7354 (u64)zone_movable_pfn[i] << PAGE_SHIFT);
7358 * Print out the early node map, and initialize the
7359 * subsection-map relative to active online memory ranges to
7360 * enable future "sub-section" extensions of the memory map.
7362 pr_info("Early memory node ranges\n");
7363 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7364 pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid,
7365 (u64)start_pfn << PAGE_SHIFT,
7366 ((u64)end_pfn << PAGE_SHIFT) - 1);
7367 subsection_map_init(start_pfn, end_pfn - start_pfn);
7370 /* Initialise every node */
7371 mminit_verify_pageflags_layout();
7372 setup_nr_node_ids();
7373 zero_resv_unavail();
7374 for_each_online_node(nid) {
7375 pg_data_t *pgdat = NODE_DATA(nid);
7376 free_area_init_node(nid, NULL,
7377 find_min_pfn_for_node(nid), NULL);
7379 /* Any memory on that node */
7380 if (pgdat->node_present_pages)
7381 node_set_state(nid, N_MEMORY);
7382 check_for_memory(pgdat, nid);
7386 static int __init cmdline_parse_core(char *p, unsigned long *core,
7387 unsigned long *percent)
7389 unsigned long long coremem;
7395 /* Value may be a percentage of total memory, otherwise bytes */
7396 coremem = simple_strtoull(p, &endptr, 0);
7397 if (*endptr == '%') {
7398 /* Paranoid check for percent values greater than 100 */
7399 WARN_ON(coremem > 100);
7403 coremem = memparse(p, &p);
7404 /* Paranoid check that UL is enough for the coremem value */
7405 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
7407 *core = coremem >> PAGE_SHIFT;
7414 * kernelcore=size sets the amount of memory for use for allocations that
7415 * cannot be reclaimed or migrated.
7417 static int __init cmdline_parse_kernelcore(char *p)
7419 /* parse kernelcore=mirror */
7420 if (parse_option_str(p, "mirror")) {
7421 mirrored_kernelcore = true;
7425 return cmdline_parse_core(p, &required_kernelcore,
7426 &required_kernelcore_percent);
7430 * movablecore=size sets the amount of memory for use for allocations that
7431 * can be reclaimed or migrated.
7433 static int __init cmdline_parse_movablecore(char *p)
7435 return cmdline_parse_core(p, &required_movablecore,
7436 &required_movablecore_percent);
7439 early_param("kernelcore", cmdline_parse_kernelcore);
7440 early_param("movablecore", cmdline_parse_movablecore);
7442 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
7444 void adjust_managed_page_count(struct page *page, long count)
7446 atomic_long_add(count, &page_zone(page)->managed_pages);
7447 totalram_pages_add(count);
7448 #ifdef CONFIG_HIGHMEM
7449 if (PageHighMem(page))
7450 totalhigh_pages_add(count);
7453 EXPORT_SYMBOL(adjust_managed_page_count);
7455 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
7458 unsigned long pages = 0;
7460 start = (void *)PAGE_ALIGN((unsigned long)start);
7461 end = (void *)((unsigned long)end & PAGE_MASK);
7462 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
7463 struct page *page = virt_to_page(pos);
7464 void *direct_map_addr;
7467 * 'direct_map_addr' might be different from 'pos'
7468 * because some architectures' virt_to_page()
7469 * work with aliases. Getting the direct map
7470 * address ensures that we get a _writeable_
7471 * alias for the memset().
7473 direct_map_addr = page_address(page);
7474 if ((unsigned int)poison <= 0xFF)
7475 memset(direct_map_addr, poison, PAGE_SIZE);
7477 free_reserved_page(page);
7481 pr_info("Freeing %s memory: %ldK\n",
7482 s, pages << (PAGE_SHIFT - 10));
7487 #ifdef CONFIG_HIGHMEM
7488 void free_highmem_page(struct page *page)
7490 __free_reserved_page(page);
7491 totalram_pages_inc();
7492 atomic_long_inc(&page_zone(page)->managed_pages);
7493 totalhigh_pages_inc();
7498 void __init mem_init_print_info(const char *str)
7500 unsigned long physpages, codesize, datasize, rosize, bss_size;
7501 unsigned long init_code_size, init_data_size;
7503 physpages = get_num_physpages();
7504 codesize = _etext - _stext;
7505 datasize = _edata - _sdata;
7506 rosize = __end_rodata - __start_rodata;
7507 bss_size = __bss_stop - __bss_start;
7508 init_data_size = __init_end - __init_begin;
7509 init_code_size = _einittext - _sinittext;
7512 * Detect special cases and adjust section sizes accordingly:
7513 * 1) .init.* may be embedded into .data sections
7514 * 2) .init.text.* may be out of [__init_begin, __init_end],
7515 * please refer to arch/tile/kernel/vmlinux.lds.S.
7516 * 3) .rodata.* may be embedded into .text or .data sections.
7518 #define adj_init_size(start, end, size, pos, adj) \
7520 if (start <= pos && pos < end && size > adj) \
7524 adj_init_size(__init_begin, __init_end, init_data_size,
7525 _sinittext, init_code_size);
7526 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
7527 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
7528 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
7529 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
7531 #undef adj_init_size
7533 pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
7534 #ifdef CONFIG_HIGHMEM
7538 nr_free_pages() << (PAGE_SHIFT - 10),
7539 physpages << (PAGE_SHIFT - 10),
7540 codesize >> 10, datasize >> 10, rosize >> 10,
7541 (init_data_size + init_code_size) >> 10, bss_size >> 10,
7542 (physpages - totalram_pages() - totalcma_pages) << (PAGE_SHIFT - 10),
7543 totalcma_pages << (PAGE_SHIFT - 10),
7544 #ifdef CONFIG_HIGHMEM
7545 totalhigh_pages() << (PAGE_SHIFT - 10),
7547 str ? ", " : "", str ? str : "");
7551 * set_dma_reserve - set the specified number of pages reserved in the first zone
7552 * @new_dma_reserve: The number of pages to mark reserved
7554 * The per-cpu batchsize and zone watermarks are determined by managed_pages.
7555 * In the DMA zone, a significant percentage may be consumed by kernel image
7556 * and other unfreeable allocations which can skew the watermarks badly. This
7557 * function may optionally be used to account for unfreeable pages in the
7558 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
7559 * smaller per-cpu batchsize.
7561 void __init set_dma_reserve(unsigned long new_dma_reserve)
7563 dma_reserve = new_dma_reserve;
7566 void __init free_area_init(unsigned long *zones_size)
7568 zero_resv_unavail();
7569 free_area_init_node(0, zones_size,
7570 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
7573 static int page_alloc_cpu_dead(unsigned int cpu)
7576 lru_add_drain_cpu(cpu);
7580 * Spill the event counters of the dead processor
7581 * into the current processors event counters.
7582 * This artificially elevates the count of the current
7585 vm_events_fold_cpu(cpu);
7588 * Zero the differential counters of the dead processor
7589 * so that the vm statistics are consistent.
7591 * This is only okay since the processor is dead and cannot
7592 * race with what we are doing.
7594 cpu_vm_stats_fold(cpu);
7599 int hashdist = HASHDIST_DEFAULT;
7601 static int __init set_hashdist(char *str)
7605 hashdist = simple_strtoul(str, &str, 0);
7608 __setup("hashdist=", set_hashdist);
7611 void __init page_alloc_init(void)
7616 if (num_node_state(N_MEMORY) == 1)
7620 ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC_DEAD,
7621 "mm/page_alloc:dead", NULL,
7622 page_alloc_cpu_dead);
7627 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
7628 * or min_free_kbytes changes.
7630 static void calculate_totalreserve_pages(void)
7632 struct pglist_data *pgdat;
7633 unsigned long reserve_pages = 0;
7634 enum zone_type i, j;
7636 for_each_online_pgdat(pgdat) {
7638 pgdat->totalreserve_pages = 0;
7640 for (i = 0; i < MAX_NR_ZONES; i++) {
7641 struct zone *zone = pgdat->node_zones + i;
7643 unsigned long managed_pages = zone_managed_pages(zone);
7645 /* Find valid and maximum lowmem_reserve in the zone */
7646 for (j = i; j < MAX_NR_ZONES; j++) {
7647 if (zone->lowmem_reserve[j] > max)
7648 max = zone->lowmem_reserve[j];
7651 /* we treat the high watermark as reserved pages. */
7652 max += high_wmark_pages(zone);
7654 if (max > managed_pages)
7655 max = managed_pages;
7657 pgdat->totalreserve_pages += max;
7659 reserve_pages += max;
7662 totalreserve_pages = reserve_pages;
7666 * setup_per_zone_lowmem_reserve - called whenever
7667 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
7668 * has a correct pages reserved value, so an adequate number of
7669 * pages are left in the zone after a successful __alloc_pages().
7671 static void setup_per_zone_lowmem_reserve(void)
7673 struct pglist_data *pgdat;
7674 enum zone_type j, idx;
7676 for_each_online_pgdat(pgdat) {
7677 for (j = 0; j < MAX_NR_ZONES; j++) {
7678 struct zone *zone = pgdat->node_zones + j;
7679 unsigned long managed_pages = zone_managed_pages(zone);
7681 zone->lowmem_reserve[j] = 0;
7685 struct zone *lower_zone;
7688 lower_zone = pgdat->node_zones + idx;
7690 if (sysctl_lowmem_reserve_ratio[idx] < 1) {
7691 sysctl_lowmem_reserve_ratio[idx] = 0;
7692 lower_zone->lowmem_reserve[j] = 0;
7694 lower_zone->lowmem_reserve[j] =
7695 managed_pages / sysctl_lowmem_reserve_ratio[idx];
7697 managed_pages += zone_managed_pages(lower_zone);
7702 /* update totalreserve_pages */
7703 calculate_totalreserve_pages();
7706 static void __setup_per_zone_wmarks(void)
7708 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
7709 unsigned long lowmem_pages = 0;
7711 unsigned long flags;
7713 /* Calculate total number of !ZONE_HIGHMEM pages */
7714 for_each_zone(zone) {
7715 if (!is_highmem(zone))
7716 lowmem_pages += zone_managed_pages(zone);
7719 for_each_zone(zone) {
7722 spin_lock_irqsave(&zone->lock, flags);
7723 tmp = (u64)pages_min * zone_managed_pages(zone);
7724 do_div(tmp, lowmem_pages);
7725 if (is_highmem(zone)) {
7727 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
7728 * need highmem pages, so cap pages_min to a small
7731 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
7732 * deltas control async page reclaim, and so should
7733 * not be capped for highmem.
7735 unsigned long min_pages;
7737 min_pages = zone_managed_pages(zone) / 1024;
7738 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
7739 zone->_watermark[WMARK_MIN] = min_pages;
7742 * If it's a lowmem zone, reserve a number of pages
7743 * proportionate to the zone's size.
7745 zone->_watermark[WMARK_MIN] = tmp;
7749 * Set the kswapd watermarks distance according to the
7750 * scale factor in proportion to available memory, but
7751 * ensure a minimum size on small systems.
7753 tmp = max_t(u64, tmp >> 2,
7754 mult_frac(zone_managed_pages(zone),
7755 watermark_scale_factor, 10000));
7757 zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp;
7758 zone->_watermark[WMARK_HIGH] = min_wmark_pages(zone) + tmp * 2;
7759 zone->watermark_boost = 0;
7761 spin_unlock_irqrestore(&zone->lock, flags);
7764 /* update totalreserve_pages */
7765 calculate_totalreserve_pages();
7769 * setup_per_zone_wmarks - called when min_free_kbytes changes
7770 * or when memory is hot-{added|removed}
7772 * Ensures that the watermark[min,low,high] values for each zone are set
7773 * correctly with respect to min_free_kbytes.
7775 void setup_per_zone_wmarks(void)
7777 static DEFINE_SPINLOCK(lock);
7780 __setup_per_zone_wmarks();
7785 * Initialise min_free_kbytes.
7787 * For small machines we want it small (128k min). For large machines
7788 * we want it large (64MB max). But it is not linear, because network
7789 * bandwidth does not increase linearly with machine size. We use
7791 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
7792 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
7808 int __meminit init_per_zone_wmark_min(void)
7810 unsigned long lowmem_kbytes;
7811 int new_min_free_kbytes;
7813 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
7814 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
7816 if (new_min_free_kbytes > user_min_free_kbytes) {
7817 min_free_kbytes = new_min_free_kbytes;
7818 if (min_free_kbytes < 128)
7819 min_free_kbytes = 128;
7820 if (min_free_kbytes > 65536)
7821 min_free_kbytes = 65536;
7823 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
7824 new_min_free_kbytes, user_min_free_kbytes);
7826 setup_per_zone_wmarks();
7827 refresh_zone_stat_thresholds();
7828 setup_per_zone_lowmem_reserve();
7831 setup_min_unmapped_ratio();
7832 setup_min_slab_ratio();
7837 core_initcall(init_per_zone_wmark_min)
7840 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
7841 * that we can call two helper functions whenever min_free_kbytes
7844 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
7845 void __user *buffer, size_t *length, loff_t *ppos)
7849 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7854 user_min_free_kbytes = min_free_kbytes;
7855 setup_per_zone_wmarks();
7860 int watermark_boost_factor_sysctl_handler(struct ctl_table *table, int write,
7861 void __user *buffer, size_t *length, loff_t *ppos)
7865 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7872 int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write,
7873 void __user *buffer, size_t *length, loff_t *ppos)
7877 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7882 setup_per_zone_wmarks();
7888 static void setup_min_unmapped_ratio(void)
7893 for_each_online_pgdat(pgdat)
7894 pgdat->min_unmapped_pages = 0;
7897 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
7898 sysctl_min_unmapped_ratio) / 100;
7902 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
7903 void __user *buffer, size_t *length, loff_t *ppos)
7907 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7911 setup_min_unmapped_ratio();
7916 static void setup_min_slab_ratio(void)
7921 for_each_online_pgdat(pgdat)
7922 pgdat->min_slab_pages = 0;
7925 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
7926 sysctl_min_slab_ratio) / 100;
7929 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
7930 void __user *buffer, size_t *length, loff_t *ppos)
7934 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7938 setup_min_slab_ratio();
7945 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
7946 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
7947 * whenever sysctl_lowmem_reserve_ratio changes.
7949 * The reserve ratio obviously has absolutely no relation with the
7950 * minimum watermarks. The lowmem reserve ratio can only make sense
7951 * if in function of the boot time zone sizes.
7953 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
7954 void __user *buffer, size_t *length, loff_t *ppos)
7956 proc_dointvec_minmax(table, write, buffer, length, ppos);
7957 setup_per_zone_lowmem_reserve();
7962 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
7963 * cpu. It is the fraction of total pages in each zone that a hot per cpu
7964 * pagelist can have before it gets flushed back to buddy allocator.
7966 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
7967 void __user *buffer, size_t *length, loff_t *ppos)
7970 int old_percpu_pagelist_fraction;
7973 mutex_lock(&pcp_batch_high_lock);
7974 old_percpu_pagelist_fraction = percpu_pagelist_fraction;
7976 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
7977 if (!write || ret < 0)
7980 /* Sanity checking to avoid pcp imbalance */
7981 if (percpu_pagelist_fraction &&
7982 percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
7983 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
7989 if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
7992 for_each_populated_zone(zone) {
7995 for_each_possible_cpu(cpu)
7996 pageset_set_high_and_batch(zone,
7997 per_cpu_ptr(zone->pageset, cpu));
8000 mutex_unlock(&pcp_batch_high_lock);
8004 #ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES
8006 * Returns the number of pages that arch has reserved but
8007 * is not known to alloc_large_system_hash().
8009 static unsigned long __init arch_reserved_kernel_pages(void)
8016 * Adaptive scale is meant to reduce sizes of hash tables on large memory
8017 * machines. As memory size is increased the scale is also increased but at
8018 * slower pace. Starting from ADAPT_SCALE_BASE (64G), every time memory
8019 * quadruples the scale is increased by one, which means the size of hash table
8020 * only doubles, instead of quadrupling as well.
8021 * Because 32-bit systems cannot have large physical memory, where this scaling
8022 * makes sense, it is disabled on such platforms.
8024 #if __BITS_PER_LONG > 32
8025 #define ADAPT_SCALE_BASE (64ul << 30)
8026 #define ADAPT_SCALE_SHIFT 2
8027 #define ADAPT_SCALE_NPAGES (ADAPT_SCALE_BASE >> PAGE_SHIFT)
8031 * allocate a large system hash table from bootmem
8032 * - it is assumed that the hash table must contain an exact power-of-2
8033 * quantity of entries
8034 * - limit is the number of hash buckets, not the total allocation size
8036 void *__init alloc_large_system_hash(const char *tablename,
8037 unsigned long bucketsize,
8038 unsigned long numentries,
8041 unsigned int *_hash_shift,
8042 unsigned int *_hash_mask,
8043 unsigned long low_limit,
8044 unsigned long high_limit)
8046 unsigned long long max = high_limit;
8047 unsigned long log2qty, size;
8052 /* allow the kernel cmdline to have a say */
8054 /* round applicable memory size up to nearest megabyte */
8055 numentries = nr_kernel_pages;
8056 numentries -= arch_reserved_kernel_pages();
8058 /* It isn't necessary when PAGE_SIZE >= 1MB */
8059 if (PAGE_SHIFT < 20)
8060 numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
8062 #if __BITS_PER_LONG > 32
8064 unsigned long adapt;
8066 for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
8067 adapt <<= ADAPT_SCALE_SHIFT)
8072 /* limit to 1 bucket per 2^scale bytes of low memory */
8073 if (scale > PAGE_SHIFT)
8074 numentries >>= (scale - PAGE_SHIFT);
8076 numentries <<= (PAGE_SHIFT - scale);
8078 /* Make sure we've got at least a 0-order allocation.. */
8079 if (unlikely(flags & HASH_SMALL)) {
8080 /* Makes no sense without HASH_EARLY */
8081 WARN_ON(!(flags & HASH_EARLY));
8082 if (!(numentries >> *_hash_shift)) {
8083 numentries = 1UL << *_hash_shift;
8084 BUG_ON(!numentries);
8086 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
8087 numentries = PAGE_SIZE / bucketsize;
8089 numentries = roundup_pow_of_two(numentries);
8091 /* limit allocation size to 1/16 total memory by default */
8093 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
8094 do_div(max, bucketsize);
8096 max = min(max, 0x80000000ULL);
8098 if (numentries < low_limit)
8099 numentries = low_limit;
8100 if (numentries > max)
8103 log2qty = ilog2(numentries);
8105 gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
8108 size = bucketsize << log2qty;
8109 if (flags & HASH_EARLY) {
8110 if (flags & HASH_ZERO)
8111 table = memblock_alloc(size, SMP_CACHE_BYTES);
8113 table = memblock_alloc_raw(size,
8115 } else if (get_order(size) >= MAX_ORDER || hashdist) {
8116 table = __vmalloc(size, gfp_flags, PAGE_KERNEL);
8120 * If bucketsize is not a power-of-two, we may free
8121 * some pages at the end of hash table which
8122 * alloc_pages_exact() automatically does
8124 table = alloc_pages_exact(size, gfp_flags);
8125 kmemleak_alloc(table, size, 1, gfp_flags);
8127 } while (!table && size > PAGE_SIZE && --log2qty);
8130 panic("Failed to allocate %s hash table\n", tablename);
8132 pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n",
8133 tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size,
8134 virt ? "vmalloc" : "linear");
8137 *_hash_shift = log2qty;
8139 *_hash_mask = (1 << log2qty) - 1;
8145 * This function checks whether pageblock includes unmovable pages or not.
8146 * If @count is not zero, it is okay to include less @count unmovable pages
8148 * PageLRU check without isolation or lru_lock could race so that
8149 * MIGRATE_MOVABLE block might include unmovable pages. And __PageMovable
8150 * check without lock_page also may miss some movable non-lru pages at
8151 * race condition. So you can't expect this function should be exact.
8153 bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
8154 int migratetype, int flags)
8156 unsigned long found;
8157 unsigned long iter = 0;
8158 unsigned long pfn = page_to_pfn(page);
8159 const char *reason = "unmovable page";
8162 * TODO we could make this much more efficient by not checking every
8163 * page in the range if we know all of them are in MOVABLE_ZONE and
8164 * that the movable zone guarantees that pages are migratable but
8165 * the later is not the case right now unfortunatelly. E.g. movablecore
8166 * can still lead to having bootmem allocations in zone_movable.
8169 if (is_migrate_cma_page(page)) {
8171 * CMA allocations (alloc_contig_range) really need to mark
8172 * isolate CMA pageblocks even when they are not movable in fact
8173 * so consider them movable here.
8175 if (is_migrate_cma(migratetype))
8178 reason = "CMA page";
8182 for (found = 0; iter < pageblock_nr_pages; iter++) {
8183 unsigned long check = pfn + iter;
8185 if (!pfn_valid_within(check))
8188 page = pfn_to_page(check);
8190 if (PageReserved(page))
8194 * If the zone is movable and we have ruled out all reserved
8195 * pages then it should be reasonably safe to assume the rest
8198 if (zone_idx(zone) == ZONE_MOVABLE)
8202 * Hugepages are not in LRU lists, but they're movable.
8203 * We need not scan over tail pages because we don't
8204 * handle each tail page individually in migration.
8206 if (PageHuge(page)) {
8207 struct page *head = compound_head(page);
8208 unsigned int skip_pages;
8210 if (!hugepage_migration_supported(page_hstate(head)))
8213 skip_pages = (1 << compound_order(head)) - (page - head);
8214 iter += skip_pages - 1;
8219 * We can't use page_count without pin a page
8220 * because another CPU can free compound page.
8221 * This check already skips compound tails of THP
8222 * because their page->_refcount is zero at all time.
8224 if (!page_ref_count(page)) {
8225 if (PageBuddy(page))
8226 iter += (1 << page_order(page)) - 1;
8231 * The HWPoisoned page may be not in buddy system, and
8232 * page_count() is not 0.
8234 if ((flags & SKIP_HWPOISON) && PageHWPoison(page))
8237 if (__PageMovable(page))
8243 * If there are RECLAIMABLE pages, we need to check
8244 * it. But now, memory offline itself doesn't call
8245 * shrink_node_slabs() and it still to be fixed.
8248 * If the page is not RAM, page_count()should be 0.
8249 * we don't need more check. This is an _used_ not-movable page.
8251 * The problematic thing here is PG_reserved pages. PG_reserved
8252 * is set to both of a memory hole page and a _used_ kernel
8260 WARN_ON_ONCE(zone_idx(zone) == ZONE_MOVABLE);
8261 if (flags & REPORT_FAILURE)
8262 dump_page(pfn_to_page(pfn + iter), reason);
8266 #ifdef CONFIG_CONTIG_ALLOC
8267 static unsigned long pfn_max_align_down(unsigned long pfn)
8269 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
8270 pageblock_nr_pages) - 1);
8273 static unsigned long pfn_max_align_up(unsigned long pfn)
8275 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
8276 pageblock_nr_pages));
8279 /* [start, end) must belong to a single zone. */
8280 static int __alloc_contig_migrate_range(struct compact_control *cc,
8281 unsigned long start, unsigned long end)
8283 /* This function is based on compact_zone() from compaction.c. */
8284 unsigned long nr_reclaimed;
8285 unsigned long pfn = start;
8286 unsigned int tries = 0;
8291 while (pfn < end || !list_empty(&cc->migratepages)) {
8292 if (fatal_signal_pending(current)) {
8297 if (list_empty(&cc->migratepages)) {
8298 cc->nr_migratepages = 0;
8299 pfn = isolate_migratepages_range(cc, pfn, end);
8305 } else if (++tries == 5) {
8306 ret = ret < 0 ? ret : -EBUSY;
8310 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
8312 cc->nr_migratepages -= nr_reclaimed;
8314 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
8315 NULL, 0, cc->mode, MR_CONTIG_RANGE);
8318 putback_movable_pages(&cc->migratepages);
8325 * alloc_contig_range() -- tries to allocate given range of pages
8326 * @start: start PFN to allocate
8327 * @end: one-past-the-last PFN to allocate
8328 * @migratetype: migratetype of the underlaying pageblocks (either
8329 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
8330 * in range must have the same migratetype and it must
8331 * be either of the two.
8332 * @gfp_mask: GFP mask to use during compaction
8334 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
8335 * aligned. The PFN range must belong to a single zone.
8337 * The first thing this routine does is attempt to MIGRATE_ISOLATE all
8338 * pageblocks in the range. Once isolated, the pageblocks should not
8339 * be modified by others.
8341 * Return: zero on success or negative error code. On success all
8342 * pages which PFN is in [start, end) are allocated for the caller and
8343 * need to be freed with free_contig_range().
8345 int alloc_contig_range(unsigned long start, unsigned long end,
8346 unsigned migratetype, gfp_t gfp_mask)
8348 unsigned long outer_start, outer_end;
8352 struct compact_control cc = {
8353 .nr_migratepages = 0,
8355 .zone = page_zone(pfn_to_page(start)),
8356 .mode = MIGRATE_SYNC,
8357 .ignore_skip_hint = true,
8358 .no_set_skip_hint = true,
8359 .gfp_mask = current_gfp_context(gfp_mask),
8361 INIT_LIST_HEAD(&cc.migratepages);
8364 * What we do here is we mark all pageblocks in range as
8365 * MIGRATE_ISOLATE. Because pageblock and max order pages may
8366 * have different sizes, and due to the way page allocator
8367 * work, we align the range to biggest of the two pages so
8368 * that page allocator won't try to merge buddies from
8369 * different pageblocks and change MIGRATE_ISOLATE to some
8370 * other migration type.
8372 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
8373 * migrate the pages from an unaligned range (ie. pages that
8374 * we are interested in). This will put all the pages in
8375 * range back to page allocator as MIGRATE_ISOLATE.
8377 * When this is done, we take the pages in range from page
8378 * allocator removing them from the buddy system. This way
8379 * page allocator will never consider using them.
8381 * This lets us mark the pageblocks back as
8382 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
8383 * aligned range but not in the unaligned, original range are
8384 * put back to page allocator so that buddy can use them.
8387 ret = start_isolate_page_range(pfn_max_align_down(start),
8388 pfn_max_align_up(end), migratetype, 0);
8393 * In case of -EBUSY, we'd like to know which page causes problem.
8394 * So, just fall through. test_pages_isolated() has a tracepoint
8395 * which will report the busy page.
8397 * It is possible that busy pages could become available before
8398 * the call to test_pages_isolated, and the range will actually be
8399 * allocated. So, if we fall through be sure to clear ret so that
8400 * -EBUSY is not accidentally used or returned to caller.
8402 ret = __alloc_contig_migrate_range(&cc, start, end);
8403 if (ret && ret != -EBUSY)
8408 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
8409 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
8410 * more, all pages in [start, end) are free in page allocator.
8411 * What we are going to do is to allocate all pages from
8412 * [start, end) (that is remove them from page allocator).
8414 * The only problem is that pages at the beginning and at the
8415 * end of interesting range may be not aligned with pages that
8416 * page allocator holds, ie. they can be part of higher order
8417 * pages. Because of this, we reserve the bigger range and
8418 * once this is done free the pages we are not interested in.
8420 * We don't have to hold zone->lock here because the pages are
8421 * isolated thus they won't get removed from buddy.
8424 lru_add_drain_all();
8427 outer_start = start;
8428 while (!PageBuddy(pfn_to_page(outer_start))) {
8429 if (++order >= MAX_ORDER) {
8430 outer_start = start;
8433 outer_start &= ~0UL << order;
8436 if (outer_start != start) {
8437 order = page_order(pfn_to_page(outer_start));
8440 * outer_start page could be small order buddy page and
8441 * it doesn't include start page. Adjust outer_start
8442 * in this case to report failed page properly
8443 * on tracepoint in test_pages_isolated()
8445 if (outer_start + (1UL << order) <= start)
8446 outer_start = start;
8449 /* Make sure the range is really isolated. */
8450 if (test_pages_isolated(outer_start, end, false)) {
8451 pr_info_ratelimited("%s: [%lx, %lx) PFNs busy\n",
8452 __func__, outer_start, end);
8457 /* Grab isolated pages from freelists. */
8458 outer_end = isolate_freepages_range(&cc, outer_start, end);
8464 /* Free head and tail (if any) */
8465 if (start != outer_start)
8466 free_contig_range(outer_start, start - outer_start);
8467 if (end != outer_end)
8468 free_contig_range(end, outer_end - end);
8471 undo_isolate_page_range(pfn_max_align_down(start),
8472 pfn_max_align_up(end), migratetype);
8475 #endif /* CONFIG_CONTIG_ALLOC */
8477 void free_contig_range(unsigned long pfn, unsigned int nr_pages)
8479 unsigned int count = 0;
8481 for (; nr_pages--; pfn++) {
8482 struct page *page = pfn_to_page(pfn);
8484 count += page_count(page) != 1;
8487 WARN(count != 0, "%d pages are still in use!\n", count);
8491 * The zone indicated has a new number of managed_pages; batch sizes and percpu
8492 * page high values need to be recalulated.
8494 void __meminit zone_pcp_update(struct zone *zone)
8497 mutex_lock(&pcp_batch_high_lock);
8498 for_each_possible_cpu(cpu)
8499 pageset_set_high_and_batch(zone,
8500 per_cpu_ptr(zone->pageset, cpu));
8501 mutex_unlock(&pcp_batch_high_lock);
8504 void zone_pcp_reset(struct zone *zone)
8506 unsigned long flags;
8508 struct per_cpu_pageset *pset;
8510 /* avoid races with drain_pages() */
8511 local_irq_save(flags);
8512 if (zone->pageset != &boot_pageset) {
8513 for_each_online_cpu(cpu) {
8514 pset = per_cpu_ptr(zone->pageset, cpu);
8515 drain_zonestat(zone, pset);
8517 free_percpu(zone->pageset);
8518 zone->pageset = &boot_pageset;
8520 local_irq_restore(flags);
8523 #ifdef CONFIG_MEMORY_HOTREMOVE
8525 * All pages in the range must be in a single zone and isolated
8526 * before calling this.
8529 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
8533 unsigned int order, i;
8535 unsigned long flags;
8536 unsigned long offlined_pages = 0;
8538 /* find the first valid pfn */
8539 for (pfn = start_pfn; pfn < end_pfn; pfn++)
8543 return offlined_pages;
8545 offline_mem_sections(pfn, end_pfn);
8546 zone = page_zone(pfn_to_page(pfn));
8547 spin_lock_irqsave(&zone->lock, flags);
8549 while (pfn < end_pfn) {
8550 if (!pfn_valid(pfn)) {
8554 page = pfn_to_page(pfn);
8556 * The HWPoisoned page may be not in buddy system, and
8557 * page_count() is not 0.
8559 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
8561 SetPageReserved(page);
8566 BUG_ON(page_count(page));
8567 BUG_ON(!PageBuddy(page));
8568 order = page_order(page);
8569 offlined_pages += 1 << order;
8570 #ifdef CONFIG_DEBUG_VM
8571 pr_info("remove from free list %lx %d %lx\n",
8572 pfn, 1 << order, end_pfn);
8574 del_page_from_free_area(page, &zone->free_area[order]);
8575 for (i = 0; i < (1 << order); i++)
8576 SetPageReserved((page+i));
8577 pfn += (1 << order);
8579 spin_unlock_irqrestore(&zone->lock, flags);
8581 return offlined_pages;
8585 bool is_free_buddy_page(struct page *page)
8587 struct zone *zone = page_zone(page);
8588 unsigned long pfn = page_to_pfn(page);
8589 unsigned long flags;
8592 spin_lock_irqsave(&zone->lock, flags);
8593 for (order = 0; order < MAX_ORDER; order++) {
8594 struct page *page_head = page - (pfn & ((1 << order) - 1));
8596 if (PageBuddy(page_head) && page_order(page_head) >= order)
8599 spin_unlock_irqrestore(&zone->lock, flags);
8601 return order < MAX_ORDER;
8604 #ifdef CONFIG_MEMORY_FAILURE
8606 * Set PG_hwpoison flag if a given page is confirmed to be a free page. This
8607 * test is performed under the zone lock to prevent a race against page
8610 bool set_hwpoison_free_buddy_page(struct page *page)
8612 struct zone *zone = page_zone(page);
8613 unsigned long pfn = page_to_pfn(page);
8614 unsigned long flags;
8616 bool hwpoisoned = false;
8618 spin_lock_irqsave(&zone->lock, flags);
8619 for (order = 0; order < MAX_ORDER; order++) {
8620 struct page *page_head = page - (pfn & ((1 << order) - 1));
8622 if (PageBuddy(page_head) && page_order(page_head) >= order) {
8623 if (!TestSetPageHWPoison(page))
8628 spin_unlock_irqrestore(&zone->lock, flags);