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>
77 #include "page_reporting.h"
79 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
80 static DEFINE_MUTEX(pcp_batch_high_lock);
81 #define MIN_PERCPU_PAGELIST_FRACTION (8)
83 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
84 DEFINE_PER_CPU(int, numa_node);
85 EXPORT_PER_CPU_SYMBOL(numa_node);
88 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
90 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
92 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
93 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
94 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
95 * defined in <linux/topology.h>.
97 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
98 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
101 /* work_structs for global per-cpu drains */
104 struct work_struct work;
106 static DEFINE_MUTEX(pcpu_drain_mutex);
107 static 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 static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata;
339 static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata;
340 static unsigned long required_kernelcore __initdata;
341 static unsigned long required_kernelcore_percent __initdata;
342 static unsigned long required_movablecore __initdata;
343 static unsigned long required_movablecore_percent __initdata;
344 static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata;
345 static bool mirrored_kernelcore __meminitdata;
347 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
349 EXPORT_SYMBOL(movable_zone);
352 unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
353 unsigned int nr_online_nodes __read_mostly = 1;
354 EXPORT_SYMBOL(nr_node_ids);
355 EXPORT_SYMBOL(nr_online_nodes);
358 int page_group_by_mobility_disabled __read_mostly;
360 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
362 * During boot we initialize deferred pages on-demand, as needed, but once
363 * page_alloc_init_late() has finished, the deferred pages are all initialized,
364 * and we can permanently disable that path.
366 static DEFINE_STATIC_KEY_TRUE(deferred_pages);
369 * Calling kasan_free_pages() only after deferred memory initialization
370 * has completed. Poisoning pages during deferred memory init will greatly
371 * lengthen the process and cause problem in large memory systems as the
372 * deferred pages initialization is done with interrupt disabled.
374 * Assuming that there will be no reference to those newly initialized
375 * pages before they are ever allocated, this should have no effect on
376 * KASAN memory tracking as the poison will be properly inserted at page
377 * allocation time. The only corner case is when pages are allocated by
378 * on-demand allocation and then freed again before the deferred pages
379 * initialization is done, but this is not likely to happen.
381 static inline void kasan_free_nondeferred_pages(struct page *page, int order)
383 if (!static_branch_unlikely(&deferred_pages))
384 kasan_free_pages(page, order);
387 /* Returns true if the struct page for the pfn is uninitialised */
388 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
390 int nid = early_pfn_to_nid(pfn);
392 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
399 * Returns true when the remaining initialisation should be deferred until
400 * later in the boot cycle when it can be parallelised.
402 static bool __meminit
403 defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
405 static unsigned long prev_end_pfn, nr_initialised;
408 * prev_end_pfn static that contains the end of previous zone
409 * No need to protect because called very early in boot before smp_init.
411 if (prev_end_pfn != end_pfn) {
412 prev_end_pfn = end_pfn;
416 /* Always populate low zones for address-constrained allocations */
417 if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
421 * We start only with one section of pages, more pages are added as
422 * needed until the rest of deferred pages are initialized.
425 if ((nr_initialised > PAGES_PER_SECTION) &&
426 (pfn & (PAGES_PER_SECTION - 1)) == 0) {
427 NODE_DATA(nid)->first_deferred_pfn = pfn;
433 #define kasan_free_nondeferred_pages(p, o) kasan_free_pages(p, o)
435 static inline bool early_page_uninitialised(unsigned long pfn)
440 static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
446 /* Return a pointer to the bitmap storing bits affecting a block of pages */
447 static inline unsigned long *get_pageblock_bitmap(struct page *page,
450 #ifdef CONFIG_SPARSEMEM
451 return section_to_usemap(__pfn_to_section(pfn));
453 return page_zone(page)->pageblock_flags;
454 #endif /* CONFIG_SPARSEMEM */
457 static inline int pfn_to_bitidx(struct page *page, unsigned long pfn)
459 #ifdef CONFIG_SPARSEMEM
460 pfn &= (PAGES_PER_SECTION-1);
461 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
463 pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
464 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
465 #endif /* CONFIG_SPARSEMEM */
469 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
470 * @page: The page within the block of interest
471 * @pfn: The target page frame number
472 * @end_bitidx: The last bit of interest to retrieve
473 * @mask: mask of bits that the caller is interested in
475 * Return: pageblock_bits flags
477 static __always_inline unsigned long __get_pfnblock_flags_mask(struct page *page,
479 unsigned long end_bitidx,
482 unsigned long *bitmap;
483 unsigned long bitidx, word_bitidx;
486 bitmap = get_pageblock_bitmap(page, pfn);
487 bitidx = pfn_to_bitidx(page, pfn);
488 word_bitidx = bitidx / BITS_PER_LONG;
489 bitidx &= (BITS_PER_LONG-1);
491 word = bitmap[word_bitidx];
492 bitidx += end_bitidx;
493 return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
496 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
497 unsigned long end_bitidx,
500 return __get_pfnblock_flags_mask(page, pfn, end_bitidx, mask);
503 static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn)
505 return __get_pfnblock_flags_mask(page, pfn, PB_migrate_end, MIGRATETYPE_MASK);
509 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
510 * @page: The page within the block of interest
511 * @flags: The flags to set
512 * @pfn: The target page frame number
513 * @end_bitidx: The last bit of interest
514 * @mask: mask of bits that the caller is interested in
516 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
518 unsigned long end_bitidx,
521 unsigned long *bitmap;
522 unsigned long bitidx, word_bitidx;
523 unsigned long old_word, word;
525 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
526 BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits));
528 bitmap = get_pageblock_bitmap(page, pfn);
529 bitidx = pfn_to_bitidx(page, pfn);
530 word_bitidx = bitidx / BITS_PER_LONG;
531 bitidx &= (BITS_PER_LONG-1);
533 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
535 bitidx += end_bitidx;
536 mask <<= (BITS_PER_LONG - bitidx - 1);
537 flags <<= (BITS_PER_LONG - bitidx - 1);
539 word = READ_ONCE(bitmap[word_bitidx]);
541 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
542 if (word == old_word)
548 void set_pageblock_migratetype(struct page *page, int migratetype)
550 if (unlikely(page_group_by_mobility_disabled &&
551 migratetype < MIGRATE_PCPTYPES))
552 migratetype = MIGRATE_UNMOVABLE;
554 set_pageblock_flags_group(page, (unsigned long)migratetype,
555 PB_migrate, PB_migrate_end);
558 #ifdef CONFIG_DEBUG_VM
559 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
563 unsigned long pfn = page_to_pfn(page);
564 unsigned long sp, start_pfn;
567 seq = zone_span_seqbegin(zone);
568 start_pfn = zone->zone_start_pfn;
569 sp = zone->spanned_pages;
570 if (!zone_spans_pfn(zone, pfn))
572 } while (zone_span_seqretry(zone, seq));
575 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
576 pfn, zone_to_nid(zone), zone->name,
577 start_pfn, start_pfn + sp);
582 static int page_is_consistent(struct zone *zone, struct page *page)
584 if (!pfn_valid_within(page_to_pfn(page)))
586 if (zone != page_zone(page))
592 * Temporary debugging check for pages not lying within a given zone.
594 static int __maybe_unused bad_range(struct zone *zone, struct page *page)
596 if (page_outside_zone_boundaries(zone, page))
598 if (!page_is_consistent(zone, page))
604 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
610 static void bad_page(struct page *page, const char *reason,
611 unsigned long bad_flags)
613 static unsigned long resume;
614 static unsigned long nr_shown;
615 static unsigned long nr_unshown;
618 * Allow a burst of 60 reports, then keep quiet for that minute;
619 * or allow a steady drip of one report per second.
621 if (nr_shown == 60) {
622 if (time_before(jiffies, resume)) {
628 "BUG: Bad page state: %lu messages suppressed\n",
635 resume = jiffies + 60 * HZ;
637 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
638 current->comm, page_to_pfn(page));
639 __dump_page(page, reason);
640 bad_flags &= page->flags;
642 pr_alert("bad because of flags: %#lx(%pGp)\n",
643 bad_flags, &bad_flags);
644 dump_page_owner(page);
649 /* Leave bad fields for debug, except PageBuddy could make trouble */
650 page_mapcount_reset(page); /* remove PageBuddy */
651 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
655 * Higher-order pages are called "compound pages". They are structured thusly:
657 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
659 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
660 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
662 * The first tail page's ->compound_dtor holds the offset in array of compound
663 * page destructors. See compound_page_dtors.
665 * The first tail page's ->compound_order holds the order of allocation.
666 * This usage means that zero-order pages may not be compound.
669 void free_compound_page(struct page *page)
671 mem_cgroup_uncharge(page);
672 __free_pages_ok(page, compound_order(page));
675 void prep_compound_page(struct page *page, unsigned int order)
678 int nr_pages = 1 << order;
680 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
681 set_compound_order(page, order);
683 for (i = 1; i < nr_pages; i++) {
684 struct page *p = page + i;
685 set_page_count(p, 0);
686 p->mapping = TAIL_MAPPING;
687 set_compound_head(p, page);
689 atomic_set(compound_mapcount_ptr(page), -1);
690 if (hpage_pincount_available(page))
691 atomic_set(compound_pincount_ptr(page), 0);
694 #ifdef CONFIG_DEBUG_PAGEALLOC
695 unsigned int _debug_guardpage_minorder;
697 bool _debug_pagealloc_enabled_early __read_mostly
698 = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
699 EXPORT_SYMBOL(_debug_pagealloc_enabled_early);
700 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)
707 return kstrtobool(buf, &_debug_pagealloc_enabled_early);
709 early_param("debug_pagealloc", early_debug_pagealloc);
711 void init_debug_pagealloc(void)
713 if (!debug_pagealloc_enabled())
716 static_branch_enable(&_debug_pagealloc_enabled);
718 if (!debug_guardpage_minorder())
721 static_branch_enable(&_debug_guardpage_enabled);
724 static int __init debug_guardpage_minorder_setup(char *buf)
728 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
729 pr_err("Bad debug_guardpage_minorder value\n");
732 _debug_guardpage_minorder = res;
733 pr_info("Setting debug_guardpage_minorder to %lu\n", res);
736 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
738 static inline bool set_page_guard(struct zone *zone, struct page *page,
739 unsigned int order, int migratetype)
741 if (!debug_guardpage_enabled())
744 if (order >= debug_guardpage_minorder())
747 __SetPageGuard(page);
748 INIT_LIST_HEAD(&page->lru);
749 set_page_private(page, order);
750 /* Guard pages are not available for any usage */
751 __mod_zone_freepage_state(zone, -(1 << order), migratetype);
756 static inline void clear_page_guard(struct zone *zone, struct page *page,
757 unsigned int order, int migratetype)
759 if (!debug_guardpage_enabled())
762 __ClearPageGuard(page);
764 set_page_private(page, 0);
765 if (!is_migrate_isolate(migratetype))
766 __mod_zone_freepage_state(zone, (1 << order), migratetype);
769 static inline bool set_page_guard(struct zone *zone, struct page *page,
770 unsigned int order, int migratetype) { return false; }
771 static inline void clear_page_guard(struct zone *zone, struct page *page,
772 unsigned int order, int migratetype) {}
775 static inline void set_page_order(struct page *page, unsigned int order)
777 set_page_private(page, order);
778 __SetPageBuddy(page);
782 * This function checks whether a page is free && is the buddy
783 * we can coalesce a page and its buddy if
784 * (a) the buddy is not in a hole (check before calling!) &&
785 * (b) the buddy is in the buddy system &&
786 * (c) a page and its buddy have the same order &&
787 * (d) a page and its buddy are in the same zone.
789 * For recording whether a page is in the buddy system, we set PageBuddy.
790 * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
792 * For recording page's order, we use page_private(page).
794 static inline bool page_is_buddy(struct page *page, struct page *buddy,
797 if (!page_is_guard(buddy) && !PageBuddy(buddy))
800 if (page_order(buddy) != order)
804 * zone check is done late to avoid uselessly calculating
805 * zone/node ids for pages that could never merge.
807 if (page_zone_id(page) != page_zone_id(buddy))
810 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
815 #ifdef CONFIG_COMPACTION
816 static inline struct capture_control *task_capc(struct zone *zone)
818 struct capture_control *capc = current->capture_control;
821 !(current->flags & PF_KTHREAD) &&
823 capc->cc->zone == zone &&
824 capc->cc->direct_compaction ? capc : NULL;
828 compaction_capture(struct capture_control *capc, struct page *page,
829 int order, int migratetype)
831 if (!capc || order != capc->cc->order)
834 /* Do not accidentally pollute CMA or isolated regions*/
835 if (is_migrate_cma(migratetype) ||
836 is_migrate_isolate(migratetype))
840 * Do not let lower order allocations polluate a movable pageblock.
841 * This might let an unmovable request use a reclaimable pageblock
842 * and vice-versa but no more than normal fallback logic which can
843 * have trouble finding a high-order free page.
845 if (order < pageblock_order && migratetype == MIGRATE_MOVABLE)
853 static inline struct capture_control *task_capc(struct zone *zone)
859 compaction_capture(struct capture_control *capc, struct page *page,
860 int order, int migratetype)
864 #endif /* CONFIG_COMPACTION */
866 /* Used for pages not on another list */
867 static inline void add_to_free_list(struct page *page, struct zone *zone,
868 unsigned int order, int migratetype)
870 struct free_area *area = &zone->free_area[order];
872 list_add(&page->lru, &area->free_list[migratetype]);
876 /* Used for pages not on another list */
877 static inline void add_to_free_list_tail(struct page *page, struct zone *zone,
878 unsigned int order, int migratetype)
880 struct free_area *area = &zone->free_area[order];
882 list_add_tail(&page->lru, &area->free_list[migratetype]);
886 /* Used for pages which are on another list */
887 static inline void move_to_free_list(struct page *page, struct zone *zone,
888 unsigned int order, int migratetype)
890 struct free_area *area = &zone->free_area[order];
892 list_move(&page->lru, &area->free_list[migratetype]);
895 static inline void del_page_from_free_list(struct page *page, struct zone *zone,
898 /* clear reported state and update reported page count */
899 if (page_reported(page))
900 __ClearPageReported(page);
902 list_del(&page->lru);
903 __ClearPageBuddy(page);
904 set_page_private(page, 0);
905 zone->free_area[order].nr_free--;
909 * If this is not the largest possible page, check if the buddy
910 * of the next-highest order is free. If it is, it's possible
911 * that pages are being freed that will coalesce soon. In case,
912 * that is happening, add the free page to the tail of the list
913 * so it's less likely to be used soon and more likely to be merged
914 * as a higher order page
917 buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
918 struct page *page, unsigned int order)
920 struct page *higher_page, *higher_buddy;
921 unsigned long combined_pfn;
923 if (order >= MAX_ORDER - 2)
926 if (!pfn_valid_within(buddy_pfn))
929 combined_pfn = buddy_pfn & pfn;
930 higher_page = page + (combined_pfn - pfn);
931 buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
932 higher_buddy = higher_page + (buddy_pfn - combined_pfn);
934 return pfn_valid_within(buddy_pfn) &&
935 page_is_buddy(higher_page, higher_buddy, order + 1);
939 * Freeing function for a buddy system allocator.
941 * The concept of a buddy system is to maintain direct-mapped table
942 * (containing bit values) for memory blocks of various "orders".
943 * The bottom level table contains the map for the smallest allocatable
944 * units of memory (here, pages), and each level above it describes
945 * pairs of units from the levels below, hence, "buddies".
946 * At a high level, all that happens here is marking the table entry
947 * at the bottom level available, and propagating the changes upward
948 * as necessary, plus some accounting needed to play nicely with other
949 * parts of the VM system.
950 * At each level, we keep a list of pages, which are heads of continuous
951 * free pages of length of (1 << order) and marked with PageBuddy.
952 * Page's order is recorded in page_private(page) field.
953 * So when we are allocating or freeing one, we can derive the state of the
954 * other. That is, if we allocate a small block, and both were
955 * free, the remainder of the region must be split into blocks.
956 * If a block is freed, and its buddy is also free, then this
957 * triggers coalescing into a block of larger size.
962 static inline void __free_one_page(struct page *page,
964 struct zone *zone, unsigned int order,
965 int migratetype, bool report)
967 struct capture_control *capc = task_capc(zone);
968 unsigned long uninitialized_var(buddy_pfn);
969 unsigned long combined_pfn;
970 unsigned int max_order;
974 max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
976 VM_BUG_ON(!zone_is_initialized(zone));
977 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
979 VM_BUG_ON(migratetype == -1);
980 if (likely(!is_migrate_isolate(migratetype)))
981 __mod_zone_freepage_state(zone, 1 << order, migratetype);
983 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
984 VM_BUG_ON_PAGE(bad_range(zone, page), page);
987 while (order < max_order - 1) {
988 if (compaction_capture(capc, page, order, migratetype)) {
989 __mod_zone_freepage_state(zone, -(1 << order),
993 buddy_pfn = __find_buddy_pfn(pfn, order);
994 buddy = page + (buddy_pfn - pfn);
996 if (!pfn_valid_within(buddy_pfn))
998 if (!page_is_buddy(page, buddy, order))
1001 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
1002 * merge with it and move up one order.
1004 if (page_is_guard(buddy))
1005 clear_page_guard(zone, buddy, order, migratetype);
1007 del_page_from_free_list(buddy, zone, order);
1008 combined_pfn = buddy_pfn & pfn;
1009 page = page + (combined_pfn - pfn);
1013 if (max_order < MAX_ORDER) {
1014 /* If we are here, it means order is >= pageblock_order.
1015 * We want to prevent merge between freepages on isolate
1016 * pageblock and normal pageblock. Without this, pageblock
1017 * isolation could cause incorrect freepage or CMA accounting.
1019 * We don't want to hit this code for the more frequent
1020 * low-order merging.
1022 if (unlikely(has_isolate_pageblock(zone))) {
1025 buddy_pfn = __find_buddy_pfn(pfn, order);
1026 buddy = page + (buddy_pfn - pfn);
1027 buddy_mt = get_pageblock_migratetype(buddy);
1029 if (migratetype != buddy_mt
1030 && (is_migrate_isolate(migratetype) ||
1031 is_migrate_isolate(buddy_mt)))
1035 goto continue_merging;
1039 set_page_order(page, order);
1041 if (is_shuffle_order(order))
1042 to_tail = shuffle_pick_tail();
1044 to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
1047 add_to_free_list_tail(page, zone, order, migratetype);
1049 add_to_free_list(page, zone, order, migratetype);
1051 /* Notify page reporting subsystem of freed page */
1053 page_reporting_notify_free(order);
1057 * A bad page could be due to a number of fields. Instead of multiple branches,
1058 * try and check multiple fields with one check. The caller must do a detailed
1059 * check if necessary.
1061 static inline bool page_expected_state(struct page *page,
1062 unsigned long check_flags)
1064 if (unlikely(atomic_read(&page->_mapcount) != -1))
1067 if (unlikely((unsigned long)page->mapping |
1068 page_ref_count(page) |
1070 (unsigned long)page->mem_cgroup |
1072 (page->flags & check_flags)))
1078 static void free_pages_check_bad(struct page *page)
1080 const char *bad_reason;
1081 unsigned long bad_flags;
1086 if (unlikely(atomic_read(&page->_mapcount) != -1))
1087 bad_reason = "nonzero mapcount";
1088 if (unlikely(page->mapping != NULL))
1089 bad_reason = "non-NULL mapping";
1090 if (unlikely(page_ref_count(page) != 0))
1091 bad_reason = "nonzero _refcount";
1092 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
1093 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
1094 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
1097 if (unlikely(page->mem_cgroup))
1098 bad_reason = "page still charged to cgroup";
1100 bad_page(page, bad_reason, bad_flags);
1103 static inline int free_pages_check(struct page *page)
1105 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
1108 /* Something has gone sideways, find it */
1109 free_pages_check_bad(page);
1113 static int free_tail_pages_check(struct page *head_page, struct page *page)
1118 * We rely page->lru.next never has bit 0 set, unless the page
1119 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
1121 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
1123 if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
1127 switch (page - head_page) {
1129 /* the first tail page: ->mapping may be compound_mapcount() */
1130 if (unlikely(compound_mapcount(page))) {
1131 bad_page(page, "nonzero compound_mapcount", 0);
1137 * the second tail page: ->mapping is
1138 * deferred_list.next -- ignore value.
1142 if (page->mapping != TAIL_MAPPING) {
1143 bad_page(page, "corrupted mapping in tail page", 0);
1148 if (unlikely(!PageTail(page))) {
1149 bad_page(page, "PageTail not set", 0);
1152 if (unlikely(compound_head(page) != head_page)) {
1153 bad_page(page, "compound_head not consistent", 0);
1158 page->mapping = NULL;
1159 clear_compound_head(page);
1163 static void kernel_init_free_pages(struct page *page, int numpages)
1167 for (i = 0; i < numpages; i++)
1168 clear_highpage(page + i);
1171 static __always_inline bool free_pages_prepare(struct page *page,
1172 unsigned int order, bool check_free)
1176 VM_BUG_ON_PAGE(PageTail(page), page);
1178 trace_mm_page_free(page, order);
1181 * Check tail pages before head page information is cleared to
1182 * avoid checking PageCompound for order-0 pages.
1184 if (unlikely(order)) {
1185 bool compound = PageCompound(page);
1188 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1191 ClearPageDoubleMap(page);
1192 for (i = 1; i < (1 << order); i++) {
1194 bad += free_tail_pages_check(page, page + i);
1195 if (unlikely(free_pages_check(page + i))) {
1199 (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1202 if (PageMappingFlags(page))
1203 page->mapping = NULL;
1204 if (memcg_kmem_enabled() && PageKmemcg(page))
1205 __memcg_kmem_uncharge_page(page, order);
1207 bad += free_pages_check(page);
1211 page_cpupid_reset_last(page);
1212 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1213 reset_page_owner(page, order);
1215 if (!PageHighMem(page)) {
1216 debug_check_no_locks_freed(page_address(page),
1217 PAGE_SIZE << order);
1218 debug_check_no_obj_freed(page_address(page),
1219 PAGE_SIZE << order);
1221 if (want_init_on_free())
1222 kernel_init_free_pages(page, 1 << order);
1224 kernel_poison_pages(page, 1 << order, 0);
1226 * arch_free_page() can make the page's contents inaccessible. s390
1227 * does this. So nothing which can access the page's contents should
1228 * happen after this.
1230 arch_free_page(page, order);
1232 if (debug_pagealloc_enabled_static())
1233 kernel_map_pages(page, 1 << order, 0);
1235 kasan_free_nondeferred_pages(page, order);
1240 #ifdef CONFIG_DEBUG_VM
1242 * With DEBUG_VM enabled, order-0 pages are checked immediately when being freed
1243 * to pcp lists. With debug_pagealloc also enabled, they are also rechecked when
1244 * moved from pcp lists to free lists.
1246 static bool free_pcp_prepare(struct page *page)
1248 return free_pages_prepare(page, 0, true);
1251 static bool bulkfree_pcp_prepare(struct page *page)
1253 if (debug_pagealloc_enabled_static())
1254 return free_pages_check(page);
1260 * With DEBUG_VM disabled, order-0 pages being freed are checked only when
1261 * moving from pcp lists to free list in order to reduce overhead. With
1262 * debug_pagealloc enabled, they are checked also immediately when being freed
1265 static bool free_pcp_prepare(struct page *page)
1267 if (debug_pagealloc_enabled_static())
1268 return free_pages_prepare(page, 0, true);
1270 return free_pages_prepare(page, 0, false);
1273 static bool bulkfree_pcp_prepare(struct page *page)
1275 return free_pages_check(page);
1277 #endif /* CONFIG_DEBUG_VM */
1279 static inline void prefetch_buddy(struct page *page)
1281 unsigned long pfn = page_to_pfn(page);
1282 unsigned long buddy_pfn = __find_buddy_pfn(pfn, 0);
1283 struct page *buddy = page + (buddy_pfn - pfn);
1289 * Frees a number of pages from the PCP lists
1290 * Assumes all pages on list are in same zone, and of same order.
1291 * count is the number of pages to free.
1293 * If the zone was previously in an "all pages pinned" state then look to
1294 * see if this freeing clears that state.
1296 * And clear the zone's pages_scanned counter, to hold off the "all pages are
1297 * pinned" detection logic.
1299 static void free_pcppages_bulk(struct zone *zone, int count,
1300 struct per_cpu_pages *pcp)
1302 int migratetype = 0;
1304 int prefetch_nr = 0;
1305 bool isolated_pageblocks;
1306 struct page *page, *tmp;
1310 struct list_head *list;
1313 * Remove pages from lists in a round-robin fashion. A
1314 * batch_free count is maintained that is incremented when an
1315 * empty list is encountered. This is so more pages are freed
1316 * off fuller lists instead of spinning excessively around empty
1321 if (++migratetype == MIGRATE_PCPTYPES)
1323 list = &pcp->lists[migratetype];
1324 } while (list_empty(list));
1326 /* This is the only non-empty list. Free them all. */
1327 if (batch_free == MIGRATE_PCPTYPES)
1331 page = list_last_entry(list, struct page, lru);
1332 /* must delete to avoid corrupting pcp list */
1333 list_del(&page->lru);
1336 if (bulkfree_pcp_prepare(page))
1339 list_add_tail(&page->lru, &head);
1342 * We are going to put the page back to the global
1343 * pool, prefetch its buddy to speed up later access
1344 * under zone->lock. It is believed the overhead of
1345 * an additional test and calculating buddy_pfn here
1346 * can be offset by reduced memory latency later. To
1347 * avoid excessive prefetching due to large count, only
1348 * prefetch buddy for the first pcp->batch nr of pages.
1350 if (prefetch_nr++ < pcp->batch)
1351 prefetch_buddy(page);
1352 } while (--count && --batch_free && !list_empty(list));
1355 spin_lock(&zone->lock);
1356 isolated_pageblocks = has_isolate_pageblock(zone);
1359 * Use safe version since after __free_one_page(),
1360 * page->lru.next will not point to original list.
1362 list_for_each_entry_safe(page, tmp, &head, lru) {
1363 int mt = get_pcppage_migratetype(page);
1364 /* MIGRATE_ISOLATE page should not go to pcplists */
1365 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1366 /* Pageblock could have been isolated meanwhile */
1367 if (unlikely(isolated_pageblocks))
1368 mt = get_pageblock_migratetype(page);
1370 __free_one_page(page, page_to_pfn(page), zone, 0, mt, true);
1371 trace_mm_page_pcpu_drain(page, 0, mt);
1373 spin_unlock(&zone->lock);
1376 static void free_one_page(struct zone *zone,
1377 struct page *page, unsigned long pfn,
1381 spin_lock(&zone->lock);
1382 if (unlikely(has_isolate_pageblock(zone) ||
1383 is_migrate_isolate(migratetype))) {
1384 migratetype = get_pfnblock_migratetype(page, pfn);
1386 __free_one_page(page, pfn, zone, order, migratetype, true);
1387 spin_unlock(&zone->lock);
1390 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
1391 unsigned long zone, int nid)
1393 mm_zero_struct_page(page);
1394 set_page_links(page, zone, nid, pfn);
1395 init_page_count(page);
1396 page_mapcount_reset(page);
1397 page_cpupid_reset_last(page);
1398 page_kasan_tag_reset(page);
1400 INIT_LIST_HEAD(&page->lru);
1401 #ifdef WANT_PAGE_VIRTUAL
1402 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1403 if (!is_highmem_idx(zone))
1404 set_page_address(page, __va(pfn << PAGE_SHIFT));
1408 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1409 static void __meminit init_reserved_page(unsigned long pfn)
1414 if (!early_page_uninitialised(pfn))
1417 nid = early_pfn_to_nid(pfn);
1418 pgdat = NODE_DATA(nid);
1420 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1421 struct zone *zone = &pgdat->node_zones[zid];
1423 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
1426 __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
1429 static inline void init_reserved_page(unsigned long pfn)
1432 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1435 * Initialised pages do not have PageReserved set. This function is
1436 * called for each range allocated by the bootmem allocator and
1437 * marks the pages PageReserved. The remaining valid pages are later
1438 * sent to the buddy page allocator.
1440 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1442 unsigned long start_pfn = PFN_DOWN(start);
1443 unsigned long end_pfn = PFN_UP(end);
1445 for (; start_pfn < end_pfn; start_pfn++) {
1446 if (pfn_valid(start_pfn)) {
1447 struct page *page = pfn_to_page(start_pfn);
1449 init_reserved_page(start_pfn);
1451 /* Avoid false-positive PageTail() */
1452 INIT_LIST_HEAD(&page->lru);
1455 * no need for atomic set_bit because the struct
1456 * page is not visible yet so nobody should
1459 __SetPageReserved(page);
1464 static void __free_pages_ok(struct page *page, unsigned int order)
1466 unsigned long flags;
1468 unsigned long pfn = page_to_pfn(page);
1470 if (!free_pages_prepare(page, order, true))
1473 migratetype = get_pfnblock_migratetype(page, pfn);
1474 local_irq_save(flags);
1475 __count_vm_events(PGFREE, 1 << order);
1476 free_one_page(page_zone(page), page, pfn, order, migratetype);
1477 local_irq_restore(flags);
1480 void __free_pages_core(struct page *page, unsigned int order)
1482 unsigned int nr_pages = 1 << order;
1483 struct page *p = page;
1487 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1489 __ClearPageReserved(p);
1490 set_page_count(p, 0);
1492 __ClearPageReserved(p);
1493 set_page_count(p, 0);
1495 atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
1496 set_page_refcounted(page);
1497 __free_pages(page, order);
1500 #ifdef CONFIG_NEED_MULTIPLE_NODES
1502 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1504 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
1507 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
1509 int __meminit __early_pfn_to_nid(unsigned long pfn,
1510 struct mminit_pfnnid_cache *state)
1512 unsigned long start_pfn, end_pfn;
1515 if (state->last_start <= pfn && pfn < state->last_end)
1516 return state->last_nid;
1518 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
1519 if (nid != NUMA_NO_NODE) {
1520 state->last_start = start_pfn;
1521 state->last_end = end_pfn;
1522 state->last_nid = nid;
1527 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
1529 int __meminit early_pfn_to_nid(unsigned long pfn)
1531 static DEFINE_SPINLOCK(early_pfn_lock);
1534 spin_lock(&early_pfn_lock);
1535 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1537 nid = first_online_node;
1538 spin_unlock(&early_pfn_lock);
1542 #endif /* CONFIG_NEED_MULTIPLE_NODES */
1544 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1545 /* Only safe to use early in boot when initialisation is single-threaded */
1546 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1550 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1551 if (nid >= 0 && nid != node)
1557 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1564 void __init memblock_free_pages(struct page *page, unsigned long pfn,
1567 if (early_page_uninitialised(pfn))
1569 __free_pages_core(page, order);
1573 * Check that the whole (or subset of) a pageblock given by the interval of
1574 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1575 * with the migration of free compaction scanner. The scanners then need to
1576 * use only pfn_valid_within() check for arches that allow holes within
1579 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1581 * It's possible on some configurations to have a setup like node0 node1 node0
1582 * i.e. it's possible that all pages within a zones range of pages do not
1583 * belong to a single zone. We assume that a border between node0 and node1
1584 * can occur within a single pageblock, but not a node0 node1 node0
1585 * interleaving within a single pageblock. It is therefore sufficient to check
1586 * the first and last page of a pageblock and avoid checking each individual
1587 * page in a pageblock.
1589 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1590 unsigned long end_pfn, struct zone *zone)
1592 struct page *start_page;
1593 struct page *end_page;
1595 /* end_pfn is one past the range we are checking */
1598 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1601 start_page = pfn_to_online_page(start_pfn);
1605 if (page_zone(start_page) != zone)
1608 end_page = pfn_to_page(end_pfn);
1610 /* This gives a shorter code than deriving page_zone(end_page) */
1611 if (page_zone_id(start_page) != page_zone_id(end_page))
1617 void set_zone_contiguous(struct zone *zone)
1619 unsigned long block_start_pfn = zone->zone_start_pfn;
1620 unsigned long block_end_pfn;
1622 block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1623 for (; block_start_pfn < zone_end_pfn(zone);
1624 block_start_pfn = block_end_pfn,
1625 block_end_pfn += pageblock_nr_pages) {
1627 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1629 if (!__pageblock_pfn_to_page(block_start_pfn,
1630 block_end_pfn, zone))
1635 /* We confirm that there is no hole */
1636 zone->contiguous = true;
1639 void clear_zone_contiguous(struct zone *zone)
1641 zone->contiguous = false;
1644 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1645 static void __init deferred_free_range(unsigned long pfn,
1646 unsigned long nr_pages)
1654 page = pfn_to_page(pfn);
1656 /* Free a large naturally-aligned chunk if possible */
1657 if (nr_pages == pageblock_nr_pages &&
1658 (pfn & (pageblock_nr_pages - 1)) == 0) {
1659 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1660 __free_pages_core(page, pageblock_order);
1664 for (i = 0; i < nr_pages; i++, page++, pfn++) {
1665 if ((pfn & (pageblock_nr_pages - 1)) == 0)
1666 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1667 __free_pages_core(page, 0);
1671 /* Completion tracking for deferred_init_memmap() threads */
1672 static atomic_t pgdat_init_n_undone __initdata;
1673 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1675 static inline void __init pgdat_init_report_one_done(void)
1677 if (atomic_dec_and_test(&pgdat_init_n_undone))
1678 complete(&pgdat_init_all_done_comp);
1682 * Returns true if page needs to be initialized or freed to buddy allocator.
1684 * First we check if pfn is valid on architectures where it is possible to have
1685 * holes within pageblock_nr_pages. On systems where it is not possible, this
1686 * function is optimized out.
1688 * Then, we check if a current large page is valid by only checking the validity
1691 static inline bool __init deferred_pfn_valid(unsigned long pfn)
1693 if (!pfn_valid_within(pfn))
1695 if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1701 * Free pages to buddy allocator. Try to free aligned pages in
1702 * pageblock_nr_pages sizes.
1704 static void __init deferred_free_pages(unsigned long pfn,
1705 unsigned long end_pfn)
1707 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1708 unsigned long nr_free = 0;
1710 for (; pfn < end_pfn; pfn++) {
1711 if (!deferred_pfn_valid(pfn)) {
1712 deferred_free_range(pfn - nr_free, nr_free);
1714 } else if (!(pfn & nr_pgmask)) {
1715 deferred_free_range(pfn - nr_free, nr_free);
1717 touch_nmi_watchdog();
1722 /* Free the last block of pages to allocator */
1723 deferred_free_range(pfn - nr_free, nr_free);
1727 * Initialize struct pages. We minimize pfn page lookups and scheduler checks
1728 * by performing it only once every pageblock_nr_pages.
1729 * Return number of pages initialized.
1731 static unsigned long __init deferred_init_pages(struct zone *zone,
1733 unsigned long end_pfn)
1735 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1736 int nid = zone_to_nid(zone);
1737 unsigned long nr_pages = 0;
1738 int zid = zone_idx(zone);
1739 struct page *page = NULL;
1741 for (; pfn < end_pfn; pfn++) {
1742 if (!deferred_pfn_valid(pfn)) {
1745 } else if (!page || !(pfn & nr_pgmask)) {
1746 page = pfn_to_page(pfn);
1747 touch_nmi_watchdog();
1751 __init_single_page(page, pfn, zid, nid);
1758 * This function is meant to pre-load the iterator for the zone init.
1759 * Specifically it walks through the ranges until we are caught up to the
1760 * first_init_pfn value and exits there. If we never encounter the value we
1761 * return false indicating there are no valid ranges left.
1764 deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone,
1765 unsigned long *spfn, unsigned long *epfn,
1766 unsigned long first_init_pfn)
1771 * Start out by walking through the ranges in this zone that have
1772 * already been initialized. We don't need to do anything with them
1773 * so we just need to flush them out of the system.
1775 for_each_free_mem_pfn_range_in_zone(j, zone, spfn, epfn) {
1776 if (*epfn <= first_init_pfn)
1778 if (*spfn < first_init_pfn)
1779 *spfn = first_init_pfn;
1788 * Initialize and free pages. We do it in two loops: first we initialize
1789 * struct page, then free to buddy allocator, because while we are
1790 * freeing pages we can access pages that are ahead (computing buddy
1791 * page in __free_one_page()).
1793 * In order to try and keep some memory in the cache we have the loop
1794 * broken along max page order boundaries. This way we will not cause
1795 * any issues with the buddy page computation.
1797 static unsigned long __init
1798 deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn,
1799 unsigned long *end_pfn)
1801 unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES);
1802 unsigned long spfn = *start_pfn, epfn = *end_pfn;
1803 unsigned long nr_pages = 0;
1806 /* First we loop through and initialize the page values */
1807 for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) {
1810 if (mo_pfn <= *start_pfn)
1813 t = min(mo_pfn, *end_pfn);
1814 nr_pages += deferred_init_pages(zone, *start_pfn, t);
1816 if (mo_pfn < *end_pfn) {
1817 *start_pfn = mo_pfn;
1822 /* Reset values and now loop through freeing pages as needed */
1825 for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) {
1831 t = min(mo_pfn, epfn);
1832 deferred_free_pages(spfn, t);
1841 /* Initialise remaining memory on a node */
1842 static int __init deferred_init_memmap(void *data)
1844 pg_data_t *pgdat = data;
1845 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1846 unsigned long spfn = 0, epfn = 0, nr_pages = 0;
1847 unsigned long first_init_pfn, flags;
1848 unsigned long start = jiffies;
1853 /* Bind memory initialisation thread to a local node if possible */
1854 if (!cpumask_empty(cpumask))
1855 set_cpus_allowed_ptr(current, cpumask);
1857 pgdat_resize_lock(pgdat, &flags);
1858 first_init_pfn = pgdat->first_deferred_pfn;
1859 if (first_init_pfn == ULONG_MAX) {
1860 pgdat_resize_unlock(pgdat, &flags);
1861 pgdat_init_report_one_done();
1865 /* Sanity check boundaries */
1866 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1867 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1868 pgdat->first_deferred_pfn = ULONG_MAX;
1870 /* Only the highest zone is deferred so find it */
1871 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1872 zone = pgdat->node_zones + zid;
1873 if (first_init_pfn < zone_end_pfn(zone))
1877 /* If the zone is empty somebody else may have cleared out the zone */
1878 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
1883 * Initialize and free pages in MAX_ORDER sized increments so
1884 * that we can avoid introducing any issues with the buddy
1888 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
1890 pgdat_resize_unlock(pgdat, &flags);
1892 /* Sanity check that the next zone really is unpopulated */
1893 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1895 pr_info("node %d initialised, %lu pages in %ums\n",
1896 pgdat->node_id, nr_pages, jiffies_to_msecs(jiffies - start));
1898 pgdat_init_report_one_done();
1903 * If this zone has deferred pages, try to grow it by initializing enough
1904 * deferred pages to satisfy the allocation specified by order, rounded up to
1905 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
1906 * of SECTION_SIZE bytes by initializing struct pages in increments of
1907 * PAGES_PER_SECTION * sizeof(struct page) bytes.
1909 * Return true when zone was grown, otherwise return false. We return true even
1910 * when we grow less than requested, to let the caller decide if there are
1911 * enough pages to satisfy the allocation.
1913 * Note: We use noinline because this function is needed only during boot, and
1914 * it is called from a __ref function _deferred_grow_zone. This way we are
1915 * making sure that it is not inlined into permanent text section.
1917 static noinline bool __init
1918 deferred_grow_zone(struct zone *zone, unsigned int order)
1920 unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
1921 pg_data_t *pgdat = zone->zone_pgdat;
1922 unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
1923 unsigned long spfn, epfn, flags;
1924 unsigned long nr_pages = 0;
1927 /* Only the last zone may have deferred pages */
1928 if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
1931 pgdat_resize_lock(pgdat, &flags);
1934 * If deferred pages have been initialized while we were waiting for
1935 * the lock, return true, as the zone was grown. The caller will retry
1936 * this zone. We won't return to this function since the caller also
1937 * has this static branch.
1939 if (!static_branch_unlikely(&deferred_pages)) {
1940 pgdat_resize_unlock(pgdat, &flags);
1945 * If someone grew this zone while we were waiting for spinlock, return
1946 * true, as there might be enough pages already.
1948 if (first_deferred_pfn != pgdat->first_deferred_pfn) {
1949 pgdat_resize_unlock(pgdat, &flags);
1953 /* If the zone is empty somebody else may have cleared out the zone */
1954 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
1955 first_deferred_pfn)) {
1956 pgdat->first_deferred_pfn = ULONG_MAX;
1957 pgdat_resize_unlock(pgdat, &flags);
1958 /* Retry only once. */
1959 return first_deferred_pfn != ULONG_MAX;
1963 * Initialize and free pages in MAX_ORDER sized increments so
1964 * that we can avoid introducing any issues with the buddy
1967 while (spfn < epfn) {
1968 /* update our first deferred PFN for this section */
1969 first_deferred_pfn = spfn;
1971 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
1973 /* We should only stop along section boundaries */
1974 if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION)
1977 /* If our quota has been met we can stop here */
1978 if (nr_pages >= nr_pages_needed)
1982 pgdat->first_deferred_pfn = spfn;
1983 pgdat_resize_unlock(pgdat, &flags);
1985 return nr_pages > 0;
1989 * deferred_grow_zone() is __init, but it is called from
1990 * get_page_from_freelist() during early boot until deferred_pages permanently
1991 * disables this call. This is why we have refdata wrapper to avoid warning,
1992 * and to ensure that the function body gets unloaded.
1995 _deferred_grow_zone(struct zone *zone, unsigned int order)
1997 return deferred_grow_zone(zone, order);
2000 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
2002 void __init page_alloc_init_late(void)
2007 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
2009 /* There will be num_node_state(N_MEMORY) threads */
2010 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
2011 for_each_node_state(nid, N_MEMORY) {
2012 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
2015 /* Block until all are initialised */
2016 wait_for_completion(&pgdat_init_all_done_comp);
2019 * The number of managed pages has changed due to the initialisation
2020 * so the pcpu batch and high limits needs to be updated or the limits
2021 * will be artificially small.
2023 for_each_populated_zone(zone)
2024 zone_pcp_update(zone);
2027 * We initialized the rest of the deferred pages. Permanently disable
2028 * on-demand struct page initialization.
2030 static_branch_disable(&deferred_pages);
2032 /* Reinit limits that are based on free pages after the kernel is up */
2033 files_maxfiles_init();
2036 /* Discard memblock private memory */
2039 for_each_node_state(nid, N_MEMORY)
2040 shuffle_free_memory(NODE_DATA(nid));
2042 for_each_populated_zone(zone)
2043 set_zone_contiguous(zone);
2047 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
2048 void __init init_cma_reserved_pageblock(struct page *page)
2050 unsigned i = pageblock_nr_pages;
2051 struct page *p = page;
2054 __ClearPageReserved(p);
2055 set_page_count(p, 0);
2058 set_pageblock_migratetype(page, MIGRATE_CMA);
2060 if (pageblock_order >= MAX_ORDER) {
2061 i = pageblock_nr_pages;
2064 set_page_refcounted(p);
2065 __free_pages(p, MAX_ORDER - 1);
2066 p += MAX_ORDER_NR_PAGES;
2067 } while (i -= MAX_ORDER_NR_PAGES);
2069 set_page_refcounted(page);
2070 __free_pages(page, pageblock_order);
2073 adjust_managed_page_count(page, pageblock_nr_pages);
2078 * The order of subdivision here is critical for the IO subsystem.
2079 * Please do not alter this order without good reasons and regression
2080 * testing. Specifically, as large blocks of memory are subdivided,
2081 * the order in which smaller blocks are delivered depends on the order
2082 * they're subdivided in this function. This is the primary factor
2083 * influencing the order in which pages are delivered to the IO
2084 * subsystem according to empirical testing, and this is also justified
2085 * by considering the behavior of a buddy system containing a single
2086 * large block of memory acted on by a series of small allocations.
2087 * This behavior is a critical factor in sglist merging's success.
2091 static inline void expand(struct zone *zone, struct page *page,
2092 int low, int high, int migratetype)
2094 unsigned long size = 1 << high;
2096 while (high > low) {
2099 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
2102 * Mark as guard pages (or page), that will allow to
2103 * merge back to allocator when buddy will be freed.
2104 * Corresponding page table entries will not be touched,
2105 * pages will stay not present in virtual address space
2107 if (set_page_guard(zone, &page[size], high, migratetype))
2110 add_to_free_list(&page[size], zone, high, migratetype);
2111 set_page_order(&page[size], high);
2115 static void check_new_page_bad(struct page *page)
2117 const char *bad_reason = NULL;
2118 unsigned long bad_flags = 0;
2120 if (unlikely(atomic_read(&page->_mapcount) != -1))
2121 bad_reason = "nonzero mapcount";
2122 if (unlikely(page->mapping != NULL))
2123 bad_reason = "non-NULL mapping";
2124 if (unlikely(page_ref_count(page) != 0))
2125 bad_reason = "nonzero _refcount";
2126 if (unlikely(page->flags & __PG_HWPOISON)) {
2127 bad_reason = "HWPoisoned (hardware-corrupted)";
2128 bad_flags = __PG_HWPOISON;
2129 /* Don't complain about hwpoisoned pages */
2130 page_mapcount_reset(page); /* remove PageBuddy */
2133 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
2134 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
2135 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
2138 if (unlikely(page->mem_cgroup))
2139 bad_reason = "page still charged to cgroup";
2141 bad_page(page, bad_reason, bad_flags);
2145 * This page is about to be returned from the page allocator
2147 static inline int check_new_page(struct page *page)
2149 if (likely(page_expected_state(page,
2150 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
2153 check_new_page_bad(page);
2157 static inline bool free_pages_prezeroed(void)
2159 return (IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) &&
2160 page_poisoning_enabled()) || want_init_on_free();
2163 #ifdef CONFIG_DEBUG_VM
2165 * With DEBUG_VM enabled, order-0 pages are checked for expected state when
2166 * being allocated from pcp lists. With debug_pagealloc also enabled, they are
2167 * also checked when pcp lists are refilled from the free lists.
2169 static inline bool check_pcp_refill(struct page *page)
2171 if (debug_pagealloc_enabled_static())
2172 return check_new_page(page);
2177 static inline bool check_new_pcp(struct page *page)
2179 return check_new_page(page);
2183 * With DEBUG_VM disabled, free order-0 pages are checked for expected state
2184 * when pcp lists are being refilled from the free lists. With debug_pagealloc
2185 * enabled, they are also checked when being allocated from the pcp lists.
2187 static inline bool check_pcp_refill(struct page *page)
2189 return check_new_page(page);
2191 static inline bool check_new_pcp(struct page *page)
2193 if (debug_pagealloc_enabled_static())
2194 return check_new_page(page);
2198 #endif /* CONFIG_DEBUG_VM */
2200 static bool check_new_pages(struct page *page, unsigned int order)
2203 for (i = 0; i < (1 << order); i++) {
2204 struct page *p = page + i;
2206 if (unlikely(check_new_page(p)))
2213 inline void post_alloc_hook(struct page *page, unsigned int order,
2216 set_page_private(page, 0);
2217 set_page_refcounted(page);
2219 arch_alloc_page(page, order);
2220 if (debug_pagealloc_enabled_static())
2221 kernel_map_pages(page, 1 << order, 1);
2222 kasan_alloc_pages(page, order);
2223 kernel_poison_pages(page, 1 << order, 1);
2224 set_page_owner(page, order, gfp_flags);
2227 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
2228 unsigned int alloc_flags)
2230 post_alloc_hook(page, order, gfp_flags);
2232 if (!free_pages_prezeroed() && want_init_on_alloc(gfp_flags))
2233 kernel_init_free_pages(page, 1 << order);
2235 if (order && (gfp_flags & __GFP_COMP))
2236 prep_compound_page(page, order);
2239 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
2240 * allocate the page. The expectation is that the caller is taking
2241 * steps that will free more memory. The caller should avoid the page
2242 * being used for !PFMEMALLOC purposes.
2244 if (alloc_flags & ALLOC_NO_WATERMARKS)
2245 set_page_pfmemalloc(page);
2247 clear_page_pfmemalloc(page);
2251 * Go through the free lists for the given migratetype and remove
2252 * the smallest available page from the freelists
2254 static __always_inline
2255 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
2258 unsigned int current_order;
2259 struct free_area *area;
2262 /* Find a page of the appropriate size in the preferred list */
2263 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
2264 area = &(zone->free_area[current_order]);
2265 page = get_page_from_free_area(area, migratetype);
2268 del_page_from_free_list(page, zone, current_order);
2269 expand(zone, page, order, current_order, migratetype);
2270 set_pcppage_migratetype(page, migratetype);
2279 * This array describes the order lists are fallen back to when
2280 * the free lists for the desirable migrate type are depleted
2282 static int fallbacks[MIGRATE_TYPES][4] = {
2283 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2284 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
2285 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2287 [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */
2289 #ifdef CONFIG_MEMORY_ISOLATION
2290 [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */
2295 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2298 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
2301 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2302 unsigned int order) { return NULL; }
2306 * Move the free pages in a range to the free lists of the requested type.
2307 * Note that start_page and end_pages are not aligned on a pageblock
2308 * boundary. If alignment is required, use move_freepages_block()
2310 static int move_freepages(struct zone *zone,
2311 struct page *start_page, struct page *end_page,
2312 int migratetype, int *num_movable)
2316 int pages_moved = 0;
2318 for (page = start_page; page <= end_page;) {
2319 if (!pfn_valid_within(page_to_pfn(page))) {
2324 if (!PageBuddy(page)) {
2326 * We assume that pages that could be isolated for
2327 * migration are movable. But we don't actually try
2328 * isolating, as that would be expensive.
2331 (PageLRU(page) || __PageMovable(page)))
2338 /* Make sure we are not inadvertently changing nodes */
2339 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2340 VM_BUG_ON_PAGE(page_zone(page) != zone, page);
2342 order = page_order(page);
2343 move_to_free_list(page, zone, order, migratetype);
2345 pages_moved += 1 << order;
2351 int move_freepages_block(struct zone *zone, struct page *page,
2352 int migratetype, int *num_movable)
2354 unsigned long start_pfn, end_pfn;
2355 struct page *start_page, *end_page;
2360 start_pfn = page_to_pfn(page);
2361 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
2362 start_page = pfn_to_page(start_pfn);
2363 end_page = start_page + pageblock_nr_pages - 1;
2364 end_pfn = start_pfn + pageblock_nr_pages - 1;
2366 /* Do not cross zone boundaries */
2367 if (!zone_spans_pfn(zone, start_pfn))
2369 if (!zone_spans_pfn(zone, end_pfn))
2372 return move_freepages(zone, start_page, end_page, migratetype,
2376 static void change_pageblock_range(struct page *pageblock_page,
2377 int start_order, int migratetype)
2379 int nr_pageblocks = 1 << (start_order - pageblock_order);
2381 while (nr_pageblocks--) {
2382 set_pageblock_migratetype(pageblock_page, migratetype);
2383 pageblock_page += pageblock_nr_pages;
2388 * When we are falling back to another migratetype during allocation, try to
2389 * steal extra free pages from the same pageblocks to satisfy further
2390 * allocations, instead of polluting multiple pageblocks.
2392 * If we are stealing a relatively large buddy page, it is likely there will
2393 * be more free pages in the pageblock, so try to steal them all. For
2394 * reclaimable and unmovable allocations, we steal regardless of page size,
2395 * as fragmentation caused by those allocations polluting movable pageblocks
2396 * is worse than movable allocations stealing from unmovable and reclaimable
2399 static bool can_steal_fallback(unsigned int order, int start_mt)
2402 * Leaving this order check is intended, although there is
2403 * relaxed order check in next check. The reason is that
2404 * we can actually steal whole pageblock if this condition met,
2405 * but, below check doesn't guarantee it and that is just heuristic
2406 * so could be changed anytime.
2408 if (order >= pageblock_order)
2411 if (order >= pageblock_order / 2 ||
2412 start_mt == MIGRATE_RECLAIMABLE ||
2413 start_mt == MIGRATE_UNMOVABLE ||
2414 page_group_by_mobility_disabled)
2420 static inline void boost_watermark(struct zone *zone)
2422 unsigned long max_boost;
2424 if (!watermark_boost_factor)
2427 * Don't bother in zones that are unlikely to produce results.
2428 * On small machines, including kdump capture kernels running
2429 * in a small area, boosting the watermark can cause an out of
2430 * memory situation immediately.
2432 if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
2435 max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
2436 watermark_boost_factor, 10000);
2439 * high watermark may be uninitialised if fragmentation occurs
2440 * very early in boot so do not boost. We do not fall
2441 * through and boost by pageblock_nr_pages as failing
2442 * allocations that early means that reclaim is not going
2443 * to help and it may even be impossible to reclaim the
2444 * boosted watermark resulting in a hang.
2449 max_boost = max(pageblock_nr_pages, max_boost);
2451 zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
2456 * This function implements actual steal behaviour. If order is large enough,
2457 * we can steal whole pageblock. If not, we first move freepages in this
2458 * pageblock to our migratetype and determine how many already-allocated pages
2459 * are there in the pageblock with a compatible migratetype. If at least half
2460 * of pages are free or compatible, we can change migratetype of the pageblock
2461 * itself, so pages freed in the future will be put on the correct free list.
2463 static void steal_suitable_fallback(struct zone *zone, struct page *page,
2464 unsigned int alloc_flags, int start_type, bool whole_block)
2466 unsigned int current_order = page_order(page);
2467 int free_pages, movable_pages, alike_pages;
2470 old_block_type = get_pageblock_migratetype(page);
2473 * This can happen due to races and we want to prevent broken
2474 * highatomic accounting.
2476 if (is_migrate_highatomic(old_block_type))
2479 /* Take ownership for orders >= pageblock_order */
2480 if (current_order >= pageblock_order) {
2481 change_pageblock_range(page, current_order, start_type);
2486 * Boost watermarks to increase reclaim pressure to reduce the
2487 * likelihood of future fallbacks. Wake kswapd now as the node
2488 * may be balanced overall and kswapd will not wake naturally.
2490 boost_watermark(zone);
2491 if (alloc_flags & ALLOC_KSWAPD)
2492 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
2494 /* We are not allowed to try stealing from the whole block */
2498 free_pages = move_freepages_block(zone, page, start_type,
2501 * Determine how many pages are compatible with our allocation.
2502 * For movable allocation, it's the number of movable pages which
2503 * we just obtained. For other types it's a bit more tricky.
2505 if (start_type == MIGRATE_MOVABLE) {
2506 alike_pages = movable_pages;
2509 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2510 * to MOVABLE pageblock, consider all non-movable pages as
2511 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2512 * vice versa, be conservative since we can't distinguish the
2513 * exact migratetype of non-movable pages.
2515 if (old_block_type == MIGRATE_MOVABLE)
2516 alike_pages = pageblock_nr_pages
2517 - (free_pages + movable_pages);
2522 /* moving whole block can fail due to zone boundary conditions */
2527 * If a sufficient number of pages in the block are either free or of
2528 * comparable migratability as our allocation, claim the whole block.
2530 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2531 page_group_by_mobility_disabled)
2532 set_pageblock_migratetype(page, start_type);
2537 move_to_free_list(page, zone, current_order, start_type);
2541 * Check whether there is a suitable fallback freepage with requested order.
2542 * If only_stealable is true, this function returns fallback_mt only if
2543 * we can steal other freepages all together. This would help to reduce
2544 * fragmentation due to mixed migratetype pages in one pageblock.
2546 int find_suitable_fallback(struct free_area *area, unsigned int order,
2547 int migratetype, bool only_stealable, bool *can_steal)
2552 if (area->nr_free == 0)
2557 fallback_mt = fallbacks[migratetype][i];
2558 if (fallback_mt == MIGRATE_TYPES)
2561 if (free_area_empty(area, fallback_mt))
2564 if (can_steal_fallback(order, migratetype))
2567 if (!only_stealable)
2578 * Reserve a pageblock for exclusive use of high-order atomic allocations if
2579 * there are no empty page blocks that contain a page with a suitable order
2581 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2582 unsigned int alloc_order)
2585 unsigned long max_managed, flags;
2588 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2589 * Check is race-prone but harmless.
2591 max_managed = (zone_managed_pages(zone) / 100) + pageblock_nr_pages;
2592 if (zone->nr_reserved_highatomic >= max_managed)
2595 spin_lock_irqsave(&zone->lock, flags);
2597 /* Recheck the nr_reserved_highatomic limit under the lock */
2598 if (zone->nr_reserved_highatomic >= max_managed)
2602 mt = get_pageblock_migratetype(page);
2603 if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
2604 && !is_migrate_cma(mt)) {
2605 zone->nr_reserved_highatomic += pageblock_nr_pages;
2606 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
2607 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
2611 spin_unlock_irqrestore(&zone->lock, flags);
2615 * Used when an allocation is about to fail under memory pressure. This
2616 * potentially hurts the reliability of high-order allocations when under
2617 * intense memory pressure but failed atomic allocations should be easier
2618 * to recover from than an OOM.
2620 * If @force is true, try to unreserve a pageblock even though highatomic
2621 * pageblock is exhausted.
2623 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2626 struct zonelist *zonelist = ac->zonelist;
2627 unsigned long flags;
2634 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2637 * Preserve at least one pageblock unless memory pressure
2640 if (!force && zone->nr_reserved_highatomic <=
2644 spin_lock_irqsave(&zone->lock, flags);
2645 for (order = 0; order < MAX_ORDER; order++) {
2646 struct free_area *area = &(zone->free_area[order]);
2648 page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
2653 * In page freeing path, migratetype change is racy so
2654 * we can counter several free pages in a pageblock
2655 * in this loop althoug we changed the pageblock type
2656 * from highatomic to ac->migratetype. So we should
2657 * adjust the count once.
2659 if (is_migrate_highatomic_page(page)) {
2661 * It should never happen but changes to
2662 * locking could inadvertently allow a per-cpu
2663 * drain to add pages to MIGRATE_HIGHATOMIC
2664 * while unreserving so be safe and watch for
2667 zone->nr_reserved_highatomic -= min(
2669 zone->nr_reserved_highatomic);
2673 * Convert to ac->migratetype and avoid the normal
2674 * pageblock stealing heuristics. Minimally, the caller
2675 * is doing the work and needs the pages. More
2676 * importantly, if the block was always converted to
2677 * MIGRATE_UNMOVABLE or another type then the number
2678 * of pageblocks that cannot be completely freed
2681 set_pageblock_migratetype(page, ac->migratetype);
2682 ret = move_freepages_block(zone, page, ac->migratetype,
2685 spin_unlock_irqrestore(&zone->lock, flags);
2689 spin_unlock_irqrestore(&zone->lock, flags);
2696 * Try finding a free buddy page on the fallback list and put it on the free
2697 * list of requested migratetype, possibly along with other pages from the same
2698 * block, depending on fragmentation avoidance heuristics. Returns true if
2699 * fallback was found so that __rmqueue_smallest() can grab it.
2701 * The use of signed ints for order and current_order is a deliberate
2702 * deviation from the rest of this file, to make the for loop
2703 * condition simpler.
2705 static __always_inline bool
2706 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype,
2707 unsigned int alloc_flags)
2709 struct free_area *area;
2711 int min_order = order;
2717 * Do not steal pages from freelists belonging to other pageblocks
2718 * i.e. orders < pageblock_order. If there are no local zones free,
2719 * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2721 if (alloc_flags & ALLOC_NOFRAGMENT)
2722 min_order = pageblock_order;
2725 * Find the largest available free page in the other list. This roughly
2726 * approximates finding the pageblock with the most free pages, which
2727 * would be too costly to do exactly.
2729 for (current_order = MAX_ORDER - 1; current_order >= min_order;
2731 area = &(zone->free_area[current_order]);
2732 fallback_mt = find_suitable_fallback(area, current_order,
2733 start_migratetype, false, &can_steal);
2734 if (fallback_mt == -1)
2738 * We cannot steal all free pages from the pageblock and the
2739 * requested migratetype is movable. In that case it's better to
2740 * steal and split the smallest available page instead of the
2741 * largest available page, because even if the next movable
2742 * allocation falls back into a different pageblock than this
2743 * one, it won't cause permanent fragmentation.
2745 if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2746 && current_order > order)
2755 for (current_order = order; current_order < MAX_ORDER;
2757 area = &(zone->free_area[current_order]);
2758 fallback_mt = find_suitable_fallback(area, current_order,
2759 start_migratetype, false, &can_steal);
2760 if (fallback_mt != -1)
2765 * This should not happen - we already found a suitable fallback
2766 * when looking for the largest page.
2768 VM_BUG_ON(current_order == MAX_ORDER);
2771 page = get_page_from_free_area(area, fallback_mt);
2773 steal_suitable_fallback(zone, page, alloc_flags, start_migratetype,
2776 trace_mm_page_alloc_extfrag(page, order, current_order,
2777 start_migratetype, fallback_mt);
2784 * Do the hard work of removing an element from the buddy allocator.
2785 * Call me with the zone->lock already held.
2787 static __always_inline struct page *
2788 __rmqueue(struct zone *zone, unsigned int order, int migratetype,
2789 unsigned int alloc_flags)
2794 page = __rmqueue_smallest(zone, order, migratetype);
2795 if (unlikely(!page)) {
2796 if (migratetype == MIGRATE_MOVABLE)
2797 page = __rmqueue_cma_fallback(zone, order);
2799 if (!page && __rmqueue_fallback(zone, order, migratetype,
2804 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2809 * Obtain a specified number of elements from the buddy allocator, all under
2810 * a single hold of the lock, for efficiency. Add them to the supplied list.
2811 * Returns the number of new pages which were placed at *list.
2813 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2814 unsigned long count, struct list_head *list,
2815 int migratetype, unsigned int alloc_flags)
2819 spin_lock(&zone->lock);
2820 for (i = 0; i < count; ++i) {
2821 struct page *page = __rmqueue(zone, order, migratetype,
2823 if (unlikely(page == NULL))
2826 if (unlikely(check_pcp_refill(page)))
2830 * Split buddy pages returned by expand() are received here in
2831 * physical page order. The page is added to the tail of
2832 * caller's list. From the callers perspective, the linked list
2833 * is ordered by page number under some conditions. This is
2834 * useful for IO devices that can forward direction from the
2835 * head, thus also in the physical page order. This is useful
2836 * for IO devices that can merge IO requests if the physical
2837 * pages are ordered properly.
2839 list_add_tail(&page->lru, list);
2841 if (is_migrate_cma(get_pcppage_migratetype(page)))
2842 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
2847 * i pages were removed from the buddy list even if some leak due
2848 * to check_pcp_refill failing so adjust NR_FREE_PAGES based
2849 * on i. Do not confuse with 'alloced' which is the number of
2850 * pages added to the pcp list.
2852 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
2853 spin_unlock(&zone->lock);
2859 * Called from the vmstat counter updater to drain pagesets of this
2860 * currently executing processor on remote nodes after they have
2863 * Note that this function must be called with the thread pinned to
2864 * a single processor.
2866 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2868 unsigned long flags;
2869 int to_drain, batch;
2871 local_irq_save(flags);
2872 batch = READ_ONCE(pcp->batch);
2873 to_drain = min(pcp->count, batch);
2875 free_pcppages_bulk(zone, to_drain, pcp);
2876 local_irq_restore(flags);
2881 * Drain pcplists of the indicated processor and zone.
2883 * The processor must either be the current processor and the
2884 * thread pinned to the current processor or a processor that
2887 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2889 unsigned long flags;
2890 struct per_cpu_pageset *pset;
2891 struct per_cpu_pages *pcp;
2893 local_irq_save(flags);
2894 pset = per_cpu_ptr(zone->pageset, cpu);
2898 free_pcppages_bulk(zone, pcp->count, pcp);
2899 local_irq_restore(flags);
2903 * Drain pcplists of all zones on the indicated processor.
2905 * The processor must either be the current processor and the
2906 * thread pinned to the current processor or a processor that
2909 static void drain_pages(unsigned int cpu)
2913 for_each_populated_zone(zone) {
2914 drain_pages_zone(cpu, zone);
2919 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2921 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2922 * the single zone's pages.
2924 void drain_local_pages(struct zone *zone)
2926 int cpu = smp_processor_id();
2929 drain_pages_zone(cpu, zone);
2934 static void drain_local_pages_wq(struct work_struct *work)
2936 struct pcpu_drain *drain;
2938 drain = container_of(work, struct pcpu_drain, work);
2941 * drain_all_pages doesn't use proper cpu hotplug protection so
2942 * we can race with cpu offline when the WQ can move this from
2943 * a cpu pinned worker to an unbound one. We can operate on a different
2944 * cpu which is allright but we also have to make sure to not move to
2948 drain_local_pages(drain->zone);
2953 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2955 * When zone parameter is non-NULL, spill just the single zone's pages.
2957 * Note that this can be extremely slow as the draining happens in a workqueue.
2959 void drain_all_pages(struct zone *zone)
2964 * Allocate in the BSS so we wont require allocation in
2965 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2967 static cpumask_t cpus_with_pcps;
2970 * Make sure nobody triggers this path before mm_percpu_wq is fully
2973 if (WARN_ON_ONCE(!mm_percpu_wq))
2977 * Do not drain if one is already in progress unless it's specific to
2978 * a zone. Such callers are primarily CMA and memory hotplug and need
2979 * the drain to be complete when the call returns.
2981 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
2984 mutex_lock(&pcpu_drain_mutex);
2988 * We don't care about racing with CPU hotplug event
2989 * as offline notification will cause the notified
2990 * cpu to drain that CPU pcps and on_each_cpu_mask
2991 * disables preemption as part of its processing
2993 for_each_online_cpu(cpu) {
2994 struct per_cpu_pageset *pcp;
2996 bool has_pcps = false;
2999 pcp = per_cpu_ptr(zone->pageset, cpu);
3003 for_each_populated_zone(z) {
3004 pcp = per_cpu_ptr(z->pageset, cpu);
3005 if (pcp->pcp.count) {
3013 cpumask_set_cpu(cpu, &cpus_with_pcps);
3015 cpumask_clear_cpu(cpu, &cpus_with_pcps);
3018 for_each_cpu(cpu, &cpus_with_pcps) {
3019 struct pcpu_drain *drain = per_cpu_ptr(&pcpu_drain, cpu);
3022 INIT_WORK(&drain->work, drain_local_pages_wq);
3023 queue_work_on(cpu, mm_percpu_wq, &drain->work);
3025 for_each_cpu(cpu, &cpus_with_pcps)
3026 flush_work(&per_cpu_ptr(&pcpu_drain, cpu)->work);
3028 mutex_unlock(&pcpu_drain_mutex);
3031 #ifdef CONFIG_HIBERNATION
3034 * Touch the watchdog for every WD_PAGE_COUNT pages.
3036 #define WD_PAGE_COUNT (128*1024)
3038 void mark_free_pages(struct zone *zone)
3040 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
3041 unsigned long flags;
3042 unsigned int order, t;
3045 if (zone_is_empty(zone))
3048 spin_lock_irqsave(&zone->lock, flags);
3050 max_zone_pfn = zone_end_pfn(zone);
3051 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
3052 if (pfn_valid(pfn)) {
3053 page = pfn_to_page(pfn);
3055 if (!--page_count) {
3056 touch_nmi_watchdog();
3057 page_count = WD_PAGE_COUNT;
3060 if (page_zone(page) != zone)
3063 if (!swsusp_page_is_forbidden(page))
3064 swsusp_unset_page_free(page);
3067 for_each_migratetype_order(order, t) {
3068 list_for_each_entry(page,
3069 &zone->free_area[order].free_list[t], lru) {
3072 pfn = page_to_pfn(page);
3073 for (i = 0; i < (1UL << order); i++) {
3074 if (!--page_count) {
3075 touch_nmi_watchdog();
3076 page_count = WD_PAGE_COUNT;
3078 swsusp_set_page_free(pfn_to_page(pfn + i));
3082 spin_unlock_irqrestore(&zone->lock, flags);
3084 #endif /* CONFIG_PM */
3086 static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
3090 if (!free_pcp_prepare(page))
3093 migratetype = get_pfnblock_migratetype(page, pfn);
3094 set_pcppage_migratetype(page, migratetype);
3098 static void free_unref_page_commit(struct page *page, unsigned long pfn)
3100 struct zone *zone = page_zone(page);
3101 struct per_cpu_pages *pcp;
3104 migratetype = get_pcppage_migratetype(page);
3105 __count_vm_event(PGFREE);
3108 * We only track unmovable, reclaimable and movable on pcp lists.
3109 * Free ISOLATE pages back to the allocator because they are being
3110 * offlined but treat HIGHATOMIC as movable pages so we can get those
3111 * areas back if necessary. Otherwise, we may have to free
3112 * excessively into the page allocator
3114 if (migratetype >= MIGRATE_PCPTYPES) {
3115 if (unlikely(is_migrate_isolate(migratetype))) {
3116 free_one_page(zone, page, pfn, 0, migratetype);
3119 migratetype = MIGRATE_MOVABLE;
3122 pcp = &this_cpu_ptr(zone->pageset)->pcp;
3123 list_add(&page->lru, &pcp->lists[migratetype]);
3125 if (pcp->count >= pcp->high) {
3126 unsigned long batch = READ_ONCE(pcp->batch);
3127 free_pcppages_bulk(zone, batch, pcp);
3132 * Free a 0-order page
3134 void free_unref_page(struct page *page)
3136 unsigned long flags;
3137 unsigned long pfn = page_to_pfn(page);
3139 if (!free_unref_page_prepare(page, pfn))
3142 local_irq_save(flags);
3143 free_unref_page_commit(page, pfn);
3144 local_irq_restore(flags);
3148 * Free a list of 0-order pages
3150 void free_unref_page_list(struct list_head *list)
3152 struct page *page, *next;
3153 unsigned long flags, pfn;
3154 int batch_count = 0;
3156 /* Prepare pages for freeing */
3157 list_for_each_entry_safe(page, next, list, lru) {
3158 pfn = page_to_pfn(page);
3159 if (!free_unref_page_prepare(page, pfn))
3160 list_del(&page->lru);
3161 set_page_private(page, pfn);
3164 local_irq_save(flags);
3165 list_for_each_entry_safe(page, next, list, lru) {
3166 unsigned long pfn = page_private(page);
3168 set_page_private(page, 0);
3169 trace_mm_page_free_batched(page);
3170 free_unref_page_commit(page, pfn);
3173 * Guard against excessive IRQ disabled times when we get
3174 * a large list of pages to free.
3176 if (++batch_count == SWAP_CLUSTER_MAX) {
3177 local_irq_restore(flags);
3179 local_irq_save(flags);
3182 local_irq_restore(flags);
3186 * split_page takes a non-compound higher-order page, and splits it into
3187 * n (1<<order) sub-pages: page[0..n]
3188 * Each sub-page must be freed individually.
3190 * Note: this is probably too low level an operation for use in drivers.
3191 * Please consult with lkml before using this in your driver.
3193 void split_page(struct page *page, unsigned int order)
3197 VM_BUG_ON_PAGE(PageCompound(page), page);
3198 VM_BUG_ON_PAGE(!page_count(page), page);
3200 for (i = 1; i < (1 << order); i++)
3201 set_page_refcounted(page + i);
3202 split_page_owner(page, order);
3204 EXPORT_SYMBOL_GPL(split_page);
3206 int __isolate_free_page(struct page *page, unsigned int order)
3208 unsigned long watermark;
3212 BUG_ON(!PageBuddy(page));
3214 zone = page_zone(page);
3215 mt = get_pageblock_migratetype(page);
3217 if (!is_migrate_isolate(mt)) {
3219 * Obey watermarks as if the page was being allocated. We can
3220 * emulate a high-order watermark check with a raised order-0
3221 * watermark, because we already know our high-order page
3224 watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
3225 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
3228 __mod_zone_freepage_state(zone, -(1UL << order), mt);
3231 /* Remove page from free list */
3233 del_page_from_free_list(page, zone, order);
3236 * Set the pageblock if the isolated page is at least half of a
3239 if (order >= pageblock_order - 1) {
3240 struct page *endpage = page + (1 << order) - 1;
3241 for (; page < endpage; page += pageblock_nr_pages) {
3242 int mt = get_pageblock_migratetype(page);
3243 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
3244 && !is_migrate_highatomic(mt))
3245 set_pageblock_migratetype(page,
3251 return 1UL << order;
3255 * __putback_isolated_page - Return a now-isolated page back where we got it
3256 * @page: Page that was isolated
3257 * @order: Order of the isolated page
3258 * @mt: The page's pageblock's migratetype
3260 * This function is meant to return a page pulled from the free lists via
3261 * __isolate_free_page back to the free lists they were pulled from.
3263 void __putback_isolated_page(struct page *page, unsigned int order, int mt)
3265 struct zone *zone = page_zone(page);
3267 /* zone lock should be held when this function is called */
3268 lockdep_assert_held(&zone->lock);
3270 /* Return isolated page to tail of freelist. */
3271 __free_one_page(page, page_to_pfn(page), zone, order, mt, false);
3275 * Update NUMA hit/miss statistics
3277 * Must be called with interrupts disabled.
3279 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z)
3282 enum numa_stat_item local_stat = NUMA_LOCAL;
3284 /* skip numa counters update if numa stats is disabled */
3285 if (!static_branch_likely(&vm_numa_stat_key))
3288 if (zone_to_nid(z) != numa_node_id())
3289 local_stat = NUMA_OTHER;
3291 if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3292 __inc_numa_state(z, NUMA_HIT);
3294 __inc_numa_state(z, NUMA_MISS);
3295 __inc_numa_state(preferred_zone, NUMA_FOREIGN);
3297 __inc_numa_state(z, local_stat);
3301 /* Remove page from the per-cpu list, caller must protect the list */
3302 static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
3303 unsigned int alloc_flags,
3304 struct per_cpu_pages *pcp,
3305 struct list_head *list)
3310 if (list_empty(list)) {
3311 pcp->count += rmqueue_bulk(zone, 0,
3313 migratetype, alloc_flags);
3314 if (unlikely(list_empty(list)))
3318 page = list_first_entry(list, struct page, lru);
3319 list_del(&page->lru);
3321 } while (check_new_pcp(page));
3326 /* Lock and remove page from the per-cpu list */
3327 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
3328 struct zone *zone, gfp_t gfp_flags,
3329 int migratetype, unsigned int alloc_flags)
3331 struct per_cpu_pages *pcp;
3332 struct list_head *list;
3334 unsigned long flags;
3336 local_irq_save(flags);
3337 pcp = &this_cpu_ptr(zone->pageset)->pcp;
3338 list = &pcp->lists[migratetype];
3339 page = __rmqueue_pcplist(zone, migratetype, alloc_flags, pcp, list);
3341 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1);
3342 zone_statistics(preferred_zone, zone);
3344 local_irq_restore(flags);
3349 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
3352 struct page *rmqueue(struct zone *preferred_zone,
3353 struct zone *zone, unsigned int order,
3354 gfp_t gfp_flags, unsigned int alloc_flags,
3357 unsigned long flags;
3360 if (likely(order == 0)) {
3361 page = rmqueue_pcplist(preferred_zone, zone, gfp_flags,
3362 migratetype, alloc_flags);
3367 * We most definitely don't want callers attempting to
3368 * allocate greater than order-1 page units with __GFP_NOFAIL.
3370 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
3371 spin_lock_irqsave(&zone->lock, flags);
3375 if (alloc_flags & ALLOC_HARDER) {
3376 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3378 trace_mm_page_alloc_zone_locked(page, order, migratetype);
3381 page = __rmqueue(zone, order, migratetype, alloc_flags);
3382 } while (page && check_new_pages(page, order));
3383 spin_unlock(&zone->lock);
3386 __mod_zone_freepage_state(zone, -(1 << order),
3387 get_pcppage_migratetype(page));
3389 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3390 zone_statistics(preferred_zone, zone);
3391 local_irq_restore(flags);
3394 /* Separate test+clear to avoid unnecessary atomics */
3395 if (test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags)) {
3396 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3397 wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3400 VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3404 local_irq_restore(flags);
3408 #ifdef CONFIG_FAIL_PAGE_ALLOC
3411 struct fault_attr attr;
3413 bool ignore_gfp_highmem;
3414 bool ignore_gfp_reclaim;
3416 } fail_page_alloc = {
3417 .attr = FAULT_ATTR_INITIALIZER,
3418 .ignore_gfp_reclaim = true,
3419 .ignore_gfp_highmem = true,
3423 static int __init setup_fail_page_alloc(char *str)
3425 return setup_fault_attr(&fail_page_alloc.attr, str);
3427 __setup("fail_page_alloc=", setup_fail_page_alloc);
3429 static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3431 if (order < fail_page_alloc.min_order)
3433 if (gfp_mask & __GFP_NOFAIL)
3435 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3437 if (fail_page_alloc.ignore_gfp_reclaim &&
3438 (gfp_mask & __GFP_DIRECT_RECLAIM))
3441 return should_fail(&fail_page_alloc.attr, 1 << order);
3444 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3446 static int __init fail_page_alloc_debugfs(void)
3448 umode_t mode = S_IFREG | 0600;
3451 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3452 &fail_page_alloc.attr);
3454 debugfs_create_bool("ignore-gfp-wait", mode, dir,
3455 &fail_page_alloc.ignore_gfp_reclaim);
3456 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3457 &fail_page_alloc.ignore_gfp_highmem);
3458 debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order);
3463 late_initcall(fail_page_alloc_debugfs);
3465 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3467 #else /* CONFIG_FAIL_PAGE_ALLOC */
3469 static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3474 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3476 static noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3478 return __should_fail_alloc_page(gfp_mask, order);
3480 ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE);
3483 * Return true if free base pages are above 'mark'. For high-order checks it
3484 * will return true of the order-0 watermark is reached and there is at least
3485 * one free page of a suitable size. Checking now avoids taking the zone lock
3486 * to check in the allocation paths if no pages are free.
3488 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3489 int classzone_idx, unsigned int alloc_flags,
3494 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3496 /* free_pages may go negative - that's OK */
3497 free_pages -= (1 << order) - 1;
3499 if (alloc_flags & ALLOC_HIGH)
3503 * If the caller does not have rights to ALLOC_HARDER then subtract
3504 * the high-atomic reserves. This will over-estimate the size of the
3505 * atomic reserve but it avoids a search.
3507 if (likely(!alloc_harder)) {
3508 free_pages -= z->nr_reserved_highatomic;
3511 * OOM victims can try even harder than normal ALLOC_HARDER
3512 * users on the grounds that it's definitely going to be in
3513 * the exit path shortly and free memory. Any allocation it
3514 * makes during the free path will be small and short-lived.
3516 if (alloc_flags & ALLOC_OOM)
3524 /* If allocation can't use CMA areas don't use free CMA pages */
3525 if (!(alloc_flags & ALLOC_CMA))
3526 free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
3530 * Check watermarks for an order-0 allocation request. If these
3531 * are not met, then a high-order request also cannot go ahead
3532 * even if a suitable page happened to be free.
3534 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
3537 /* If this is an order-0 request then the watermark is fine */
3541 /* For a high-order request, check at least one suitable page is free */
3542 for (o = order; o < MAX_ORDER; o++) {
3543 struct free_area *area = &z->free_area[o];
3549 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3550 if (!free_area_empty(area, mt))
3555 if ((alloc_flags & ALLOC_CMA) &&
3556 !free_area_empty(area, MIGRATE_CMA)) {
3560 if (alloc_harder && !free_area_empty(area, MIGRATE_HIGHATOMIC))
3566 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3567 int classzone_idx, unsigned int alloc_flags)
3569 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3570 zone_page_state(z, NR_FREE_PAGES));
3573 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3574 unsigned long mark, int classzone_idx, unsigned int alloc_flags)
3576 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3580 /* If allocation can't use CMA areas don't use free CMA pages */
3581 if (!(alloc_flags & ALLOC_CMA))
3582 cma_pages = zone_page_state(z, NR_FREE_CMA_PAGES);
3586 * Fast check for order-0 only. If this fails then the reserves
3587 * need to be calculated. There is a corner case where the check
3588 * passes but only the high-order atomic reserve are free. If
3589 * the caller is !atomic then it'll uselessly search the free
3590 * list. That corner case is then slower but it is harmless.
3592 if (!order && (free_pages - cma_pages) > mark + z->lowmem_reserve[classzone_idx])
3595 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3599 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3600 unsigned long mark, int classzone_idx)
3602 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3604 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3605 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3607 return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
3612 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3614 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3615 node_reclaim_distance;
3617 #else /* CONFIG_NUMA */
3618 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3622 #endif /* CONFIG_NUMA */
3625 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3626 * fragmentation is subtle. If the preferred zone was HIGHMEM then
3627 * premature use of a lower zone may cause lowmem pressure problems that
3628 * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3629 * probably too small. It only makes sense to spread allocations to avoid
3630 * fragmentation between the Normal and DMA32 zones.
3632 static inline unsigned int
3633 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3635 unsigned int alloc_flags;
3638 * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
3641 alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
3643 #ifdef CONFIG_ZONE_DMA32
3647 if (zone_idx(zone) != ZONE_NORMAL)
3651 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3652 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3653 * on UMA that if Normal is populated then so is DMA32.
3655 BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3656 if (nr_online_nodes > 1 && !populated_zone(--zone))
3659 alloc_flags |= ALLOC_NOFRAGMENT;
3660 #endif /* CONFIG_ZONE_DMA32 */
3665 * get_page_from_freelist goes through the zonelist trying to allocate
3668 static struct page *
3669 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3670 const struct alloc_context *ac)
3674 struct pglist_data *last_pgdat_dirty_limit = NULL;
3679 * Scan zonelist, looking for a zone with enough free.
3680 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3682 no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3683 z = ac->preferred_zoneref;
3684 for_next_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
3689 if (cpusets_enabled() &&
3690 (alloc_flags & ALLOC_CPUSET) &&
3691 !__cpuset_zone_allowed(zone, gfp_mask))
3694 * When allocating a page cache page for writing, we
3695 * want to get it from a node that is within its dirty
3696 * limit, such that no single node holds more than its
3697 * proportional share of globally allowed dirty pages.
3698 * The dirty limits take into account the node's
3699 * lowmem reserves and high watermark so that kswapd
3700 * should be able to balance it without having to
3701 * write pages from its LRU list.
3703 * XXX: For now, allow allocations to potentially
3704 * exceed the per-node dirty limit in the slowpath
3705 * (spread_dirty_pages unset) before going into reclaim,
3706 * which is important when on a NUMA setup the allowed
3707 * nodes are together not big enough to reach the
3708 * global limit. The proper fix for these situations
3709 * will require awareness of nodes in the
3710 * dirty-throttling and the flusher threads.
3712 if (ac->spread_dirty_pages) {
3713 if (last_pgdat_dirty_limit == zone->zone_pgdat)
3716 if (!node_dirty_ok(zone->zone_pgdat)) {
3717 last_pgdat_dirty_limit = zone->zone_pgdat;
3722 if (no_fallback && nr_online_nodes > 1 &&
3723 zone != ac->preferred_zoneref->zone) {
3727 * If moving to a remote node, retry but allow
3728 * fragmenting fallbacks. Locality is more important
3729 * than fragmentation avoidance.
3731 local_nid = zone_to_nid(ac->preferred_zoneref->zone);
3732 if (zone_to_nid(zone) != local_nid) {
3733 alloc_flags &= ~ALLOC_NOFRAGMENT;
3738 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
3739 if (!zone_watermark_fast(zone, order, mark,
3740 ac_classzone_idx(ac), alloc_flags)) {
3743 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3745 * Watermark failed for this zone, but see if we can
3746 * grow this zone if it contains deferred pages.
3748 if (static_branch_unlikely(&deferred_pages)) {
3749 if (_deferred_grow_zone(zone, order))
3753 /* Checked here to keep the fast path fast */
3754 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3755 if (alloc_flags & ALLOC_NO_WATERMARKS)
3758 if (node_reclaim_mode == 0 ||
3759 !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
3762 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3764 case NODE_RECLAIM_NOSCAN:
3767 case NODE_RECLAIM_FULL:
3768 /* scanned but unreclaimable */
3771 /* did we reclaim enough */
3772 if (zone_watermark_ok(zone, order, mark,
3773 ac_classzone_idx(ac), alloc_flags))