2 * linux/mm/page_alloc.c
4 * Manages the free list, the system allocates free pages here.
5 * Note that kmalloc() lives in slab.c
7 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
8 * Swap reorganised 29.12.95, Stephen Tweedie
9 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
17 #include <linux/stddef.h>
19 #include <linux/swap.h>
20 #include <linux/interrupt.h>
21 #include <linux/pagemap.h>
22 #include <linux/jiffies.h>
23 #include <linux/bootmem.h>
24 #include <linux/memblock.h>
25 #include <linux/compiler.h>
26 #include <linux/kernel.h>
27 #include <linux/kasan.h>
28 #include <linux/module.h>
29 #include <linux/suspend.h>
30 #include <linux/pagevec.h>
31 #include <linux/blkdev.h>
32 #include <linux/slab.h>
33 #include <linux/ratelimit.h>
34 #include <linux/oom.h>
35 #include <linux/topology.h>
36 #include <linux/sysctl.h>
37 #include <linux/cpu.h>
38 #include <linux/cpuset.h>
39 #include <linux/memory_hotplug.h>
40 #include <linux/nodemask.h>
41 #include <linux/vmalloc.h>
42 #include <linux/vmstat.h>
43 #include <linux/mempolicy.h>
44 #include <linux/memremap.h>
45 #include <linux/stop_machine.h>
46 #include <linux/sort.h>
47 #include <linux/pfn.h>
48 #include <linux/backing-dev.h>
49 #include <linux/fault-inject.h>
50 #include <linux/page-isolation.h>
51 #include <linux/page_ext.h>
52 #include <linux/debugobjects.h>
53 #include <linux/kmemleak.h>
54 #include <linux/compaction.h>
55 #include <trace/events/kmem.h>
56 #include <trace/events/oom.h>
57 #include <linux/prefetch.h>
58 #include <linux/mm_inline.h>
59 #include <linux/migrate.h>
60 #include <linux/hugetlb.h>
61 #include <linux/sched/rt.h>
62 #include <linux/sched/mm.h>
63 #include <linux/page_owner.h>
64 #include <linux/kthread.h>
65 #include <linux/memcontrol.h>
66 #include <linux/ftrace.h>
67 #include <linux/lockdep.h>
68 #include <linux/nmi.h>
69 #include <linux/psi.h>
71 #include <asm/sections.h>
72 #include <asm/tlbflush.h>
73 #include <asm/div64.h>
76 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
77 static DEFINE_MUTEX(pcp_batch_high_lock);
78 #define MIN_PERCPU_PAGELIST_FRACTION (8)
80 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
81 DEFINE_PER_CPU(int, numa_node);
82 EXPORT_PER_CPU_SYMBOL(numa_node);
85 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
87 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
89 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
90 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
91 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
92 * defined in <linux/topology.h>.
94 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
95 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
96 int _node_numa_mem_[MAX_NUMNODES];
99 /* work_structs for global per-cpu drains */
100 DEFINE_MUTEX(pcpu_drain_mutex);
101 DEFINE_PER_CPU(struct work_struct, pcpu_drain);
103 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
104 volatile unsigned long latent_entropy __latent_entropy;
105 EXPORT_SYMBOL(latent_entropy);
109 * Array of node states.
111 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
112 [N_POSSIBLE] = NODE_MASK_ALL,
113 [N_ONLINE] = { { [0] = 1UL } },
115 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
116 #ifdef CONFIG_HIGHMEM
117 [N_HIGH_MEMORY] = { { [0] = 1UL } },
119 [N_MEMORY] = { { [0] = 1UL } },
120 [N_CPU] = { { [0] = 1UL } },
123 EXPORT_SYMBOL(node_states);
125 /* Protect totalram_pages and zone->managed_pages */
126 static DEFINE_SPINLOCK(managed_page_count_lock);
128 unsigned long totalram_pages __read_mostly;
129 unsigned long totalreserve_pages __read_mostly;
130 unsigned long totalcma_pages __read_mostly;
132 int percpu_pagelist_fraction;
133 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
136 * A cached value of the page's pageblock's migratetype, used when the page is
137 * put on a pcplist. Used to avoid the pageblock migratetype lookup when
138 * freeing from pcplists in most cases, at the cost of possibly becoming stale.
139 * Also the migratetype set in the page does not necessarily match the pcplist
140 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
141 * other index - this ensures that it will be put on the correct CMA freelist.
143 static inline int get_pcppage_migratetype(struct page *page)
148 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
150 page->index = migratetype;
153 #ifdef CONFIG_PM_SLEEP
155 * The following functions are used by the suspend/hibernate code to temporarily
156 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
157 * while devices are suspended. To avoid races with the suspend/hibernate code,
158 * they should always be called with system_transition_mutex held
159 * (gfp_allowed_mask also should only be modified with system_transition_mutex
160 * held, unless the suspend/hibernate code is guaranteed not to run in parallel
161 * with that modification).
164 static gfp_t saved_gfp_mask;
166 void pm_restore_gfp_mask(void)
168 WARN_ON(!mutex_is_locked(&system_transition_mutex));
169 if (saved_gfp_mask) {
170 gfp_allowed_mask = saved_gfp_mask;
175 void pm_restrict_gfp_mask(void)
177 WARN_ON(!mutex_is_locked(&system_transition_mutex));
178 WARN_ON(saved_gfp_mask);
179 saved_gfp_mask = gfp_allowed_mask;
180 gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
183 bool pm_suspended_storage(void)
185 if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
189 #endif /* CONFIG_PM_SLEEP */
191 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
192 unsigned int pageblock_order __read_mostly;
195 static void __free_pages_ok(struct page *page, unsigned int order);
198 * results with 256, 32 in the lowmem_reserve sysctl:
199 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
200 * 1G machine -> (16M dma, 784M normal, 224M high)
201 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
202 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
203 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
205 * TBD: should special case ZONE_DMA32 machines here - in those we normally
206 * don't need any ZONE_NORMAL reservation
208 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
209 #ifdef CONFIG_ZONE_DMA
212 #ifdef CONFIG_ZONE_DMA32
216 #ifdef CONFIG_HIGHMEM
222 EXPORT_SYMBOL(totalram_pages);
224 static char * const zone_names[MAX_NR_ZONES] = {
225 #ifdef CONFIG_ZONE_DMA
228 #ifdef CONFIG_ZONE_DMA32
232 #ifdef CONFIG_HIGHMEM
236 #ifdef CONFIG_ZONE_DEVICE
241 char * const migratetype_names[MIGRATE_TYPES] = {
249 #ifdef CONFIG_MEMORY_ISOLATION
254 compound_page_dtor * const compound_page_dtors[] = {
257 #ifdef CONFIG_HUGETLB_PAGE
260 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
265 int min_free_kbytes = 1024;
266 int user_min_free_kbytes = -1;
267 int watermark_scale_factor = 10;
269 static unsigned long nr_kernel_pages __meminitdata;
270 static unsigned long nr_all_pages __meminitdata;
271 static unsigned long dma_reserve __meminitdata;
273 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
274 static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __meminitdata;
275 static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __meminitdata;
276 static unsigned long required_kernelcore __initdata;
277 static unsigned long required_kernelcore_percent __initdata;
278 static unsigned long required_movablecore __initdata;
279 static unsigned long required_movablecore_percent __initdata;
280 static unsigned long zone_movable_pfn[MAX_NUMNODES] __meminitdata;
281 static bool mirrored_kernelcore __meminitdata;
283 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
285 EXPORT_SYMBOL(movable_zone);
286 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
289 int nr_node_ids __read_mostly = MAX_NUMNODES;
290 int nr_online_nodes __read_mostly = 1;
291 EXPORT_SYMBOL(nr_node_ids);
292 EXPORT_SYMBOL(nr_online_nodes);
295 int page_group_by_mobility_disabled __read_mostly;
297 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
298 /* Returns true if the struct page for the pfn is uninitialised */
299 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
301 int nid = early_pfn_to_nid(pfn);
303 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
310 * Returns true when the remaining initialisation should be deferred until
311 * later in the boot cycle when it can be parallelised.
313 static bool __meminit
314 defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
316 static unsigned long prev_end_pfn, nr_initialised;
319 * prev_end_pfn static that contains the end of previous zone
320 * No need to protect because called very early in boot before smp_init.
322 if (prev_end_pfn != end_pfn) {
323 prev_end_pfn = end_pfn;
327 /* Always populate low zones for address-constrained allocations */
328 if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
331 if ((nr_initialised > NODE_DATA(nid)->static_init_pgcnt) &&
332 (pfn & (PAGES_PER_SECTION - 1)) == 0) {
333 NODE_DATA(nid)->first_deferred_pfn = pfn;
339 static inline bool early_page_uninitialised(unsigned long pfn)
344 static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
350 /* Return a pointer to the bitmap storing bits affecting a block of pages */
351 static inline unsigned long *get_pageblock_bitmap(struct page *page,
354 #ifdef CONFIG_SPARSEMEM
355 return __pfn_to_section(pfn)->pageblock_flags;
357 return page_zone(page)->pageblock_flags;
358 #endif /* CONFIG_SPARSEMEM */
361 static inline int pfn_to_bitidx(struct page *page, unsigned long pfn)
363 #ifdef CONFIG_SPARSEMEM
364 pfn &= (PAGES_PER_SECTION-1);
365 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
367 pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
368 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
369 #endif /* CONFIG_SPARSEMEM */
373 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
374 * @page: The page within the block of interest
375 * @pfn: The target page frame number
376 * @end_bitidx: The last bit of interest to retrieve
377 * @mask: mask of bits that the caller is interested in
379 * Return: pageblock_bits flags
381 static __always_inline unsigned long __get_pfnblock_flags_mask(struct page *page,
383 unsigned long end_bitidx,
386 unsigned long *bitmap;
387 unsigned long bitidx, word_bitidx;
390 bitmap = get_pageblock_bitmap(page, pfn);
391 bitidx = pfn_to_bitidx(page, pfn);
392 word_bitidx = bitidx / BITS_PER_LONG;
393 bitidx &= (BITS_PER_LONG-1);
395 word = bitmap[word_bitidx];
396 bitidx += end_bitidx;
397 return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
400 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
401 unsigned long end_bitidx,
404 return __get_pfnblock_flags_mask(page, pfn, end_bitidx, mask);
407 static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn)
409 return __get_pfnblock_flags_mask(page, pfn, PB_migrate_end, MIGRATETYPE_MASK);
413 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
414 * @page: The page within the block of interest
415 * @flags: The flags to set
416 * @pfn: The target page frame number
417 * @end_bitidx: The last bit of interest
418 * @mask: mask of bits that the caller is interested in
420 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
422 unsigned long end_bitidx,
425 unsigned long *bitmap;
426 unsigned long bitidx, word_bitidx;
427 unsigned long old_word, word;
429 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
431 bitmap = get_pageblock_bitmap(page, pfn);
432 bitidx = pfn_to_bitidx(page, pfn);
433 word_bitidx = bitidx / BITS_PER_LONG;
434 bitidx &= (BITS_PER_LONG-1);
436 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
438 bitidx += end_bitidx;
439 mask <<= (BITS_PER_LONG - bitidx - 1);
440 flags <<= (BITS_PER_LONG - bitidx - 1);
442 word = READ_ONCE(bitmap[word_bitidx]);
444 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
445 if (word == old_word)
451 void set_pageblock_migratetype(struct page *page, int migratetype)
453 if (unlikely(page_group_by_mobility_disabled &&
454 migratetype < MIGRATE_PCPTYPES))
455 migratetype = MIGRATE_UNMOVABLE;
457 set_pageblock_flags_group(page, (unsigned long)migratetype,
458 PB_migrate, PB_migrate_end);
461 #ifdef CONFIG_DEBUG_VM
462 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
466 unsigned long pfn = page_to_pfn(page);
467 unsigned long sp, start_pfn;
470 seq = zone_span_seqbegin(zone);
471 start_pfn = zone->zone_start_pfn;
472 sp = zone->spanned_pages;
473 if (!zone_spans_pfn(zone, pfn))
475 } while (zone_span_seqretry(zone, seq));
478 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
479 pfn, zone_to_nid(zone), zone->name,
480 start_pfn, start_pfn + sp);
485 static int page_is_consistent(struct zone *zone, struct page *page)
487 if (!pfn_valid_within(page_to_pfn(page)))
489 if (zone != page_zone(page))
495 * Temporary debugging check for pages not lying within a given zone.
497 static int __maybe_unused bad_range(struct zone *zone, struct page *page)
499 if (page_outside_zone_boundaries(zone, page))
501 if (!page_is_consistent(zone, page))
507 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
513 static void bad_page(struct page *page, const char *reason,
514 unsigned long bad_flags)
516 static unsigned long resume;
517 static unsigned long nr_shown;
518 static unsigned long nr_unshown;
521 * Allow a burst of 60 reports, then keep quiet for that minute;
522 * or allow a steady drip of one report per second.
524 if (nr_shown == 60) {
525 if (time_before(jiffies, resume)) {
531 "BUG: Bad page state: %lu messages suppressed\n",
538 resume = jiffies + 60 * HZ;
540 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
541 current->comm, page_to_pfn(page));
542 __dump_page(page, reason);
543 bad_flags &= page->flags;
545 pr_alert("bad because of flags: %#lx(%pGp)\n",
546 bad_flags, &bad_flags);
547 dump_page_owner(page);
552 /* Leave bad fields for debug, except PageBuddy could make trouble */
553 page_mapcount_reset(page); /* remove PageBuddy */
554 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
558 * Higher-order pages are called "compound pages". They are structured thusly:
560 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
562 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
563 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
565 * The first tail page's ->compound_dtor holds the offset in array of compound
566 * page destructors. See compound_page_dtors.
568 * The first tail page's ->compound_order holds the order of allocation.
569 * This usage means that zero-order pages may not be compound.
572 void free_compound_page(struct page *page)
574 __free_pages_ok(page, compound_order(page));
577 void prep_compound_page(struct page *page, unsigned int order)
580 int nr_pages = 1 << order;
582 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
583 set_compound_order(page, order);
585 for (i = 1; i < nr_pages; i++) {
586 struct page *p = page + i;
587 set_page_count(p, 0);
588 p->mapping = TAIL_MAPPING;
589 set_compound_head(p, page);
591 atomic_set(compound_mapcount_ptr(page), -1);
594 #ifdef CONFIG_DEBUG_PAGEALLOC
595 unsigned int _debug_guardpage_minorder;
596 bool _debug_pagealloc_enabled __read_mostly
597 = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
598 EXPORT_SYMBOL(_debug_pagealloc_enabled);
599 bool _debug_guardpage_enabled __read_mostly;
601 static int __init early_debug_pagealloc(char *buf)
605 return kstrtobool(buf, &_debug_pagealloc_enabled);
607 early_param("debug_pagealloc", early_debug_pagealloc);
609 static bool need_debug_guardpage(void)
611 /* If we don't use debug_pagealloc, we don't need guard page */
612 if (!debug_pagealloc_enabled())
615 if (!debug_guardpage_minorder())
621 static void init_debug_guardpage(void)
623 if (!debug_pagealloc_enabled())
626 if (!debug_guardpage_minorder())
629 _debug_guardpage_enabled = true;
632 struct page_ext_operations debug_guardpage_ops = {
633 .need = need_debug_guardpage,
634 .init = init_debug_guardpage,
637 static int __init debug_guardpage_minorder_setup(char *buf)
641 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
642 pr_err("Bad debug_guardpage_minorder value\n");
645 _debug_guardpage_minorder = res;
646 pr_info("Setting debug_guardpage_minorder to %lu\n", res);
649 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
651 static inline bool set_page_guard(struct zone *zone, struct page *page,
652 unsigned int order, int migratetype)
654 struct page_ext *page_ext;
656 if (!debug_guardpage_enabled())
659 if (order >= debug_guardpage_minorder())
662 page_ext = lookup_page_ext(page);
663 if (unlikely(!page_ext))
666 __set_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
668 INIT_LIST_HEAD(&page->lru);
669 set_page_private(page, order);
670 /* Guard pages are not available for any usage */
671 __mod_zone_freepage_state(zone, -(1 << order), migratetype);
676 static inline void clear_page_guard(struct zone *zone, struct page *page,
677 unsigned int order, int migratetype)
679 struct page_ext *page_ext;
681 if (!debug_guardpage_enabled())
684 page_ext = lookup_page_ext(page);
685 if (unlikely(!page_ext))
688 __clear_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
690 set_page_private(page, 0);
691 if (!is_migrate_isolate(migratetype))
692 __mod_zone_freepage_state(zone, (1 << order), migratetype);
695 struct page_ext_operations debug_guardpage_ops;
696 static inline bool set_page_guard(struct zone *zone, struct page *page,
697 unsigned int order, int migratetype) { return false; }
698 static inline void clear_page_guard(struct zone *zone, struct page *page,
699 unsigned int order, int migratetype) {}
702 static inline void set_page_order(struct page *page, unsigned int order)
704 set_page_private(page, order);
705 __SetPageBuddy(page);
708 static inline void rmv_page_order(struct page *page)
710 __ClearPageBuddy(page);
711 set_page_private(page, 0);
715 * This function checks whether a page is free && is the buddy
716 * we can coalesce a page and its buddy if
717 * (a) the buddy is not in a hole (check before calling!) &&
718 * (b) the buddy is in the buddy system &&
719 * (c) a page and its buddy have the same order &&
720 * (d) a page and its buddy are in the same zone.
722 * For recording whether a page is in the buddy system, we set PageBuddy.
723 * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
725 * For recording page's order, we use page_private(page).
727 static inline int page_is_buddy(struct page *page, struct page *buddy,
730 if (page_is_guard(buddy) && page_order(buddy) == order) {
731 if (page_zone_id(page) != page_zone_id(buddy))
734 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
739 if (PageBuddy(buddy) && page_order(buddy) == order) {
741 * zone check is done late to avoid uselessly
742 * calculating zone/node ids for pages that could
745 if (page_zone_id(page) != page_zone_id(buddy))
748 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
756 * Freeing function for a buddy system allocator.
758 * The concept of a buddy system is to maintain direct-mapped table
759 * (containing bit values) for memory blocks of various "orders".
760 * The bottom level table contains the map for the smallest allocatable
761 * units of memory (here, pages), and each level above it describes
762 * pairs of units from the levels below, hence, "buddies".
763 * At a high level, all that happens here is marking the table entry
764 * at the bottom level available, and propagating the changes upward
765 * as necessary, plus some accounting needed to play nicely with other
766 * parts of the VM system.
767 * At each level, we keep a list of pages, which are heads of continuous
768 * free pages of length of (1 << order) and marked with PageBuddy.
769 * Page's order is recorded in page_private(page) field.
770 * So when we are allocating or freeing one, we can derive the state of the
771 * other. That is, if we allocate a small block, and both were
772 * free, the remainder of the region must be split into blocks.
773 * If a block is freed, and its buddy is also free, then this
774 * triggers coalescing into a block of larger size.
779 static inline void __free_one_page(struct page *page,
781 struct zone *zone, unsigned int order,
784 unsigned long combined_pfn;
785 unsigned long uninitialized_var(buddy_pfn);
787 unsigned int max_order;
789 max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
791 VM_BUG_ON(!zone_is_initialized(zone));
792 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
794 VM_BUG_ON(migratetype == -1);
795 if (likely(!is_migrate_isolate(migratetype)))
796 __mod_zone_freepage_state(zone, 1 << order, migratetype);
798 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
799 VM_BUG_ON_PAGE(bad_range(zone, page), page);
802 while (order < max_order - 1) {
803 buddy_pfn = __find_buddy_pfn(pfn, order);
804 buddy = page + (buddy_pfn - pfn);
806 if (!pfn_valid_within(buddy_pfn))
808 if (!page_is_buddy(page, buddy, order))
811 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
812 * merge with it and move up one order.
814 if (page_is_guard(buddy)) {
815 clear_page_guard(zone, buddy, order, migratetype);
817 list_del(&buddy->lru);
818 zone->free_area[order].nr_free--;
819 rmv_page_order(buddy);
821 combined_pfn = buddy_pfn & pfn;
822 page = page + (combined_pfn - pfn);
826 if (max_order < MAX_ORDER) {
827 /* If we are here, it means order is >= pageblock_order.
828 * We want to prevent merge between freepages on isolate
829 * pageblock and normal pageblock. Without this, pageblock
830 * isolation could cause incorrect freepage or CMA accounting.
832 * We don't want to hit this code for the more frequent
835 if (unlikely(has_isolate_pageblock(zone))) {
838 buddy_pfn = __find_buddy_pfn(pfn, order);
839 buddy = page + (buddy_pfn - pfn);
840 buddy_mt = get_pageblock_migratetype(buddy);
842 if (migratetype != buddy_mt
843 && (is_migrate_isolate(migratetype) ||
844 is_migrate_isolate(buddy_mt)))
848 goto continue_merging;
852 set_page_order(page, order);
855 * If this is not the largest possible page, check if the buddy
856 * of the next-highest order is free. If it is, it's possible
857 * that pages are being freed that will coalesce soon. In case,
858 * that is happening, add the free page to the tail of the list
859 * so it's less likely to be used soon and more likely to be merged
860 * as a higher order page
862 if ((order < MAX_ORDER-2) && pfn_valid_within(buddy_pfn)) {
863 struct page *higher_page, *higher_buddy;
864 combined_pfn = buddy_pfn & pfn;
865 higher_page = page + (combined_pfn - pfn);
866 buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
867 higher_buddy = higher_page + (buddy_pfn - combined_pfn);
868 if (pfn_valid_within(buddy_pfn) &&
869 page_is_buddy(higher_page, higher_buddy, order + 1)) {
870 list_add_tail(&page->lru,
871 &zone->free_area[order].free_list[migratetype]);
876 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
878 zone->free_area[order].nr_free++;
882 * A bad page could be due to a number of fields. Instead of multiple branches,
883 * try and check multiple fields with one check. The caller must do a detailed
884 * check if necessary.
886 static inline bool page_expected_state(struct page *page,
887 unsigned long check_flags)
889 if (unlikely(atomic_read(&page->_mapcount) != -1))
892 if (unlikely((unsigned long)page->mapping |
893 page_ref_count(page) |
895 (unsigned long)page->mem_cgroup |
897 (page->flags & check_flags)))
903 static void free_pages_check_bad(struct page *page)
905 const char *bad_reason;
906 unsigned long bad_flags;
911 if (unlikely(atomic_read(&page->_mapcount) != -1))
912 bad_reason = "nonzero mapcount";
913 if (unlikely(page->mapping != NULL))
914 bad_reason = "non-NULL mapping";
915 if (unlikely(page_ref_count(page) != 0))
916 bad_reason = "nonzero _refcount";
917 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
918 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
919 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
922 if (unlikely(page->mem_cgroup))
923 bad_reason = "page still charged to cgroup";
925 bad_page(page, bad_reason, bad_flags);
928 static inline int free_pages_check(struct page *page)
930 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
933 /* Something has gone sideways, find it */
934 free_pages_check_bad(page);
938 static int free_tail_pages_check(struct page *head_page, struct page *page)
943 * We rely page->lru.next never has bit 0 set, unless the page
944 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
946 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
948 if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
952 switch (page - head_page) {
954 /* the first tail page: ->mapping may be compound_mapcount() */
955 if (unlikely(compound_mapcount(page))) {
956 bad_page(page, "nonzero compound_mapcount", 0);
962 * the second tail page: ->mapping is
963 * deferred_list.next -- ignore value.
967 if (page->mapping != TAIL_MAPPING) {
968 bad_page(page, "corrupted mapping in tail page", 0);
973 if (unlikely(!PageTail(page))) {
974 bad_page(page, "PageTail not set", 0);
977 if (unlikely(compound_head(page) != head_page)) {
978 bad_page(page, "compound_head not consistent", 0);
983 page->mapping = NULL;
984 clear_compound_head(page);
988 static __always_inline bool free_pages_prepare(struct page *page,
989 unsigned int order, bool check_free)
993 VM_BUG_ON_PAGE(PageTail(page), page);
995 trace_mm_page_free(page, order);
998 * Check tail pages before head page information is cleared to
999 * avoid checking PageCompound for order-0 pages.
1001 if (unlikely(order)) {
1002 bool compound = PageCompound(page);
1005 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1008 ClearPageDoubleMap(page);
1009 for (i = 1; i < (1 << order); i++) {
1011 bad += free_tail_pages_check(page, page + i);
1012 if (unlikely(free_pages_check(page + i))) {
1016 (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1019 if (PageMappingFlags(page))
1020 page->mapping = NULL;
1021 if (memcg_kmem_enabled() && PageKmemcg(page))
1022 memcg_kmem_uncharge(page, order);
1024 bad += free_pages_check(page);
1028 page_cpupid_reset_last(page);
1029 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1030 reset_page_owner(page, order);
1032 if (!PageHighMem(page)) {
1033 debug_check_no_locks_freed(page_address(page),
1034 PAGE_SIZE << order);
1035 debug_check_no_obj_freed(page_address(page),
1036 PAGE_SIZE << order);
1038 arch_free_page(page, order);
1039 kernel_poison_pages(page, 1 << order, 0);
1040 kernel_map_pages(page, 1 << order, 0);
1041 kasan_free_pages(page, order);
1046 #ifdef CONFIG_DEBUG_VM
1047 static inline bool free_pcp_prepare(struct page *page)
1049 return free_pages_prepare(page, 0, true);
1052 static inline bool bulkfree_pcp_prepare(struct page *page)
1057 static bool free_pcp_prepare(struct page *page)
1059 return free_pages_prepare(page, 0, false);
1062 static bool bulkfree_pcp_prepare(struct page *page)
1064 return free_pages_check(page);
1066 #endif /* CONFIG_DEBUG_VM */
1068 static inline void prefetch_buddy(struct page *page)
1070 unsigned long pfn = page_to_pfn(page);
1071 unsigned long buddy_pfn = __find_buddy_pfn(pfn, 0);
1072 struct page *buddy = page + (buddy_pfn - pfn);
1078 * Frees a number of pages from the PCP lists
1079 * Assumes all pages on list are in same zone, and of same order.
1080 * count is the number of pages to free.
1082 * If the zone was previously in an "all pages pinned" state then look to
1083 * see if this freeing clears that state.
1085 * And clear the zone's pages_scanned counter, to hold off the "all pages are
1086 * pinned" detection logic.
1088 static void free_pcppages_bulk(struct zone *zone, int count,
1089 struct per_cpu_pages *pcp)
1091 int migratetype = 0;
1093 int prefetch_nr = 0;
1094 bool isolated_pageblocks;
1095 struct page *page, *tmp;
1099 struct list_head *list;
1102 * Remove pages from lists in a round-robin fashion. A
1103 * batch_free count is maintained that is incremented when an
1104 * empty list is encountered. This is so more pages are freed
1105 * off fuller lists instead of spinning excessively around empty
1110 if (++migratetype == MIGRATE_PCPTYPES)
1112 list = &pcp->lists[migratetype];
1113 } while (list_empty(list));
1115 /* This is the only non-empty list. Free them all. */
1116 if (batch_free == MIGRATE_PCPTYPES)
1120 page = list_last_entry(list, struct page, lru);
1121 /* must delete to avoid corrupting pcp list */
1122 list_del(&page->lru);
1125 if (bulkfree_pcp_prepare(page))
1128 list_add_tail(&page->lru, &head);
1131 * We are going to put the page back to the global
1132 * pool, prefetch its buddy to speed up later access
1133 * under zone->lock. It is believed the overhead of
1134 * an additional test and calculating buddy_pfn here
1135 * can be offset by reduced memory latency later. To
1136 * avoid excessive prefetching due to large count, only
1137 * prefetch buddy for the first pcp->batch nr of pages.
1139 if (prefetch_nr++ < pcp->batch)
1140 prefetch_buddy(page);
1141 } while (--count && --batch_free && !list_empty(list));
1144 spin_lock(&zone->lock);
1145 isolated_pageblocks = has_isolate_pageblock(zone);
1148 * Use safe version since after __free_one_page(),
1149 * page->lru.next will not point to original list.
1151 list_for_each_entry_safe(page, tmp, &head, lru) {
1152 int mt = get_pcppage_migratetype(page);
1153 /* MIGRATE_ISOLATE page should not go to pcplists */
1154 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1155 /* Pageblock could have been isolated meanwhile */
1156 if (unlikely(isolated_pageblocks))
1157 mt = get_pageblock_migratetype(page);
1159 __free_one_page(page, page_to_pfn(page), zone, 0, mt);
1160 trace_mm_page_pcpu_drain(page, 0, mt);
1162 spin_unlock(&zone->lock);
1165 static void free_one_page(struct zone *zone,
1166 struct page *page, unsigned long pfn,
1170 spin_lock(&zone->lock);
1171 if (unlikely(has_isolate_pageblock(zone) ||
1172 is_migrate_isolate(migratetype))) {
1173 migratetype = get_pfnblock_migratetype(page, pfn);
1175 __free_one_page(page, pfn, zone, order, migratetype);
1176 spin_unlock(&zone->lock);
1179 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
1180 unsigned long zone, int nid)
1182 mm_zero_struct_page(page);
1183 set_page_links(page, zone, nid, pfn);
1184 init_page_count(page);
1185 page_mapcount_reset(page);
1186 page_cpupid_reset_last(page);
1188 INIT_LIST_HEAD(&page->lru);
1189 #ifdef WANT_PAGE_VIRTUAL
1190 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1191 if (!is_highmem_idx(zone))
1192 set_page_address(page, __va(pfn << PAGE_SHIFT));
1196 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1197 static void __meminit init_reserved_page(unsigned long pfn)
1202 if (!early_page_uninitialised(pfn))
1205 nid = early_pfn_to_nid(pfn);
1206 pgdat = NODE_DATA(nid);
1208 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1209 struct zone *zone = &pgdat->node_zones[zid];
1211 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
1214 __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
1217 static inline void init_reserved_page(unsigned long pfn)
1220 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1223 * Initialised pages do not have PageReserved set. This function is
1224 * called for each range allocated by the bootmem allocator and
1225 * marks the pages PageReserved. The remaining valid pages are later
1226 * sent to the buddy page allocator.
1228 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1230 unsigned long start_pfn = PFN_DOWN(start);
1231 unsigned long end_pfn = PFN_UP(end);
1233 for (; start_pfn < end_pfn; start_pfn++) {
1234 if (pfn_valid(start_pfn)) {
1235 struct page *page = pfn_to_page(start_pfn);
1237 init_reserved_page(start_pfn);
1239 /* Avoid false-positive PageTail() */
1240 INIT_LIST_HEAD(&page->lru);
1243 * no need for atomic set_bit because the struct
1244 * page is not visible yet so nobody should
1247 __SetPageReserved(page);
1252 static void __free_pages_ok(struct page *page, unsigned int order)
1254 unsigned long flags;
1256 unsigned long pfn = page_to_pfn(page);
1258 if (!free_pages_prepare(page, order, true))
1261 migratetype = get_pfnblock_migratetype(page, pfn);
1262 local_irq_save(flags);
1263 __count_vm_events(PGFREE, 1 << order);
1264 free_one_page(page_zone(page), page, pfn, order, migratetype);
1265 local_irq_restore(flags);
1268 static void __init __free_pages_boot_core(struct page *page, unsigned int order)
1270 unsigned int nr_pages = 1 << order;
1271 struct page *p = page;
1275 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1277 __ClearPageReserved(p);
1278 set_page_count(p, 0);
1280 __ClearPageReserved(p);
1281 set_page_count(p, 0);
1283 page_zone(page)->managed_pages += nr_pages;
1284 set_page_refcounted(page);
1285 __free_pages(page, order);
1288 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1289 defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1291 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1293 int __meminit early_pfn_to_nid(unsigned long pfn)
1295 static DEFINE_SPINLOCK(early_pfn_lock);
1298 spin_lock(&early_pfn_lock);
1299 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1301 nid = first_online_node;
1302 spin_unlock(&early_pfn_lock);
1308 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1309 static inline bool __meminit __maybe_unused
1310 meminit_pfn_in_nid(unsigned long pfn, int node,
1311 struct mminit_pfnnid_cache *state)
1315 nid = __early_pfn_to_nid(pfn, state);
1316 if (nid >= 0 && nid != node)
1321 /* Only safe to use early in boot when initialisation is single-threaded */
1322 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1324 return meminit_pfn_in_nid(pfn, node, &early_pfnnid_cache);
1329 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1333 static inline bool __meminit __maybe_unused
1334 meminit_pfn_in_nid(unsigned long pfn, int node,
1335 struct mminit_pfnnid_cache *state)
1342 void __init __free_pages_bootmem(struct page *page, unsigned long pfn,
1345 if (early_page_uninitialised(pfn))
1347 return __free_pages_boot_core(page, order);
1351 * Check that the whole (or subset of) a pageblock given by the interval of
1352 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1353 * with the migration of free compaction scanner. The scanners then need to
1354 * use only pfn_valid_within() check for arches that allow holes within
1357 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1359 * It's possible on some configurations to have a setup like node0 node1 node0
1360 * i.e. it's possible that all pages within a zones range of pages do not
1361 * belong to a single zone. We assume that a border between node0 and node1
1362 * can occur within a single pageblock, but not a node0 node1 node0
1363 * interleaving within a single pageblock. It is therefore sufficient to check
1364 * the first and last page of a pageblock and avoid checking each individual
1365 * page in a pageblock.
1367 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1368 unsigned long end_pfn, struct zone *zone)
1370 struct page *start_page;
1371 struct page *end_page;
1373 /* end_pfn is one past the range we are checking */
1376 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1379 start_page = pfn_to_online_page(start_pfn);
1383 if (page_zone(start_page) != zone)
1386 end_page = pfn_to_page(end_pfn);
1388 /* This gives a shorter code than deriving page_zone(end_page) */
1389 if (page_zone_id(start_page) != page_zone_id(end_page))
1395 void set_zone_contiguous(struct zone *zone)
1397 unsigned long block_start_pfn = zone->zone_start_pfn;
1398 unsigned long block_end_pfn;
1400 block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1401 for (; block_start_pfn < zone_end_pfn(zone);
1402 block_start_pfn = block_end_pfn,
1403 block_end_pfn += pageblock_nr_pages) {
1405 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1407 if (!__pageblock_pfn_to_page(block_start_pfn,
1408 block_end_pfn, zone))
1412 /* We confirm that there is no hole */
1413 zone->contiguous = true;
1416 void clear_zone_contiguous(struct zone *zone)
1418 zone->contiguous = false;
1421 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1422 static void __init deferred_free_range(unsigned long pfn,
1423 unsigned long nr_pages)
1431 page = pfn_to_page(pfn);
1433 /* Free a large naturally-aligned chunk if possible */
1434 if (nr_pages == pageblock_nr_pages &&
1435 (pfn & (pageblock_nr_pages - 1)) == 0) {
1436 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1437 __free_pages_boot_core(page, pageblock_order);
1441 for (i = 0; i < nr_pages; i++, page++, pfn++) {
1442 if ((pfn & (pageblock_nr_pages - 1)) == 0)
1443 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1444 __free_pages_boot_core(page, 0);
1448 /* Completion tracking for deferred_init_memmap() threads */
1449 static atomic_t pgdat_init_n_undone __initdata;
1450 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1452 static inline void __init pgdat_init_report_one_done(void)
1454 if (atomic_dec_and_test(&pgdat_init_n_undone))
1455 complete(&pgdat_init_all_done_comp);
1459 * Returns true if page needs to be initialized or freed to buddy allocator.
1461 * First we check if pfn is valid on architectures where it is possible to have
1462 * holes within pageblock_nr_pages. On systems where it is not possible, this
1463 * function is optimized out.
1465 * Then, we check if a current large page is valid by only checking the validity
1468 * Finally, meminit_pfn_in_nid is checked on systems where pfns can interleave
1469 * within a node: a pfn is between start and end of a node, but does not belong
1470 * to this memory node.
1472 static inline bool __init
1473 deferred_pfn_valid(int nid, unsigned long pfn,
1474 struct mminit_pfnnid_cache *nid_init_state)
1476 if (!pfn_valid_within(pfn))
1478 if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1480 if (!meminit_pfn_in_nid(pfn, nid, nid_init_state))
1486 * Free pages to buddy allocator. Try to free aligned pages in
1487 * pageblock_nr_pages sizes.
1489 static void __init deferred_free_pages(int nid, int zid, unsigned long pfn,
1490 unsigned long end_pfn)
1492 struct mminit_pfnnid_cache nid_init_state = { };
1493 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1494 unsigned long nr_free = 0;
1496 for (; pfn < end_pfn; pfn++) {
1497 if (!deferred_pfn_valid(nid, pfn, &nid_init_state)) {
1498 deferred_free_range(pfn - nr_free, nr_free);
1500 } else if (!(pfn & nr_pgmask)) {
1501 deferred_free_range(pfn - nr_free, nr_free);
1503 touch_nmi_watchdog();
1508 /* Free the last block of pages to allocator */
1509 deferred_free_range(pfn - nr_free, nr_free);
1513 * Initialize struct pages. We minimize pfn page lookups and scheduler checks
1514 * by performing it only once every pageblock_nr_pages.
1515 * Return number of pages initialized.
1517 static unsigned long __init deferred_init_pages(int nid, int zid,
1519 unsigned long end_pfn)
1521 struct mminit_pfnnid_cache nid_init_state = { };
1522 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1523 unsigned long nr_pages = 0;
1524 struct page *page = NULL;
1526 for (; pfn < end_pfn; pfn++) {
1527 if (!deferred_pfn_valid(nid, pfn, &nid_init_state)) {
1530 } else if (!page || !(pfn & nr_pgmask)) {
1531 page = pfn_to_page(pfn);
1532 touch_nmi_watchdog();
1536 __init_single_page(page, pfn, zid, nid);
1542 /* Initialise remaining memory on a node */
1543 static int __init deferred_init_memmap(void *data)
1545 pg_data_t *pgdat = data;
1546 int nid = pgdat->node_id;
1547 unsigned long start = jiffies;
1548 unsigned long nr_pages = 0;
1549 unsigned long spfn, epfn, first_init_pfn, flags;
1550 phys_addr_t spa, epa;
1553 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1556 /* Bind memory initialisation thread to a local node if possible */
1557 if (!cpumask_empty(cpumask))
1558 set_cpus_allowed_ptr(current, cpumask);
1560 pgdat_resize_lock(pgdat, &flags);
1561 first_init_pfn = pgdat->first_deferred_pfn;
1562 if (first_init_pfn == ULONG_MAX) {
1563 pgdat_resize_unlock(pgdat, &flags);
1564 pgdat_init_report_one_done();
1568 /* Sanity check boundaries */
1569 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1570 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1571 pgdat->first_deferred_pfn = ULONG_MAX;
1573 /* Only the highest zone is deferred so find it */
1574 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1575 zone = pgdat->node_zones + zid;
1576 if (first_init_pfn < zone_end_pfn(zone))
1579 first_init_pfn = max(zone->zone_start_pfn, first_init_pfn);
1582 * Initialize and free pages. We do it in two loops: first we initialize
1583 * struct page, than free to buddy allocator, because while we are
1584 * freeing pages we can access pages that are ahead (computing buddy
1585 * page in __free_one_page()).
1587 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1588 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1589 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1590 nr_pages += deferred_init_pages(nid, zid, spfn, epfn);
1592 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1593 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1594 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1595 deferred_free_pages(nid, zid, spfn, epfn);
1597 pgdat_resize_unlock(pgdat, &flags);
1599 /* Sanity check that the next zone really is unpopulated */
1600 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1602 pr_info("node %d initialised, %lu pages in %ums\n", nid, nr_pages,
1603 jiffies_to_msecs(jiffies - start));
1605 pgdat_init_report_one_done();
1610 * During boot we initialize deferred pages on-demand, as needed, but once
1611 * page_alloc_init_late() has finished, the deferred pages are all initialized,
1612 * and we can permanently disable that path.
1614 static DEFINE_STATIC_KEY_TRUE(deferred_pages);
1617 * If this zone has deferred pages, try to grow it by initializing enough
1618 * deferred pages to satisfy the allocation specified by order, rounded up to
1619 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
1620 * of SECTION_SIZE bytes by initializing struct pages in increments of
1621 * PAGES_PER_SECTION * sizeof(struct page) bytes.
1623 * Return true when zone was grown, otherwise return false. We return true even
1624 * when we grow less than requested, to let the caller decide if there are
1625 * enough pages to satisfy the allocation.
1627 * Note: We use noinline because this function is needed only during boot, and
1628 * it is called from a __ref function _deferred_grow_zone. This way we are
1629 * making sure that it is not inlined into permanent text section.
1631 static noinline bool __init
1632 deferred_grow_zone(struct zone *zone, unsigned int order)
1634 int zid = zone_idx(zone);
1635 int nid = zone_to_nid(zone);
1636 pg_data_t *pgdat = NODE_DATA(nid);
1637 unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
1638 unsigned long nr_pages = 0;
1639 unsigned long first_init_pfn, spfn, epfn, t, flags;
1640 unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
1641 phys_addr_t spa, epa;
1644 /* Only the last zone may have deferred pages */
1645 if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
1648 pgdat_resize_lock(pgdat, &flags);
1651 * If deferred pages have been initialized while we were waiting for
1652 * the lock, return true, as the zone was grown. The caller will retry
1653 * this zone. We won't return to this function since the caller also
1654 * has this static branch.
1656 if (!static_branch_unlikely(&deferred_pages)) {
1657 pgdat_resize_unlock(pgdat, &flags);
1662 * If someone grew this zone while we were waiting for spinlock, return
1663 * true, as there might be enough pages already.
1665 if (first_deferred_pfn != pgdat->first_deferred_pfn) {
1666 pgdat_resize_unlock(pgdat, &flags);
1670 first_init_pfn = max(zone->zone_start_pfn, first_deferred_pfn);
1672 if (first_init_pfn >= pgdat_end_pfn(pgdat)) {
1673 pgdat_resize_unlock(pgdat, &flags);
1677 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1678 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1679 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1681 while (spfn < epfn && nr_pages < nr_pages_needed) {
1682 t = ALIGN(spfn + PAGES_PER_SECTION, PAGES_PER_SECTION);
1683 first_deferred_pfn = min(t, epfn);
1684 nr_pages += deferred_init_pages(nid, zid, spfn,
1685 first_deferred_pfn);
1686 spfn = first_deferred_pfn;
1689 if (nr_pages >= nr_pages_needed)
1693 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1694 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1695 epfn = min_t(unsigned long, first_deferred_pfn, PFN_DOWN(epa));
1696 deferred_free_pages(nid, zid, spfn, epfn);
1698 if (first_deferred_pfn == epfn)
1701 pgdat->first_deferred_pfn = first_deferred_pfn;
1702 pgdat_resize_unlock(pgdat, &flags);
1704 return nr_pages > 0;
1708 * deferred_grow_zone() is __init, but it is called from
1709 * get_page_from_freelist() during early boot until deferred_pages permanently
1710 * disables this call. This is why we have refdata wrapper to avoid warning,
1711 * and to ensure that the function body gets unloaded.
1714 _deferred_grow_zone(struct zone *zone, unsigned int order)
1716 return deferred_grow_zone(zone, order);
1719 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1721 void __init page_alloc_init_late(void)
1725 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1728 /* There will be num_node_state(N_MEMORY) threads */
1729 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1730 for_each_node_state(nid, N_MEMORY) {
1731 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1734 /* Block until all are initialised */
1735 wait_for_completion(&pgdat_init_all_done_comp);
1738 * We initialized the rest of the deferred pages. Permanently disable
1739 * on-demand struct page initialization.
1741 static_branch_disable(&deferred_pages);
1743 /* Reinit limits that are based on free pages after the kernel is up */
1744 files_maxfiles_init();
1746 #ifdef CONFIG_ARCH_DISCARD_MEMBLOCK
1747 /* Discard memblock private memory */
1751 for_each_populated_zone(zone)
1752 set_zone_contiguous(zone);
1756 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
1757 void __init init_cma_reserved_pageblock(struct page *page)
1759 unsigned i = pageblock_nr_pages;
1760 struct page *p = page;
1763 __ClearPageReserved(p);
1764 set_page_count(p, 0);
1767 set_pageblock_migratetype(page, MIGRATE_CMA);
1769 if (pageblock_order >= MAX_ORDER) {
1770 i = pageblock_nr_pages;
1773 set_page_refcounted(p);
1774 __free_pages(p, MAX_ORDER - 1);
1775 p += MAX_ORDER_NR_PAGES;
1776 } while (i -= MAX_ORDER_NR_PAGES);
1778 set_page_refcounted(page);
1779 __free_pages(page, pageblock_order);
1782 adjust_managed_page_count(page, pageblock_nr_pages);
1787 * The order of subdivision here is critical for the IO subsystem.
1788 * Please do not alter this order without good reasons and regression
1789 * testing. Specifically, as large blocks of memory are subdivided,
1790 * the order in which smaller blocks are delivered depends on the order
1791 * they're subdivided in this function. This is the primary factor
1792 * influencing the order in which pages are delivered to the IO
1793 * subsystem according to empirical testing, and this is also justified
1794 * by considering the behavior of a buddy system containing a single
1795 * large block of memory acted on by a series of small allocations.
1796 * This behavior is a critical factor in sglist merging's success.
1800 static inline void expand(struct zone *zone, struct page *page,
1801 int low, int high, struct free_area *area,
1804 unsigned long size = 1 << high;
1806 while (high > low) {
1810 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
1813 * Mark as guard pages (or page), that will allow to
1814 * merge back to allocator when buddy will be freed.
1815 * Corresponding page table entries will not be touched,
1816 * pages will stay not present in virtual address space
1818 if (set_page_guard(zone, &page[size], high, migratetype))
1821 list_add(&page[size].lru, &area->free_list[migratetype]);
1823 set_page_order(&page[size], high);
1827 static void check_new_page_bad(struct page *page)
1829 const char *bad_reason = NULL;
1830 unsigned long bad_flags = 0;
1832 if (unlikely(atomic_read(&page->_mapcount) != -1))
1833 bad_reason = "nonzero mapcount";
1834 if (unlikely(page->mapping != NULL))
1835 bad_reason = "non-NULL mapping";
1836 if (unlikely(page_ref_count(page) != 0))
1837 bad_reason = "nonzero _count";
1838 if (unlikely(page->flags & __PG_HWPOISON)) {
1839 bad_reason = "HWPoisoned (hardware-corrupted)";
1840 bad_flags = __PG_HWPOISON;
1841 /* Don't complain about hwpoisoned pages */
1842 page_mapcount_reset(page); /* remove PageBuddy */
1845 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
1846 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
1847 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
1850 if (unlikely(page->mem_cgroup))
1851 bad_reason = "page still charged to cgroup";
1853 bad_page(page, bad_reason, bad_flags);
1857 * This page is about to be returned from the page allocator
1859 static inline int check_new_page(struct page *page)
1861 if (likely(page_expected_state(page,
1862 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
1865 check_new_page_bad(page);
1869 static inline bool free_pages_prezeroed(void)
1871 return IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) &&
1872 page_poisoning_enabled();
1875 #ifdef CONFIG_DEBUG_VM
1876 static bool check_pcp_refill(struct page *page)
1881 static bool check_new_pcp(struct page *page)
1883 return check_new_page(page);
1886 static bool check_pcp_refill(struct page *page)
1888 return check_new_page(page);
1890 static bool check_new_pcp(struct page *page)
1894 #endif /* CONFIG_DEBUG_VM */
1896 static bool check_new_pages(struct page *page, unsigned int order)
1899 for (i = 0; i < (1 << order); i++) {
1900 struct page *p = page + i;
1902 if (unlikely(check_new_page(p)))
1909 inline void post_alloc_hook(struct page *page, unsigned int order,
1912 set_page_private(page, 0);
1913 set_page_refcounted(page);
1915 arch_alloc_page(page, order);
1916 kernel_map_pages(page, 1 << order, 1);
1917 kernel_poison_pages(page, 1 << order, 1);
1918 kasan_alloc_pages(page, order);
1919 set_page_owner(page, order, gfp_flags);
1922 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
1923 unsigned int alloc_flags)
1927 post_alloc_hook(page, order, gfp_flags);
1929 if (!free_pages_prezeroed() && (gfp_flags & __GFP_ZERO))
1930 for (i = 0; i < (1 << order); i++)
1931 clear_highpage(page + i);
1933 if (order && (gfp_flags & __GFP_COMP))
1934 prep_compound_page(page, order);
1937 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1938 * allocate the page. The expectation is that the caller is taking
1939 * steps that will free more memory. The caller should avoid the page
1940 * being used for !PFMEMALLOC purposes.
1942 if (alloc_flags & ALLOC_NO_WATERMARKS)
1943 set_page_pfmemalloc(page);
1945 clear_page_pfmemalloc(page);
1949 * Go through the free lists for the given migratetype and remove
1950 * the smallest available page from the freelists
1952 static __always_inline
1953 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
1956 unsigned int current_order;
1957 struct free_area *area;
1960 /* Find a page of the appropriate size in the preferred list */
1961 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
1962 area = &(zone->free_area[current_order]);
1963 page = list_first_entry_or_null(&area->free_list[migratetype],
1967 list_del(&page->lru);
1968 rmv_page_order(page);
1970 expand(zone, page, order, current_order, area, migratetype);
1971 set_pcppage_migratetype(page, migratetype);
1980 * This array describes the order lists are fallen back to when
1981 * the free lists for the desirable migrate type are depleted
1983 static int fallbacks[MIGRATE_TYPES][4] = {
1984 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
1985 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
1986 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
1988 [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */
1990 #ifdef CONFIG_MEMORY_ISOLATION
1991 [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */
1996 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1999 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
2002 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2003 unsigned int order) { return NULL; }
2007 * Move the free pages in a range to the free lists of the requested type.
2008 * Note that start_page and end_pages are not aligned on a pageblock
2009 * boundary. If alignment is required, use move_freepages_block()
2011 static int move_freepages(struct zone *zone,
2012 struct page *start_page, struct page *end_page,
2013 int migratetype, int *num_movable)
2017 int pages_moved = 0;
2019 #ifndef CONFIG_HOLES_IN_ZONE
2021 * page_zone is not safe to call in this context when
2022 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
2023 * anyway as we check zone boundaries in move_freepages_block().
2024 * Remove at a later date when no bug reports exist related to
2025 * grouping pages by mobility
2027 VM_BUG_ON(pfn_valid(page_to_pfn(start_page)) &&
2028 pfn_valid(page_to_pfn(end_page)) &&
2029 page_zone(start_page) != page_zone(end_page));
2031 for (page = start_page; page <= end_page;) {
2032 if (!pfn_valid_within(page_to_pfn(page))) {
2037 /* Make sure we are not inadvertently changing nodes */
2038 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2040 if (!PageBuddy(page)) {
2042 * We assume that pages that could be isolated for
2043 * migration are movable. But we don't actually try
2044 * isolating, as that would be expensive.
2047 (PageLRU(page) || __PageMovable(page)))
2054 order = page_order(page);
2055 list_move(&page->lru,
2056 &zone->free_area[order].free_list[migratetype]);
2058 pages_moved += 1 << order;
2064 int move_freepages_block(struct zone *zone, struct page *page,
2065 int migratetype, int *num_movable)
2067 unsigned long start_pfn, end_pfn;
2068 struct page *start_page, *end_page;
2073 start_pfn = page_to_pfn(page);
2074 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
2075 start_page = pfn_to_page(start_pfn);
2076 end_page = start_page + pageblock_nr_pages - 1;
2077 end_pfn = start_pfn + pageblock_nr_pages - 1;
2079 /* Do not cross zone boundaries */
2080 if (!zone_spans_pfn(zone, start_pfn))
2082 if (!zone_spans_pfn(zone, end_pfn))
2085 return move_freepages(zone, start_page, end_page, migratetype,
2089 static void change_pageblock_range(struct page *pageblock_page,
2090 int start_order, int migratetype)
2092 int nr_pageblocks = 1 << (start_order - pageblock_order);
2094 while (nr_pageblocks--) {
2095 set_pageblock_migratetype(pageblock_page, migratetype);
2096 pageblock_page += pageblock_nr_pages;
2101 * When we are falling back to another migratetype during allocation, try to
2102 * steal extra free pages from the same pageblocks to satisfy further
2103 * allocations, instead of polluting multiple pageblocks.
2105 * If we are stealing a relatively large buddy page, it is likely there will
2106 * be more free pages in the pageblock, so try to steal them all. For
2107 * reclaimable and unmovable allocations, we steal regardless of page size,
2108 * as fragmentation caused by those allocations polluting movable pageblocks
2109 * is worse than movable allocations stealing from unmovable and reclaimable
2112 static bool can_steal_fallback(unsigned int order, int start_mt)
2115 * Leaving this order check is intended, although there is
2116 * relaxed order check in next check. The reason is that
2117 * we can actually steal whole pageblock if this condition met,
2118 * but, below check doesn't guarantee it and that is just heuristic
2119 * so could be changed anytime.
2121 if (order >= pageblock_order)
2124 if (order >= pageblock_order / 2 ||
2125 start_mt == MIGRATE_RECLAIMABLE ||
2126 start_mt == MIGRATE_UNMOVABLE ||
2127 page_group_by_mobility_disabled)
2134 * This function implements actual steal behaviour. If order is large enough,
2135 * we can steal whole pageblock. If not, we first move freepages in this
2136 * pageblock to our migratetype and determine how many already-allocated pages
2137 * are there in the pageblock with a compatible migratetype. If at least half
2138 * of pages are free or compatible, we can change migratetype of the pageblock
2139 * itself, so pages freed in the future will be put on the correct free list.
2141 static void steal_suitable_fallback(struct zone *zone, struct page *page,
2142 int start_type, bool whole_block)
2144 unsigned int current_order = page_order(page);
2145 struct free_area *area;
2146 int free_pages, movable_pages, alike_pages;
2149 old_block_type = get_pageblock_migratetype(page);
2152 * This can happen due to races and we want to prevent broken
2153 * highatomic accounting.
2155 if (is_migrate_highatomic(old_block_type))
2158 /* Take ownership for orders >= pageblock_order */
2159 if (current_order >= pageblock_order) {
2160 change_pageblock_range(page, current_order, start_type);
2164 /* We are not allowed to try stealing from the whole block */
2168 free_pages = move_freepages_block(zone, page, start_type,
2171 * Determine how many pages are compatible with our allocation.
2172 * For movable allocation, it's the number of movable pages which
2173 * we just obtained. For other types it's a bit more tricky.
2175 if (start_type == MIGRATE_MOVABLE) {
2176 alike_pages = movable_pages;
2179 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2180 * to MOVABLE pageblock, consider all non-movable pages as
2181 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2182 * vice versa, be conservative since we can't distinguish the
2183 * exact migratetype of non-movable pages.
2185 if (old_block_type == MIGRATE_MOVABLE)
2186 alike_pages = pageblock_nr_pages
2187 - (free_pages + movable_pages);
2192 /* moving whole block can fail due to zone boundary conditions */
2197 * If a sufficient number of pages in the block are either free or of
2198 * comparable migratability as our allocation, claim the whole block.
2200 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2201 page_group_by_mobility_disabled)
2202 set_pageblock_migratetype(page, start_type);
2207 area = &zone->free_area[current_order];
2208 list_move(&page->lru, &area->free_list[start_type]);
2212 * Check whether there is a suitable fallback freepage with requested order.
2213 * If only_stealable is true, this function returns fallback_mt only if
2214 * we can steal other freepages all together. This would help to reduce
2215 * fragmentation due to mixed migratetype pages in one pageblock.
2217 int find_suitable_fallback(struct free_area *area, unsigned int order,
2218 int migratetype, bool only_stealable, bool *can_steal)
2223 if (area->nr_free == 0)
2228 fallback_mt = fallbacks[migratetype][i];
2229 if (fallback_mt == MIGRATE_TYPES)
2232 if (list_empty(&area->free_list[fallback_mt]))
2235 if (can_steal_fallback(order, migratetype))
2238 if (!only_stealable)
2249 * Reserve a pageblock for exclusive use of high-order atomic allocations if
2250 * there are no empty page blocks that contain a page with a suitable order
2252 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2253 unsigned int alloc_order)
2256 unsigned long max_managed, flags;
2259 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2260 * Check is race-prone but harmless.
2262 max_managed = (zone->managed_pages / 100) + pageblock_nr_pages;
2263 if (zone->nr_reserved_highatomic >= max_managed)
2266 spin_lock_irqsave(&zone->lock, flags);
2268 /* Recheck the nr_reserved_highatomic limit under the lock */
2269 if (zone->nr_reserved_highatomic >= max_managed)
2273 mt = get_pageblock_migratetype(page);
2274 if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
2275 && !is_migrate_cma(mt)) {
2276 zone->nr_reserved_highatomic += pageblock_nr_pages;
2277 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
2278 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
2282 spin_unlock_irqrestore(&zone->lock, flags);
2286 * Used when an allocation is about to fail under memory pressure. This
2287 * potentially hurts the reliability of high-order allocations when under
2288 * intense memory pressure but failed atomic allocations should be easier
2289 * to recover from than an OOM.
2291 * If @force is true, try to unreserve a pageblock even though highatomic
2292 * pageblock is exhausted.
2294 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2297 struct zonelist *zonelist = ac->zonelist;
2298 unsigned long flags;
2305 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2308 * Preserve at least one pageblock unless memory pressure
2311 if (!force && zone->nr_reserved_highatomic <=
2315 spin_lock_irqsave(&zone->lock, flags);
2316 for (order = 0; order < MAX_ORDER; order++) {
2317 struct free_area *area = &(zone->free_area[order]);
2319 page = list_first_entry_or_null(
2320 &area->free_list[MIGRATE_HIGHATOMIC],
2326 * In page freeing path, migratetype change is racy so
2327 * we can counter several free pages in a pageblock
2328 * in this loop althoug we changed the pageblock type
2329 * from highatomic to ac->migratetype. So we should
2330 * adjust the count once.
2332 if (is_migrate_highatomic_page(page)) {
2334 * It should never happen but changes to
2335 * locking could inadvertently allow a per-cpu
2336 * drain to add pages to MIGRATE_HIGHATOMIC
2337 * while unreserving so be safe and watch for
2340 zone->nr_reserved_highatomic -= min(
2342 zone->nr_reserved_highatomic);
2346 * Convert to ac->migratetype and avoid the normal
2347 * pageblock stealing heuristics. Minimally, the caller
2348 * is doing the work and needs the pages. More
2349 * importantly, if the block was always converted to
2350 * MIGRATE_UNMOVABLE or another type then the number
2351 * of pageblocks that cannot be completely freed
2354 set_pageblock_migratetype(page, ac->migratetype);
2355 ret = move_freepages_block(zone, page, ac->migratetype,
2358 spin_unlock_irqrestore(&zone->lock, flags);
2362 spin_unlock_irqrestore(&zone->lock, flags);
2369 * Try finding a free buddy page on the fallback list and put it on the free
2370 * list of requested migratetype, possibly along with other pages from the same
2371 * block, depending on fragmentation avoidance heuristics. Returns true if
2372 * fallback was found so that __rmqueue_smallest() can grab it.
2374 * The use of signed ints for order and current_order is a deliberate
2375 * deviation from the rest of this file, to make the for loop
2376 * condition simpler.
2378 static __always_inline bool
2379 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype)
2381 struct free_area *area;
2388 * Find the largest available free page in the other list. This roughly
2389 * approximates finding the pageblock with the most free pages, which
2390 * would be too costly to do exactly.
2392 for (current_order = MAX_ORDER - 1; current_order >= order;
2394 area = &(zone->free_area[current_order]);
2395 fallback_mt = find_suitable_fallback(area, current_order,
2396 start_migratetype, false, &can_steal);
2397 if (fallback_mt == -1)
2401 * We cannot steal all free pages from the pageblock and the
2402 * requested migratetype is movable. In that case it's better to
2403 * steal and split the smallest available page instead of the
2404 * largest available page, because even if the next movable
2405 * allocation falls back into a different pageblock than this
2406 * one, it won't cause permanent fragmentation.
2408 if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2409 && current_order > order)
2418 for (current_order = order; current_order < MAX_ORDER;
2420 area = &(zone->free_area[current_order]);
2421 fallback_mt = find_suitable_fallback(area, current_order,
2422 start_migratetype, false, &can_steal);
2423 if (fallback_mt != -1)
2428 * This should not happen - we already found a suitable fallback
2429 * when looking for the largest page.
2431 VM_BUG_ON(current_order == MAX_ORDER);
2434 page = list_first_entry(&area->free_list[fallback_mt],
2437 steal_suitable_fallback(zone, page, start_migratetype, can_steal);
2439 trace_mm_page_alloc_extfrag(page, order, current_order,
2440 start_migratetype, fallback_mt);
2447 * Do the hard work of removing an element from the buddy allocator.
2448 * Call me with the zone->lock already held.
2450 static __always_inline struct page *
2451 __rmqueue(struct zone *zone, unsigned int order, int migratetype)
2456 page = __rmqueue_smallest(zone, order, migratetype);
2457 if (unlikely(!page)) {
2458 if (migratetype == MIGRATE_MOVABLE)
2459 page = __rmqueue_cma_fallback(zone, order);
2461 if (!page && __rmqueue_fallback(zone, order, migratetype))
2465 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2470 * Obtain a specified number of elements from the buddy allocator, all under
2471 * a single hold of the lock, for efficiency. Add them to the supplied list.
2472 * Returns the number of new pages which were placed at *list.
2474 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2475 unsigned long count, struct list_head *list,
2480 spin_lock(&zone->lock);
2481 for (i = 0; i < count; ++i) {
2482 struct page *page = __rmqueue(zone, order, migratetype);
2483 if (unlikely(page == NULL))
2486 if (unlikely(check_pcp_refill(page)))
2490 * Split buddy pages returned by expand() are received here in
2491 * physical page order. The page is added to the tail of
2492 * caller's list. From the callers perspective, the linked list
2493 * is ordered by page number under some conditions. This is
2494 * useful for IO devices that can forward direction from the
2495 * head, thus also in the physical page order. This is useful
2496 * for IO devices that can merge IO requests if the physical
2497 * pages are ordered properly.
2499 list_add_tail(&page->lru, list);
2501 if (is_migrate_cma(get_pcppage_migratetype(page)))
2502 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
2507 * i pages were removed from the buddy list even if some leak due
2508 * to check_pcp_refill failing so adjust NR_FREE_PAGES based
2509 * on i. Do not confuse with 'alloced' which is the number of
2510 * pages added to the pcp list.
2512 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
2513 spin_unlock(&zone->lock);
2519 * Called from the vmstat counter updater to drain pagesets of this
2520 * currently executing processor on remote nodes after they have
2523 * Note that this function must be called with the thread pinned to
2524 * a single processor.
2526 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2528 unsigned long flags;
2529 int to_drain, batch;
2531 local_irq_save(flags);
2532 batch = READ_ONCE(pcp->batch);
2533 to_drain = min(pcp->count, batch);
2535 free_pcppages_bulk(zone, to_drain, pcp);
2536 local_irq_restore(flags);
2541 * Drain pcplists of the indicated processor and zone.
2543 * The processor must either be the current processor and the
2544 * thread pinned to the current processor or a processor that
2547 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2549 unsigned long flags;
2550 struct per_cpu_pageset *pset;
2551 struct per_cpu_pages *pcp;
2553 local_irq_save(flags);
2554 pset = per_cpu_ptr(zone->pageset, cpu);
2558 free_pcppages_bulk(zone, pcp->count, pcp);
2559 local_irq_restore(flags);
2563 * Drain pcplists of all zones on the indicated processor.
2565 * The processor must either be the current processor and the
2566 * thread pinned to the current processor or a processor that
2569 static void drain_pages(unsigned int cpu)
2573 for_each_populated_zone(zone) {
2574 drain_pages_zone(cpu, zone);
2579 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2581 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2582 * the single zone's pages.
2584 void drain_local_pages(struct zone *zone)
2586 int cpu = smp_processor_id();
2589 drain_pages_zone(cpu, zone);
2594 static void drain_local_pages_wq(struct work_struct *work)
2597 * drain_all_pages doesn't use proper cpu hotplug protection so
2598 * we can race with cpu offline when the WQ can move this from
2599 * a cpu pinned worker to an unbound one. We can operate on a different
2600 * cpu which is allright but we also have to make sure to not move to
2604 drain_local_pages(NULL);
2609 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2611 * When zone parameter is non-NULL, spill just the single zone's pages.
2613 * Note that this can be extremely slow as the draining happens in a workqueue.
2615 void drain_all_pages(struct zone *zone)
2620 * Allocate in the BSS so we wont require allocation in
2621 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2623 static cpumask_t cpus_with_pcps;
2626 * Make sure nobody triggers this path before mm_percpu_wq is fully
2629 if (WARN_ON_ONCE(!mm_percpu_wq))
2633 * Do not drain if one is already in progress unless it's specific to
2634 * a zone. Such callers are primarily CMA and memory hotplug and need
2635 * the drain to be complete when the call returns.
2637 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
2640 mutex_lock(&pcpu_drain_mutex);
2644 * We don't care about racing with CPU hotplug event
2645 * as offline notification will cause the notified
2646 * cpu to drain that CPU pcps and on_each_cpu_mask
2647 * disables preemption as part of its processing
2649 for_each_online_cpu(cpu) {
2650 struct per_cpu_pageset *pcp;
2652 bool has_pcps = false;
2655 pcp = per_cpu_ptr(zone->pageset, cpu);
2659 for_each_populated_zone(z) {
2660 pcp = per_cpu_ptr(z->pageset, cpu);
2661 if (pcp->pcp.count) {
2669 cpumask_set_cpu(cpu, &cpus_with_pcps);
2671 cpumask_clear_cpu(cpu, &cpus_with_pcps);
2674 for_each_cpu(cpu, &cpus_with_pcps) {
2675 struct work_struct *work = per_cpu_ptr(&pcpu_drain, cpu);
2676 INIT_WORK(work, drain_local_pages_wq);
2677 queue_work_on(cpu, mm_percpu_wq, work);
2679 for_each_cpu(cpu, &cpus_with_pcps)
2680 flush_work(per_cpu_ptr(&pcpu_drain, cpu));
2682 mutex_unlock(&pcpu_drain_mutex);
2685 #ifdef CONFIG_HIBERNATION
2688 * Touch the watchdog for every WD_PAGE_COUNT pages.
2690 #define WD_PAGE_COUNT (128*1024)
2692 void mark_free_pages(struct zone *zone)
2694 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
2695 unsigned long flags;
2696 unsigned int order, t;
2699 if (zone_is_empty(zone))
2702 spin_lock_irqsave(&zone->lock, flags);
2704 max_zone_pfn = zone_end_pfn(zone);
2705 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
2706 if (pfn_valid(pfn)) {
2707 page = pfn_to_page(pfn);
2709 if (!--page_count) {
2710 touch_nmi_watchdog();
2711 page_count = WD_PAGE_COUNT;
2714 if (page_zone(page) != zone)
2717 if (!swsusp_page_is_forbidden(page))
2718 swsusp_unset_page_free(page);
2721 for_each_migratetype_order(order, t) {
2722 list_for_each_entry(page,
2723 &zone->free_area[order].free_list[t], lru) {
2726 pfn = page_to_pfn(page);
2727 for (i = 0; i < (1UL << order); i++) {
2728 if (!--page_count) {
2729 touch_nmi_watchdog();
2730 page_count = WD_PAGE_COUNT;
2732 swsusp_set_page_free(pfn_to_page(pfn + i));
2736 spin_unlock_irqrestore(&zone->lock, flags);
2738 #endif /* CONFIG_PM */
2740 static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
2744 if (!free_pcp_prepare(page))
2747 migratetype = get_pfnblock_migratetype(page, pfn);
2748 set_pcppage_migratetype(page, migratetype);
2752 static void free_unref_page_commit(struct page *page, unsigned long pfn)
2754 struct zone *zone = page_zone(page);
2755 struct per_cpu_pages *pcp;
2758 migratetype = get_pcppage_migratetype(page);
2759 __count_vm_event(PGFREE);
2762 * We only track unmovable, reclaimable and movable on pcp lists.
2763 * Free ISOLATE pages back to the allocator because they are being
2764 * offlined but treat HIGHATOMIC as movable pages so we can get those
2765 * areas back if necessary. Otherwise, we may have to free
2766 * excessively into the page allocator
2768 if (migratetype >= MIGRATE_PCPTYPES) {
2769 if (unlikely(is_migrate_isolate(migratetype))) {
2770 free_one_page(zone, page, pfn, 0, migratetype);
2773 migratetype = MIGRATE_MOVABLE;
2776 pcp = &this_cpu_ptr(zone->pageset)->pcp;
2777 list_add(&page->lru, &pcp->lists[migratetype]);
2779 if (pcp->count >= pcp->high) {
2780 unsigned long batch = READ_ONCE(pcp->batch);
2781 free_pcppages_bulk(zone, batch, pcp);
2786 * Free a 0-order page
2788 void free_unref_page(struct page *page)
2790 unsigned long flags;
2791 unsigned long pfn = page_to_pfn(page);
2793 if (!free_unref_page_prepare(page, pfn))
2796 local_irq_save(flags);
2797 free_unref_page_commit(page, pfn);
2798 local_irq_restore(flags);
2802 * Free a list of 0-order pages
2804 void free_unref_page_list(struct list_head *list)
2806 struct page *page, *next;
2807 unsigned long flags, pfn;
2808 int batch_count = 0;
2810 /* Prepare pages for freeing */
2811 list_for_each_entry_safe(page, next, list, lru) {
2812 pfn = page_to_pfn(page);
2813 if (!free_unref_page_prepare(page, pfn))
2814 list_del(&page->lru);
2815 set_page_private(page, pfn);
2818 local_irq_save(flags);
2819 list_for_each_entry_safe(page, next, list, lru) {
2820 unsigned long pfn = page_private(page);
2822 set_page_private(page, 0);
2823 trace_mm_page_free_batched(page);
2824 free_unref_page_commit(page, pfn);
2827 * Guard against excessive IRQ disabled times when we get
2828 * a large list of pages to free.
2830 if (++batch_count == SWAP_CLUSTER_MAX) {
2831 local_irq_restore(flags);
2833 local_irq_save(flags);
2836 local_irq_restore(flags);
2840 * split_page takes a non-compound higher-order page, and splits it into
2841 * n (1<<order) sub-pages: page[0..n]
2842 * Each sub-page must be freed individually.
2844 * Note: this is probably too low level an operation for use in drivers.
2845 * Please consult with lkml before using this in your driver.
2847 void split_page(struct page *page, unsigned int order)
2851 VM_BUG_ON_PAGE(PageCompound(page), page);
2852 VM_BUG_ON_PAGE(!page_count(page), page);
2854 for (i = 1; i < (1 << order); i++)
2855 set_page_refcounted(page + i);
2856 split_page_owner(page, order);
2858 EXPORT_SYMBOL_GPL(split_page);
2860 int __isolate_free_page(struct page *page, unsigned int order)
2862 unsigned long watermark;
2866 BUG_ON(!PageBuddy(page));
2868 zone = page_zone(page);
2869 mt = get_pageblock_migratetype(page);
2871 if (!is_migrate_isolate(mt)) {
2873 * Obey watermarks as if the page was being allocated. We can
2874 * emulate a high-order watermark check with a raised order-0
2875 * watermark, because we already know our high-order page
2878 watermark = min_wmark_pages(zone) + (1UL << order);
2879 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
2882 __mod_zone_freepage_state(zone, -(1UL << order), mt);
2885 /* Remove page from free list */
2886 list_del(&page->lru);
2887 zone->free_area[order].nr_free--;
2888 rmv_page_order(page);
2891 * Set the pageblock if the isolated page is at least half of a
2894 if (order >= pageblock_order - 1) {
2895 struct page *endpage = page + (1 << order) - 1;
2896 for (; page < endpage; page += pageblock_nr_pages) {
2897 int mt = get_pageblock_migratetype(page);
2898 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
2899 && !is_migrate_highatomic(mt))
2900 set_pageblock_migratetype(page,
2906 return 1UL << order;
2910 * Update NUMA hit/miss statistics
2912 * Must be called with interrupts disabled.
2914 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z)
2917 enum numa_stat_item local_stat = NUMA_LOCAL;
2919 /* skip numa counters update if numa stats is disabled */
2920 if (!static_branch_likely(&vm_numa_stat_key))
2923 if (zone_to_nid(z) != numa_node_id())
2924 local_stat = NUMA_OTHER;
2926 if (zone_to_nid(z) == zone_to_nid(preferred_zone))
2927 __inc_numa_state(z, NUMA_HIT);
2929 __inc_numa_state(z, NUMA_MISS);
2930 __inc_numa_state(preferred_zone, NUMA_FOREIGN);
2932 __inc_numa_state(z, local_stat);
2936 /* Remove page from the per-cpu list, caller must protect the list */
2937 static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
2938 struct per_cpu_pages *pcp,
2939 struct list_head *list)
2944 if (list_empty(list)) {
2945 pcp->count += rmqueue_bulk(zone, 0,
2948 if (unlikely(list_empty(list)))
2952 page = list_first_entry(list, struct page, lru);
2953 list_del(&page->lru);
2955 } while (check_new_pcp(page));
2960 /* Lock and remove page from the per-cpu list */
2961 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
2962 struct zone *zone, unsigned int order,
2963 gfp_t gfp_flags, int migratetype)
2965 struct per_cpu_pages *pcp;
2966 struct list_head *list;
2968 unsigned long flags;
2970 local_irq_save(flags);
2971 pcp = &this_cpu_ptr(zone->pageset)->pcp;
2972 list = &pcp->lists[migratetype];
2973 page = __rmqueue_pcplist(zone, migratetype, pcp, list);
2975 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
2976 zone_statistics(preferred_zone, zone);
2978 local_irq_restore(flags);
2983 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
2986 struct page *rmqueue(struct zone *preferred_zone,
2987 struct zone *zone, unsigned int order,
2988 gfp_t gfp_flags, unsigned int alloc_flags,
2991 unsigned long flags;
2994 if (likely(order == 0)) {
2995 page = rmqueue_pcplist(preferred_zone, zone, order,
2996 gfp_flags, migratetype);
3001 * We most definitely don't want callers attempting to
3002 * allocate greater than order-1 page units with __GFP_NOFAIL.
3004 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
3005 spin_lock_irqsave(&zone->lock, flags);
3009 if (alloc_flags & ALLOC_HARDER) {
3010 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3012 trace_mm_page_alloc_zone_locked(page, order, migratetype);
3015 page = __rmqueue(zone, order, migratetype);
3016 } while (page && check_new_pages(page, order));
3017 spin_unlock(&zone->lock);
3020 __mod_zone_freepage_state(zone, -(1 << order),
3021 get_pcppage_migratetype(page));
3023 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3024 zone_statistics(preferred_zone, zone);
3025 local_irq_restore(flags);
3028 VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3032 local_irq_restore(flags);
3036 #ifdef CONFIG_FAIL_PAGE_ALLOC
3039 struct fault_attr attr;
3041 bool ignore_gfp_highmem;
3042 bool ignore_gfp_reclaim;
3044 } fail_page_alloc = {
3045 .attr = FAULT_ATTR_INITIALIZER,
3046 .ignore_gfp_reclaim = true,
3047 .ignore_gfp_highmem = true,
3051 static int __init setup_fail_page_alloc(char *str)
3053 return setup_fault_attr(&fail_page_alloc.attr, str);
3055 __setup("fail_page_alloc=", setup_fail_page_alloc);
3057 static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3059 if (order < fail_page_alloc.min_order)
3061 if (gfp_mask & __GFP_NOFAIL)
3063 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3065 if (fail_page_alloc.ignore_gfp_reclaim &&
3066 (gfp_mask & __GFP_DIRECT_RECLAIM))
3069 return should_fail(&fail_page_alloc.attr, 1 << order);
3072 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3074 static int __init fail_page_alloc_debugfs(void)
3076 umode_t mode = S_IFREG | 0600;
3079 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3080 &fail_page_alloc.attr);
3082 return PTR_ERR(dir);
3084 if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
3085 &fail_page_alloc.ignore_gfp_reclaim))
3087 if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3088 &fail_page_alloc.ignore_gfp_highmem))
3090 if (!debugfs_create_u32("min-order", mode, dir,
3091 &fail_page_alloc.min_order))
3096 debugfs_remove_recursive(dir);
3101 late_initcall(fail_page_alloc_debugfs);
3103 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3105 #else /* CONFIG_FAIL_PAGE_ALLOC */
3107 static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3112 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3115 * Return true if free base pages are above 'mark'. For high-order checks it
3116 * will return true of the order-0 watermark is reached and there is at least
3117 * one free page of a suitable size. Checking now avoids taking the zone lock
3118 * to check in the allocation paths if no pages are free.
3120 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3121 int classzone_idx, unsigned int alloc_flags,
3126 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3128 /* free_pages may go negative - that's OK */
3129 free_pages -= (1 << order) - 1;
3131 if (alloc_flags & ALLOC_HIGH)
3135 * If the caller does not have rights to ALLOC_HARDER then subtract
3136 * the high-atomic reserves. This will over-estimate the size of the
3137 * atomic reserve but it avoids a search.
3139 if (likely(!alloc_harder)) {
3140 free_pages -= z->nr_reserved_highatomic;
3143 * OOM victims can try even harder than normal ALLOC_HARDER
3144 * users on the grounds that it's definitely going to be in
3145 * the exit path shortly and free memory. Any allocation it
3146 * makes during the free path will be small and short-lived.
3148 if (alloc_flags & ALLOC_OOM)
3156 /* If allocation can't use CMA areas don't use free CMA pages */
3157 if (!(alloc_flags & ALLOC_CMA))
3158 free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
3162 * Check watermarks for an order-0 allocation request. If these
3163 * are not met, then a high-order request also cannot go ahead
3164 * even if a suitable page happened to be free.
3166 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
3169 /* If this is an order-0 request then the watermark is fine */
3173 /* For a high-order request, check at least one suitable page is free */
3174 for (o = order; o < MAX_ORDER; o++) {
3175 struct free_area *area = &z->free_area[o];
3181 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3182 if (!list_empty(&area->free_list[mt]))
3187 if ((alloc_flags & ALLOC_CMA) &&
3188 !list_empty(&area->free_list[MIGRATE_CMA])) {
3193 !list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
3199 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3200 int classzone_idx, unsigned int alloc_flags)
3202 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3203 zone_page_state(z, NR_FREE_PAGES));
3206 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3207 unsigned long mark, int classzone_idx, unsigned int alloc_flags)
3209 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3213 /* If allocation can't use CMA areas don't use free CMA pages */
3214 if (!(alloc_flags & ALLOC_CMA))
3215 cma_pages = zone_page_state(z, NR_FREE_CMA_PAGES);
3219 * Fast check for order-0 only. If this fails then the reserves
3220 * need to be calculated. There is a corner case where the check
3221 * passes but only the high-order atomic reserve are free. If
3222 * the caller is !atomic then it'll uselessly search the free
3223 * list. That corner case is then slower but it is harmless.
3225 if (!order && (free_pages - cma_pages) > mark + z->lowmem_reserve[classzone_idx])
3228 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3232 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3233 unsigned long mark, int classzone_idx)
3235 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3237 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3238 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3240 return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
3245 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3247 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3250 #else /* CONFIG_NUMA */
3251 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3255 #endif /* CONFIG_NUMA */
3258 * get_page_from_freelist goes through the zonelist trying to allocate
3261 static struct page *
3262 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3263 const struct alloc_context *ac)
3265 struct zoneref *z = ac->preferred_zoneref;
3267 struct pglist_data *last_pgdat_dirty_limit = NULL;
3270 * Scan zonelist, looking for a zone with enough free.
3271 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3273 for_next_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
3278 if (cpusets_enabled() &&
3279 (alloc_flags & ALLOC_CPUSET) &&
3280 !__cpuset_zone_allowed(zone, gfp_mask))
3283 * When allocating a page cache page for writing, we
3284 * want to get it from a node that is within its dirty
3285 * limit, such that no single node holds more than its
3286 * proportional share of globally allowed dirty pages.
3287 * The dirty limits take into account the node's
3288 * lowmem reserves and high watermark so that kswapd
3289 * should be able to balance it without having to
3290 * write pages from its LRU list.
3292 * XXX: For now, allow allocations to potentially
3293 * exceed the per-node dirty limit in the slowpath
3294 * (spread_dirty_pages unset) before going into reclaim,
3295 * which is important when on a NUMA setup the allowed
3296 * nodes are together not big enough to reach the
3297 * global limit. The proper fix for these situations
3298 * will require awareness of nodes in the
3299 * dirty-throttling and the flusher threads.
3301 if (ac->spread_dirty_pages) {
3302 if (last_pgdat_dirty_limit == zone->zone_pgdat)
3305 if (!node_dirty_ok(zone->zone_pgdat)) {
3306 last_pgdat_dirty_limit = zone->zone_pgdat;
3311 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
3312 if (!zone_watermark_fast(zone, order, mark,
3313 ac_classzone_idx(ac), alloc_flags)) {
3316 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3318 * Watermark failed for this zone, but see if we can
3319 * grow this zone if it contains deferred pages.
3321 if (static_branch_unlikely(&deferred_pages)) {
3322 if (_deferred_grow_zone(zone, order))
3326 /* Checked here to keep the fast path fast */
3327 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3328 if (alloc_flags & ALLOC_NO_WATERMARKS)
3331 if (node_reclaim_mode == 0 ||
3332 !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
3335 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3337 case NODE_RECLAIM_NOSCAN:
3340 case NODE_RECLAIM_FULL:
3341 /* scanned but unreclaimable */
3344 /* did we reclaim enough */
3345 if (zone_watermark_ok(zone, order, mark,
3346 ac_classzone_idx(ac), alloc_flags))
3354 page = rmqueue(ac->preferred_zoneref->zone, zone, order,
3355 gfp_mask, alloc_flags, ac->migratetype);
3357 prep_new_page(page, order, gfp_mask, alloc_flags);
3360 * If this is a high-order atomic allocation then check
3361 * if the pageblock should be reserved for the future
3363 if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
3364 reserve_highatomic_pageblock(page, zone, order);
3368 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3369 /* Try again if zone has deferred pages */
3370 if (static_branch_unlikely(&deferred_pages)) {
3371 if (_deferred_grow_zone(zone, order))
3381 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
3383 unsigned int filter = SHOW_MEM_FILTER_NODES;
3384 static DEFINE_RATELIMIT_STATE(show_mem_rs, HZ, 1);
3386 if (!__ratelimit(&show_mem_rs))
3390 * This documents exceptions given to allocations in certain
3391 * contexts that are allowed to allocate outside current's set
3394 if (!(gfp_mask & __GFP_NOMEMALLOC))
3395 if (tsk_is_oom_victim(current) ||
3396 (current->flags & (PF_MEMALLOC | PF_EXITING)))
3397 filter &= ~SHOW_MEM_FILTER_NODES;
3398 if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
3399 filter &= ~SHOW_MEM_FILTER_NODES;
3401 show_mem(filter, nodemask);
3404 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
3406 struct va_format vaf;
3408 static DEFINE_RATELIMIT_STATE(nopage_rs, DEFAULT_RATELIMIT_INTERVAL,
3409 DEFAULT_RATELIMIT_BURST);
3411 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs))
3414 va_start(args, fmt);
3417 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl\n",
3418 current->comm, &vaf, gfp_mask, &gfp_mask,
3419 nodemask_pr_args(nodemask));
3422 cpuset_print_current_mems_allowed();
3425 warn_alloc_show_mem(gfp_mask, nodemask);
3428 static inline struct page *
3429 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
3430 unsigned int alloc_flags,
3431 const struct alloc_context *ac)
3435 page = get_page_from_freelist(gfp_mask, order,
3436 alloc_flags|ALLOC_CPUSET, ac);
3438 * fallback to ignore cpuset restriction if our nodes
3442 page = get_page_from_freelist(gfp_mask, order,
3448 static inline struct page *
3449 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
3450 const struct alloc_context *ac, unsigned long *did_some_progress)
3452 struct oom_control oc = {
3453 .zonelist = ac->zonelist,
3454 .nodemask = ac->nodemask,
3456 .gfp_mask = gfp_mask,
3461 *did_some_progress = 0;
3464 * Acquire the oom lock. If that fails, somebody else is
3465 * making progress for us.
3467 if (!mutex_trylock(&oom_lock)) {
3468 *did_some_progress = 1;
3469 schedule_timeout_uninterruptible(1);
3474 * Go through the zonelist yet one more time, keep very high watermark
3475 * here, this is only to catch a parallel oom killing, we must fail if
3476 * we're still under heavy pressure. But make sure that this reclaim
3477 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
3478 * allocation which will never fail due to oom_lock already held.
3480 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
3481 ~__GFP_DIRECT_RECLAIM, order,
3482 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
3486 /* Coredumps can quickly deplete all memory reserves */
3487 if (current->flags & PF_DUMPCORE)
3489 /* The OOM killer will not help higher order allocs */
3490 if (order > PAGE_ALLOC_COSTLY_ORDER)
3493 * We have already exhausted all our reclaim opportunities without any
3494 * success so it is time to admit defeat. We will skip the OOM killer
3495 * because it is very likely that the caller has a more reasonable
3496 * fallback than shooting a random task.
3498 if (gfp_mask & __GFP_RETRY_MAYFAIL)
3500 /* The OOM killer does not needlessly kill tasks for lowmem */
3501 if (ac->high_zoneidx < ZONE_NORMAL)
3503 if (pm_suspended_storage())
3506 * XXX: GFP_NOFS allocations should rather fail than rely on
3507 * other request to make a forward progress.
3508 * We are in an unfortunate situation where out_of_memory cannot
3509 * do much for this context but let's try it to at least get
3510 * access to memory reserved if the current task is killed (see
3511 * out_of_memory). Once filesystems are ready to handle allocation
3512 * failures more gracefully we should just bail out here.
3515 /* The OOM killer may not free memory on a specific node */
3516 if (gfp_mask & __GFP_THISNODE)
3519 /* Exhausted what can be done so it's blame time */
3520 if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
3521 *did_some_progress = 1;
3524 * Help non-failing allocations by giving them access to memory
3527 if (gfp_mask & __GFP_NOFAIL)
3528 page = __alloc_pages_cpuset_fallback(gfp_mask, order,
3529 ALLOC_NO_WATERMARKS, ac);
3532 mutex_unlock(&oom_lock);
3537 * Maximum number of compaction retries wit a progress before OOM
3538 * killer is consider as the only way to move forward.