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/notifier.h>
36 #include <linux/topology.h>
37 #include <linux/sysctl.h>
38 #include <linux/cpu.h>
39 #include <linux/cpuset.h>
40 #include <linux/memory_hotplug.h>
41 #include <linux/nodemask.h>
42 #include <linux/vmalloc.h>
43 #include <linux/vmstat.h>
44 #include <linux/mempolicy.h>
45 #include <linux/memremap.h>
46 #include <linux/stop_machine.h>
47 #include <linux/sort.h>
48 #include <linux/pfn.h>
50 #include <linux/backing-dev.h>
51 #include <linux/fault-inject.h>
52 #include <linux/page-isolation.h>
53 #include <linux/page_ext.h>
54 #include <linux/debugobjects.h>
55 #include <linux/kmemleak.h>
56 #include <linux/compaction.h>
57 #include <trace/events/kmem.h>
58 #include <trace/events/oom.h>
59 #include <linux/prefetch.h>
60 #include <linux/mm_inline.h>
61 #include <linux/migrate.h>
62 #include <linux/hugetlb.h>
63 #include <linux/sched/rt.h>
64 #include <linux/sched/mm.h>
65 #include <linux/page_owner.h>
66 #include <linux/kthread.h>
67 #include <linux/memcontrol.h>
68 #include <linux/ftrace.h>
69 #include <linux/lockdep.h>
70 #include <linux/nmi.h>
72 #include <asm/sections.h>
73 #include <asm/tlbflush.h>
74 #include <asm/div64.h>
77 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
78 static DEFINE_MUTEX(pcp_batch_high_lock);
79 #define MIN_PERCPU_PAGELIST_FRACTION (8)
81 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
82 DEFINE_PER_CPU(int, numa_node);
83 EXPORT_PER_CPU_SYMBOL(numa_node);
86 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
88 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
90 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
91 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
92 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
93 * defined in <linux/topology.h>.
95 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
96 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
97 int _node_numa_mem_[MAX_NUMNODES];
100 /* work_structs for global per-cpu drains */
101 DEFINE_MUTEX(pcpu_drain_mutex);
102 DEFINE_PER_CPU(struct work_struct, pcpu_drain);
104 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
105 volatile unsigned long latent_entropy __latent_entropy;
106 EXPORT_SYMBOL(latent_entropy);
110 * Array of node states.
112 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
113 [N_POSSIBLE] = NODE_MASK_ALL,
114 [N_ONLINE] = { { [0] = 1UL } },
116 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
117 #ifdef CONFIG_HIGHMEM
118 [N_HIGH_MEMORY] = { { [0] = 1UL } },
120 [N_MEMORY] = { { [0] = 1UL } },
121 [N_CPU] = { { [0] = 1UL } },
124 EXPORT_SYMBOL(node_states);
126 /* Protect totalram_pages and zone->managed_pages */
127 static DEFINE_SPINLOCK(managed_page_count_lock);
129 unsigned long totalram_pages __read_mostly;
130 unsigned long totalreserve_pages __read_mostly;
131 unsigned long totalcma_pages __read_mostly;
133 int percpu_pagelist_fraction;
134 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
137 * A cached value of the page's pageblock's migratetype, used when the page is
138 * put on a pcplist. Used to avoid the pageblock migratetype lookup when
139 * freeing from pcplists in most cases, at the cost of possibly becoming stale.
140 * Also the migratetype set in the page does not necessarily match the pcplist
141 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
142 * other index - this ensures that it will be put on the correct CMA freelist.
144 static inline int get_pcppage_migratetype(struct page *page)
149 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
151 page->index = migratetype;
154 #ifdef CONFIG_PM_SLEEP
156 * The following functions are used by the suspend/hibernate code to temporarily
157 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
158 * while devices are suspended. To avoid races with the suspend/hibernate code,
159 * they should always be called with pm_mutex held (gfp_allowed_mask also should
160 * only be modified with pm_mutex held, unless the suspend/hibernate code is
161 * guaranteed not to run in parallel with that modification).
164 static gfp_t saved_gfp_mask;
166 void pm_restore_gfp_mask(void)
168 WARN_ON(!mutex_is_locked(&pm_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(&pm_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-1] = {
209 #ifdef CONFIG_ZONE_DMA
212 #ifdef CONFIG_ZONE_DMA32
215 #ifdef CONFIG_HIGHMEM
221 EXPORT_SYMBOL(totalram_pages);
223 static char * const zone_names[MAX_NR_ZONES] = {
224 #ifdef CONFIG_ZONE_DMA
227 #ifdef CONFIG_ZONE_DMA32
231 #ifdef CONFIG_HIGHMEM
235 #ifdef CONFIG_ZONE_DEVICE
240 char * const migratetype_names[MIGRATE_TYPES] = {
248 #ifdef CONFIG_MEMORY_ISOLATION
253 compound_page_dtor * const compound_page_dtors[] = {
256 #ifdef CONFIG_HUGETLB_PAGE
259 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
264 int min_free_kbytes = 1024;
265 int user_min_free_kbytes = -1;
266 int watermark_scale_factor = 10;
268 static unsigned long __meminitdata nr_kernel_pages;
269 static unsigned long __meminitdata nr_all_pages;
270 static unsigned long __meminitdata dma_reserve;
272 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
273 static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES];
274 static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES];
275 static unsigned long __initdata required_kernelcore;
276 static unsigned long __initdata required_movablecore;
277 static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES];
278 static bool mirrored_kernelcore;
280 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
282 EXPORT_SYMBOL(movable_zone);
283 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
286 int nr_node_ids __read_mostly = MAX_NUMNODES;
287 int nr_online_nodes __read_mostly = 1;
288 EXPORT_SYMBOL(nr_node_ids);
289 EXPORT_SYMBOL(nr_online_nodes);
292 int page_group_by_mobility_disabled __read_mostly;
294 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
295 /* Returns true if the struct page for the pfn is uninitialised */
296 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
298 int nid = early_pfn_to_nid(pfn);
300 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
307 * Returns false when the remaining initialisation should be deferred until
308 * later in the boot cycle when it can be parallelised.
310 static inline bool update_defer_init(pg_data_t *pgdat,
311 unsigned long pfn, unsigned long zone_end,
312 unsigned long *nr_initialised)
314 /* Always populate low zones for address-constrained allocations */
315 if (zone_end < pgdat_end_pfn(pgdat))
317 /* Xen PV domains need page structures early */
321 if ((*nr_initialised > pgdat->static_init_pgcnt) &&
322 (pfn & (PAGES_PER_SECTION - 1)) == 0) {
323 pgdat->first_deferred_pfn = pfn;
330 static inline bool early_page_uninitialised(unsigned long pfn)
335 static inline bool update_defer_init(pg_data_t *pgdat,
336 unsigned long pfn, unsigned long zone_end,
337 unsigned long *nr_initialised)
343 /* Return a pointer to the bitmap storing bits affecting a block of pages */
344 static inline unsigned long *get_pageblock_bitmap(struct page *page,
347 #ifdef CONFIG_SPARSEMEM
348 return __pfn_to_section(pfn)->pageblock_flags;
350 return page_zone(page)->pageblock_flags;
351 #endif /* CONFIG_SPARSEMEM */
354 static inline int pfn_to_bitidx(struct page *page, unsigned long pfn)
356 #ifdef CONFIG_SPARSEMEM
357 pfn &= (PAGES_PER_SECTION-1);
358 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
360 pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
361 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
362 #endif /* CONFIG_SPARSEMEM */
366 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
367 * @page: The page within the block of interest
368 * @pfn: The target page frame number
369 * @end_bitidx: The last bit of interest to retrieve
370 * @mask: mask of bits that the caller is interested in
372 * Return: pageblock_bits flags
374 static __always_inline unsigned long __get_pfnblock_flags_mask(struct page *page,
376 unsigned long end_bitidx,
379 unsigned long *bitmap;
380 unsigned long bitidx, word_bitidx;
383 bitmap = get_pageblock_bitmap(page, pfn);
384 bitidx = pfn_to_bitidx(page, pfn);
385 word_bitidx = bitidx / BITS_PER_LONG;
386 bitidx &= (BITS_PER_LONG-1);
388 word = bitmap[word_bitidx];
389 bitidx += end_bitidx;
390 return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
393 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
394 unsigned long end_bitidx,
397 return __get_pfnblock_flags_mask(page, pfn, end_bitidx, mask);
400 static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn)
402 return __get_pfnblock_flags_mask(page, pfn, PB_migrate_end, MIGRATETYPE_MASK);
406 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
407 * @page: The page within the block of interest
408 * @flags: The flags to set
409 * @pfn: The target page frame number
410 * @end_bitidx: The last bit of interest
411 * @mask: mask of bits that the caller is interested in
413 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
415 unsigned long end_bitidx,
418 unsigned long *bitmap;
419 unsigned long bitidx, word_bitidx;
420 unsigned long old_word, word;
422 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
424 bitmap = get_pageblock_bitmap(page, pfn);
425 bitidx = pfn_to_bitidx(page, pfn);
426 word_bitidx = bitidx / BITS_PER_LONG;
427 bitidx &= (BITS_PER_LONG-1);
429 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
431 bitidx += end_bitidx;
432 mask <<= (BITS_PER_LONG - bitidx - 1);
433 flags <<= (BITS_PER_LONG - bitidx - 1);
435 word = READ_ONCE(bitmap[word_bitidx]);
437 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
438 if (word == old_word)
444 void set_pageblock_migratetype(struct page *page, int migratetype)
446 if (unlikely(page_group_by_mobility_disabled &&
447 migratetype < MIGRATE_PCPTYPES))
448 migratetype = MIGRATE_UNMOVABLE;
450 set_pageblock_flags_group(page, (unsigned long)migratetype,
451 PB_migrate, PB_migrate_end);
454 #ifdef CONFIG_DEBUG_VM
455 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
459 unsigned long pfn = page_to_pfn(page);
460 unsigned long sp, start_pfn;
463 seq = zone_span_seqbegin(zone);
464 start_pfn = zone->zone_start_pfn;
465 sp = zone->spanned_pages;
466 if (!zone_spans_pfn(zone, pfn))
468 } while (zone_span_seqretry(zone, seq));
471 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
472 pfn, zone_to_nid(zone), zone->name,
473 start_pfn, start_pfn + sp);
478 static int page_is_consistent(struct zone *zone, struct page *page)
480 if (!pfn_valid_within(page_to_pfn(page)))
482 if (zone != page_zone(page))
488 * Temporary debugging check for pages not lying within a given zone.
490 static int __maybe_unused bad_range(struct zone *zone, struct page *page)
492 if (page_outside_zone_boundaries(zone, page))
494 if (!page_is_consistent(zone, page))
500 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
506 static void bad_page(struct page *page, const char *reason,
507 unsigned long bad_flags)
509 static unsigned long resume;
510 static unsigned long nr_shown;
511 static unsigned long nr_unshown;
514 * Allow a burst of 60 reports, then keep quiet for that minute;
515 * or allow a steady drip of one report per second.
517 if (nr_shown == 60) {
518 if (time_before(jiffies, resume)) {
524 "BUG: Bad page state: %lu messages suppressed\n",
531 resume = jiffies + 60 * HZ;
533 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
534 current->comm, page_to_pfn(page));
535 __dump_page(page, reason);
536 bad_flags &= page->flags;
538 pr_alert("bad because of flags: %#lx(%pGp)\n",
539 bad_flags, &bad_flags);
540 dump_page_owner(page);
545 /* Leave bad fields for debug, except PageBuddy could make trouble */
546 page_mapcount_reset(page); /* remove PageBuddy */
547 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
551 * Higher-order pages are called "compound pages". They are structured thusly:
553 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
555 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
556 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
558 * The first tail page's ->compound_dtor holds the offset in array of compound
559 * page destructors. See compound_page_dtors.
561 * The first tail page's ->compound_order holds the order of allocation.
562 * This usage means that zero-order pages may not be compound.
565 void free_compound_page(struct page *page)
567 __free_pages_ok(page, compound_order(page));
570 void prep_compound_page(struct page *page, unsigned int order)
573 int nr_pages = 1 << order;
575 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
576 set_compound_order(page, order);
578 for (i = 1; i < nr_pages; i++) {
579 struct page *p = page + i;
580 set_page_count(p, 0);
581 p->mapping = TAIL_MAPPING;
582 set_compound_head(p, page);
584 atomic_set(compound_mapcount_ptr(page), -1);
587 #ifdef CONFIG_DEBUG_PAGEALLOC
588 unsigned int _debug_guardpage_minorder;
589 bool _debug_pagealloc_enabled __read_mostly
590 = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
591 EXPORT_SYMBOL(_debug_pagealloc_enabled);
592 bool _debug_guardpage_enabled __read_mostly;
594 static int __init early_debug_pagealloc(char *buf)
598 return kstrtobool(buf, &_debug_pagealloc_enabled);
600 early_param("debug_pagealloc", early_debug_pagealloc);
602 static bool need_debug_guardpage(void)
604 /* If we don't use debug_pagealloc, we don't need guard page */
605 if (!debug_pagealloc_enabled())
608 if (!debug_guardpage_minorder())
614 static void init_debug_guardpage(void)
616 if (!debug_pagealloc_enabled())
619 if (!debug_guardpage_minorder())
622 _debug_guardpage_enabled = true;
625 struct page_ext_operations debug_guardpage_ops = {
626 .need = need_debug_guardpage,
627 .init = init_debug_guardpage,
630 static int __init debug_guardpage_minorder_setup(char *buf)
634 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
635 pr_err("Bad debug_guardpage_minorder value\n");
638 _debug_guardpage_minorder = res;
639 pr_info("Setting debug_guardpage_minorder to %lu\n", res);
642 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
644 static inline bool set_page_guard(struct zone *zone, struct page *page,
645 unsigned int order, int migratetype)
647 struct page_ext *page_ext;
649 if (!debug_guardpage_enabled())
652 if (order >= debug_guardpage_minorder())
655 page_ext = lookup_page_ext(page);
656 if (unlikely(!page_ext))
659 __set_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
661 INIT_LIST_HEAD(&page->lru);
662 set_page_private(page, order);
663 /* Guard pages are not available for any usage */
664 __mod_zone_freepage_state(zone, -(1 << order), migratetype);
669 static inline void clear_page_guard(struct zone *zone, struct page *page,
670 unsigned int order, int migratetype)
672 struct page_ext *page_ext;
674 if (!debug_guardpage_enabled())
677 page_ext = lookup_page_ext(page);
678 if (unlikely(!page_ext))
681 __clear_bit(PAGE_EXT_DEBUG_GUARD, &page_ext->flags);
683 set_page_private(page, 0);
684 if (!is_migrate_isolate(migratetype))
685 __mod_zone_freepage_state(zone, (1 << order), migratetype);
688 struct page_ext_operations debug_guardpage_ops;
689 static inline bool set_page_guard(struct zone *zone, struct page *page,
690 unsigned int order, int migratetype) { return false; }
691 static inline void clear_page_guard(struct zone *zone, struct page *page,
692 unsigned int order, int migratetype) {}
695 static inline void set_page_order(struct page *page, unsigned int order)
697 set_page_private(page, order);
698 __SetPageBuddy(page);
701 static inline void rmv_page_order(struct page *page)
703 __ClearPageBuddy(page);
704 set_page_private(page, 0);
708 * This function checks whether a page is free && is the buddy
709 * we can do coalesce a page and its buddy if
710 * (a) the buddy is not in a hole (check before calling!) &&
711 * (b) the buddy is in the buddy system &&
712 * (c) a page and its buddy have the same order &&
713 * (d) a page and its buddy are in the same zone.
715 * For recording whether a page is in the buddy system, we set ->_mapcount
716 * PAGE_BUDDY_MAPCOUNT_VALUE.
717 * Setting, clearing, and testing _mapcount PAGE_BUDDY_MAPCOUNT_VALUE is
718 * serialized by zone->lock.
720 * For recording page's order, we use page_private(page).
722 static inline int page_is_buddy(struct page *page, struct page *buddy,
725 if (page_is_guard(buddy) && page_order(buddy) == order) {
726 if (page_zone_id(page) != page_zone_id(buddy))
729 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
734 if (PageBuddy(buddy) && page_order(buddy) == order) {
736 * zone check is done late to avoid uselessly
737 * calculating zone/node ids for pages that could
740 if (page_zone_id(page) != page_zone_id(buddy))
743 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
751 * Freeing function for a buddy system allocator.
753 * The concept of a buddy system is to maintain direct-mapped table
754 * (containing bit values) for memory blocks of various "orders".
755 * The bottom level table contains the map for the smallest allocatable
756 * units of memory (here, pages), and each level above it describes
757 * pairs of units from the levels below, hence, "buddies".
758 * At a high level, all that happens here is marking the table entry
759 * at the bottom level available, and propagating the changes upward
760 * as necessary, plus some accounting needed to play nicely with other
761 * parts of the VM system.
762 * At each level, we keep a list of pages, which are heads of continuous
763 * free pages of length of (1 << order) and marked with _mapcount
764 * PAGE_BUDDY_MAPCOUNT_VALUE. Page's order is recorded in page_private(page)
766 * So when we are allocating or freeing one, we can derive the state of the
767 * other. That is, if we allocate a small block, and both were
768 * free, the remainder of the region must be split into blocks.
769 * If a block is freed, and its buddy is also free, then this
770 * triggers coalescing into a block of larger size.
775 static inline void __free_one_page(struct page *page,
777 struct zone *zone, unsigned int order,
780 unsigned long combined_pfn;
781 unsigned long uninitialized_var(buddy_pfn);
783 unsigned int max_order;
785 max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
787 VM_BUG_ON(!zone_is_initialized(zone));
788 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
790 VM_BUG_ON(migratetype == -1);
791 if (likely(!is_migrate_isolate(migratetype)))
792 __mod_zone_freepage_state(zone, 1 << order, migratetype);
794 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
795 VM_BUG_ON_PAGE(bad_range(zone, page), page);
798 while (order < max_order - 1) {
799 buddy_pfn = __find_buddy_pfn(pfn, order);
800 buddy = page + (buddy_pfn - pfn);
802 if (!pfn_valid_within(buddy_pfn))
804 if (!page_is_buddy(page, buddy, order))
807 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
808 * merge with it and move up one order.
810 if (page_is_guard(buddy)) {
811 clear_page_guard(zone, buddy, order, migratetype);
813 list_del(&buddy->lru);
814 zone->free_area[order].nr_free--;
815 rmv_page_order(buddy);
817 combined_pfn = buddy_pfn & pfn;
818 page = page + (combined_pfn - pfn);
822 if (max_order < MAX_ORDER) {
823 /* If we are here, it means order is >= pageblock_order.
824 * We want to prevent merge between freepages on isolate
825 * pageblock and normal pageblock. Without this, pageblock
826 * isolation could cause incorrect freepage or CMA accounting.
828 * We don't want to hit this code for the more frequent
831 if (unlikely(has_isolate_pageblock(zone))) {
834 buddy_pfn = __find_buddy_pfn(pfn, order);
835 buddy = page + (buddy_pfn - pfn);
836 buddy_mt = get_pageblock_migratetype(buddy);
838 if (migratetype != buddy_mt
839 && (is_migrate_isolate(migratetype) ||
840 is_migrate_isolate(buddy_mt)))
844 goto continue_merging;
848 set_page_order(page, order);
851 * If this is not the largest possible page, check if the buddy
852 * of the next-highest order is free. If it is, it's possible
853 * that pages are being freed that will coalesce soon. In case,
854 * that is happening, add the free page to the tail of the list
855 * so it's less likely to be used soon and more likely to be merged
856 * as a higher order page
858 if ((order < MAX_ORDER-2) && pfn_valid_within(buddy_pfn)) {
859 struct page *higher_page, *higher_buddy;
860 combined_pfn = buddy_pfn & pfn;
861 higher_page = page + (combined_pfn - pfn);
862 buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
863 higher_buddy = higher_page + (buddy_pfn - combined_pfn);
864 if (pfn_valid_within(buddy_pfn) &&
865 page_is_buddy(higher_page, higher_buddy, order + 1)) {
866 list_add_tail(&page->lru,
867 &zone->free_area[order].free_list[migratetype]);
872 list_add(&page->lru, &zone->free_area[order].free_list[migratetype]);
874 zone->free_area[order].nr_free++;
878 * A bad page could be due to a number of fields. Instead of multiple branches,
879 * try and check multiple fields with one check. The caller must do a detailed
880 * check if necessary.
882 static inline bool page_expected_state(struct page *page,
883 unsigned long check_flags)
885 if (unlikely(atomic_read(&page->_mapcount) != -1))
888 if (unlikely((unsigned long)page->mapping |
889 page_ref_count(page) |
891 (unsigned long)page->mem_cgroup |
893 (page->flags & check_flags)))
899 static void free_pages_check_bad(struct page *page)
901 const char *bad_reason;
902 unsigned long bad_flags;
907 if (unlikely(atomic_read(&page->_mapcount) != -1))
908 bad_reason = "nonzero mapcount";
909 if (unlikely(page->mapping != NULL))
910 bad_reason = "non-NULL mapping";
911 if (unlikely(page_ref_count(page) != 0))
912 bad_reason = "nonzero _refcount";
913 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
914 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
915 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
918 if (unlikely(page->mem_cgroup))
919 bad_reason = "page still charged to cgroup";
921 bad_page(page, bad_reason, bad_flags);
924 static inline int free_pages_check(struct page *page)
926 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
929 /* Something has gone sideways, find it */
930 free_pages_check_bad(page);
934 static int free_tail_pages_check(struct page *head_page, struct page *page)
939 * We rely page->lru.next never has bit 0 set, unless the page
940 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
942 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
944 if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
948 switch (page - head_page) {
950 /* the first tail page: ->mapping is compound_mapcount() */
951 if (unlikely(compound_mapcount(page))) {
952 bad_page(page, "nonzero compound_mapcount", 0);
958 * the second tail page: ->mapping is
959 * page_deferred_list().next -- ignore value.
963 if (page->mapping != TAIL_MAPPING) {
964 bad_page(page, "corrupted mapping in tail page", 0);
969 if (unlikely(!PageTail(page))) {
970 bad_page(page, "PageTail not set", 0);
973 if (unlikely(compound_head(page) != head_page)) {
974 bad_page(page, "compound_head not consistent", 0);
979 page->mapping = NULL;
980 clear_compound_head(page);
984 static __always_inline bool free_pages_prepare(struct page *page,
985 unsigned int order, bool check_free)
989 VM_BUG_ON_PAGE(PageTail(page), page);
991 trace_mm_page_free(page, order);
994 * Check tail pages before head page information is cleared to
995 * avoid checking PageCompound for order-0 pages.
997 if (unlikely(order)) {
998 bool compound = PageCompound(page);
1001 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1004 ClearPageDoubleMap(page);
1005 for (i = 1; i < (1 << order); i++) {
1007 bad += free_tail_pages_check(page, page + i);
1008 if (unlikely(free_pages_check(page + i))) {
1012 (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1015 if (PageMappingFlags(page))
1016 page->mapping = NULL;
1017 if (memcg_kmem_enabled() && PageKmemcg(page))
1018 memcg_kmem_uncharge(page, order);
1020 bad += free_pages_check(page);
1024 page_cpupid_reset_last(page);
1025 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1026 reset_page_owner(page, order);
1028 if (!PageHighMem(page)) {
1029 debug_check_no_locks_freed(page_address(page),
1030 PAGE_SIZE << order);
1031 debug_check_no_obj_freed(page_address(page),
1032 PAGE_SIZE << order);
1034 arch_free_page(page, order);
1035 kernel_poison_pages(page, 1 << order, 0);
1036 kernel_map_pages(page, 1 << order, 0);
1037 kasan_free_pages(page, order);
1042 #ifdef CONFIG_DEBUG_VM
1043 static inline bool free_pcp_prepare(struct page *page)
1045 return free_pages_prepare(page, 0, true);
1048 static inline bool bulkfree_pcp_prepare(struct page *page)
1053 static bool free_pcp_prepare(struct page *page)
1055 return free_pages_prepare(page, 0, false);
1058 static bool bulkfree_pcp_prepare(struct page *page)
1060 return free_pages_check(page);
1062 #endif /* CONFIG_DEBUG_VM */
1065 * Frees a number of pages from the PCP lists
1066 * Assumes all pages on list are in same zone, and of same order.
1067 * count is the number of pages to free.
1069 * If the zone was previously in an "all pages pinned" state then look to
1070 * see if this freeing clears that state.
1072 * And clear the zone's pages_scanned counter, to hold off the "all pages are
1073 * pinned" detection logic.
1075 static void free_pcppages_bulk(struct zone *zone, int count,
1076 struct per_cpu_pages *pcp)
1078 int migratetype = 0;
1080 bool isolated_pageblocks;
1082 spin_lock(&zone->lock);
1083 isolated_pageblocks = has_isolate_pageblock(zone);
1087 struct list_head *list;
1090 * Remove pages from lists in a round-robin fashion. A
1091 * batch_free count is maintained that is incremented when an
1092 * empty list is encountered. This is so more pages are freed
1093 * off fuller lists instead of spinning excessively around empty
1098 if (++migratetype == MIGRATE_PCPTYPES)
1100 list = &pcp->lists[migratetype];
1101 } while (list_empty(list));
1103 /* This is the only non-empty list. Free them all. */
1104 if (batch_free == MIGRATE_PCPTYPES)
1108 int mt; /* migratetype of the to-be-freed page */
1110 page = list_last_entry(list, struct page, lru);
1111 /* must delete as __free_one_page list manipulates */
1112 list_del(&page->lru);
1114 mt = get_pcppage_migratetype(page);
1115 /* MIGRATE_ISOLATE page should not go to pcplists */
1116 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1117 /* Pageblock could have been isolated meanwhile */
1118 if (unlikely(isolated_pageblocks))
1119 mt = get_pageblock_migratetype(page);
1121 if (bulkfree_pcp_prepare(page))
1124 __free_one_page(page, page_to_pfn(page), zone, 0, mt);
1125 trace_mm_page_pcpu_drain(page, 0, mt);
1126 } while (--count && --batch_free && !list_empty(list));
1128 spin_unlock(&zone->lock);
1131 static void free_one_page(struct zone *zone,
1132 struct page *page, unsigned long pfn,
1136 spin_lock(&zone->lock);
1137 if (unlikely(has_isolate_pageblock(zone) ||
1138 is_migrate_isolate(migratetype))) {
1139 migratetype = get_pfnblock_migratetype(page, pfn);
1141 __free_one_page(page, pfn, zone, order, migratetype);
1142 spin_unlock(&zone->lock);
1145 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
1146 unsigned long zone, int nid)
1148 mm_zero_struct_page(page);
1149 set_page_links(page, zone, nid, pfn);
1150 init_page_count(page);
1151 page_mapcount_reset(page);
1152 page_cpupid_reset_last(page);
1154 INIT_LIST_HEAD(&page->lru);
1155 #ifdef WANT_PAGE_VIRTUAL
1156 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1157 if (!is_highmem_idx(zone))
1158 set_page_address(page, __va(pfn << PAGE_SHIFT));
1162 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1163 static void __meminit init_reserved_page(unsigned long pfn)
1168 if (!early_page_uninitialised(pfn))
1171 nid = early_pfn_to_nid(pfn);
1172 pgdat = NODE_DATA(nid);
1174 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1175 struct zone *zone = &pgdat->node_zones[zid];
1177 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
1180 __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
1183 static inline void init_reserved_page(unsigned long pfn)
1186 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1189 * Initialised pages do not have PageReserved set. This function is
1190 * called for each range allocated by the bootmem allocator and
1191 * marks the pages PageReserved. The remaining valid pages are later
1192 * sent to the buddy page allocator.
1194 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1196 unsigned long start_pfn = PFN_DOWN(start);
1197 unsigned long end_pfn = PFN_UP(end);
1199 for (; start_pfn < end_pfn; start_pfn++) {
1200 if (pfn_valid(start_pfn)) {
1201 struct page *page = pfn_to_page(start_pfn);
1203 init_reserved_page(start_pfn);
1205 /* Avoid false-positive PageTail() */
1206 INIT_LIST_HEAD(&page->lru);
1208 SetPageReserved(page);
1213 static void __free_pages_ok(struct page *page, unsigned int order)
1215 unsigned long flags;
1217 unsigned long pfn = page_to_pfn(page);
1219 if (!free_pages_prepare(page, order, true))
1222 migratetype = get_pfnblock_migratetype(page, pfn);
1223 local_irq_save(flags);
1224 __count_vm_events(PGFREE, 1 << order);
1225 free_one_page(page_zone(page), page, pfn, order, migratetype);
1226 local_irq_restore(flags);
1229 static void __init __free_pages_boot_core(struct page *page, unsigned int order)
1231 unsigned int nr_pages = 1 << order;
1232 struct page *p = page;
1236 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1238 __ClearPageReserved(p);
1239 set_page_count(p, 0);
1241 __ClearPageReserved(p);
1242 set_page_count(p, 0);
1244 page_zone(page)->managed_pages += nr_pages;
1245 set_page_refcounted(page);
1246 __free_pages(page, order);
1249 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1250 defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1252 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1254 int __meminit early_pfn_to_nid(unsigned long pfn)
1256 static DEFINE_SPINLOCK(early_pfn_lock);
1259 spin_lock(&early_pfn_lock);
1260 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1262 nid = first_online_node;
1263 spin_unlock(&early_pfn_lock);
1269 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1270 static inline bool __meminit __maybe_unused
1271 meminit_pfn_in_nid(unsigned long pfn, int node,
1272 struct mminit_pfnnid_cache *state)
1276 nid = __early_pfn_to_nid(pfn, state);
1277 if (nid >= 0 && nid != node)
1282 /* Only safe to use early in boot when initialisation is single-threaded */
1283 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1285 return meminit_pfn_in_nid(pfn, node, &early_pfnnid_cache);
1290 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1294 static inline bool __meminit __maybe_unused
1295 meminit_pfn_in_nid(unsigned long pfn, int node,
1296 struct mminit_pfnnid_cache *state)
1303 void __init __free_pages_bootmem(struct page *page, unsigned long pfn,
1306 if (early_page_uninitialised(pfn))
1308 return __free_pages_boot_core(page, order);
1312 * Check that the whole (or subset of) a pageblock given by the interval of
1313 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1314 * with the migration of free compaction scanner. The scanners then need to
1315 * use only pfn_valid_within() check for arches that allow holes within
1318 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1320 * It's possible on some configurations to have a setup like node0 node1 node0
1321 * i.e. it's possible that all pages within a zones range of pages do not
1322 * belong to a single zone. We assume that a border between node0 and node1
1323 * can occur within a single pageblock, but not a node0 node1 node0
1324 * interleaving within a single pageblock. It is therefore sufficient to check
1325 * the first and last page of a pageblock and avoid checking each individual
1326 * page in a pageblock.
1328 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1329 unsigned long end_pfn, struct zone *zone)
1331 struct page *start_page;
1332 struct page *end_page;
1334 /* end_pfn is one past the range we are checking */
1337 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1340 start_page = pfn_to_online_page(start_pfn);
1344 if (page_zone(start_page) != zone)
1347 end_page = pfn_to_page(end_pfn);
1349 /* This gives a shorter code than deriving page_zone(end_page) */
1350 if (page_zone_id(start_page) != page_zone_id(end_page))
1356 void set_zone_contiguous(struct zone *zone)
1358 unsigned long block_start_pfn = zone->zone_start_pfn;
1359 unsigned long block_end_pfn;
1361 block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1362 for (; block_start_pfn < zone_end_pfn(zone);
1363 block_start_pfn = block_end_pfn,
1364 block_end_pfn += pageblock_nr_pages) {
1366 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1368 if (!__pageblock_pfn_to_page(block_start_pfn,
1369 block_end_pfn, zone))
1373 /* We confirm that there is no hole */
1374 zone->contiguous = true;
1377 void clear_zone_contiguous(struct zone *zone)
1379 zone->contiguous = false;
1382 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1383 static void __init deferred_free_range(unsigned long pfn,
1384 unsigned long nr_pages)
1392 page = pfn_to_page(pfn);
1394 /* Free a large naturally-aligned chunk if possible */
1395 if (nr_pages == pageblock_nr_pages &&
1396 (pfn & (pageblock_nr_pages - 1)) == 0) {
1397 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1398 __free_pages_boot_core(page, pageblock_order);
1402 for (i = 0; i < nr_pages; i++, page++, pfn++) {
1403 if ((pfn & (pageblock_nr_pages - 1)) == 0)
1404 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1405 __free_pages_boot_core(page, 0);
1409 /* Completion tracking for deferred_init_memmap() threads */
1410 static atomic_t pgdat_init_n_undone __initdata;
1411 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1413 static inline void __init pgdat_init_report_one_done(void)
1415 if (atomic_dec_and_test(&pgdat_init_n_undone))
1416 complete(&pgdat_init_all_done_comp);
1420 * Returns true if page needs to be initialized or freed to buddy allocator.
1422 * First we check if pfn is valid on architectures where it is possible to have
1423 * holes within pageblock_nr_pages. On systems where it is not possible, this
1424 * function is optimized out.
1426 * Then, we check if a current large page is valid by only checking the validity
1429 * Finally, meminit_pfn_in_nid is checked on systems where pfns can interleave
1430 * within a node: a pfn is between start and end of a node, but does not belong
1431 * to this memory node.
1433 static inline bool __init
1434 deferred_pfn_valid(int nid, unsigned long pfn,
1435 struct mminit_pfnnid_cache *nid_init_state)
1437 if (!pfn_valid_within(pfn))
1439 if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1441 if (!meminit_pfn_in_nid(pfn, nid, nid_init_state))
1447 * Free pages to buddy allocator. Try to free aligned pages in
1448 * pageblock_nr_pages sizes.
1450 static void __init deferred_free_pages(int nid, int zid, unsigned long pfn,
1451 unsigned long end_pfn)
1453 struct mminit_pfnnid_cache nid_init_state = { };
1454 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1455 unsigned long nr_free = 0;
1457 for (; pfn < end_pfn; pfn++) {
1458 if (!deferred_pfn_valid(nid, pfn, &nid_init_state)) {
1459 deferred_free_range(pfn - nr_free, nr_free);
1461 } else if (!(pfn & nr_pgmask)) {
1462 deferred_free_range(pfn - nr_free, nr_free);
1464 touch_nmi_watchdog();
1469 /* Free the last block of pages to allocator */
1470 deferred_free_range(pfn - nr_free, nr_free);
1474 * Initialize struct pages. We minimize pfn page lookups and scheduler checks
1475 * by performing it only once every pageblock_nr_pages.
1476 * Return number of pages initialized.
1478 static unsigned long __init deferred_init_pages(int nid, int zid,
1480 unsigned long end_pfn)
1482 struct mminit_pfnnid_cache nid_init_state = { };
1483 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1484 unsigned long nr_pages = 0;
1485 struct page *page = NULL;
1487 for (; pfn < end_pfn; pfn++) {
1488 if (!deferred_pfn_valid(nid, pfn, &nid_init_state)) {
1491 } else if (!page || !(pfn & nr_pgmask)) {
1492 page = pfn_to_page(pfn);
1493 touch_nmi_watchdog();
1497 __init_single_page(page, pfn, zid, nid);
1503 /* Initialise remaining memory on a node */
1504 static int __init deferred_init_memmap(void *data)
1506 pg_data_t *pgdat = data;
1507 int nid = pgdat->node_id;
1508 unsigned long start = jiffies;
1509 unsigned long nr_pages = 0;
1510 unsigned long spfn, epfn, first_init_pfn, flags;
1511 phys_addr_t spa, epa;
1514 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1517 /* Bind memory initialisation thread to a local node if possible */
1518 if (!cpumask_empty(cpumask))
1519 set_cpus_allowed_ptr(current, cpumask);
1521 pgdat_resize_lock(pgdat, &flags);
1522 first_init_pfn = pgdat->first_deferred_pfn;
1523 if (first_init_pfn == ULONG_MAX) {
1524 pgdat_resize_unlock(pgdat, &flags);
1525 pgdat_init_report_one_done();
1529 /* Sanity check boundaries */
1530 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1531 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1532 pgdat->first_deferred_pfn = ULONG_MAX;
1534 /* Only the highest zone is deferred so find it */
1535 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1536 zone = pgdat->node_zones + zid;
1537 if (first_init_pfn < zone_end_pfn(zone))
1540 first_init_pfn = max(zone->zone_start_pfn, first_init_pfn);
1543 * Initialize and free pages. We do it in two loops: first we initialize
1544 * struct page, than free to buddy allocator, because while we are
1545 * freeing pages we can access pages that are ahead (computing buddy
1546 * page in __free_one_page()).
1548 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1549 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1550 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1551 nr_pages += deferred_init_pages(nid, zid, spfn, epfn);
1553 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1554 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1555 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1556 deferred_free_pages(nid, zid, spfn, epfn);
1558 pgdat_resize_unlock(pgdat, &flags);
1560 /* Sanity check that the next zone really is unpopulated */
1561 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1563 pr_info("node %d initialised, %lu pages in %ums\n", nid, nr_pages,
1564 jiffies_to_msecs(jiffies - start));
1566 pgdat_init_report_one_done();
1571 * During boot we initialize deferred pages on-demand, as needed, but once
1572 * page_alloc_init_late() has finished, the deferred pages are all initialized,
1573 * and we can permanently disable that path.
1575 static DEFINE_STATIC_KEY_TRUE(deferred_pages);
1578 * If this zone has deferred pages, try to grow it by initializing enough
1579 * deferred pages to satisfy the allocation specified by order, rounded up to
1580 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
1581 * of SECTION_SIZE bytes by initializing struct pages in increments of
1582 * PAGES_PER_SECTION * sizeof(struct page) bytes.
1584 * Return true when zone was grown, otherwise return false. We return true even
1585 * when we grow less than requested, to let the caller decide if there are
1586 * enough pages to satisfy the allocation.
1588 * Note: We use noinline because this function is needed only during boot, and
1589 * it is called from a __ref function _deferred_grow_zone. This way we are
1590 * making sure that it is not inlined into permanent text section.
1592 static noinline bool __init
1593 deferred_grow_zone(struct zone *zone, unsigned int order)
1595 int zid = zone_idx(zone);
1596 int nid = zone_to_nid(zone);
1597 pg_data_t *pgdat = NODE_DATA(nid);
1598 unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
1599 unsigned long nr_pages = 0;
1600 unsigned long first_init_pfn, spfn, epfn, t, flags;
1601 unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
1602 phys_addr_t spa, epa;
1605 /* Only the last zone may have deferred pages */
1606 if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
1609 pgdat_resize_lock(pgdat, &flags);
1612 * If deferred pages have been initialized while we were waiting for
1613 * the lock, return true, as the zone was grown. The caller will retry
1614 * this zone. We won't return to this function since the caller also
1615 * has this static branch.
1617 if (!static_branch_unlikely(&deferred_pages)) {
1618 pgdat_resize_unlock(pgdat, &flags);
1623 * If someone grew this zone while we were waiting for spinlock, return
1624 * true, as there might be enough pages already.
1626 if (first_deferred_pfn != pgdat->first_deferred_pfn) {
1627 pgdat_resize_unlock(pgdat, &flags);
1631 first_init_pfn = max(zone->zone_start_pfn, first_deferred_pfn);
1633 if (first_init_pfn >= pgdat_end_pfn(pgdat)) {
1634 pgdat_resize_unlock(pgdat, &flags);
1638 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1639 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1640 epfn = min_t(unsigned long, zone_end_pfn(zone), PFN_DOWN(epa));
1642 while (spfn < epfn && nr_pages < nr_pages_needed) {
1643 t = ALIGN(spfn + PAGES_PER_SECTION, PAGES_PER_SECTION);
1644 first_deferred_pfn = min(t, epfn);
1645 nr_pages += deferred_init_pages(nid, zid, spfn,
1646 first_deferred_pfn);
1647 spfn = first_deferred_pfn;
1650 if (nr_pages >= nr_pages_needed)
1654 for_each_free_mem_range(i, nid, MEMBLOCK_NONE, &spa, &epa, NULL) {
1655 spfn = max_t(unsigned long, first_init_pfn, PFN_UP(spa));
1656 epfn = min_t(unsigned long, first_deferred_pfn, PFN_DOWN(epa));
1657 deferred_free_pages(nid, zid, spfn, epfn);
1659 if (first_deferred_pfn == epfn)
1662 pgdat->first_deferred_pfn = first_deferred_pfn;
1663 pgdat_resize_unlock(pgdat, &flags);
1665 return nr_pages > 0;
1669 * deferred_grow_zone() is __init, but it is called from
1670 * get_page_from_freelist() during early boot until deferred_pages permanently
1671 * disables this call. This is why we have refdata wrapper to avoid warning,
1672 * and to ensure that the function body gets unloaded.
1675 _deferred_grow_zone(struct zone *zone, unsigned int order)
1677 return deferred_grow_zone(zone, order);
1680 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1682 void __init page_alloc_init_late(void)
1686 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1689 /* There will be num_node_state(N_MEMORY) threads */
1690 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1691 for_each_node_state(nid, N_MEMORY) {
1692 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1695 /* Block until all are initialised */
1696 wait_for_completion(&pgdat_init_all_done_comp);
1699 * We initialized the rest of the deferred pages. Permanently disable
1700 * on-demand struct page initialization.
1702 static_branch_disable(&deferred_pages);
1704 /* Reinit limits that are based on free pages after the kernel is up */
1705 files_maxfiles_init();
1707 #ifdef CONFIG_ARCH_DISCARD_MEMBLOCK
1708 /* Discard memblock private memory */
1712 for_each_populated_zone(zone)
1713 set_zone_contiguous(zone);
1717 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
1718 void __init init_cma_reserved_pageblock(struct page *page)
1720 unsigned i = pageblock_nr_pages;
1721 struct page *p = page;
1724 __ClearPageReserved(p);
1725 set_page_count(p, 0);
1728 set_pageblock_migratetype(page, MIGRATE_CMA);
1730 if (pageblock_order >= MAX_ORDER) {
1731 i = pageblock_nr_pages;
1734 set_page_refcounted(p);
1735 __free_pages(p, MAX_ORDER - 1);
1736 p += MAX_ORDER_NR_PAGES;
1737 } while (i -= MAX_ORDER_NR_PAGES);
1739 set_page_refcounted(page);
1740 __free_pages(page, pageblock_order);
1743 adjust_managed_page_count(page, pageblock_nr_pages);
1748 * The order of subdivision here is critical for the IO subsystem.
1749 * Please do not alter this order without good reasons and regression
1750 * testing. Specifically, as large blocks of memory are subdivided,
1751 * the order in which smaller blocks are delivered depends on the order
1752 * they're subdivided in this function. This is the primary factor
1753 * influencing the order in which pages are delivered to the IO
1754 * subsystem according to empirical testing, and this is also justified
1755 * by considering the behavior of a buddy system containing a single
1756 * large block of memory acted on by a series of small allocations.
1757 * This behavior is a critical factor in sglist merging's success.
1761 static inline void expand(struct zone *zone, struct page *page,
1762 int low, int high, struct free_area *area,
1765 unsigned long size = 1 << high;
1767 while (high > low) {
1771 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
1774 * Mark as guard pages (or page), that will allow to
1775 * merge back to allocator when buddy will be freed.
1776 * Corresponding page table entries will not be touched,
1777 * pages will stay not present in virtual address space
1779 if (set_page_guard(zone, &page[size], high, migratetype))
1782 list_add(&page[size].lru, &area->free_list[migratetype]);
1784 set_page_order(&page[size], high);
1788 static void check_new_page_bad(struct page *page)
1790 const char *bad_reason = NULL;
1791 unsigned long bad_flags = 0;
1793 if (unlikely(atomic_read(&page->_mapcount) != -1))
1794 bad_reason = "nonzero mapcount";
1795 if (unlikely(page->mapping != NULL))
1796 bad_reason = "non-NULL mapping";
1797 if (unlikely(page_ref_count(page) != 0))
1798 bad_reason = "nonzero _count";
1799 if (unlikely(page->flags & __PG_HWPOISON)) {
1800 bad_reason = "HWPoisoned (hardware-corrupted)";
1801 bad_flags = __PG_HWPOISON;
1802 /* Don't complain about hwpoisoned pages */
1803 page_mapcount_reset(page); /* remove PageBuddy */
1806 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
1807 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
1808 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
1811 if (unlikely(page->mem_cgroup))
1812 bad_reason = "page still charged to cgroup";
1814 bad_page(page, bad_reason, bad_flags);
1818 * This page is about to be returned from the page allocator
1820 static inline int check_new_page(struct page *page)
1822 if (likely(page_expected_state(page,
1823 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
1826 check_new_page_bad(page);
1830 static inline bool free_pages_prezeroed(void)
1832 return IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) &&
1833 page_poisoning_enabled();
1836 #ifdef CONFIG_DEBUG_VM
1837 static bool check_pcp_refill(struct page *page)
1842 static bool check_new_pcp(struct page *page)
1844 return check_new_page(page);
1847 static bool check_pcp_refill(struct page *page)
1849 return check_new_page(page);
1851 static bool check_new_pcp(struct page *page)
1855 #endif /* CONFIG_DEBUG_VM */
1857 static bool check_new_pages(struct page *page, unsigned int order)
1860 for (i = 0; i < (1 << order); i++) {
1861 struct page *p = page + i;
1863 if (unlikely(check_new_page(p)))
1870 inline void post_alloc_hook(struct page *page, unsigned int order,
1873 set_page_private(page, 0);
1874 set_page_refcounted(page);
1876 arch_alloc_page(page, order);
1877 kernel_map_pages(page, 1 << order, 1);
1878 kernel_poison_pages(page, 1 << order, 1);
1879 kasan_alloc_pages(page, order);
1880 set_page_owner(page, order, gfp_flags);
1883 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
1884 unsigned int alloc_flags)
1888 post_alloc_hook(page, order, gfp_flags);
1890 if (!free_pages_prezeroed() && (gfp_flags & __GFP_ZERO))
1891 for (i = 0; i < (1 << order); i++)
1892 clear_highpage(page + i);
1894 if (order && (gfp_flags & __GFP_COMP))
1895 prep_compound_page(page, order);
1898 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1899 * allocate the page. The expectation is that the caller is taking
1900 * steps that will free more memory. The caller should avoid the page
1901 * being used for !PFMEMALLOC purposes.
1903 if (alloc_flags & ALLOC_NO_WATERMARKS)
1904 set_page_pfmemalloc(page);
1906 clear_page_pfmemalloc(page);
1910 * Go through the free lists for the given migratetype and remove
1911 * the smallest available page from the freelists
1913 static __always_inline
1914 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
1917 unsigned int current_order;
1918 struct free_area *area;
1921 /* Find a page of the appropriate size in the preferred list */
1922 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
1923 area = &(zone->free_area[current_order]);
1924 page = list_first_entry_or_null(&area->free_list[migratetype],
1928 list_del(&page->lru);
1929 rmv_page_order(page);
1931 expand(zone, page, order, current_order, area, migratetype);
1932 set_pcppage_migratetype(page, migratetype);
1941 * This array describes the order lists are fallen back to when
1942 * the free lists for the desirable migrate type are depleted
1944 static int fallbacks[MIGRATE_TYPES][4] = {
1945 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
1946 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
1947 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
1949 [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */
1951 #ifdef CONFIG_MEMORY_ISOLATION
1952 [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */
1957 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1960 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
1963 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1964 unsigned int order) { return NULL; }
1968 * Move the free pages in a range to the free lists of the requested type.
1969 * Note that start_page and end_pages are not aligned on a pageblock
1970 * boundary. If alignment is required, use move_freepages_block()
1972 static int move_freepages(struct zone *zone,
1973 struct page *start_page, struct page *end_page,
1974 int migratetype, int *num_movable)
1978 int pages_moved = 0;
1980 #ifndef CONFIG_HOLES_IN_ZONE
1982 * page_zone is not safe to call in this context when
1983 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
1984 * anyway as we check zone boundaries in move_freepages_block().
1985 * Remove at a later date when no bug reports exist related to
1986 * grouping pages by mobility
1988 VM_BUG_ON(pfn_valid(page_to_pfn(start_page)) &&
1989 pfn_valid(page_to_pfn(end_page)) &&
1990 page_zone(start_page) != page_zone(end_page));
1996 for (page = start_page; page <= end_page;) {
1997 if (!pfn_valid_within(page_to_pfn(page))) {
2002 /* Make sure we are not inadvertently changing nodes */
2003 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2005 if (!PageBuddy(page)) {
2007 * We assume that pages that could be isolated for
2008 * migration are movable. But we don't actually try
2009 * isolating, as that would be expensive.
2012 (PageLRU(page) || __PageMovable(page)))
2019 order = page_order(page);
2020 list_move(&page->lru,
2021 &zone->free_area[order].free_list[migratetype]);
2023 pages_moved += 1 << order;
2029 int move_freepages_block(struct zone *zone, struct page *page,
2030 int migratetype, int *num_movable)
2032 unsigned long start_pfn, end_pfn;
2033 struct page *start_page, *end_page;
2035 start_pfn = page_to_pfn(page);
2036 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
2037 start_page = pfn_to_page(start_pfn);
2038 end_page = start_page + pageblock_nr_pages - 1;
2039 end_pfn = start_pfn + pageblock_nr_pages - 1;
2041 /* Do not cross zone boundaries */
2042 if (!zone_spans_pfn(zone, start_pfn))
2044 if (!zone_spans_pfn(zone, end_pfn))
2047 return move_freepages(zone, start_page, end_page, migratetype,
2051 static void change_pageblock_range(struct page *pageblock_page,
2052 int start_order, int migratetype)
2054 int nr_pageblocks = 1 << (start_order - pageblock_order);
2056 while (nr_pageblocks--) {
2057 set_pageblock_migratetype(pageblock_page, migratetype);
2058 pageblock_page += pageblock_nr_pages;
2063 * When we are falling back to another migratetype during allocation, try to
2064 * steal extra free pages from the same pageblocks to satisfy further
2065 * allocations, instead of polluting multiple pageblocks.
2067 * If we are stealing a relatively large buddy page, it is likely there will
2068 * be more free pages in the pageblock, so try to steal them all. For
2069 * reclaimable and unmovable allocations, we steal regardless of page size,
2070 * as fragmentation caused by those allocations polluting movable pageblocks
2071 * is worse than movable allocations stealing from unmovable and reclaimable
2074 static bool can_steal_fallback(unsigned int order, int start_mt)
2077 * Leaving this order check is intended, although there is
2078 * relaxed order check in next check. The reason is that
2079 * we can actually steal whole pageblock if this condition met,
2080 * but, below check doesn't guarantee it and that is just heuristic
2081 * so could be changed anytime.
2083 if (order >= pageblock_order)
2086 if (order >= pageblock_order / 2 ||
2087 start_mt == MIGRATE_RECLAIMABLE ||
2088 start_mt == MIGRATE_UNMOVABLE ||
2089 page_group_by_mobility_disabled)
2096 * This function implements actual steal behaviour. If order is large enough,
2097 * we can steal whole pageblock. If not, we first move freepages in this
2098 * pageblock to our migratetype and determine how many already-allocated pages
2099 * are there in the pageblock with a compatible migratetype. If at least half
2100 * of pages are free or compatible, we can change migratetype of the pageblock
2101 * itself, so pages freed in the future will be put on the correct free list.
2103 static void steal_suitable_fallback(struct zone *zone, struct page *page,
2104 int start_type, bool whole_block)
2106 unsigned int current_order = page_order(page);
2107 struct free_area *area;
2108 int free_pages, movable_pages, alike_pages;
2111 old_block_type = get_pageblock_migratetype(page);
2114 * This can happen due to races and we want to prevent broken
2115 * highatomic accounting.
2117 if (is_migrate_highatomic(old_block_type))
2120 /* Take ownership for orders >= pageblock_order */
2121 if (current_order >= pageblock_order) {
2122 change_pageblock_range(page, current_order, start_type);
2126 /* We are not allowed to try stealing from the whole block */
2130 free_pages = move_freepages_block(zone, page, start_type,
2133 * Determine how many pages are compatible with our allocation.
2134 * For movable allocation, it's the number of movable pages which
2135 * we just obtained. For other types it's a bit more tricky.
2137 if (start_type == MIGRATE_MOVABLE) {
2138 alike_pages = movable_pages;
2141 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2142 * to MOVABLE pageblock, consider all non-movable pages as
2143 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2144 * vice versa, be conservative since we can't distinguish the
2145 * exact migratetype of non-movable pages.
2147 if (old_block_type == MIGRATE_MOVABLE)
2148 alike_pages = pageblock_nr_pages
2149 - (free_pages + movable_pages);
2154 /* moving whole block can fail due to zone boundary conditions */
2159 * If a sufficient number of pages in the block are either free or of
2160 * comparable migratability as our allocation, claim the whole block.
2162 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2163 page_group_by_mobility_disabled)
2164 set_pageblock_migratetype(page, start_type);
2169 area = &zone->free_area[current_order];
2170 list_move(&page->lru, &area->free_list[start_type]);
2174 * Check whether there is a suitable fallback freepage with requested order.
2175 * If only_stealable is true, this function returns fallback_mt only if
2176 * we can steal other freepages all together. This would help to reduce
2177 * fragmentation due to mixed migratetype pages in one pageblock.
2179 int find_suitable_fallback(struct free_area *area, unsigned int order,
2180 int migratetype, bool only_stealable, bool *can_steal)
2185 if (area->nr_free == 0)
2190 fallback_mt = fallbacks[migratetype][i];
2191 if (fallback_mt == MIGRATE_TYPES)
2194 if (list_empty(&area->free_list[fallback_mt]))
2197 if (can_steal_fallback(order, migratetype))
2200 if (!only_stealable)
2211 * Reserve a pageblock for exclusive use of high-order atomic allocations if
2212 * there are no empty page blocks that contain a page with a suitable order
2214 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2215 unsigned int alloc_order)
2218 unsigned long max_managed, flags;
2221 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2222 * Check is race-prone but harmless.
2224 max_managed = (zone->managed_pages / 100) + pageblock_nr_pages;
2225 if (zone->nr_reserved_highatomic >= max_managed)
2228 spin_lock_irqsave(&zone->lock, flags);
2230 /* Recheck the nr_reserved_highatomic limit under the lock */
2231 if (zone->nr_reserved_highatomic >= max_managed)
2235 mt = get_pageblock_migratetype(page);
2236 if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
2237 && !is_migrate_cma(mt)) {
2238 zone->nr_reserved_highatomic += pageblock_nr_pages;
2239 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
2240 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
2244 spin_unlock_irqrestore(&zone->lock, flags);
2248 * Used when an allocation is about to fail under memory pressure. This
2249 * potentially hurts the reliability of high-order allocations when under
2250 * intense memory pressure but failed atomic allocations should be easier
2251 * to recover from than an OOM.
2253 * If @force is true, try to unreserve a pageblock even though highatomic
2254 * pageblock is exhausted.
2256 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2259 struct zonelist *zonelist = ac->zonelist;
2260 unsigned long flags;
2267 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2270 * Preserve at least one pageblock unless memory pressure
2273 if (!force && zone->nr_reserved_highatomic <=
2277 spin_lock_irqsave(&zone->lock, flags);
2278 for (order = 0; order < MAX_ORDER; order++) {
2279 struct free_area *area = &(zone->free_area[order]);
2281 page = list_first_entry_or_null(
2282 &area->free_list[MIGRATE_HIGHATOMIC],
2288 * In page freeing path, migratetype change is racy so
2289 * we can counter several free pages in a pageblock
2290 * in this loop althoug we changed the pageblock type
2291 * from highatomic to ac->migratetype. So we should
2292 * adjust the count once.
2294 if (is_migrate_highatomic_page(page)) {
2296 * It should never happen but changes to
2297 * locking could inadvertently allow a per-cpu
2298 * drain to add pages to MIGRATE_HIGHATOMIC
2299 * while unreserving so be safe and watch for
2302 zone->nr_reserved_highatomic -= min(
2304 zone->nr_reserved_highatomic);
2308 * Convert to ac->migratetype and avoid the normal
2309 * pageblock stealing heuristics. Minimally, the caller
2310 * is doing the work and needs the pages. More
2311 * importantly, if the block was always converted to
2312 * MIGRATE_UNMOVABLE or another type then the number
2313 * of pageblocks that cannot be completely freed
2316 set_pageblock_migratetype(page, ac->migratetype);
2317 ret = move_freepages_block(zone, page, ac->migratetype,
2320 spin_unlock_irqrestore(&zone->lock, flags);
2324 spin_unlock_irqrestore(&zone->lock, flags);
2331 * Try finding a free buddy page on the fallback list and put it on the free
2332 * list of requested migratetype, possibly along with other pages from the same
2333 * block, depending on fragmentation avoidance heuristics. Returns true if
2334 * fallback was found so that __rmqueue_smallest() can grab it.
2336 * The use of signed ints for order and current_order is a deliberate
2337 * deviation from the rest of this file, to make the for loop
2338 * condition simpler.
2340 static __always_inline bool
2341 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype)
2343 struct free_area *area;
2350 * Find the largest available free page in the other list. This roughly
2351 * approximates finding the pageblock with the most free pages, which
2352 * would be too costly to do exactly.
2354 for (current_order = MAX_ORDER - 1; current_order >= order;
2356 area = &(zone->free_area[current_order]);
2357 fallback_mt = find_suitable_fallback(area, current_order,
2358 start_migratetype, false, &can_steal);
2359 if (fallback_mt == -1)
2363 * We cannot steal all free pages from the pageblock and the
2364 * requested migratetype is movable. In that case it's better to
2365 * steal and split the smallest available page instead of the
2366 * largest available page, because even if the next movable
2367 * allocation falls back into a different pageblock than this
2368 * one, it won't cause permanent fragmentation.
2370 if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2371 && current_order > order)
2380 for (current_order = order; current_order < MAX_ORDER;
2382 area = &(zone->free_area[current_order]);
2383 fallback_mt = find_suitable_fallback(area, current_order,
2384 start_migratetype, false, &can_steal);
2385 if (fallback_mt != -1)
2390 * This should not happen - we already found a suitable fallback
2391 * when looking for the largest page.
2393 VM_BUG_ON(current_order == MAX_ORDER);
2396 page = list_first_entry(&area->free_list[fallback_mt],
2399 steal_suitable_fallback(zone, page, start_migratetype, can_steal);
2401 trace_mm_page_alloc_extfrag(page, order, current_order,
2402 start_migratetype, fallback_mt);
2409 * Do the hard work of removing an element from the buddy allocator.
2410 * Call me with the zone->lock already held.
2412 static __always_inline struct page *
2413 __rmqueue(struct zone *zone, unsigned int order, int migratetype)
2418 page = __rmqueue_smallest(zone, order, migratetype);
2419 if (unlikely(!page)) {
2420 if (migratetype == MIGRATE_MOVABLE)
2421 page = __rmqueue_cma_fallback(zone, order);
2423 if (!page && __rmqueue_fallback(zone, order, migratetype))
2427 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2432 * Obtain a specified number of elements from the buddy allocator, all under
2433 * a single hold of the lock, for efficiency. Add them to the supplied list.
2434 * Returns the number of new pages which were placed at *list.
2436 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2437 unsigned long count, struct list_head *list,
2442 spin_lock(&zone->lock);
2443 for (i = 0; i < count; ++i) {
2444 struct page *page = __rmqueue(zone, order, migratetype);
2445 if (unlikely(page == NULL))
2448 if (unlikely(check_pcp_refill(page)))
2452 * Split buddy pages returned by expand() are received here in
2453 * physical page order. The page is added to the tail of
2454 * caller's list. From the callers perspective, the linked list
2455 * is ordered by page number under some conditions. This is
2456 * useful for IO devices that can forward direction from the
2457 * head, thus also in the physical page order. This is useful
2458 * for IO devices that can merge IO requests if the physical
2459 * pages are ordered properly.
2461 list_add_tail(&page->lru, list);
2463 if (is_migrate_cma(get_pcppage_migratetype(page)))
2464 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
2469 * i pages were removed from the buddy list even if some leak due
2470 * to check_pcp_refill failing so adjust NR_FREE_PAGES based
2471 * on i. Do not confuse with 'alloced' which is the number of
2472 * pages added to the pcp list.
2474 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
2475 spin_unlock(&zone->lock);
2481 * Called from the vmstat counter updater to drain pagesets of this
2482 * currently executing processor on remote nodes after they have
2485 * Note that this function must be called with the thread pinned to
2486 * a single processor.
2488 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2490 unsigned long flags;
2491 int to_drain, batch;
2493 local_irq_save(flags);
2494 batch = READ_ONCE(pcp->batch);
2495 to_drain = min(pcp->count, batch);
2497 free_pcppages_bulk(zone, to_drain, pcp);
2498 pcp->count -= to_drain;
2500 local_irq_restore(flags);
2505 * Drain pcplists of the indicated processor and zone.
2507 * The processor must either be the current processor and the
2508 * thread pinned to the current processor or a processor that
2511 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2513 unsigned long flags;
2514 struct per_cpu_pageset *pset;
2515 struct per_cpu_pages *pcp;
2517 local_irq_save(flags);
2518 pset = per_cpu_ptr(zone->pageset, cpu);
2522 free_pcppages_bulk(zone, pcp->count, pcp);
2525 local_irq_restore(flags);
2529 * Drain pcplists of all zones on the indicated processor.
2531 * The processor must either be the current processor and the
2532 * thread pinned to the current processor or a processor that
2535 static void drain_pages(unsigned int cpu)
2539 for_each_populated_zone(zone) {
2540 drain_pages_zone(cpu, zone);
2545 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2547 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2548 * the single zone's pages.
2550 void drain_local_pages(struct zone *zone)
2552 int cpu = smp_processor_id();
2555 drain_pages_zone(cpu, zone);
2560 static void drain_local_pages_wq(struct work_struct *work)
2563 * drain_all_pages doesn't use proper cpu hotplug protection so
2564 * we can race with cpu offline when the WQ can move this from
2565 * a cpu pinned worker to an unbound one. We can operate on a different
2566 * cpu which is allright but we also have to make sure to not move to
2570 drain_local_pages(NULL);
2575 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2577 * When zone parameter is non-NULL, spill just the single zone's pages.
2579 * Note that this can be extremely slow as the draining happens in a workqueue.
2581 void drain_all_pages(struct zone *zone)
2586 * Allocate in the BSS so we wont require allocation in
2587 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2589 static cpumask_t cpus_with_pcps;
2592 * Make sure nobody triggers this path before mm_percpu_wq is fully
2595 if (WARN_ON_ONCE(!mm_percpu_wq))
2599 * Do not drain if one is already in progress unless it's specific to
2600 * a zone. Such callers are primarily CMA and memory hotplug and need
2601 * the drain to be complete when the call returns.
2603 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
2606 mutex_lock(&pcpu_drain_mutex);
2610 * We don't care about racing with CPU hotplug event
2611 * as offline notification will cause the notified
2612 * cpu to drain that CPU pcps and on_each_cpu_mask
2613 * disables preemption as part of its processing
2615 for_each_online_cpu(cpu) {
2616 struct per_cpu_pageset *pcp;
2618 bool has_pcps = false;
2621 pcp = per_cpu_ptr(zone->pageset, cpu);
2625 for_each_populated_zone(z) {
2626 pcp = per_cpu_ptr(z->pageset, cpu);
2627 if (pcp->pcp.count) {
2635 cpumask_set_cpu(cpu, &cpus_with_pcps);
2637 cpumask_clear_cpu(cpu, &cpus_with_pcps);
2640 for_each_cpu(cpu, &cpus_with_pcps) {
2641 struct work_struct *work = per_cpu_ptr(&pcpu_drain, cpu);
2642 INIT_WORK(work, drain_local_pages_wq);
2643 queue_work_on(cpu, mm_percpu_wq, work);
2645 for_each_cpu(cpu, &cpus_with_pcps)
2646 flush_work(per_cpu_ptr(&pcpu_drain, cpu));
2648 mutex_unlock(&pcpu_drain_mutex);
2651 #ifdef CONFIG_HIBERNATION
2654 * Touch the watchdog for every WD_PAGE_COUNT pages.
2656 #define WD_PAGE_COUNT (128*1024)
2658 void mark_free_pages(struct zone *zone)
2660 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
2661 unsigned long flags;
2662 unsigned int order, t;
2665 if (zone_is_empty(zone))
2668 spin_lock_irqsave(&zone->lock, flags);
2670 max_zone_pfn = zone_end_pfn(zone);
2671 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
2672 if (pfn_valid(pfn)) {
2673 page = pfn_to_page(pfn);
2675 if (!--page_count) {
2676 touch_nmi_watchdog();
2677 page_count = WD_PAGE_COUNT;
2680 if (page_zone(page) != zone)
2683 if (!swsusp_page_is_forbidden(page))
2684 swsusp_unset_page_free(page);
2687 for_each_migratetype_order(order, t) {
2688 list_for_each_entry(page,
2689 &zone->free_area[order].free_list[t], lru) {
2692 pfn = page_to_pfn(page);
2693 for (i = 0; i < (1UL << order); i++) {
2694 if (!--page_count) {
2695 touch_nmi_watchdog();
2696 page_count = WD_PAGE_COUNT;
2698 swsusp_set_page_free(pfn_to_page(pfn + i));
2702 spin_unlock_irqrestore(&zone->lock, flags);
2704 #endif /* CONFIG_PM */
2706 static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
2710 if (!free_pcp_prepare(page))
2713 migratetype = get_pfnblock_migratetype(page, pfn);
2714 set_pcppage_migratetype(page, migratetype);
2718 static void free_unref_page_commit(struct page *page, unsigned long pfn)
2720 struct zone *zone = page_zone(page);
2721 struct per_cpu_pages *pcp;
2724 migratetype = get_pcppage_migratetype(page);
2725 __count_vm_event(PGFREE);
2728 * We only track unmovable, reclaimable and movable on pcp lists.
2729 * Free ISOLATE pages back to the allocator because they are being
2730 * offlined but treat HIGHATOMIC as movable pages so we can get those
2731 * areas back if necessary. Otherwise, we may have to free
2732 * excessively into the page allocator
2734 if (migratetype >= MIGRATE_PCPTYPES) {
2735 if (unlikely(is_migrate_isolate(migratetype))) {
2736 free_one_page(zone, page, pfn, 0, migratetype);
2739 migratetype = MIGRATE_MOVABLE;
2742 pcp = &this_cpu_ptr(zone->pageset)->pcp;
2743 list_add(&page->lru, &pcp->lists[migratetype]);
2745 if (pcp->count >= pcp->high) {
2746 unsigned long batch = READ_ONCE(pcp->batch);
2747 free_pcppages_bulk(zone, batch, pcp);
2748 pcp->count -= batch;
2753 * Free a 0-order page
2755 void free_unref_page(struct page *page)
2757 unsigned long flags;
2758 unsigned long pfn = page_to_pfn(page);
2760 if (!free_unref_page_prepare(page, pfn))
2763 local_irq_save(flags);
2764 free_unref_page_commit(page, pfn);
2765 local_irq_restore(flags);
2769 * Free a list of 0-order pages
2771 void free_unref_page_list(struct list_head *list)
2773 struct page *page, *next;
2774 unsigned long flags, pfn;
2775 int batch_count = 0;
2777 /* Prepare pages for freeing */
2778 list_for_each_entry_safe(page, next, list, lru) {
2779 pfn = page_to_pfn(page);
2780 if (!free_unref_page_prepare(page, pfn))
2781 list_del(&page->lru);
2782 set_page_private(page, pfn);
2785 local_irq_save(flags);
2786 list_for_each_entry_safe(page, next, list, lru) {
2787 unsigned long pfn = page_private(page);
2789 set_page_private(page, 0);
2790 trace_mm_page_free_batched(page);
2791 free_unref_page_commit(page, pfn);
2794 * Guard against excessive IRQ disabled times when we get
2795 * a large list of pages to free.
2797 if (++batch_count == SWAP_CLUSTER_MAX) {
2798 local_irq_restore(flags);
2800 local_irq_save(flags);
2803 local_irq_restore(flags);
2807 * split_page takes a non-compound higher-order page, and splits it into
2808 * n (1<<order) sub-pages: page[0..n]
2809 * Each sub-page must be freed individually.
2811 * Note: this is probably too low level an operation for use in drivers.
2812 * Please consult with lkml before using this in your driver.
2814 void split_page(struct page *page, unsigned int order)
2818 VM_BUG_ON_PAGE(PageCompound(page), page);
2819 VM_BUG_ON_PAGE(!page_count(page), page);
2821 for (i = 1; i < (1 << order); i++)
2822 set_page_refcounted(page + i);
2823 split_page_owner(page, order);
2825 EXPORT_SYMBOL_GPL(split_page);
2827 int __isolate_free_page(struct page *page, unsigned int order)
2829 unsigned long watermark;
2833 BUG_ON(!PageBuddy(page));
2835 zone = page_zone(page);
2836 mt = get_pageblock_migratetype(page);
2838 if (!is_migrate_isolate(mt)) {
2840 * Obey watermarks as if the page was being allocated. We can
2841 * emulate a high-order watermark check with a raised order-0
2842 * watermark, because we already know our high-order page
2845 watermark = min_wmark_pages(zone) + (1UL << order);
2846 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
2849 __mod_zone_freepage_state(zone, -(1UL << order), mt);
2852 /* Remove page from free list */
2853 list_del(&page->lru);
2854 zone->free_area[order].nr_free--;
2855 rmv_page_order(page);
2858 * Set the pageblock if the isolated page is at least half of a
2861 if (order >= pageblock_order - 1) {
2862 struct page *endpage = page + (1 << order) - 1;
2863 for (; page < endpage; page += pageblock_nr_pages) {
2864 int mt = get_pageblock_migratetype(page);
2865 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
2866 && !is_migrate_highatomic(mt))
2867 set_pageblock_migratetype(page,
2873 return 1UL << order;
2877 * Update NUMA hit/miss statistics
2879 * Must be called with interrupts disabled.
2881 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z)
2884 enum numa_stat_item local_stat = NUMA_LOCAL;
2886 /* skip numa counters update if numa stats is disabled */
2887 if (!static_branch_likely(&vm_numa_stat_key))
2890 if (z->node != numa_node_id())
2891 local_stat = NUMA_OTHER;
2893 if (z->node == preferred_zone->node)
2894 __inc_numa_state(z, NUMA_HIT);
2896 __inc_numa_state(z, NUMA_MISS);
2897 __inc_numa_state(preferred_zone, NUMA_FOREIGN);
2899 __inc_numa_state(z, local_stat);
2903 /* Remove page from the per-cpu list, caller must protect the list */
2904 static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
2905 struct per_cpu_pages *pcp,
2906 struct list_head *list)
2911 if (list_empty(list)) {
2912 pcp->count += rmqueue_bulk(zone, 0,
2915 if (unlikely(list_empty(list)))
2919 page = list_first_entry(list, struct page, lru);
2920 list_del(&page->lru);
2922 } while (check_new_pcp(page));
2927 /* Lock and remove page from the per-cpu list */
2928 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
2929 struct zone *zone, unsigned int order,
2930 gfp_t gfp_flags, int migratetype)
2932 struct per_cpu_pages *pcp;
2933 struct list_head *list;
2935 unsigned long flags;
2937 local_irq_save(flags);
2938 pcp = &this_cpu_ptr(zone->pageset)->pcp;
2939 list = &pcp->lists[migratetype];
2940 page = __rmqueue_pcplist(zone, migratetype, pcp, list);
2942 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
2943 zone_statistics(preferred_zone, zone);
2945 local_irq_restore(flags);
2950 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
2953 struct page *rmqueue(struct zone *preferred_zone,
2954 struct zone *zone, unsigned int order,
2955 gfp_t gfp_flags, unsigned int alloc_flags,
2958 unsigned long flags;
2961 if (likely(order == 0)) {
2962 page = rmqueue_pcplist(preferred_zone, zone, order,
2963 gfp_flags, migratetype);
2968 * We most definitely don't want callers attempting to
2969 * allocate greater than order-1 page units with __GFP_NOFAIL.
2971 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
2972 spin_lock_irqsave(&zone->lock, flags);
2976 if (alloc_flags & ALLOC_HARDER) {
2977 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
2979 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2982 page = __rmqueue(zone, order, migratetype);
2983 } while (page && check_new_pages(page, order));
2984 spin_unlock(&zone->lock);
2987 __mod_zone_freepage_state(zone, -(1 << order),
2988 get_pcppage_migratetype(page));
2990 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
2991 zone_statistics(preferred_zone, zone);
2992 local_irq_restore(flags);
2995 VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
2999 local_irq_restore(flags);
3003 #ifdef CONFIG_FAIL_PAGE_ALLOC
3006 struct fault_attr attr;
3008 bool ignore_gfp_highmem;
3009 bool ignore_gfp_reclaim;
3011 } fail_page_alloc = {
3012 .attr = FAULT_ATTR_INITIALIZER,
3013 .ignore_gfp_reclaim = true,
3014 .ignore_gfp_highmem = true,
3018 static int __init setup_fail_page_alloc(char *str)
3020 return setup_fault_attr(&fail_page_alloc.attr, str);
3022 __setup("fail_page_alloc=", setup_fail_page_alloc);
3024 static bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3026 if (order < fail_page_alloc.min_order)
3028 if (gfp_mask & __GFP_NOFAIL)
3030 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3032 if (fail_page_alloc.ignore_gfp_reclaim &&
3033 (gfp_mask & __GFP_DIRECT_RECLAIM))
3036 return should_fail(&fail_page_alloc.attr, 1 << order);
3039 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3041 static int __init fail_page_alloc_debugfs(void)
3043 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
3046 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3047 &fail_page_alloc.attr);
3049 return PTR_ERR(dir);
3051 if (!debugfs_create_bool("ignore-gfp-wait", mode, dir,
3052 &fail_page_alloc.ignore_gfp_reclaim))
3054 if (!debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3055 &fail_page_alloc.ignore_gfp_highmem))
3057 if (!debugfs_create_u32("min-order", mode, dir,
3058 &fail_page_alloc.min_order))
3063 debugfs_remove_recursive(dir);
3068 late_initcall(fail_page_alloc_debugfs);
3070 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3072 #else /* CONFIG_FAIL_PAGE_ALLOC */
3074 static inline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3079 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3082 * Return true if free base pages are above 'mark'. For high-order checks it
3083 * will return true of the order-0 watermark is reached and there is at least
3084 * one free page of a suitable size. Checking now avoids taking the zone lock
3085 * to check in the allocation paths if no pages are free.
3087 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3088 int classzone_idx, unsigned int alloc_flags,
3093 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3095 /* free_pages may go negative - that's OK */
3096 free_pages -= (1 << order) - 1;
3098 if (alloc_flags & ALLOC_HIGH)
3102 * If the caller does not have rights to ALLOC_HARDER then subtract
3103 * the high-atomic reserves. This will over-estimate the size of the
3104 * atomic reserve but it avoids a search.
3106 if (likely(!alloc_harder)) {
3107 free_pages -= z->nr_reserved_highatomic;
3110 * OOM victims can try even harder than normal ALLOC_HARDER
3111 * users on the grounds that it's definitely going to be in
3112 * the exit path shortly and free memory. Any allocation it
3113 * makes during the free path will be small and short-lived.
3115 if (alloc_flags & ALLOC_OOM)
3123 /* If allocation can't use CMA areas don't use free CMA pages */
3124 if (!(alloc_flags & ALLOC_CMA))
3125 free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
3129 * Check watermarks for an order-0 allocation request. If these
3130 * are not met, then a high-order request also cannot go ahead
3131 * even if a suitable page happened to be free.
3133 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
3136 /* If this is an order-0 request then the watermark is fine */
3140 /* For a high-order request, check at least one suitable page is free */
3141 for (o = order; o < MAX_ORDER; o++) {
3142 struct free_area *area = &z->free_area[o];
3148 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3149 if (!list_empty(&area->free_list[mt]))
3154 if ((alloc_flags & ALLOC_CMA) &&
3155 !list_empty(&area->free_list[MIGRATE_CMA])) {
3160 !list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
3166 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3167 int classzone_idx, unsigned int alloc_flags)
3169 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3170 zone_page_state(z, NR_FREE_PAGES));
3173 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3174 unsigned long mark, int classzone_idx, unsigned int alloc_flags)
3176 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3180 /* If allocation can't use CMA areas don't use free CMA pages */
3181 if (!(alloc_flags & ALLOC_CMA))
3182 cma_pages = zone_page_state(z, NR_FREE_CMA_PAGES);
3186 * Fast check for order-0 only. If this fails then the reserves
3187 * need to be calculated. There is a corner case where the check
3188 * passes but only the high-order atomic reserve are free. If
3189 * the caller is !atomic then it'll uselessly search the free
3190 * list. That corner case is then slower but it is harmless.
3192 if (!order && (free_pages - cma_pages) > mark + z->lowmem_reserve[classzone_idx])
3195 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3199 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3200 unsigned long mark, int classzone_idx)
3202 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3204 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3205 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3207 return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
3212 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3214 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3217 #else /* CONFIG_NUMA */
3218 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3222 #endif /* CONFIG_NUMA */
3225 * get_page_from_freelist goes through the zonelist trying to allocate
3228 static struct page *
3229 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3230 const struct alloc_context *ac)
3232 struct zoneref *z = ac->preferred_zoneref;
3234 struct pglist_data *last_pgdat_dirty_limit = NULL;
3237 * Scan zonelist, looking for a zone with enough free.
3238 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3240 for_next_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
3245 if (cpusets_enabled() &&
3246 (alloc_flags & ALLOC_CPUSET) &&
3247 !__cpuset_zone_allowed(zone, gfp_mask))
3250 * When allocating a page cache page for writing, we
3251 * want to get it from a node that is within its dirty
3252 * limit, such that no single node holds more than its
3253 * proportional share of globally allowed dirty pages.
3254 * The dirty limits take into account the node's
3255 * lowmem reserves and high watermark so that kswapd
3256 * should be able to balance it without having to
3257 * write pages from its LRU list.
3259 * XXX: For now, allow allocations to potentially
3260 * exceed the per-node dirty limit in the slowpath
3261 * (spread_dirty_pages unset) before going into reclaim,
3262 * which is important when on a NUMA setup the allowed
3263 * nodes are together not big enough to reach the
3264 * global limit. The proper fix for these situations
3265 * will require awareness of nodes in the
3266 * dirty-throttling and the flusher threads.
3268 if (ac->spread_dirty_pages) {
3269 if (last_pgdat_dirty_limit == zone->zone_pgdat)
3272 if (!node_dirty_ok(zone->zone_pgdat)) {
3273 last_pgdat_dirty_limit = zone->zone_pgdat;
3278 mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
3279 if (!zone_watermark_fast(zone, order, mark,
3280 ac_classzone_idx(ac), alloc_flags)) {
3283 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3285 * Watermark failed for this zone, but see if we can
3286 * grow this zone if it contains deferred pages.
3288 if (static_branch_unlikely(&deferred_pages)) {
3289 if (_deferred_grow_zone(zone, order))
3293 /* Checked here to keep the fast path fast */
3294 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3295 if (alloc_flags & ALLOC_NO_WATERMARKS)
3298 if (node_reclaim_mode == 0 ||
3299 !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
3302 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3304 case NODE_RECLAIM_NOSCAN:
3307 case NODE_RECLAIM_FULL:
3308 /* scanned but unreclaimable */
3311 /* did we reclaim enough */
3312 if (zone_watermark_ok(zone, order, mark,
3313 ac_classzone_idx(ac), alloc_flags))
3321 page = rmqueue(ac->preferred_zoneref->zone, zone, order,
3322 gfp_mask, alloc_flags, ac->migratetype);
3324 prep_new_page(page, order, gfp_mask, alloc_flags);
3327 * If this is a high-order atomic allocation then check
3328 * if the pageblock should be reserved for the future
3330 if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
3331 reserve_highatomic_pageblock(page, zone, order);
3335 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3336 /* Try again if zone has deferred pages */
3337 if (static_branch_unlikely(&deferred_pages)) {
3338 if (_deferred_grow_zone(zone, order))
3349 * Large machines with many possible nodes should not always dump per-node
3350 * meminfo in irq context.
3352 static inline bool should_suppress_show_mem(void)
3357 ret = in_interrupt();
3362 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
3364 unsigned int filter = SHOW_MEM_FILTER_NODES;
3365 static DEFINE_RATELIMIT_STATE(show_mem_rs, HZ, 1);
3367 if (should_suppress_show_mem() || !__ratelimit(&show_mem_rs))
3371 * This documents exceptions given to allocations in certain
3372 * contexts that are allowed to allocate outside current's set
3375 if (!(gfp_mask & __GFP_NOMEMALLOC))
3376 if (tsk_is_oom_victim(current) ||
3377 (current->flags & (PF_MEMALLOC | PF_EXITING)))
3378 filter &= ~SHOW_MEM_FILTER_NODES;
3379 if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
3380 filter &= ~SHOW_MEM_FILTER_NODES;
3382 show_mem(filter, nodemask);
3385 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
3387 struct va_format vaf;
3389 static DEFINE_RATELIMIT_STATE(nopage_rs, DEFAULT_RATELIMIT_INTERVAL,
3390 DEFAULT_RATELIMIT_BURST);
3392 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs))
3395 va_start(args, fmt);
3398 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl\n",
3399 current->comm, &vaf, gfp_mask, &gfp_mask,
3400 nodemask_pr_args(nodemask));
3403 cpuset_print_current_mems_allowed();
3406 warn_alloc_show_mem(gfp_mask, nodemask);
3409 static inline struct page *
3410 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
3411 unsigned int alloc_flags,
3412 const struct alloc_context *ac)
3416 page = get_page_from_freelist(gfp_mask, order,
3417 alloc_flags|ALLOC_CPUSET, ac);
3419 * fallback to ignore cpuset restriction if our nodes
3423 page = get_page_from_freelist(gfp_mask, order,
3429 static inline struct page *
3430 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
3431 const struct alloc_context *ac, unsigned long *did_some_progress)
3433 struct oom_control oc = {
3434 .zonelist = ac->zonelist,
3435 .nodemask = ac->nodemask,
3437 .gfp_mask = gfp_mask,
3442 *did_some_progress = 0;
3445 * Acquire the oom lock. If that fails, somebody else is
3446 * making progress for us.
3448 if (!mutex_trylock(&oom_lock)) {
3449 *did_some_progress = 1;
3450 schedule_timeout_uninterruptible(1);
3455 * Go through the zonelist yet one more time, keep very high watermark
3456 * here, this is only to catch a parallel oom killing, we must fail if
3457 * we're still under heavy pressure. But make sure that this reclaim
3458 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
3459 * allocation which will never fail due to oom_lock already held.
3461 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
3462 ~__GFP_DIRECT_RECLAIM, order,
3463 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
3467 /* Coredumps can quickly deplete all memory reserves */
3468 if (current->flags & PF_DUMPCORE)
3470 /* The OOM killer will not help higher order allocs */
3471 if (order > PAGE_ALLOC_COSTLY_ORDER)
3474 * We have already exhausted all our reclaim opportunities without any
3475 * success so it is time to admit defeat. We will skip the OOM killer
3476 * because it is very likely that the caller has a more reasonable
3477 * fallback than shooting a random task.
3479 if (gfp_mask & __GFP_RETRY_MAYFAIL)
3481 /* The OOM killer does not needlessly kill tasks for lowmem */
3482 if (ac->high_zoneidx < ZONE_NORMAL)
3484 if (pm_suspended_storage())
3487 * XXX: GFP_NOFS allocations should rather fail than rely on
3488 * other request to make a forward progress.
3489 * We are in an unfortunate situation where out_of_memory cannot
3490 * do much for this context but let's try it to at least get
3491 * access to memory reserved if the current task is killed (see
3492 * out_of_memory). Once filesystems are ready to handle allocation
3493 * failures more gracefully we should just bail out here.
3496 /* The OOM killer may not free memory on a specific node */
3497 if (gfp_mask & __GFP_THISNODE)
3500 /* Exhausted what can be done so it's blame time */
3501 if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
3502 *did_some_progress = 1;
3505 * Help non-failing allocations by giving them access to memory
3508 if (gfp_mask & __GFP_NOFAIL)
3509 page = __alloc_pages_cpuset_fallback(gfp_mask, order,
3510 ALLOC_NO_WATERMARKS, ac);
3513 mutex_unlock(&oom_lock);
3518 * Maximum number of compaction retries wit a progress before OOM
3519 * killer is consider as the only way to move forward.
3521 #define MAX_COMPACT_RETRIES 16
3523 #ifdef CONFIG_COMPACTION
3524 /* Try memory compaction for high-order allocations before reclaim */
3525 static struct page *
3526 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
3527 unsigned int alloc_flags, const struct alloc_context *ac,
3528 enum compact_priority prio, enum compact_result *compact_result)
3531 unsigned int noreclaim_flag;
3536 noreclaim_flag = memalloc_noreclaim_save();
3537 *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
3539 memalloc_noreclaim_restore(noreclaim_flag);
3541 if (*compact_result <= COMPACT_INACTIVE)
3545 * At least in one zone compaction wasn't deferred or skipped, so let