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/highmem.h>
20 #include <linux/swap.h>
21 #include <linux/interrupt.h>
22 #include <linux/pagemap.h>
23 #include <linux/jiffies.h>
24 #include <linux/memblock.h>
25 #include <linux/compiler.h>
26 #include <linux/kernel.h>
27 #include <linux/kasan.h>
28 #include <linux/module.h>
29 #include <linux/suspend.h>
30 #include <linux/pagevec.h>
31 #include <linux/blkdev.h>
32 #include <linux/slab.h>
33 #include <linux/ratelimit.h>
34 #include <linux/oom.h>
35 #include <linux/topology.h>
36 #include <linux/sysctl.h>
37 #include <linux/cpu.h>
38 #include <linux/cpuset.h>
39 #include <linux/memory_hotplug.h>
40 #include <linux/nodemask.h>
41 #include <linux/vmalloc.h>
42 #include <linux/vmstat.h>
43 #include <linux/mempolicy.h>
44 #include <linux/memremap.h>
45 #include <linux/stop_machine.h>
46 #include <linux/sort.h>
47 #include <linux/pfn.h>
48 #include <linux/backing-dev.h>
49 #include <linux/fault-inject.h>
50 #include <linux/page-isolation.h>
51 #include <linux/page_ext.h>
52 #include <linux/debugobjects.h>
53 #include <linux/kmemleak.h>
54 #include <linux/compaction.h>
55 #include <trace/events/kmem.h>
56 #include <trace/events/oom.h>
57 #include <linux/prefetch.h>
58 #include <linux/mm_inline.h>
59 #include <linux/migrate.h>
60 #include <linux/hugetlb.h>
61 #include <linux/sched/rt.h>
62 #include <linux/sched/mm.h>
63 #include <linux/page_owner.h>
64 #include <linux/kthread.h>
65 #include <linux/memcontrol.h>
66 #include <linux/ftrace.h>
67 #include <linux/lockdep.h>
68 #include <linux/nmi.h>
69 #include <linux/psi.h>
71 #include <asm/sections.h>
72 #include <asm/tlbflush.h>
73 #include <asm/div64.h>
76 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
77 static DEFINE_MUTEX(pcp_batch_high_lock
);
78 #define MIN_PERCPU_PAGELIST_FRACTION (8)
80 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
81 DEFINE_PER_CPU(int, numa_node
);
82 EXPORT_PER_CPU_SYMBOL(numa_node
);
85 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key
);
87 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
89 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
90 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
91 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
92 * defined in <linux/topology.h>.
94 DEFINE_PER_CPU(int, _numa_mem_
); /* Kernel "local memory" node */
95 EXPORT_PER_CPU_SYMBOL(_numa_mem_
);
96 int _node_numa_mem_
[MAX_NUMNODES
];
99 /* work_structs for global per-cpu drains */
102 struct work_struct work
;
104 DEFINE_MUTEX(pcpu_drain_mutex
);
105 DEFINE_PER_CPU(struct pcpu_drain
, pcpu_drain
);
107 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
108 volatile unsigned long latent_entropy __latent_entropy
;
109 EXPORT_SYMBOL(latent_entropy
);
113 * Array of node states.
115 nodemask_t node_states
[NR_NODE_STATES
] __read_mostly
= {
116 [N_POSSIBLE
] = NODE_MASK_ALL
,
117 [N_ONLINE
] = { { [0] = 1UL } },
119 [N_NORMAL_MEMORY
] = { { [0] = 1UL } },
120 #ifdef CONFIG_HIGHMEM
121 [N_HIGH_MEMORY
] = { { [0] = 1UL } },
123 [N_MEMORY
] = { { [0] = 1UL } },
124 [N_CPU
] = { { [0] = 1UL } },
127 EXPORT_SYMBOL(node_states
);
129 atomic_long_t _totalram_pages __read_mostly
;
130 EXPORT_SYMBOL(_totalram_pages
);
131 unsigned long totalreserve_pages __read_mostly
;
132 unsigned long totalcma_pages __read_mostly
;
134 int percpu_pagelist_fraction
;
135 gfp_t gfp_allowed_mask __read_mostly
= GFP_BOOT_MASK
;
138 * A cached value of the page's pageblock's migratetype, used when the page is
139 * put on a pcplist. Used to avoid the pageblock migratetype lookup when
140 * freeing from pcplists in most cases, at the cost of possibly becoming stale.
141 * Also the migratetype set in the page does not necessarily match the pcplist
142 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
143 * other index - this ensures that it will be put on the correct CMA freelist.
145 static inline int get_pcppage_migratetype(struct page
*page
)
150 static inline void set_pcppage_migratetype(struct page
*page
, int migratetype
)
152 page
->index
= migratetype
;
155 #ifdef CONFIG_PM_SLEEP
157 * The following functions are used by the suspend/hibernate code to temporarily
158 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
159 * while devices are suspended. To avoid races with the suspend/hibernate code,
160 * they should always be called with system_transition_mutex held
161 * (gfp_allowed_mask also should only be modified with system_transition_mutex
162 * held, unless the suspend/hibernate code is guaranteed not to run in parallel
163 * with that modification).
166 static gfp_t saved_gfp_mask
;
168 void pm_restore_gfp_mask(void)
170 WARN_ON(!mutex_is_locked(&system_transition_mutex
));
171 if (saved_gfp_mask
) {
172 gfp_allowed_mask
= saved_gfp_mask
;
177 void pm_restrict_gfp_mask(void)
179 WARN_ON(!mutex_is_locked(&system_transition_mutex
));
180 WARN_ON(saved_gfp_mask
);
181 saved_gfp_mask
= gfp_allowed_mask
;
182 gfp_allowed_mask
&= ~(__GFP_IO
| __GFP_FS
);
185 bool pm_suspended_storage(void)
187 if ((gfp_allowed_mask
& (__GFP_IO
| __GFP_FS
)) == (__GFP_IO
| __GFP_FS
))
191 #endif /* CONFIG_PM_SLEEP */
193 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
194 unsigned int pageblock_order __read_mostly
;
197 static void __free_pages_ok(struct page
*page
, unsigned int order
);
200 * results with 256, 32 in the lowmem_reserve sysctl:
201 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
202 * 1G machine -> (16M dma, 784M normal, 224M high)
203 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
204 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
205 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
207 * TBD: should special case ZONE_DMA32 machines here - in those we normally
208 * don't need any ZONE_NORMAL reservation
210 int sysctl_lowmem_reserve_ratio
[MAX_NR_ZONES
] = {
211 #ifdef CONFIG_ZONE_DMA
214 #ifdef CONFIG_ZONE_DMA32
218 #ifdef CONFIG_HIGHMEM
224 EXPORT_SYMBOL(totalram_pages
);
226 static char * const zone_names
[MAX_NR_ZONES
] = {
227 #ifdef CONFIG_ZONE_DMA
230 #ifdef CONFIG_ZONE_DMA32
234 #ifdef CONFIG_HIGHMEM
238 #ifdef CONFIG_ZONE_DEVICE
243 const char * const migratetype_names
[MIGRATE_TYPES
] = {
251 #ifdef CONFIG_MEMORY_ISOLATION
256 compound_page_dtor
* const compound_page_dtors
[] = {
259 #ifdef CONFIG_HUGETLB_PAGE
262 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
267 int min_free_kbytes
= 1024;
268 int user_min_free_kbytes
= -1;
269 #ifdef CONFIG_DISCONTIGMEM
271 * DiscontigMem defines memory ranges as separate pg_data_t even if the ranges
272 * are not on separate NUMA nodes. Functionally this works but with
273 * watermark_boost_factor, it can reclaim prematurely as the ranges can be
274 * quite small. By default, do not boost watermarks on discontigmem as in
275 * many cases very high-order allocations like THP are likely to be
276 * unsupported and the premature reclaim offsets the advantage of long-term
277 * fragmentation avoidance.
279 int watermark_boost_factor __read_mostly
;
281 int watermark_boost_factor __read_mostly
= 15000;
283 int watermark_scale_factor
= 10;
285 static unsigned long nr_kernel_pages __initdata
;
286 static unsigned long nr_all_pages __initdata
;
287 static unsigned long dma_reserve __initdata
;
289 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
290 static unsigned long arch_zone_lowest_possible_pfn
[MAX_NR_ZONES
] __initdata
;
291 static unsigned long arch_zone_highest_possible_pfn
[MAX_NR_ZONES
] __initdata
;
292 static unsigned long required_kernelcore __initdata
;
293 static unsigned long required_kernelcore_percent __initdata
;
294 static unsigned long required_movablecore __initdata
;
295 static unsigned long required_movablecore_percent __initdata
;
296 static unsigned long zone_movable_pfn
[MAX_NUMNODES
] __initdata
;
297 static bool mirrored_kernelcore __meminitdata
;
299 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
301 EXPORT_SYMBOL(movable_zone
);
302 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
305 int nr_node_ids __read_mostly
= MAX_NUMNODES
;
306 int nr_online_nodes __read_mostly
= 1;
307 EXPORT_SYMBOL(nr_node_ids
);
308 EXPORT_SYMBOL(nr_online_nodes
);
311 int page_group_by_mobility_disabled __read_mostly
;
313 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
315 * During boot we initialize deferred pages on-demand, as needed, but once
316 * page_alloc_init_late() has finished, the deferred pages are all initialized,
317 * and we can permanently disable that path.
319 static DEFINE_STATIC_KEY_TRUE(deferred_pages
);
322 * Calling kasan_free_pages() only after deferred memory initialization
323 * has completed. Poisoning pages during deferred memory init will greatly
324 * lengthen the process and cause problem in large memory systems as the
325 * deferred pages initialization is done with interrupt disabled.
327 * Assuming that there will be no reference to those newly initialized
328 * pages before they are ever allocated, this should have no effect on
329 * KASAN memory tracking as the poison will be properly inserted at page
330 * allocation time. The only corner case is when pages are allocated by
331 * on-demand allocation and then freed again before the deferred pages
332 * initialization is done, but this is not likely to happen.
334 static inline void kasan_free_nondeferred_pages(struct page
*page
, int order
)
336 if (!static_branch_unlikely(&deferred_pages
))
337 kasan_free_pages(page
, order
);
340 /* Returns true if the struct page for the pfn is uninitialised */
341 static inline bool __meminit
early_page_uninitialised(unsigned long pfn
)
343 int nid
= early_pfn_to_nid(pfn
);
345 if (node_online(nid
) && pfn
>= NODE_DATA(nid
)->first_deferred_pfn
)
352 * Returns true when the remaining initialisation should be deferred until
353 * later in the boot cycle when it can be parallelised.
355 static bool __meminit
356 defer_init(int nid
, unsigned long pfn
, unsigned long end_pfn
)
358 static unsigned long prev_end_pfn
, nr_initialised
;
361 * prev_end_pfn static that contains the end of previous zone
362 * No need to protect because called very early in boot before smp_init.
364 if (prev_end_pfn
!= end_pfn
) {
365 prev_end_pfn
= end_pfn
;
369 /* Always populate low zones for address-constrained allocations */
370 if (end_pfn
< pgdat_end_pfn(NODE_DATA(nid
)))
374 * We start only with one section of pages, more pages are added as
375 * needed until the rest of deferred pages are initialized.
378 if ((nr_initialised
> PAGES_PER_SECTION
) &&
379 (pfn
& (PAGES_PER_SECTION
- 1)) == 0) {
380 NODE_DATA(nid
)->first_deferred_pfn
= pfn
;
386 #define kasan_free_nondeferred_pages(p, o) kasan_free_pages(p, o)
388 static inline bool early_page_uninitialised(unsigned long pfn
)
393 static inline bool defer_init(int nid
, unsigned long pfn
, unsigned long end_pfn
)
399 /* Return a pointer to the bitmap storing bits affecting a block of pages */
400 static inline unsigned long *get_pageblock_bitmap(struct page
*page
,
403 #ifdef CONFIG_SPARSEMEM
404 return __pfn_to_section(pfn
)->pageblock_flags
;
406 return page_zone(page
)->pageblock_flags
;
407 #endif /* CONFIG_SPARSEMEM */
410 static inline int pfn_to_bitidx(struct page
*page
, unsigned long pfn
)
412 #ifdef CONFIG_SPARSEMEM
413 pfn
&= (PAGES_PER_SECTION
-1);
414 return (pfn
>> pageblock_order
) * NR_PAGEBLOCK_BITS
;
416 pfn
= pfn
- round_down(page_zone(page
)->zone_start_pfn
, pageblock_nr_pages
);
417 return (pfn
>> pageblock_order
) * NR_PAGEBLOCK_BITS
;
418 #endif /* CONFIG_SPARSEMEM */
422 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
423 * @page: The page within the block of interest
424 * @pfn: The target page frame number
425 * @end_bitidx: The last bit of interest to retrieve
426 * @mask: mask of bits that the caller is interested in
428 * Return: pageblock_bits flags
430 static __always_inline
unsigned long __get_pfnblock_flags_mask(struct page
*page
,
432 unsigned long end_bitidx
,
435 unsigned long *bitmap
;
436 unsigned long bitidx
, word_bitidx
;
439 bitmap
= get_pageblock_bitmap(page
, pfn
);
440 bitidx
= pfn_to_bitidx(page
, pfn
);
441 word_bitidx
= bitidx
/ BITS_PER_LONG
;
442 bitidx
&= (BITS_PER_LONG
-1);
444 word
= bitmap
[word_bitidx
];
445 bitidx
+= end_bitidx
;
446 return (word
>> (BITS_PER_LONG
- bitidx
- 1)) & mask
;
449 unsigned long get_pfnblock_flags_mask(struct page
*page
, unsigned long pfn
,
450 unsigned long end_bitidx
,
453 return __get_pfnblock_flags_mask(page
, pfn
, end_bitidx
, mask
);
456 static __always_inline
int get_pfnblock_migratetype(struct page
*page
, unsigned long pfn
)
458 return __get_pfnblock_flags_mask(page
, pfn
, PB_migrate_end
, MIGRATETYPE_MASK
);
462 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
463 * @page: The page within the block of interest
464 * @flags: The flags to set
465 * @pfn: The target page frame number
466 * @end_bitidx: The last bit of interest
467 * @mask: mask of bits that the caller is interested in
469 void set_pfnblock_flags_mask(struct page
*page
, unsigned long flags
,
471 unsigned long end_bitidx
,
474 unsigned long *bitmap
;
475 unsigned long bitidx
, word_bitidx
;
476 unsigned long old_word
, word
;
478 BUILD_BUG_ON(NR_PAGEBLOCK_BITS
!= 4);
479 BUILD_BUG_ON(MIGRATE_TYPES
> (1 << PB_migratetype_bits
));
481 bitmap
= get_pageblock_bitmap(page
, pfn
);
482 bitidx
= pfn_to_bitidx(page
, pfn
);
483 word_bitidx
= bitidx
/ BITS_PER_LONG
;
484 bitidx
&= (BITS_PER_LONG
-1);
486 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page
), pfn
), page
);
488 bitidx
+= end_bitidx
;
489 mask
<<= (BITS_PER_LONG
- bitidx
- 1);
490 flags
<<= (BITS_PER_LONG
- bitidx
- 1);
492 word
= READ_ONCE(bitmap
[word_bitidx
]);
494 old_word
= cmpxchg(&bitmap
[word_bitidx
], word
, (word
& ~mask
) | flags
);
495 if (word
== old_word
)
501 void set_pageblock_migratetype(struct page
*page
, int migratetype
)
503 if (unlikely(page_group_by_mobility_disabled
&&
504 migratetype
< MIGRATE_PCPTYPES
))
505 migratetype
= MIGRATE_UNMOVABLE
;
507 set_pageblock_flags_group(page
, (unsigned long)migratetype
,
508 PB_migrate
, PB_migrate_end
);
511 #ifdef CONFIG_DEBUG_VM
512 static int page_outside_zone_boundaries(struct zone
*zone
, struct page
*page
)
516 unsigned long pfn
= page_to_pfn(page
);
517 unsigned long sp
, start_pfn
;
520 seq
= zone_span_seqbegin(zone
);
521 start_pfn
= zone
->zone_start_pfn
;
522 sp
= zone
->spanned_pages
;
523 if (!zone_spans_pfn(zone
, pfn
))
525 } while (zone_span_seqretry(zone
, seq
));
528 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
529 pfn
, zone_to_nid(zone
), zone
->name
,
530 start_pfn
, start_pfn
+ sp
);
535 static int page_is_consistent(struct zone
*zone
, struct page
*page
)
537 if (!pfn_valid_within(page_to_pfn(page
)))
539 if (zone
!= page_zone(page
))
545 * Temporary debugging check for pages not lying within a given zone.
547 static int __maybe_unused
bad_range(struct zone
*zone
, struct page
*page
)
549 if (page_outside_zone_boundaries(zone
, page
))
551 if (!page_is_consistent(zone
, page
))
557 static inline int __maybe_unused
bad_range(struct zone
*zone
, struct page
*page
)
563 static void bad_page(struct page
*page
, const char *reason
,
564 unsigned long bad_flags
)
566 static unsigned long resume
;
567 static unsigned long nr_shown
;
568 static unsigned long nr_unshown
;
571 * Allow a burst of 60 reports, then keep quiet for that minute;
572 * or allow a steady drip of one report per second.
574 if (nr_shown
== 60) {
575 if (time_before(jiffies
, resume
)) {
581 "BUG: Bad page state: %lu messages suppressed\n",
588 resume
= jiffies
+ 60 * HZ
;
590 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
591 current
->comm
, page_to_pfn(page
));
592 __dump_page(page
, reason
);
593 bad_flags
&= page
->flags
;
595 pr_alert("bad because of flags: %#lx(%pGp)\n",
596 bad_flags
, &bad_flags
);
597 dump_page_owner(page
);
602 /* Leave bad fields for debug, except PageBuddy could make trouble */
603 page_mapcount_reset(page
); /* remove PageBuddy */
604 add_taint(TAINT_BAD_PAGE
, LOCKDEP_NOW_UNRELIABLE
);
608 * Higher-order pages are called "compound pages". They are structured thusly:
610 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
612 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
613 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
615 * The first tail page's ->compound_dtor holds the offset in array of compound
616 * page destructors. See compound_page_dtors.
618 * The first tail page's ->compound_order holds the order of allocation.
619 * This usage means that zero-order pages may not be compound.
622 void free_compound_page(struct page
*page
)
624 __free_pages_ok(page
, compound_order(page
));
627 void prep_compound_page(struct page
*page
, unsigned int order
)
630 int nr_pages
= 1 << order
;
632 set_compound_page_dtor(page
, COMPOUND_PAGE_DTOR
);
633 set_compound_order(page
, order
);
635 for (i
= 1; i
< nr_pages
; i
++) {
636 struct page
*p
= page
+ i
;
637 set_page_count(p
, 0);
638 p
->mapping
= TAIL_MAPPING
;
639 set_compound_head(p
, page
);
641 atomic_set(compound_mapcount_ptr(page
), -1);
644 #ifdef CONFIG_DEBUG_PAGEALLOC
645 unsigned int _debug_guardpage_minorder
;
646 bool _debug_pagealloc_enabled __read_mostly
647 = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT
);
648 EXPORT_SYMBOL(_debug_pagealloc_enabled
);
649 bool _debug_guardpage_enabled __read_mostly
;
651 static int __init
early_debug_pagealloc(char *buf
)
655 return kstrtobool(buf
, &_debug_pagealloc_enabled
);
657 early_param("debug_pagealloc", early_debug_pagealloc
);
659 static bool need_debug_guardpage(void)
661 /* If we don't use debug_pagealloc, we don't need guard page */
662 if (!debug_pagealloc_enabled())
665 if (!debug_guardpage_minorder())
671 static void init_debug_guardpage(void)
673 if (!debug_pagealloc_enabled())
676 if (!debug_guardpage_minorder())
679 _debug_guardpage_enabled
= true;
682 struct page_ext_operations debug_guardpage_ops
= {
683 .need
= need_debug_guardpage
,
684 .init
= init_debug_guardpage
,
687 static int __init
debug_guardpage_minorder_setup(char *buf
)
691 if (kstrtoul(buf
, 10, &res
) < 0 || res
> MAX_ORDER
/ 2) {
692 pr_err("Bad debug_guardpage_minorder value\n");
695 _debug_guardpage_minorder
= res
;
696 pr_info("Setting debug_guardpage_minorder to %lu\n", res
);
699 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup
);
701 static inline bool set_page_guard(struct zone
*zone
, struct page
*page
,
702 unsigned int order
, int migratetype
)
704 struct page_ext
*page_ext
;
706 if (!debug_guardpage_enabled())
709 if (order
>= debug_guardpage_minorder())
712 page_ext
= lookup_page_ext(page
);
713 if (unlikely(!page_ext
))
716 __set_bit(PAGE_EXT_DEBUG_GUARD
, &page_ext
->flags
);
718 INIT_LIST_HEAD(&page
->lru
);
719 set_page_private(page
, order
);
720 /* Guard pages are not available for any usage */
721 __mod_zone_freepage_state(zone
, -(1 << order
), migratetype
);
726 static inline void clear_page_guard(struct zone
*zone
, struct page
*page
,
727 unsigned int order
, int migratetype
)
729 struct page_ext
*page_ext
;
731 if (!debug_guardpage_enabled())
734 page_ext
= lookup_page_ext(page
);
735 if (unlikely(!page_ext
))
738 __clear_bit(PAGE_EXT_DEBUG_GUARD
, &page_ext
->flags
);
740 set_page_private(page
, 0);
741 if (!is_migrate_isolate(migratetype
))
742 __mod_zone_freepage_state(zone
, (1 << order
), migratetype
);
745 struct page_ext_operations debug_guardpage_ops
;
746 static inline bool set_page_guard(struct zone
*zone
, struct page
*page
,
747 unsigned int order
, int migratetype
) { return false; }
748 static inline void clear_page_guard(struct zone
*zone
, struct page
*page
,
749 unsigned int order
, int migratetype
) {}
752 static inline void set_page_order(struct page
*page
, unsigned int order
)
754 set_page_private(page
, order
);
755 __SetPageBuddy(page
);
758 static inline void rmv_page_order(struct page
*page
)
760 __ClearPageBuddy(page
);
761 set_page_private(page
, 0);
765 * This function checks whether a page is free && is the buddy
766 * we can coalesce a page and its buddy if
767 * (a) the buddy is not in a hole (check before calling!) &&
768 * (b) the buddy is in the buddy system &&
769 * (c) a page and its buddy have the same order &&
770 * (d) a page and its buddy are in the same zone.
772 * For recording whether a page is in the buddy system, we set PageBuddy.
773 * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
775 * For recording page's order, we use page_private(page).
777 static inline int page_is_buddy(struct page
*page
, struct page
*buddy
,
780 if (page_is_guard(buddy
) && page_order(buddy
) == order
) {
781 if (page_zone_id(page
) != page_zone_id(buddy
))
784 VM_BUG_ON_PAGE(page_count(buddy
) != 0, buddy
);
789 if (PageBuddy(buddy
) && page_order(buddy
) == order
) {
791 * zone check is done late to avoid uselessly
792 * calculating zone/node ids for pages that could
795 if (page_zone_id(page
) != page_zone_id(buddy
))
798 VM_BUG_ON_PAGE(page_count(buddy
) != 0, buddy
);
806 * Freeing function for a buddy system allocator.
808 * The concept of a buddy system is to maintain direct-mapped table
809 * (containing bit values) for memory blocks of various "orders".
810 * The bottom level table contains the map for the smallest allocatable
811 * units of memory (here, pages), and each level above it describes
812 * pairs of units from the levels below, hence, "buddies".
813 * At a high level, all that happens here is marking the table entry
814 * at the bottom level available, and propagating the changes upward
815 * as necessary, plus some accounting needed to play nicely with other
816 * parts of the VM system.
817 * At each level, we keep a list of pages, which are heads of continuous
818 * free pages of length of (1 << order) and marked with PageBuddy.
819 * Page's order is recorded in page_private(page) field.
820 * So when we are allocating or freeing one, we can derive the state of the
821 * other. That is, if we allocate a small block, and both were
822 * free, the remainder of the region must be split into blocks.
823 * If a block is freed, and its buddy is also free, then this
824 * triggers coalescing into a block of larger size.
829 static inline void __free_one_page(struct page
*page
,
831 struct zone
*zone
, unsigned int order
,
834 unsigned long combined_pfn
;
835 unsigned long uninitialized_var(buddy_pfn
);
837 unsigned int max_order
;
839 max_order
= min_t(unsigned int, MAX_ORDER
, pageblock_order
+ 1);
841 VM_BUG_ON(!zone_is_initialized(zone
));
842 VM_BUG_ON_PAGE(page
->flags
& PAGE_FLAGS_CHECK_AT_PREP
, page
);
844 VM_BUG_ON(migratetype
== -1);
845 if (likely(!is_migrate_isolate(migratetype
)))
846 __mod_zone_freepage_state(zone
, 1 << order
, migratetype
);
848 VM_BUG_ON_PAGE(pfn
& ((1 << order
) - 1), page
);
849 VM_BUG_ON_PAGE(bad_range(zone
, page
), page
);
852 while (order
< max_order
- 1) {
853 buddy_pfn
= __find_buddy_pfn(pfn
, order
);
854 buddy
= page
+ (buddy_pfn
- pfn
);
856 if (!pfn_valid_within(buddy_pfn
))
858 if (!page_is_buddy(page
, buddy
, order
))
861 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
862 * merge with it and move up one order.
864 if (page_is_guard(buddy
)) {
865 clear_page_guard(zone
, buddy
, order
, migratetype
);
867 list_del(&buddy
->lru
);
868 zone
->free_area
[order
].nr_free
--;
869 rmv_page_order(buddy
);
871 combined_pfn
= buddy_pfn
& pfn
;
872 page
= page
+ (combined_pfn
- pfn
);
876 if (max_order
< MAX_ORDER
) {
877 /* If we are here, it means order is >= pageblock_order.
878 * We want to prevent merge between freepages on isolate
879 * pageblock and normal pageblock. Without this, pageblock
880 * isolation could cause incorrect freepage or CMA accounting.
882 * We don't want to hit this code for the more frequent
885 if (unlikely(has_isolate_pageblock(zone
))) {
888 buddy_pfn
= __find_buddy_pfn(pfn
, order
);
889 buddy
= page
+ (buddy_pfn
- pfn
);
890 buddy_mt
= get_pageblock_migratetype(buddy
);
892 if (migratetype
!= buddy_mt
893 && (is_migrate_isolate(migratetype
) ||
894 is_migrate_isolate(buddy_mt
)))
898 goto continue_merging
;
902 set_page_order(page
, order
);
905 * If this is not the largest possible page, check if the buddy
906 * of the next-highest order is free. If it is, it's possible
907 * that pages are being freed that will coalesce soon. In case,
908 * that is happening, add the free page to the tail of the list
909 * so it's less likely to be used soon and more likely to be merged
910 * as a higher order page
912 if ((order
< MAX_ORDER
-2) && pfn_valid_within(buddy_pfn
)) {
913 struct page
*higher_page
, *higher_buddy
;
914 combined_pfn
= buddy_pfn
& pfn
;
915 higher_page
= page
+ (combined_pfn
- pfn
);
916 buddy_pfn
= __find_buddy_pfn(combined_pfn
, order
+ 1);
917 higher_buddy
= higher_page
+ (buddy_pfn
- combined_pfn
);
918 if (pfn_valid_within(buddy_pfn
) &&
919 page_is_buddy(higher_page
, higher_buddy
, order
+ 1)) {
920 list_add_tail(&page
->lru
,
921 &zone
->free_area
[order
].free_list
[migratetype
]);
926 list_add(&page
->lru
, &zone
->free_area
[order
].free_list
[migratetype
]);
928 zone
->free_area
[order
].nr_free
++;
932 * A bad page could be due to a number of fields. Instead of multiple branches,
933 * try and check multiple fields with one check. The caller must do a detailed
934 * check if necessary.
936 static inline bool page_expected_state(struct page
*page
,
937 unsigned long check_flags
)
939 if (unlikely(atomic_read(&page
->_mapcount
) != -1))
942 if (unlikely((unsigned long)page
->mapping
|
943 page_ref_count(page
) |
945 (unsigned long)page
->mem_cgroup
|
947 (page
->flags
& check_flags
)))
953 static void free_pages_check_bad(struct page
*page
)
955 const char *bad_reason
;
956 unsigned long bad_flags
;
961 if (unlikely(atomic_read(&page
->_mapcount
) != -1))
962 bad_reason
= "nonzero mapcount";
963 if (unlikely(page
->mapping
!= NULL
))
964 bad_reason
= "non-NULL mapping";
965 if (unlikely(page_ref_count(page
) != 0))
966 bad_reason
= "nonzero _refcount";
967 if (unlikely(page
->flags
& PAGE_FLAGS_CHECK_AT_FREE
)) {
968 bad_reason
= "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
969 bad_flags
= PAGE_FLAGS_CHECK_AT_FREE
;
972 if (unlikely(page
->mem_cgroup
))
973 bad_reason
= "page still charged to cgroup";
975 bad_page(page
, bad_reason
, bad_flags
);
978 static inline int free_pages_check(struct page
*page
)
980 if (likely(page_expected_state(page
, PAGE_FLAGS_CHECK_AT_FREE
)))
983 /* Something has gone sideways, find it */
984 free_pages_check_bad(page
);
988 static int free_tail_pages_check(struct page
*head_page
, struct page
*page
)
993 * We rely page->lru.next never has bit 0 set, unless the page
994 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
996 BUILD_BUG_ON((unsigned long)LIST_POISON1
& 1);
998 if (!IS_ENABLED(CONFIG_DEBUG_VM
)) {
1002 switch (page
- head_page
) {
1004 /* the first tail page: ->mapping may be compound_mapcount() */
1005 if (unlikely(compound_mapcount(page
))) {
1006 bad_page(page
, "nonzero compound_mapcount", 0);
1012 * the second tail page: ->mapping is
1013 * deferred_list.next -- ignore value.
1017 if (page
->mapping
!= TAIL_MAPPING
) {
1018 bad_page(page
, "corrupted mapping in tail page", 0);
1023 if (unlikely(!PageTail(page
))) {
1024 bad_page(page
, "PageTail not set", 0);
1027 if (unlikely(compound_head(page
) != head_page
)) {
1028 bad_page(page
, "compound_head not consistent", 0);
1033 page
->mapping
= NULL
;
1034 clear_compound_head(page
);
1038 static __always_inline
bool free_pages_prepare(struct page
*page
,
1039 unsigned int order
, bool check_free
)
1043 VM_BUG_ON_PAGE(PageTail(page
), page
);
1045 trace_mm_page_free(page
, order
);
1048 * Check tail pages before head page information is cleared to
1049 * avoid checking PageCompound for order-0 pages.
1051 if (unlikely(order
)) {
1052 bool compound
= PageCompound(page
);
1055 VM_BUG_ON_PAGE(compound
&& compound_order(page
) != order
, page
);
1058 ClearPageDoubleMap(page
);
1059 for (i
= 1; i
< (1 << order
); i
++) {
1061 bad
+= free_tail_pages_check(page
, page
+ i
);
1062 if (unlikely(free_pages_check(page
+ i
))) {
1066 (page
+ i
)->flags
&= ~PAGE_FLAGS_CHECK_AT_PREP
;
1069 if (PageMappingFlags(page
))
1070 page
->mapping
= NULL
;
1071 if (memcg_kmem_enabled() && PageKmemcg(page
))
1072 memcg_kmem_uncharge(page
, order
);
1074 bad
+= free_pages_check(page
);
1078 page_cpupid_reset_last(page
);
1079 page
->flags
&= ~PAGE_FLAGS_CHECK_AT_PREP
;
1080 reset_page_owner(page
, order
);
1082 if (!PageHighMem(page
)) {
1083 debug_check_no_locks_freed(page_address(page
),
1084 PAGE_SIZE
<< order
);
1085 debug_check_no_obj_freed(page_address(page
),
1086 PAGE_SIZE
<< order
);
1088 arch_free_page(page
, order
);
1089 kernel_poison_pages(page
, 1 << order
, 0);
1090 kernel_map_pages(page
, 1 << order
, 0);
1091 kasan_free_nondeferred_pages(page
, order
);
1096 #ifdef CONFIG_DEBUG_VM
1097 static inline bool free_pcp_prepare(struct page
*page
)
1099 return free_pages_prepare(page
, 0, true);
1102 static inline bool bulkfree_pcp_prepare(struct page
*page
)
1107 static bool free_pcp_prepare(struct page
*page
)
1109 return free_pages_prepare(page
, 0, false);
1112 static bool bulkfree_pcp_prepare(struct page
*page
)
1114 return free_pages_check(page
);
1116 #endif /* CONFIG_DEBUG_VM */
1118 static inline void prefetch_buddy(struct page
*page
)
1120 unsigned long pfn
= page_to_pfn(page
);
1121 unsigned long buddy_pfn
= __find_buddy_pfn(pfn
, 0);
1122 struct page
*buddy
= page
+ (buddy_pfn
- pfn
);
1128 * Frees a number of pages from the PCP lists
1129 * Assumes all pages on list are in same zone, and of same order.
1130 * count is the number of pages to free.
1132 * If the zone was previously in an "all pages pinned" state then look to
1133 * see if this freeing clears that state.
1135 * And clear the zone's pages_scanned counter, to hold off the "all pages are
1136 * pinned" detection logic.
1138 static void free_pcppages_bulk(struct zone
*zone
, int count
,
1139 struct per_cpu_pages
*pcp
)
1141 int migratetype
= 0;
1143 int prefetch_nr
= 0;
1144 bool isolated_pageblocks
;
1145 struct page
*page
, *tmp
;
1149 struct list_head
*list
;
1152 * Remove pages from lists in a round-robin fashion. A
1153 * batch_free count is maintained that is incremented when an
1154 * empty list is encountered. This is so more pages are freed
1155 * off fuller lists instead of spinning excessively around empty
1160 if (++migratetype
== MIGRATE_PCPTYPES
)
1162 list
= &pcp
->lists
[migratetype
];
1163 } while (list_empty(list
));
1165 /* This is the only non-empty list. Free them all. */
1166 if (batch_free
== MIGRATE_PCPTYPES
)
1170 page
= list_last_entry(list
, struct page
, lru
);
1171 /* must delete to avoid corrupting pcp list */
1172 list_del(&page
->lru
);
1175 if (bulkfree_pcp_prepare(page
))
1178 list_add_tail(&page
->lru
, &head
);
1181 * We are going to put the page back to the global
1182 * pool, prefetch its buddy to speed up later access
1183 * under zone->lock. It is believed the overhead of
1184 * an additional test and calculating buddy_pfn here
1185 * can be offset by reduced memory latency later. To
1186 * avoid excessive prefetching due to large count, only
1187 * prefetch buddy for the first pcp->batch nr of pages.
1189 if (prefetch_nr
++ < pcp
->batch
)
1190 prefetch_buddy(page
);
1191 } while (--count
&& --batch_free
&& !list_empty(list
));
1194 spin_lock(&zone
->lock
);
1195 isolated_pageblocks
= has_isolate_pageblock(zone
);
1198 * Use safe version since after __free_one_page(),
1199 * page->lru.next will not point to original list.
1201 list_for_each_entry_safe(page
, tmp
, &head
, lru
) {
1202 int mt
= get_pcppage_migratetype(page
);
1203 /* MIGRATE_ISOLATE page should not go to pcplists */
1204 VM_BUG_ON_PAGE(is_migrate_isolate(mt
), page
);
1205 /* Pageblock could have been isolated meanwhile */
1206 if (unlikely(isolated_pageblocks
))
1207 mt
= get_pageblock_migratetype(page
);
1209 __free_one_page(page
, page_to_pfn(page
), zone
, 0, mt
);
1210 trace_mm_page_pcpu_drain(page
, 0, mt
);
1212 spin_unlock(&zone
->lock
);
1215 static void free_one_page(struct zone
*zone
,
1216 struct page
*page
, unsigned long pfn
,
1220 spin_lock(&zone
->lock
);
1221 if (unlikely(has_isolate_pageblock(zone
) ||
1222 is_migrate_isolate(migratetype
))) {
1223 migratetype
= get_pfnblock_migratetype(page
, pfn
);
1225 __free_one_page(page
, pfn
, zone
, order
, migratetype
);
1226 spin_unlock(&zone
->lock
);
1229 static void __meminit
__init_single_page(struct page
*page
, unsigned long pfn
,
1230 unsigned long zone
, int nid
)
1232 mm_zero_struct_page(page
);
1233 set_page_links(page
, zone
, nid
, pfn
);
1234 init_page_count(page
);
1235 page_mapcount_reset(page
);
1236 page_cpupid_reset_last(page
);
1237 page_kasan_tag_reset(page
);
1239 INIT_LIST_HEAD(&page
->lru
);
1240 #ifdef WANT_PAGE_VIRTUAL
1241 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1242 if (!is_highmem_idx(zone
))
1243 set_page_address(page
, __va(pfn
<< PAGE_SHIFT
));
1247 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1248 static void __meminit
init_reserved_page(unsigned long pfn
)
1253 if (!early_page_uninitialised(pfn
))
1256 nid
= early_pfn_to_nid(pfn
);
1257 pgdat
= NODE_DATA(nid
);
1259 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
1260 struct zone
*zone
= &pgdat
->node_zones
[zid
];
1262 if (pfn
>= zone
->zone_start_pfn
&& pfn
< zone_end_pfn(zone
))
1265 __init_single_page(pfn_to_page(pfn
), pfn
, zid
, nid
);
1268 static inline void init_reserved_page(unsigned long pfn
)
1271 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1274 * Initialised pages do not have PageReserved set. This function is
1275 * called for each range allocated by the bootmem allocator and
1276 * marks the pages PageReserved. The remaining valid pages are later
1277 * sent to the buddy page allocator.
1279 void __meminit
reserve_bootmem_region(phys_addr_t start
, phys_addr_t end
)
1281 unsigned long start_pfn
= PFN_DOWN(start
);
1282 unsigned long end_pfn
= PFN_UP(end
);
1284 for (; start_pfn
< end_pfn
; start_pfn
++) {
1285 if (pfn_valid(start_pfn
)) {
1286 struct page
*page
= pfn_to_page(start_pfn
);
1288 init_reserved_page(start_pfn
);
1290 /* Avoid false-positive PageTail() */
1291 INIT_LIST_HEAD(&page
->lru
);
1294 * no need for atomic set_bit because the struct
1295 * page is not visible yet so nobody should
1298 __SetPageReserved(page
);
1303 static void __free_pages_ok(struct page
*page
, unsigned int order
)
1305 unsigned long flags
;
1307 unsigned long pfn
= page_to_pfn(page
);
1309 if (!free_pages_prepare(page
, order
, true))
1312 migratetype
= get_pfnblock_migratetype(page
, pfn
);
1313 local_irq_save(flags
);
1314 __count_vm_events(PGFREE
, 1 << order
);
1315 free_one_page(page_zone(page
), page
, pfn
, order
, migratetype
);
1316 local_irq_restore(flags
);
1319 static void __init
__free_pages_boot_core(struct page
*page
, unsigned int order
)
1321 unsigned int nr_pages
= 1 << order
;
1322 struct page
*p
= page
;
1326 for (loop
= 0; loop
< (nr_pages
- 1); loop
++, p
++) {
1328 __ClearPageReserved(p
);
1329 set_page_count(p
, 0);
1331 __ClearPageReserved(p
);
1332 set_page_count(p
, 0);
1334 atomic_long_add(nr_pages
, &page_zone(page
)->managed_pages
);
1335 set_page_refcounted(page
);
1336 __free_pages(page
, order
);
1339 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1340 defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1342 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata
;
1344 int __meminit
early_pfn_to_nid(unsigned long pfn
)
1346 static DEFINE_SPINLOCK(early_pfn_lock
);
1349 spin_lock(&early_pfn_lock
);
1350 nid
= __early_pfn_to_nid(pfn
, &early_pfnnid_cache
);
1352 nid
= first_online_node
;
1353 spin_unlock(&early_pfn_lock
);
1359 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1360 static inline bool __meminit __maybe_unused
1361 meminit_pfn_in_nid(unsigned long pfn
, int node
,
1362 struct mminit_pfnnid_cache
*state
)
1366 nid
= __early_pfn_to_nid(pfn
, state
);
1367 if (nid
>= 0 && nid
!= node
)
1372 /* Only safe to use early in boot when initialisation is single-threaded */
1373 static inline bool __meminit
early_pfn_in_nid(unsigned long pfn
, int node
)
1375 return meminit_pfn_in_nid(pfn
, node
, &early_pfnnid_cache
);
1380 static inline bool __meminit
early_pfn_in_nid(unsigned long pfn
, int node
)
1384 static inline bool __meminit __maybe_unused
1385 meminit_pfn_in_nid(unsigned long pfn
, int node
,
1386 struct mminit_pfnnid_cache
*state
)
1393 void __init
memblock_free_pages(struct page
*page
, unsigned long pfn
,
1396 if (early_page_uninitialised(pfn
))
1398 return __free_pages_boot_core(page
, order
);
1402 * Check that the whole (or subset of) a pageblock given by the interval of
1403 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1404 * with the migration of free compaction scanner. The scanners then need to
1405 * use only pfn_valid_within() check for arches that allow holes within
1408 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1410 * It's possible on some configurations to have a setup like node0 node1 node0
1411 * i.e. it's possible that all pages within a zones range of pages do not
1412 * belong to a single zone. We assume that a border between node0 and node1
1413 * can occur within a single pageblock, but not a node0 node1 node0
1414 * interleaving within a single pageblock. It is therefore sufficient to check
1415 * the first and last page of a pageblock and avoid checking each individual
1416 * page in a pageblock.
1418 struct page
*__pageblock_pfn_to_page(unsigned long start_pfn
,
1419 unsigned long end_pfn
, struct zone
*zone
)
1421 struct page
*start_page
;
1422 struct page
*end_page
;
1424 /* end_pfn is one past the range we are checking */
1427 if (!pfn_valid(start_pfn
) || !pfn_valid(end_pfn
))
1430 start_page
= pfn_to_online_page(start_pfn
);
1434 if (page_zone(start_page
) != zone
)
1437 end_page
= pfn_to_page(end_pfn
);
1439 /* This gives a shorter code than deriving page_zone(end_page) */
1440 if (page_zone_id(start_page
) != page_zone_id(end_page
))
1446 void set_zone_contiguous(struct zone
*zone
)
1448 unsigned long block_start_pfn
= zone
->zone_start_pfn
;
1449 unsigned long block_end_pfn
;
1451 block_end_pfn
= ALIGN(block_start_pfn
+ 1, pageblock_nr_pages
);
1452 for (; block_start_pfn
< zone_end_pfn(zone
);
1453 block_start_pfn
= block_end_pfn
,
1454 block_end_pfn
+= pageblock_nr_pages
) {
1456 block_end_pfn
= min(block_end_pfn
, zone_end_pfn(zone
));
1458 if (!__pageblock_pfn_to_page(block_start_pfn
,
1459 block_end_pfn
, zone
))
1463 /* We confirm that there is no hole */
1464 zone
->contiguous
= true;
1467 void clear_zone_contiguous(struct zone
*zone
)
1469 zone
->contiguous
= false;
1472 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1473 static void __init
deferred_free_range(unsigned long pfn
,
1474 unsigned long nr_pages
)
1482 page
= pfn_to_page(pfn
);
1484 /* Free a large naturally-aligned chunk if possible */
1485 if (nr_pages
== pageblock_nr_pages
&&
1486 (pfn
& (pageblock_nr_pages
- 1)) == 0) {
1487 set_pageblock_migratetype(page
, MIGRATE_MOVABLE
);
1488 __free_pages_boot_core(page
, pageblock_order
);
1492 for (i
= 0; i
< nr_pages
; i
++, page
++, pfn
++) {
1493 if ((pfn
& (pageblock_nr_pages
- 1)) == 0)
1494 set_pageblock_migratetype(page
, MIGRATE_MOVABLE
);
1495 __free_pages_boot_core(page
, 0);
1499 /* Completion tracking for deferred_init_memmap() threads */
1500 static atomic_t pgdat_init_n_undone __initdata
;
1501 static __initdata
DECLARE_COMPLETION(pgdat_init_all_done_comp
);
1503 static inline void __init
pgdat_init_report_one_done(void)
1505 if (atomic_dec_and_test(&pgdat_init_n_undone
))
1506 complete(&pgdat_init_all_done_comp
);
1510 * Returns true if page needs to be initialized or freed to buddy allocator.
1512 * First we check if pfn is valid on architectures where it is possible to have
1513 * holes within pageblock_nr_pages. On systems where it is not possible, this
1514 * function is optimized out.
1516 * Then, we check if a current large page is valid by only checking the validity
1519 * Finally, meminit_pfn_in_nid is checked on systems where pfns can interleave
1520 * within a node: a pfn is between start and end of a node, but does not belong
1521 * to this memory node.
1523 static inline bool __init
1524 deferred_pfn_valid(int nid
, unsigned long pfn
,
1525 struct mminit_pfnnid_cache
*nid_init_state
)
1527 if (!pfn_valid_within(pfn
))
1529 if (!(pfn
& (pageblock_nr_pages
- 1)) && !pfn_valid(pfn
))
1531 if (!meminit_pfn_in_nid(pfn
, nid
, nid_init_state
))
1537 * Free pages to buddy allocator. Try to free aligned pages in
1538 * pageblock_nr_pages sizes.
1540 static void __init
deferred_free_pages(int nid
, int zid
, unsigned long pfn
,
1541 unsigned long end_pfn
)
1543 struct mminit_pfnnid_cache nid_init_state
= { };
1544 unsigned long nr_pgmask
= pageblock_nr_pages
- 1;
1545 unsigned long nr_free
= 0;
1547 for (; pfn
< end_pfn
; pfn
++) {
1548 if (!deferred_pfn_valid(nid
, pfn
, &nid_init_state
)) {
1549 deferred_free_range(pfn
- nr_free
, nr_free
);
1551 } else if (!(pfn
& nr_pgmask
)) {
1552 deferred_free_range(pfn
- nr_free
, nr_free
);
1554 touch_nmi_watchdog();
1559 /* Free the last block of pages to allocator */
1560 deferred_free_range(pfn
- nr_free
, nr_free
);
1564 * Initialize struct pages. We minimize pfn page lookups and scheduler checks
1565 * by performing it only once every pageblock_nr_pages.
1566 * Return number of pages initialized.
1568 static unsigned long __init
deferred_init_pages(int nid
, int zid
,
1570 unsigned long end_pfn
)
1572 struct mminit_pfnnid_cache nid_init_state
= { };
1573 unsigned long nr_pgmask
= pageblock_nr_pages
- 1;
1574 unsigned long nr_pages
= 0;
1575 struct page
*page
= NULL
;
1577 for (; pfn
< end_pfn
; pfn
++) {
1578 if (!deferred_pfn_valid(nid
, pfn
, &nid_init_state
)) {
1581 } else if (!page
|| !(pfn
& nr_pgmask
)) {
1582 page
= pfn_to_page(pfn
);
1583 touch_nmi_watchdog();
1587 __init_single_page(page
, pfn
, zid
, nid
);
1593 /* Initialise remaining memory on a node */
1594 static int __init
deferred_init_memmap(void *data
)
1596 pg_data_t
*pgdat
= data
;
1597 int nid
= pgdat
->node_id
;
1598 unsigned long start
= jiffies
;
1599 unsigned long nr_pages
= 0;
1600 unsigned long spfn
, epfn
, first_init_pfn
, flags
;
1601 phys_addr_t spa
, epa
;
1604 const struct cpumask
*cpumask
= cpumask_of_node(pgdat
->node_id
);
1607 /* Bind memory initialisation thread to a local node if possible */
1608 if (!cpumask_empty(cpumask
))
1609 set_cpus_allowed_ptr(current
, cpumask
);
1611 pgdat_resize_lock(pgdat
, &flags
);
1612 first_init_pfn
= pgdat
->first_deferred_pfn
;
1613 if (first_init_pfn
== ULONG_MAX
) {
1614 pgdat_resize_unlock(pgdat
, &flags
);
1615 pgdat_init_report_one_done();
1619 /* Sanity check boundaries */
1620 BUG_ON(pgdat
->first_deferred_pfn
< pgdat
->node_start_pfn
);
1621 BUG_ON(pgdat
->first_deferred_pfn
> pgdat_end_pfn(pgdat
));
1622 pgdat
->first_deferred_pfn
= ULONG_MAX
;
1624 /* Only the highest zone is deferred so find it */
1625 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
1626 zone
= pgdat
->node_zones
+ zid
;
1627 if (first_init_pfn
< zone_end_pfn(zone
))
1630 first_init_pfn
= max(zone
->zone_start_pfn
, first_init_pfn
);
1633 * Initialize and free pages. We do it in two loops: first we initialize
1634 * struct page, than free to buddy allocator, because while we are
1635 * freeing pages we can access pages that are ahead (computing buddy
1636 * page in __free_one_page()).
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
));
1641 nr_pages
+= deferred_init_pages(nid
, zid
, spfn
, epfn
);
1643 for_each_free_mem_range(i
, nid
, MEMBLOCK_NONE
, &spa
, &epa
, NULL
) {
1644 spfn
= max_t(unsigned long, first_init_pfn
, PFN_UP(spa
));
1645 epfn
= min_t(unsigned long, zone_end_pfn(zone
), PFN_DOWN(epa
));
1646 deferred_free_pages(nid
, zid
, spfn
, epfn
);
1648 pgdat_resize_unlock(pgdat
, &flags
);
1650 /* Sanity check that the next zone really is unpopulated */
1651 WARN_ON(++zid
< MAX_NR_ZONES
&& populated_zone(++zone
));
1653 pr_info("node %d initialised, %lu pages in %ums\n", nid
, nr_pages
,
1654 jiffies_to_msecs(jiffies
- start
));
1656 pgdat_init_report_one_done();
1661 * If this zone has deferred pages, try to grow it by initializing enough
1662 * deferred pages to satisfy the allocation specified by order, rounded up to
1663 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
1664 * of SECTION_SIZE bytes by initializing struct pages in increments of
1665 * PAGES_PER_SECTION * sizeof(struct page) bytes.
1667 * Return true when zone was grown, otherwise return false. We return true even
1668 * when we grow less than requested, to let the caller decide if there are
1669 * enough pages to satisfy the allocation.
1671 * Note: We use noinline because this function is needed only during boot, and
1672 * it is called from a __ref function _deferred_grow_zone. This way we are
1673 * making sure that it is not inlined into permanent text section.
1675 static noinline
bool __init
1676 deferred_grow_zone(struct zone
*zone
, unsigned int order
)
1678 int zid
= zone_idx(zone
);
1679 int nid
= zone_to_nid(zone
);
1680 pg_data_t
*pgdat
= NODE_DATA(nid
);
1681 unsigned long nr_pages_needed
= ALIGN(1 << order
, PAGES_PER_SECTION
);
1682 unsigned long nr_pages
= 0;
1683 unsigned long first_init_pfn
, spfn
, epfn
, t
, flags
;
1684 unsigned long first_deferred_pfn
= pgdat
->first_deferred_pfn
;
1685 phys_addr_t spa
, epa
;
1688 /* Only the last zone may have deferred pages */
1689 if (zone_end_pfn(zone
) != pgdat_end_pfn(pgdat
))
1692 pgdat_resize_lock(pgdat
, &flags
);
1695 * If deferred pages have been initialized while we were waiting for
1696 * the lock, return true, as the zone was grown. The caller will retry
1697 * this zone. We won't return to this function since the caller also
1698 * has this static branch.
1700 if (!static_branch_unlikely(&deferred_pages
)) {
1701 pgdat_resize_unlock(pgdat
, &flags
);
1706 * If someone grew this zone while we were waiting for spinlock, return
1707 * true, as there might be enough pages already.
1709 if (first_deferred_pfn
!= pgdat
->first_deferred_pfn
) {
1710 pgdat_resize_unlock(pgdat
, &flags
);
1714 first_init_pfn
= max(zone
->zone_start_pfn
, first_deferred_pfn
);
1716 if (first_init_pfn
>= pgdat_end_pfn(pgdat
)) {
1717 pgdat_resize_unlock(pgdat
, &flags
);
1721 for_each_free_mem_range(i
, nid
, MEMBLOCK_NONE
, &spa
, &epa
, NULL
) {
1722 spfn
= max_t(unsigned long, first_init_pfn
, PFN_UP(spa
));
1723 epfn
= min_t(unsigned long, zone_end_pfn(zone
), PFN_DOWN(epa
));
1725 while (spfn
< epfn
&& nr_pages
< nr_pages_needed
) {
1726 t
= ALIGN(spfn
+ PAGES_PER_SECTION
, PAGES_PER_SECTION
);
1727 first_deferred_pfn
= min(t
, epfn
);
1728 nr_pages
+= deferred_init_pages(nid
, zid
, spfn
,
1729 first_deferred_pfn
);
1730 spfn
= first_deferred_pfn
;
1733 if (nr_pages
>= nr_pages_needed
)
1737 for_each_free_mem_range(i
, nid
, MEMBLOCK_NONE
, &spa
, &epa
, NULL
) {
1738 spfn
= max_t(unsigned long, first_init_pfn
, PFN_UP(spa
));
1739 epfn
= min_t(unsigned long, first_deferred_pfn
, PFN_DOWN(epa
));
1740 deferred_free_pages(nid
, zid
, spfn
, epfn
);
1742 if (first_deferred_pfn
== epfn
)
1745 pgdat
->first_deferred_pfn
= first_deferred_pfn
;
1746 pgdat_resize_unlock(pgdat
, &flags
);
1748 return nr_pages
> 0;
1752 * deferred_grow_zone() is __init, but it is called from
1753 * get_page_from_freelist() during early boot until deferred_pages permanently
1754 * disables this call. This is why we have refdata wrapper to avoid warning,
1755 * and to ensure that the function body gets unloaded.
1758 _deferred_grow_zone(struct zone
*zone
, unsigned int order
)
1760 return deferred_grow_zone(zone
, order
);
1763 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1765 void __init
page_alloc_init_late(void)
1769 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1772 /* There will be num_node_state(N_MEMORY) threads */
1773 atomic_set(&pgdat_init_n_undone
, num_node_state(N_MEMORY
));
1774 for_each_node_state(nid
, N_MEMORY
) {
1775 kthread_run(deferred_init_memmap
, NODE_DATA(nid
), "pgdatinit%d", nid
);
1778 /* Block until all are initialised */
1779 wait_for_completion(&pgdat_init_all_done_comp
);
1782 * We initialized the rest of the deferred pages. Permanently disable
1783 * on-demand struct page initialization.
1785 static_branch_disable(&deferred_pages
);
1787 /* Reinit limits that are based on free pages after the kernel is up */
1788 files_maxfiles_init();
1790 #ifdef CONFIG_ARCH_DISCARD_MEMBLOCK
1791 /* Discard memblock private memory */
1795 for_each_populated_zone(zone
)
1796 set_zone_contiguous(zone
);
1800 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
1801 void __init
init_cma_reserved_pageblock(struct page
*page
)
1803 unsigned i
= pageblock_nr_pages
;
1804 struct page
*p
= page
;
1807 __ClearPageReserved(p
);
1808 set_page_count(p
, 0);
1811 set_pageblock_migratetype(page
, MIGRATE_CMA
);
1813 if (pageblock_order
>= MAX_ORDER
) {
1814 i
= pageblock_nr_pages
;
1817 set_page_refcounted(p
);
1818 __free_pages(p
, MAX_ORDER
- 1);
1819 p
+= MAX_ORDER_NR_PAGES
;
1820 } while (i
-= MAX_ORDER_NR_PAGES
);
1822 set_page_refcounted(page
);
1823 __free_pages(page
, pageblock_order
);
1826 adjust_managed_page_count(page
, pageblock_nr_pages
);
1831 * The order of subdivision here is critical for the IO subsystem.
1832 * Please do not alter this order without good reasons and regression
1833 * testing. Specifically, as large blocks of memory are subdivided,
1834 * the order in which smaller blocks are delivered depends on the order
1835 * they're subdivided in this function. This is the primary factor
1836 * influencing the order in which pages are delivered to the IO
1837 * subsystem according to empirical testing, and this is also justified
1838 * by considering the behavior of a buddy system containing a single
1839 * large block of memory acted on by a series of small allocations.
1840 * This behavior is a critical factor in sglist merging's success.
1844 static inline void expand(struct zone
*zone
, struct page
*page
,
1845 int low
, int high
, struct free_area
*area
,
1848 unsigned long size
= 1 << high
;
1850 while (high
> low
) {
1854 VM_BUG_ON_PAGE(bad_range(zone
, &page
[size
]), &page
[size
]);
1857 * Mark as guard pages (or page), that will allow to
1858 * merge back to allocator when buddy will be freed.
1859 * Corresponding page table entries will not be touched,
1860 * pages will stay not present in virtual address space
1862 if (set_page_guard(zone
, &page
[size
], high
, migratetype
))
1865 list_add(&page
[size
].lru
, &area
->free_list
[migratetype
]);
1867 set_page_order(&page
[size
], high
);
1871 static void check_new_page_bad(struct page
*page
)
1873 const char *bad_reason
= NULL
;
1874 unsigned long bad_flags
= 0;
1876 if (unlikely(atomic_read(&page
->_mapcount
) != -1))
1877 bad_reason
= "nonzero mapcount";
1878 if (unlikely(page
->mapping
!= NULL
))
1879 bad_reason
= "non-NULL mapping";
1880 if (unlikely(page_ref_count(page
) != 0))
1881 bad_reason
= "nonzero _count";
1882 if (unlikely(page
->flags
& __PG_HWPOISON
)) {
1883 bad_reason
= "HWPoisoned (hardware-corrupted)";
1884 bad_flags
= __PG_HWPOISON
;
1885 /* Don't complain about hwpoisoned pages */
1886 page_mapcount_reset(page
); /* remove PageBuddy */
1889 if (unlikely(page
->flags
& PAGE_FLAGS_CHECK_AT_PREP
)) {
1890 bad_reason
= "PAGE_FLAGS_CHECK_AT_PREP flag set";
1891 bad_flags
= PAGE_FLAGS_CHECK_AT_PREP
;
1894 if (unlikely(page
->mem_cgroup
))
1895 bad_reason
= "page still charged to cgroup";
1897 bad_page(page
, bad_reason
, bad_flags
);
1901 * This page is about to be returned from the page allocator
1903 static inline int check_new_page(struct page
*page
)
1905 if (likely(page_expected_state(page
,
1906 PAGE_FLAGS_CHECK_AT_PREP
|__PG_HWPOISON
)))
1909 check_new_page_bad(page
);
1913 static inline bool free_pages_prezeroed(void)
1915 return IS_ENABLED(CONFIG_PAGE_POISONING_ZERO
) &&
1916 page_poisoning_enabled();
1919 #ifdef CONFIG_DEBUG_VM
1920 static bool check_pcp_refill(struct page
*page
)
1925 static bool check_new_pcp(struct page
*page
)
1927 return check_new_page(page
);
1930 static bool check_pcp_refill(struct page
*page
)
1932 return check_new_page(page
);
1934 static bool check_new_pcp(struct page
*page
)
1938 #endif /* CONFIG_DEBUG_VM */
1940 static bool check_new_pages(struct page
*page
, unsigned int order
)
1943 for (i
= 0; i
< (1 << order
); i
++) {
1944 struct page
*p
= page
+ i
;
1946 if (unlikely(check_new_page(p
)))
1953 inline void post_alloc_hook(struct page
*page
, unsigned int order
,
1956 set_page_private(page
, 0);
1957 set_page_refcounted(page
);
1959 arch_alloc_page(page
, order
);
1960 kernel_map_pages(page
, 1 << order
, 1);
1961 kasan_alloc_pages(page
, order
);
1962 kernel_poison_pages(page
, 1 << order
, 1);
1963 set_page_owner(page
, order
, gfp_flags
);
1966 static void prep_new_page(struct page
*page
, unsigned int order
, gfp_t gfp_flags
,
1967 unsigned int alloc_flags
)
1971 post_alloc_hook(page
, order
, gfp_flags
);
1973 if (!free_pages_prezeroed() && (gfp_flags
& __GFP_ZERO
))
1974 for (i
= 0; i
< (1 << order
); i
++)
1975 clear_highpage(page
+ i
);
1977 if (order
&& (gfp_flags
& __GFP_COMP
))
1978 prep_compound_page(page
, order
);
1981 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1982 * allocate the page. The expectation is that the caller is taking
1983 * steps that will free more memory. The caller should avoid the page
1984 * being used for !PFMEMALLOC purposes.
1986 if (alloc_flags
& ALLOC_NO_WATERMARKS
)
1987 set_page_pfmemalloc(page
);
1989 clear_page_pfmemalloc(page
);
1993 * Go through the free lists for the given migratetype and remove
1994 * the smallest available page from the freelists
1996 static __always_inline
1997 struct page
*__rmqueue_smallest(struct zone
*zone
, unsigned int order
,
2000 unsigned int current_order
;
2001 struct free_area
*area
;
2004 /* Find a page of the appropriate size in the preferred list */
2005 for (current_order
= order
; current_order
< MAX_ORDER
; ++current_order
) {
2006 area
= &(zone
->free_area
[current_order
]);
2007 page
= list_first_entry_or_null(&area
->free_list
[migratetype
],
2011 list_del(&page
->lru
);
2012 rmv_page_order(page
);
2014 expand(zone
, page
, order
, current_order
, area
, migratetype
);
2015 set_pcppage_migratetype(page
, migratetype
);
2024 * This array describes the order lists are fallen back to when
2025 * the free lists for the desirable migrate type are depleted
2027 static int fallbacks
[MIGRATE_TYPES
][4] = {
2028 [MIGRATE_UNMOVABLE
] = { MIGRATE_RECLAIMABLE
, MIGRATE_MOVABLE
, MIGRATE_TYPES
},
2029 [MIGRATE_MOVABLE
] = { MIGRATE_RECLAIMABLE
, MIGRATE_UNMOVABLE
, MIGRATE_TYPES
},
2030 [MIGRATE_RECLAIMABLE
] = { MIGRATE_UNMOVABLE
, MIGRATE_MOVABLE
, MIGRATE_TYPES
},
2032 [MIGRATE_CMA
] = { MIGRATE_TYPES
}, /* Never used */
2034 #ifdef CONFIG_MEMORY_ISOLATION
2035 [MIGRATE_ISOLATE
] = { MIGRATE_TYPES
}, /* Never used */
2040 static __always_inline
struct page
*__rmqueue_cma_fallback(struct zone
*zone
,
2043 return __rmqueue_smallest(zone
, order
, MIGRATE_CMA
);
2046 static inline struct page
*__rmqueue_cma_fallback(struct zone
*zone
,
2047 unsigned int order
) { return NULL
; }
2051 * Move the free pages in a range to the free lists of the requested type.
2052 * Note that start_page and end_pages are not aligned on a pageblock
2053 * boundary. If alignment is required, use move_freepages_block()
2055 static int move_freepages(struct zone
*zone
,
2056 struct page
*start_page
, struct page
*end_page
,
2057 int migratetype
, int *num_movable
)
2061 int pages_moved
= 0;
2063 #ifndef CONFIG_HOLES_IN_ZONE
2065 * page_zone is not safe to call in this context when
2066 * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant
2067 * anyway as we check zone boundaries in move_freepages_block().
2068 * Remove at a later date when no bug reports exist related to
2069 * grouping pages by mobility
2071 VM_BUG_ON(pfn_valid(page_to_pfn(start_page
)) &&
2072 pfn_valid(page_to_pfn(end_page
)) &&
2073 page_zone(start_page
) != page_zone(end_page
));
2075 for (page
= start_page
; page
<= end_page
;) {
2076 if (!pfn_valid_within(page_to_pfn(page
))) {
2081 /* Make sure we are not inadvertently changing nodes */
2082 VM_BUG_ON_PAGE(page_to_nid(page
) != zone_to_nid(zone
), page
);
2084 if (!PageBuddy(page
)) {
2086 * We assume that pages that could be isolated for
2087 * migration are movable. But we don't actually try
2088 * isolating, as that would be expensive.
2091 (PageLRU(page
) || __PageMovable(page
)))
2098 order
= page_order(page
);
2099 list_move(&page
->lru
,
2100 &zone
->free_area
[order
].free_list
[migratetype
]);
2102 pages_moved
+= 1 << order
;
2108 int move_freepages_block(struct zone
*zone
, struct page
*page
,
2109 int migratetype
, int *num_movable
)
2111 unsigned long start_pfn
, end_pfn
;
2112 struct page
*start_page
, *end_page
;
2117 start_pfn
= page_to_pfn(page
);
2118 start_pfn
= start_pfn
& ~(pageblock_nr_pages
-1);
2119 start_page
= pfn_to_page(start_pfn
);
2120 end_page
= start_page
+ pageblock_nr_pages
- 1;
2121 end_pfn
= start_pfn
+ pageblock_nr_pages
- 1;
2123 /* Do not cross zone boundaries */
2124 if (!zone_spans_pfn(zone
, start_pfn
))
2126 if (!zone_spans_pfn(zone
, end_pfn
))
2129 return move_freepages(zone
, start_page
, end_page
, migratetype
,
2133 static void change_pageblock_range(struct page
*pageblock_page
,
2134 int start_order
, int migratetype
)
2136 int nr_pageblocks
= 1 << (start_order
- pageblock_order
);
2138 while (nr_pageblocks
--) {
2139 set_pageblock_migratetype(pageblock_page
, migratetype
);
2140 pageblock_page
+= pageblock_nr_pages
;
2145 * When we are falling back to another migratetype during allocation, try to
2146 * steal extra free pages from the same pageblocks to satisfy further
2147 * allocations, instead of polluting multiple pageblocks.
2149 * If we are stealing a relatively large buddy page, it is likely there will
2150 * be more free pages in the pageblock, so try to steal them all. For
2151 * reclaimable and unmovable allocations, we steal regardless of page size,
2152 * as fragmentation caused by those allocations polluting movable pageblocks
2153 * is worse than movable allocations stealing from unmovable and reclaimable
2156 static bool can_steal_fallback(unsigned int order
, int start_mt
)
2159 * Leaving this order check is intended, although there is
2160 * relaxed order check in next check. The reason is that
2161 * we can actually steal whole pageblock if this condition met,
2162 * but, below check doesn't guarantee it and that is just heuristic
2163 * so could be changed anytime.
2165 if (order
>= pageblock_order
)
2168 if (order
>= pageblock_order
/ 2 ||
2169 start_mt
== MIGRATE_RECLAIMABLE
||
2170 start_mt
== MIGRATE_UNMOVABLE
||
2171 page_group_by_mobility_disabled
)
2177 static inline void boost_watermark(struct zone
*zone
)
2179 unsigned long max_boost
;
2181 if (!watermark_boost_factor
)
2184 max_boost
= mult_frac(zone
->_watermark
[WMARK_HIGH
],
2185 watermark_boost_factor
, 10000);
2188 * high watermark may be uninitialised if fragmentation occurs
2189 * very early in boot so do not boost. We do not fall
2190 * through and boost by pageblock_nr_pages as failing
2191 * allocations that early means that reclaim is not going
2192 * to help and it may even be impossible to reclaim the
2193 * boosted watermark resulting in a hang.
2198 max_boost
= max(pageblock_nr_pages
, max_boost
);
2200 zone
->watermark_boost
= min(zone
->watermark_boost
+ pageblock_nr_pages
,
2205 * This function implements actual steal behaviour. If order is large enough,
2206 * we can steal whole pageblock. If not, we first move freepages in this
2207 * pageblock to our migratetype and determine how many already-allocated pages
2208 * are there in the pageblock with a compatible migratetype. If at least half
2209 * of pages are free or compatible, we can change migratetype of the pageblock
2210 * itself, so pages freed in the future will be put on the correct free list.
2212 static void steal_suitable_fallback(struct zone
*zone
, struct page
*page
,
2213 unsigned int alloc_flags
, int start_type
, bool whole_block
)
2215 unsigned int current_order
= page_order(page
);
2216 struct free_area
*area
;
2217 int free_pages
, movable_pages
, alike_pages
;
2220 old_block_type
= get_pageblock_migratetype(page
);
2223 * This can happen due to races and we want to prevent broken
2224 * highatomic accounting.
2226 if (is_migrate_highatomic(old_block_type
))
2229 /* Take ownership for orders >= pageblock_order */
2230 if (current_order
>= pageblock_order
) {
2231 change_pageblock_range(page
, current_order
, start_type
);
2236 * Boost watermarks to increase reclaim pressure to reduce the
2237 * likelihood of future fallbacks. Wake kswapd now as the node
2238 * may be balanced overall and kswapd will not wake naturally.
2240 boost_watermark(zone
);
2241 if (alloc_flags
& ALLOC_KSWAPD
)
2242 set_bit(ZONE_BOOSTED_WATERMARK
, &zone
->flags
);
2244 /* We are not allowed to try stealing from the whole block */
2248 free_pages
= move_freepages_block(zone
, page
, start_type
,
2251 * Determine how many pages are compatible with our allocation.
2252 * For movable allocation, it's the number of movable pages which
2253 * we just obtained. For other types it's a bit more tricky.
2255 if (start_type
== MIGRATE_MOVABLE
) {
2256 alike_pages
= movable_pages
;
2259 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2260 * to MOVABLE pageblock, consider all non-movable pages as
2261 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2262 * vice versa, be conservative since we can't distinguish the
2263 * exact migratetype of non-movable pages.
2265 if (old_block_type
== MIGRATE_MOVABLE
)
2266 alike_pages
= pageblock_nr_pages
2267 - (free_pages
+ movable_pages
);
2272 /* moving whole block can fail due to zone boundary conditions */
2277 * If a sufficient number of pages in the block are either free or of
2278 * comparable migratability as our allocation, claim the whole block.
2280 if (free_pages
+ alike_pages
>= (1 << (pageblock_order
-1)) ||
2281 page_group_by_mobility_disabled
)
2282 set_pageblock_migratetype(page
, start_type
);
2287 area
= &zone
->free_area
[current_order
];
2288 list_move(&page
->lru
, &area
->free_list
[start_type
]);
2292 * Check whether there is a suitable fallback freepage with requested order.
2293 * If only_stealable is true, this function returns fallback_mt only if
2294 * we can steal other freepages all together. This would help to reduce
2295 * fragmentation due to mixed migratetype pages in one pageblock.
2297 int find_suitable_fallback(struct free_area
*area
, unsigned int order
,
2298 int migratetype
, bool only_stealable
, bool *can_steal
)
2303 if (area
->nr_free
== 0)
2308 fallback_mt
= fallbacks
[migratetype
][i
];
2309 if (fallback_mt
== MIGRATE_TYPES
)
2312 if (list_empty(&area
->free_list
[fallback_mt
]))
2315 if (can_steal_fallback(order
, migratetype
))
2318 if (!only_stealable
)
2329 * Reserve a pageblock for exclusive use of high-order atomic allocations if
2330 * there are no empty page blocks that contain a page with a suitable order
2332 static void reserve_highatomic_pageblock(struct page
*page
, struct zone
*zone
,
2333 unsigned int alloc_order
)
2336 unsigned long max_managed
, flags
;
2339 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2340 * Check is race-prone but harmless.
2342 max_managed
= (zone_managed_pages(zone
) / 100) + pageblock_nr_pages
;
2343 if (zone
->nr_reserved_highatomic
>= max_managed
)
2346 spin_lock_irqsave(&zone
->lock
, flags
);
2348 /* Recheck the nr_reserved_highatomic limit under the lock */
2349 if (zone
->nr_reserved_highatomic
>= max_managed
)
2353 mt
= get_pageblock_migratetype(page
);
2354 if (!is_migrate_highatomic(mt
) && !is_migrate_isolate(mt
)
2355 && !is_migrate_cma(mt
)) {
2356 zone
->nr_reserved_highatomic
+= pageblock_nr_pages
;
2357 set_pageblock_migratetype(page
, MIGRATE_HIGHATOMIC
);
2358 move_freepages_block(zone
, page
, MIGRATE_HIGHATOMIC
, NULL
);
2362 spin_unlock_irqrestore(&zone
->lock
, flags
);
2366 * Used when an allocation is about to fail under memory pressure. This
2367 * potentially hurts the reliability of high-order allocations when under
2368 * intense memory pressure but failed atomic allocations should be easier
2369 * to recover from than an OOM.
2371 * If @force is true, try to unreserve a pageblock even though highatomic
2372 * pageblock is exhausted.
2374 static bool unreserve_highatomic_pageblock(const struct alloc_context
*ac
,
2377 struct zonelist
*zonelist
= ac
->zonelist
;
2378 unsigned long flags
;
2385 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
, ac
->high_zoneidx
,
2388 * Preserve at least one pageblock unless memory pressure
2391 if (!force
&& zone
->nr_reserved_highatomic
<=
2395 spin_lock_irqsave(&zone
->lock
, flags
);
2396 for (order
= 0; order
< MAX_ORDER
; order
++) {
2397 struct free_area
*area
= &(zone
->free_area
[order
]);
2399 page
= list_first_entry_or_null(
2400 &area
->free_list
[MIGRATE_HIGHATOMIC
],
2406 * In page freeing path, migratetype change is racy so
2407 * we can counter several free pages in a pageblock
2408 * in this loop althoug we changed the pageblock type
2409 * from highatomic to ac->migratetype. So we should
2410 * adjust the count once.
2412 if (is_migrate_highatomic_page(page
)) {
2414 * It should never happen but changes to
2415 * locking could inadvertently allow a per-cpu
2416 * drain to add pages to MIGRATE_HIGHATOMIC
2417 * while unreserving so be safe and watch for
2420 zone
->nr_reserved_highatomic
-= min(
2422 zone
->nr_reserved_highatomic
);
2426 * Convert to ac->migratetype and avoid the normal
2427 * pageblock stealing heuristics. Minimally, the caller
2428 * is doing the work and needs the pages. More
2429 * importantly, if the block was always converted to
2430 * MIGRATE_UNMOVABLE or another type then the number
2431 * of pageblocks that cannot be completely freed
2434 set_pageblock_migratetype(page
, ac
->migratetype
);
2435 ret
= move_freepages_block(zone
, page
, ac
->migratetype
,
2438 spin_unlock_irqrestore(&zone
->lock
, flags
);
2442 spin_unlock_irqrestore(&zone
->lock
, flags
);
2449 * Try finding a free buddy page on the fallback list and put it on the free
2450 * list of requested migratetype, possibly along with other pages from the same
2451 * block, depending on fragmentation avoidance heuristics. Returns true if
2452 * fallback was found so that __rmqueue_smallest() can grab it.
2454 * The use of signed ints for order and current_order is a deliberate
2455 * deviation from the rest of this file, to make the for loop
2456 * condition simpler.
2458 static __always_inline
bool
2459 __rmqueue_fallback(struct zone
*zone
, int order
, int start_migratetype
,
2460 unsigned int alloc_flags
)
2462 struct free_area
*area
;
2464 int min_order
= order
;
2470 * Do not steal pages from freelists belonging to other pageblocks
2471 * i.e. orders < pageblock_order. If there are no local zones free,
2472 * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2474 if (alloc_flags
& ALLOC_NOFRAGMENT
)
2475 min_order
= pageblock_order
;
2478 * Find the largest available free page in the other list. This roughly
2479 * approximates finding the pageblock with the most free pages, which
2480 * would be too costly to do exactly.
2482 for (current_order
= MAX_ORDER
- 1; current_order
>= min_order
;
2484 area
= &(zone
->free_area
[current_order
]);
2485 fallback_mt
= find_suitable_fallback(area
, current_order
,
2486 start_migratetype
, false, &can_steal
);
2487 if (fallback_mt
== -1)
2491 * We cannot steal all free pages from the pageblock and the
2492 * requested migratetype is movable. In that case it's better to
2493 * steal and split the smallest available page instead of the
2494 * largest available page, because even if the next movable
2495 * allocation falls back into a different pageblock than this
2496 * one, it won't cause permanent fragmentation.
2498 if (!can_steal
&& start_migratetype
== MIGRATE_MOVABLE
2499 && current_order
> order
)
2508 for (current_order
= order
; current_order
< MAX_ORDER
;
2510 area
= &(zone
->free_area
[current_order
]);
2511 fallback_mt
= find_suitable_fallback(area
, current_order
,
2512 start_migratetype
, false, &can_steal
);
2513 if (fallback_mt
!= -1)
2518 * This should not happen - we already found a suitable fallback
2519 * when looking for the largest page.
2521 VM_BUG_ON(current_order
== MAX_ORDER
);
2524 page
= list_first_entry(&area
->free_list
[fallback_mt
],
2527 steal_suitable_fallback(zone
, page
, alloc_flags
, start_migratetype
,
2530 trace_mm_page_alloc_extfrag(page
, order
, current_order
,
2531 start_migratetype
, fallback_mt
);
2538 * Do the hard work of removing an element from the buddy allocator.
2539 * Call me with the zone->lock already held.
2541 static __always_inline
struct page
*
2542 __rmqueue(struct zone
*zone
, unsigned int order
, int migratetype
,
2543 unsigned int alloc_flags
)
2548 page
= __rmqueue_smallest(zone
, order
, migratetype
);
2549 if (unlikely(!page
)) {
2550 if (migratetype
== MIGRATE_MOVABLE
)
2551 page
= __rmqueue_cma_fallback(zone
, order
);
2553 if (!page
&& __rmqueue_fallback(zone
, order
, migratetype
,
2558 trace_mm_page_alloc_zone_locked(page
, order
, migratetype
);
2563 * Obtain a specified number of elements from the buddy allocator, all under
2564 * a single hold of the lock, for efficiency. Add them to the supplied list.
2565 * Returns the number of new pages which were placed at *list.
2567 static int rmqueue_bulk(struct zone
*zone
, unsigned int order
,
2568 unsigned long count
, struct list_head
*list
,
2569 int migratetype
, unsigned int alloc_flags
)
2573 spin_lock(&zone
->lock
);
2574 for (i
= 0; i
< count
; ++i
) {
2575 struct page
*page
= __rmqueue(zone
, order
, migratetype
,
2577 if (unlikely(page
== NULL
))
2580 if (unlikely(check_pcp_refill(page
)))
2584 * Split buddy pages returned by expand() are received here in
2585 * physical page order. The page is added to the tail of
2586 * caller's list. From the callers perspective, the linked list
2587 * is ordered by page number under some conditions. This is
2588 * useful for IO devices that can forward direction from the
2589 * head, thus also in the physical page order. This is useful
2590 * for IO devices that can merge IO requests if the physical
2591 * pages are ordered properly.
2593 list_add_tail(&page
->lru
, list
);
2595 if (is_migrate_cma(get_pcppage_migratetype(page
)))
2596 __mod_zone_page_state(zone
, NR_FREE_CMA_PAGES
,
2601 * i pages were removed from the buddy list even if some leak due
2602 * to check_pcp_refill failing so adjust NR_FREE_PAGES based
2603 * on i. Do not confuse with 'alloced' which is the number of
2604 * pages added to the pcp list.
2606 __mod_zone_page_state(zone
, NR_FREE_PAGES
, -(i
<< order
));
2607 spin_unlock(&zone
->lock
);
2613 * Called from the vmstat counter updater to drain pagesets of this
2614 * currently executing processor on remote nodes after they have
2617 * Note that this function must be called with the thread pinned to
2618 * a single processor.
2620 void drain_zone_pages(struct zone
*zone
, struct per_cpu_pages
*pcp
)
2622 unsigned long flags
;
2623 int to_drain
, batch
;
2625 local_irq_save(flags
);
2626 batch
= READ_ONCE(pcp
->batch
);
2627 to_drain
= min(pcp
->count
, batch
);
2629 free_pcppages_bulk(zone
, to_drain
, pcp
);
2630 local_irq_restore(flags
);
2635 * Drain pcplists of the indicated processor and zone.
2637 * The processor must either be the current processor and the
2638 * thread pinned to the current processor or a processor that
2641 static void drain_pages_zone(unsigned int cpu
, struct zone
*zone
)
2643 unsigned long flags
;
2644 struct per_cpu_pageset
*pset
;
2645 struct per_cpu_pages
*pcp
;
2647 local_irq_save(flags
);
2648 pset
= per_cpu_ptr(zone
->pageset
, cpu
);
2652 free_pcppages_bulk(zone
, pcp
->count
, pcp
);
2653 local_irq_restore(flags
);
2657 * Drain pcplists of all zones on the indicated processor.
2659 * The processor must either be the current processor and the
2660 * thread pinned to the current processor or a processor that
2663 static void drain_pages(unsigned int cpu
)
2667 for_each_populated_zone(zone
) {
2668 drain_pages_zone(cpu
, zone
);
2673 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2675 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2676 * the single zone's pages.
2678 void drain_local_pages(struct zone
*zone
)
2680 int cpu
= smp_processor_id();
2683 drain_pages_zone(cpu
, zone
);
2688 static void drain_local_pages_wq(struct work_struct
*work
)
2690 struct pcpu_drain
*drain
;
2692 drain
= container_of(work
, struct pcpu_drain
, work
);
2695 * drain_all_pages doesn't use proper cpu hotplug protection so
2696 * we can race with cpu offline when the WQ can move this from
2697 * a cpu pinned worker to an unbound one. We can operate on a different
2698 * cpu which is allright but we also have to make sure to not move to
2702 drain_local_pages(drain
->zone
);
2707 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2709 * When zone parameter is non-NULL, spill just the single zone's pages.
2711 * Note that this can be extremely slow as the draining happens in a workqueue.
2713 void drain_all_pages(struct zone
*zone
)
2718 * Allocate in the BSS so we wont require allocation in
2719 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2721 static cpumask_t cpus_with_pcps
;
2724 * Make sure nobody triggers this path before mm_percpu_wq is fully
2727 if (WARN_ON_ONCE(!mm_percpu_wq
))
2731 * Do not drain if one is already in progress unless it's specific to
2732 * a zone. Such callers are primarily CMA and memory hotplug and need
2733 * the drain to be complete when the call returns.
2735 if (unlikely(!mutex_trylock(&pcpu_drain_mutex
))) {
2738 mutex_lock(&pcpu_drain_mutex
);
2742 * We don't care about racing with CPU hotplug event
2743 * as offline notification will cause the notified
2744 * cpu to drain that CPU pcps and on_each_cpu_mask
2745 * disables preemption as part of its processing
2747 for_each_online_cpu(cpu
) {
2748 struct per_cpu_pageset
*pcp
;
2750 bool has_pcps
= false;
2753 pcp
= per_cpu_ptr(zone
->pageset
, cpu
);
2757 for_each_populated_zone(z
) {
2758 pcp
= per_cpu_ptr(z
->pageset
, cpu
);
2759 if (pcp
->pcp
.count
) {
2767 cpumask_set_cpu(cpu
, &cpus_with_pcps
);
2769 cpumask_clear_cpu(cpu
, &cpus_with_pcps
);
2772 for_each_cpu(cpu
, &cpus_with_pcps
) {
2773 struct pcpu_drain
*drain
= per_cpu_ptr(&pcpu_drain
, cpu
);
2776 INIT_WORK(&drain
->work
, drain_local_pages_wq
);
2777 queue_work_on(cpu
, mm_percpu_wq
, &drain
->work
);
2779 for_each_cpu(cpu
, &cpus_with_pcps
)
2780 flush_work(&per_cpu_ptr(&pcpu_drain
, cpu
)->work
);
2782 mutex_unlock(&pcpu_drain_mutex
);
2785 #ifdef CONFIG_HIBERNATION
2788 * Touch the watchdog for every WD_PAGE_COUNT pages.
2790 #define WD_PAGE_COUNT (128*1024)
2792 void mark_free_pages(struct zone
*zone
)
2794 unsigned long pfn
, max_zone_pfn
, page_count
= WD_PAGE_COUNT
;
2795 unsigned long flags
;
2796 unsigned int order
, t
;
2799 if (zone_is_empty(zone
))
2802 spin_lock_irqsave(&zone
->lock
, flags
);
2804 max_zone_pfn
= zone_end_pfn(zone
);
2805 for (pfn
= zone
->zone_start_pfn
; pfn
< max_zone_pfn
; pfn
++)
2806 if (pfn_valid(pfn
)) {
2807 page
= pfn_to_page(pfn
);
2809 if (!--page_count
) {
2810 touch_nmi_watchdog();
2811 page_count
= WD_PAGE_COUNT
;
2814 if (page_zone(page
) != zone
)
2817 if (!swsusp_page_is_forbidden(page
))
2818 swsusp_unset_page_free(page
);
2821 for_each_migratetype_order(order
, t
) {
2822 list_for_each_entry(page
,
2823 &zone
->free_area
[order
].free_list
[t
], lru
) {
2826 pfn
= page_to_pfn(page
);
2827 for (i
= 0; i
< (1UL << order
); i
++) {
2828 if (!--page_count
) {
2829 touch_nmi_watchdog();
2830 page_count
= WD_PAGE_COUNT
;
2832 swsusp_set_page_free(pfn_to_page(pfn
+ i
));
2836 spin_unlock_irqrestore(&zone
->lock
, flags
);
2838 #endif /* CONFIG_PM */
2840 static bool free_unref_page_prepare(struct page
*page
, unsigned long pfn
)
2844 if (!free_pcp_prepare(page
))
2847 migratetype
= get_pfnblock_migratetype(page
, pfn
);
2848 set_pcppage_migratetype(page
, migratetype
);
2852 static void free_unref_page_commit(struct page
*page
, unsigned long pfn
)
2854 struct zone
*zone
= page_zone(page
);
2855 struct per_cpu_pages
*pcp
;
2858 migratetype
= get_pcppage_migratetype(page
);
2859 __count_vm_event(PGFREE
);
2862 * We only track unmovable, reclaimable and movable on pcp lists.
2863 * Free ISOLATE pages back to the allocator because they are being
2864 * offlined but treat HIGHATOMIC as movable pages so we can get those
2865 * areas back if necessary. Otherwise, we may have to free
2866 * excessively into the page allocator
2868 if (migratetype
>= MIGRATE_PCPTYPES
) {
2869 if (unlikely(is_migrate_isolate(migratetype
))) {
2870 free_one_page(zone
, page
, pfn
, 0, migratetype
);
2873 migratetype
= MIGRATE_MOVABLE
;
2876 pcp
= &this_cpu_ptr(zone
->pageset
)->pcp
;
2877 list_add(&page
->lru
, &pcp
->lists
[migratetype
]);
2879 if (pcp
->count
>= pcp
->high
) {
2880 unsigned long batch
= READ_ONCE(pcp
->batch
);
2881 free_pcppages_bulk(zone
, batch
, pcp
);
2886 * Free a 0-order page
2888 void free_unref_page(struct page
*page
)
2890 unsigned long flags
;
2891 unsigned long pfn
= page_to_pfn(page
);
2893 if (!free_unref_page_prepare(page
, pfn
))
2896 local_irq_save(flags
);
2897 free_unref_page_commit(page
, pfn
);
2898 local_irq_restore(flags
);
2902 * Free a list of 0-order pages
2904 void free_unref_page_list(struct list_head
*list
)
2906 struct page
*page
, *next
;
2907 unsigned long flags
, pfn
;
2908 int batch_count
= 0;
2910 /* Prepare pages for freeing */
2911 list_for_each_entry_safe(page
, next
, list
, lru
) {
2912 pfn
= page_to_pfn(page
);
2913 if (!free_unref_page_prepare(page
, pfn
))
2914 list_del(&page
->lru
);
2915 set_page_private(page
, pfn
);
2918 local_irq_save(flags
);
2919 list_for_each_entry_safe(page
, next
, list
, lru
) {
2920 unsigned long pfn
= page_private(page
);
2922 set_page_private(page
, 0);
2923 trace_mm_page_free_batched(page
);
2924 free_unref_page_commit(page
, pfn
);
2927 * Guard against excessive IRQ disabled times when we get
2928 * a large list of pages to free.
2930 if (++batch_count
== SWAP_CLUSTER_MAX
) {
2931 local_irq_restore(flags
);
2933 local_irq_save(flags
);
2936 local_irq_restore(flags
);
2940 * split_page takes a non-compound higher-order page, and splits it into
2941 * n (1<<order) sub-pages: page[0..n]
2942 * Each sub-page must be freed individually.
2944 * Note: this is probably too low level an operation for use in drivers.
2945 * Please consult with lkml before using this in your driver.
2947 void split_page(struct page
*page
, unsigned int order
)
2951 VM_BUG_ON_PAGE(PageCompound(page
), page
);
2952 VM_BUG_ON_PAGE(!page_count(page
), page
);
2954 for (i
= 1; i
< (1 << order
); i
++)
2955 set_page_refcounted(page
+ i
);
2956 split_page_owner(page
, order
);
2958 EXPORT_SYMBOL_GPL(split_page
);
2960 int __isolate_free_page(struct page
*page
, unsigned int order
)
2962 unsigned long watermark
;
2966 BUG_ON(!PageBuddy(page
));
2968 zone
= page_zone(page
);
2969 mt
= get_pageblock_migratetype(page
);
2971 if (!is_migrate_isolate(mt
)) {
2973 * Obey watermarks as if the page was being allocated. We can
2974 * emulate a high-order watermark check with a raised order-0
2975 * watermark, because we already know our high-order page
2978 watermark
= min_wmark_pages(zone
) + (1UL << order
);
2979 if (!zone_watermark_ok(zone
, 0, watermark
, 0, ALLOC_CMA
))
2982 __mod_zone_freepage_state(zone
, -(1UL << order
), mt
);
2985 /* Remove page from free list */
2986 list_del(&page
->lru
);
2987 zone
->free_area
[order
].nr_free
--;
2988 rmv_page_order(page
);
2991 * Set the pageblock if the isolated page is at least half of a
2994 if (order
>= pageblock_order
- 1) {
2995 struct page
*endpage
= page
+ (1 << order
) - 1;
2996 for (; page
< endpage
; page
+= pageblock_nr_pages
) {
2997 int mt
= get_pageblock_migratetype(page
);
2998 if (!is_migrate_isolate(mt
) && !is_migrate_cma(mt
)
2999 && !is_migrate_highatomic(mt
))
3000 set_pageblock_migratetype(page
,
3006 return 1UL << order
;
3010 * Update NUMA hit/miss statistics
3012 * Must be called with interrupts disabled.
3014 static inline void zone_statistics(struct zone
*preferred_zone
, struct zone
*z
)
3017 enum numa_stat_item local_stat
= NUMA_LOCAL
;
3019 /* skip numa counters update if numa stats is disabled */
3020 if (!static_branch_likely(&vm_numa_stat_key
))
3023 if (zone_to_nid(z
) != numa_node_id())
3024 local_stat
= NUMA_OTHER
;
3026 if (zone_to_nid(z
) == zone_to_nid(preferred_zone
))
3027 __inc_numa_state(z
, NUMA_HIT
);
3029 __inc_numa_state(z
, NUMA_MISS
);
3030 __inc_numa_state(preferred_zone
, NUMA_FOREIGN
);
3032 __inc_numa_state(z
, local_stat
);
3036 /* Remove page from the per-cpu list, caller must protect the list */
3037 static struct page
*__rmqueue_pcplist(struct zone
*zone
, int migratetype
,
3038 unsigned int alloc_flags
,
3039 struct per_cpu_pages
*pcp
,
3040 struct list_head
*list
)
3045 if (list_empty(list
)) {
3046 pcp
->count
+= rmqueue_bulk(zone
, 0,
3048 migratetype
, alloc_flags
);
3049 if (unlikely(list_empty(list
)))
3053 page
= list_first_entry(list
, struct page
, lru
);
3054 list_del(&page
->lru
);
3056 } while (check_new_pcp(page
));
3061 /* Lock and remove page from the per-cpu list */
3062 static struct page
*rmqueue_pcplist(struct zone
*preferred_zone
,
3063 struct zone
*zone
, unsigned int order
,
3064 gfp_t gfp_flags
, int migratetype
,
3065 unsigned int alloc_flags
)
3067 struct per_cpu_pages
*pcp
;
3068 struct list_head
*list
;
3070 unsigned long flags
;
3072 local_irq_save(flags
);
3073 pcp
= &this_cpu_ptr(zone
->pageset
)->pcp
;
3074 list
= &pcp
->lists
[migratetype
];
3075 page
= __rmqueue_pcplist(zone
, migratetype
, alloc_flags
, pcp
, list
);
3077 __count_zid_vm_events(PGALLOC
, page_zonenum(page
), 1 << order
);
3078 zone_statistics(preferred_zone
, zone
);
3080 local_irq_restore(flags
);
3085 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
3088 struct page
*rmqueue(struct zone
*preferred_zone
,
3089 struct zone
*zone
, unsigned int order
,
3090 gfp_t gfp_flags
, unsigned int alloc_flags
,
3093 unsigned long flags
;
3096 if (likely(order
== 0)) {
3097 page
= rmqueue_pcplist(preferred_zone
, zone
, order
,
3098 gfp_flags
, migratetype
, alloc_flags
);
3103 * We most definitely don't want callers attempting to
3104 * allocate greater than order-1 page units with __GFP_NOFAIL.
3106 WARN_ON_ONCE((gfp_flags
& __GFP_NOFAIL
) && (order
> 1));
3107 spin_lock_irqsave(&zone
->lock
, flags
);
3111 if (alloc_flags
& ALLOC_HARDER
) {
3112 page
= __rmqueue_smallest(zone
, order
, MIGRATE_HIGHATOMIC
);
3114 trace_mm_page_alloc_zone_locked(page
, order
, migratetype
);
3117 page
= __rmqueue(zone
, order
, migratetype
, alloc_flags
);
3118 } while (page
&& check_new_pages(page
, order
));
3119 spin_unlock(&zone
->lock
);
3122 __mod_zone_freepage_state(zone
, -(1 << order
),
3123 get_pcppage_migratetype(page
));
3125 __count_zid_vm_events(PGALLOC
, page_zonenum(page
), 1 << order
);
3126 zone_statistics(preferred_zone
, zone
);
3127 local_irq_restore(flags
);
3130 /* Separate test+clear to avoid unnecessary atomics */
3131 if (test_bit(ZONE_BOOSTED_WATERMARK
, &zone
->flags
)) {
3132 clear_bit(ZONE_BOOSTED_WATERMARK
, &zone
->flags
);
3133 wakeup_kswapd(zone
, 0, 0, zone_idx(zone
));
3136 VM_BUG_ON_PAGE(page
&& bad_range(zone
, page
), page
);
3140 local_irq_restore(flags
);
3144 #ifdef CONFIG_FAIL_PAGE_ALLOC
3147 struct fault_attr attr
;
3149 bool ignore_gfp_highmem
;
3150 bool ignore_gfp_reclaim
;
3152 } fail_page_alloc
= {
3153 .attr
= FAULT_ATTR_INITIALIZER
,
3154 .ignore_gfp_reclaim
= true,
3155 .ignore_gfp_highmem
= true,
3159 static int __init
setup_fail_page_alloc(char *str
)
3161 return setup_fault_attr(&fail_page_alloc
.attr
, str
);
3163 __setup("fail_page_alloc=", setup_fail_page_alloc
);
3165 static bool __should_fail_alloc_page(gfp_t gfp_mask
, unsigned int order
)
3167 if (order
< fail_page_alloc
.min_order
)
3169 if (gfp_mask
& __GFP_NOFAIL
)
3171 if (fail_page_alloc
.ignore_gfp_highmem
&& (gfp_mask
& __GFP_HIGHMEM
))
3173 if (fail_page_alloc
.ignore_gfp_reclaim
&&
3174 (gfp_mask
& __GFP_DIRECT_RECLAIM
))
3177 return should_fail(&fail_page_alloc
.attr
, 1 << order
);
3180 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3182 static int __init
fail_page_alloc_debugfs(void)
3184 umode_t mode
= S_IFREG
| 0600;
3187 dir
= fault_create_debugfs_attr("fail_page_alloc", NULL
,
3188 &fail_page_alloc
.attr
);
3190 return PTR_ERR(dir
);
3192 if (!debugfs_create_bool("ignore-gfp-wait", mode
, dir
,
3193 &fail_page_alloc
.ignore_gfp_reclaim
))
3195 if (!debugfs_create_bool("ignore-gfp-highmem", mode
, dir
,
3196 &fail_page_alloc
.ignore_gfp_highmem
))
3198 if (!debugfs_create_u32("min-order", mode
, dir
,
3199 &fail_page_alloc
.min_order
))
3204 debugfs_remove_recursive(dir
);
3209 late_initcall(fail_page_alloc_debugfs
);
3211 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3213 #else /* CONFIG_FAIL_PAGE_ALLOC */
3215 static inline bool __should_fail_alloc_page(gfp_t gfp_mask
, unsigned int order
)
3220 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3222 static noinline
bool should_fail_alloc_page(gfp_t gfp_mask
, unsigned int order
)
3224 return __should_fail_alloc_page(gfp_mask
, order
);
3226 ALLOW_ERROR_INJECTION(should_fail_alloc_page
, TRUE
);
3229 * Return true if free base pages are above 'mark'. For high-order checks it
3230 * will return true of the order-0 watermark is reached and there is at least
3231 * one free page of a suitable size. Checking now avoids taking the zone lock
3232 * to check in the allocation paths if no pages are free.
3234 bool __zone_watermark_ok(struct zone
*z
, unsigned int order
, unsigned long mark
,
3235 int classzone_idx
, unsigned int alloc_flags
,
3240 const bool alloc_harder
= (alloc_flags
& (ALLOC_HARDER
|ALLOC_OOM
));
3242 /* free_pages may go negative - that's OK */
3243 free_pages
-= (1 << order
) - 1;
3245 if (alloc_flags
& ALLOC_HIGH
)
3249 * If the caller does not have rights to ALLOC_HARDER then subtract
3250 * the high-atomic reserves. This will over-estimate the size of the
3251 * atomic reserve but it avoids a search.
3253 if (likely(!alloc_harder
)) {
3254 free_pages
-= z
->nr_reserved_highatomic
;
3257 * OOM victims can try even harder than normal ALLOC_HARDER
3258 * users on the grounds that it's definitely going to be in
3259 * the exit path shortly and free memory. Any allocation it
3260 * makes during the free path will be small and short-lived.
3262 if (alloc_flags
& ALLOC_OOM
)
3270 /* If allocation can't use CMA areas don't use free CMA pages */
3271 if (!(alloc_flags
& ALLOC_CMA
))
3272 free_pages
-= zone_page_state(z
, NR_FREE_CMA_PAGES
);
3276 * Check watermarks for an order-0 allocation request. If these
3277 * are not met, then a high-order request also cannot go ahead
3278 * even if a suitable page happened to be free.
3280 if (free_pages
<= min
+ z
->lowmem_reserve
[classzone_idx
])
3283 /* If this is an order-0 request then the watermark is fine */
3287 /* For a high-order request, check at least one suitable page is free */
3288 for (o
= order
; o
< MAX_ORDER
; o
++) {
3289 struct free_area
*area
= &z
->free_area
[o
];
3295 for (mt
= 0; mt
< MIGRATE_PCPTYPES
; mt
++) {
3296 if (!list_empty(&area
->free_list
[mt
]))
3301 if ((alloc_flags
& ALLOC_CMA
) &&
3302 !list_empty(&area
->free_list
[MIGRATE_CMA
])) {
3307 !list_empty(&area
->free_list
[MIGRATE_HIGHATOMIC
]))
3313 bool zone_watermark_ok(struct zone
*z
, unsigned int order
, unsigned long mark
,
3314 int classzone_idx
, unsigned int alloc_flags
)
3316 return __zone_watermark_ok(z
, order
, mark
, classzone_idx
, alloc_flags
,
3317 zone_page_state(z
, NR_FREE_PAGES
));
3320 static inline bool zone_watermark_fast(struct zone
*z
, unsigned int order
,
3321 unsigned long mark
, int classzone_idx
, unsigned int alloc_flags
)
3323 long free_pages
= zone_page_state(z
, NR_FREE_PAGES
);
3327 /* If allocation can't use CMA areas don't use free CMA pages */
3328 if (!(alloc_flags
& ALLOC_CMA
))
3329 cma_pages
= zone_page_state(z
, NR_FREE_CMA_PAGES
);
3333 * Fast check for order-0 only. If this fails then the reserves
3334 * need to be calculated. There is a corner case where the check
3335 * passes but only the high-order atomic reserve are free. If
3336 * the caller is !atomic then it'll uselessly search the free
3337 * list. That corner case is then slower but it is harmless.
3339 if (!order
&& (free_pages
- cma_pages
) > mark
+ z
->lowmem_reserve
[classzone_idx
])
3342 return __zone_watermark_ok(z
, order
, mark
, classzone_idx
, alloc_flags
,
3346 bool zone_watermark_ok_safe(struct zone
*z
, unsigned int order
,
3347 unsigned long mark
, int classzone_idx
)
3349 long free_pages
= zone_page_state(z
, NR_FREE_PAGES
);
3351 if (z
->percpu_drift_mark
&& free_pages
< z
->percpu_drift_mark
)
3352 free_pages
= zone_page_state_snapshot(z
, NR_FREE_PAGES
);
3354 return __zone_watermark_ok(z
, order
, mark
, classzone_idx
, 0,
3359 static bool zone_allows_reclaim(struct zone
*local_zone
, struct zone
*zone
)
3361 return node_distance(zone_to_nid(local_zone
), zone_to_nid(zone
)) <=
3364 #else /* CONFIG_NUMA */
3365 static bool zone_allows_reclaim(struct zone
*local_zone
, struct zone
*zone
)
3369 #endif /* CONFIG_NUMA */
3372 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3373 * fragmentation is subtle. If the preferred zone was HIGHMEM then
3374 * premature use of a lower zone may cause lowmem pressure problems that
3375 * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3376 * probably too small. It only makes sense to spread allocations to avoid
3377 * fragmentation between the Normal and DMA32 zones.
3379 static inline unsigned int
3380 alloc_flags_nofragment(struct zone
*zone
, gfp_t gfp_mask
)
3382 unsigned int alloc_flags
= 0;
3384 if (gfp_mask
& __GFP_KSWAPD_RECLAIM
)
3385 alloc_flags
|= ALLOC_KSWAPD
;
3387 #ifdef CONFIG_ZONE_DMA32
3388 if (zone_idx(zone
) != ZONE_NORMAL
)
3392 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3393 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3394 * on UMA that if Normal is populated then so is DMA32.
3396 BUILD_BUG_ON(ZONE_NORMAL
- ZONE_DMA32
!= 1);
3397 if (nr_online_nodes
> 1 && !populated_zone(--zone
))
3401 #endif /* CONFIG_ZONE_DMA32 */
3406 * get_page_from_freelist goes through the zonelist trying to allocate
3409 static struct page
*
3410 get_page_from_freelist(gfp_t gfp_mask
, unsigned int order
, int alloc_flags
,
3411 const struct alloc_context
*ac
)
3415 struct pglist_data
*last_pgdat_dirty_limit
= NULL
;
3420 * Scan zonelist, looking for a zone with enough free.
3421 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3423 no_fallback
= alloc_flags
& ALLOC_NOFRAGMENT
;
3424 z
= ac
->preferred_zoneref
;
3425 for_next_zone_zonelist_nodemask(zone
, z
, ac
->zonelist
, ac
->high_zoneidx
,
3430 if (cpusets_enabled() &&
3431 (alloc_flags
& ALLOC_CPUSET
) &&
3432 !__cpuset_zone_allowed(zone
, gfp_mask
))
3435 * When allocating a page cache page for writing, we
3436 * want to get it from a node that is within its dirty
3437 * limit, such that no single node holds more than its
3438 * proportional share of globally allowed dirty pages.
3439 * The dirty limits take into account the node's
3440 * lowmem reserves and high watermark so that kswapd
3441 * should be able to balance it without having to
3442 * write pages from its LRU list.
3444 * XXX: For now, allow allocations to potentially
3445 * exceed the per-node dirty limit in the slowpath
3446 * (spread_dirty_pages unset) before going into reclaim,
3447 * which is important when on a NUMA setup the allowed
3448 * nodes are together not big enough to reach the
3449 * global limit. The proper fix for these situations
3450 * will require awareness of nodes in the
3451 * dirty-throttling and the flusher threads.
3453 if (ac
->spread_dirty_pages
) {
3454 if (last_pgdat_dirty_limit
== zone
->zone_pgdat
)
3457 if (!node_dirty_ok(zone
->zone_pgdat
)) {
3458 last_pgdat_dirty_limit
= zone
->zone_pgdat
;
3463 if (no_fallback
&& nr_online_nodes
> 1 &&
3464 zone
!= ac
->preferred_zoneref
->zone
) {
3468 * If moving to a remote node, retry but allow
3469 * fragmenting fallbacks. Locality is more important
3470 * than fragmentation avoidance.
3472 local_nid
= zone_to_nid(ac
->preferred_zoneref
->zone
);
3473 if (zone_to_nid(zone
) != local_nid
) {
3474 alloc_flags
&= ~ALLOC_NOFRAGMENT
;
3479 mark
= wmark_pages(zone
, alloc_flags
& ALLOC_WMARK_MASK
);
3480 if (!zone_watermark_fast(zone
, order
, mark
,
3481 ac_classzone_idx(ac
), alloc_flags
)) {
3484 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3486 * Watermark failed for this zone, but see if we can
3487 * grow this zone if it contains deferred pages.
3489 if (static_branch_unlikely(&deferred_pages
)) {
3490 if (_deferred_grow_zone(zone
, order
))
3494 /* Checked here to keep the fast path fast */
3495 BUILD_BUG_ON(ALLOC_NO_WATERMARKS
< NR_WMARK
);
3496 if (alloc_flags
& ALLOC_NO_WATERMARKS
)
3499 if (node_reclaim_mode
== 0 ||
3500 !zone_allows_reclaim(ac
->preferred_zoneref
->zone
, zone
))
3503 ret
= node_reclaim(zone
->zone_pgdat
, gfp_mask
, order
);
3505 case NODE_RECLAIM_NOSCAN
:
3508 case NODE_RECLAIM_FULL
:
3509 /* scanned but unreclaimable */
3512 /* did we reclaim enough */
3513 if (zone_watermark_ok(zone
, order
, mark
,
3514 ac_classzone_idx(ac
), alloc_flags
))
3522 page
= rmqueue(ac
->preferred_zoneref
->zone
, zone
, order
,
3523 gfp_mask
, alloc_flags
, ac
->migratetype
);
3525 prep_new_page(page
, order
, gfp_mask
, alloc_flags
);
3528 * If this is a high-order atomic allocation then check
3529 * if the pageblock should be reserved for the future
3531 if (unlikely(order
&& (alloc_flags
& ALLOC_HARDER
)))
3532 reserve_highatomic_pageblock(page
, zone
, order
);
3536 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3537 /* Try again if zone has deferred pages */
3538 if (static_branch_unlikely(&deferred_pages
)) {
3539 if (_deferred_grow_zone(zone
, order
))
3547 * It's possible on a UMA machine to get through all zones that are
3548 * fragmented. If avoiding fragmentation, reset and try again.
3551 alloc_flags
&= ~ALLOC_NOFRAGMENT
;
3558 static void warn_alloc_show_mem(gfp_t gfp_mask
, nodemask_t
*nodemask
)
3560 unsigned int filter
= SHOW_MEM_FILTER_NODES
;
3561 static DEFINE_RATELIMIT_STATE(show_mem_rs
, HZ
, 1);
3563 if (!__ratelimit(&show_mem_rs
))
3567 * This documents exceptions given to allocations in certain
3568 * contexts that are allowed to allocate outside current's set
3571 if (!(gfp_mask
& __GFP_NOMEMALLOC
))
3572 if (tsk_is_oom_victim(current
) ||
3573 (current
->flags
& (PF_MEMALLOC
| PF_EXITING
)))
3574 filter
&= ~SHOW_MEM_FILTER_NODES
;
3575 if (in_interrupt() || !(gfp_mask
& __GFP_DIRECT_RECLAIM
))
3576 filter
&= ~SHOW_MEM_FILTER_NODES
;
3578 show_mem(filter
, nodemask
);
3581 void warn_alloc(gfp_t gfp_mask
, nodemask_t
*nodemask
, const char *fmt
, ...)
3583 struct va_format vaf
;
3585 static DEFINE_RATELIMIT_STATE(nopage_rs
, DEFAULT_RATELIMIT_INTERVAL
,
3586 DEFAULT_RATELIMIT_BURST
);
3588 if ((gfp_mask
& __GFP_NOWARN
) || !__ratelimit(&nopage_rs
))
3591 va_start(args
, fmt
);
3594 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
3595 current
->comm
, &vaf
, gfp_mask
, &gfp_mask
,
3596 nodemask_pr_args(nodemask
));
3599 cpuset_print_current_mems_allowed();
3602 warn_alloc_show_mem(gfp_mask
, nodemask
);
3605 static inline struct page
*
3606 __alloc_pages_cpuset_fallback(gfp_t gfp_mask
, unsigned int order
,
3607 unsigned int alloc_flags
,
3608 const struct alloc_context
*ac
)
3612 page
= get_page_from_freelist(gfp_mask
, order
,
3613 alloc_flags
|ALLOC_CPUSET
, ac
);
3615 * fallback to ignore cpuset restriction if our nodes
3619 page
= get_page_from_freelist(gfp_mask
, order
,
3625 static inline struct page
*
3626 __alloc_pages_may_oom(gfp_t gfp_mask
, unsigned int order
,
3627 const struct alloc_context
*ac
, unsigned long *did_some_progress
)
3629 struct oom_control oc
= {
3630 .zonelist
= ac
->zonelist
,
3631 .nodemask
= ac
->nodemask
,
3633 .gfp_mask
= gfp_mask
,
3638 *did_some_progress
= 0;
3641 * Acquire the oom lock. If that fails, somebody else is
3642 * making progress for us.
3644 if (!mutex_trylock(&oom_lock
)) {
3645 *did_some_progress
= 1;
3646 schedule_timeout_uninterruptible(1);
3651 * Go through the zonelist yet one more time, keep very high watermark
3652 * here, this is only to catch a parallel oom killing, we must fail if
3653 * we're still under heavy pressure. But make sure that this reclaim
3654 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
3655 * allocation which will never fail due to oom_lock already held.
3657 page
= get_page_from_freelist((gfp_mask
| __GFP_HARDWALL
) &
3658 ~__GFP_DIRECT_RECLAIM
, order
,
3659 ALLOC_WMARK_HIGH
|ALLOC_CPUSET
, ac
);
3663 /* Coredumps can quickly deplete all memory reserves */
3664 if (current
->flags
& PF_DUMPCORE
)
3666 /* The OOM killer will not help higher order allocs */
3667 if (order
> PAGE_ALLOC_COSTLY_ORDER
)
3670 * We have already exhausted all our reclaim opportunities without any
3671 * success so it is time to admit defeat. We will skip the OOM killer
3672 * because it is very likely that the caller has a more reasonable
3673 * fallback than shooting a random task.
3675 if (gfp_mask
& __GFP_RETRY_MAYFAIL
)
3677 /* The OOM killer does not needlessly kill tasks for lowmem */
3678 if (ac
->high_zoneidx
< ZONE_NORMAL
)
3680 if (pm_suspended_storage())
3683 * XXX: GFP_NOFS allocations should rather fail than rely on
3684 * other request to make a forward progress.
3685 * We are in an unfortunate situation where out_of_memory cannot
3686 * do much for this context but let's try it to at least get
3687 * access to memory reserved if the current task is killed (see
3688 * out_of_memory). Once filesystems are ready to handle allocation
3689 * failures more gracefully we should just bail out here.
3692 /* The OOM killer may not free memory on a specific node */
3693 if (gfp_mask
& __GFP_THISNODE
)
3696 /* Exhausted what can be done so it's blame time */
3697 if (out_of_memory(&oc
) || WARN_ON_ONCE(gfp_mask
& __GFP_NOFAIL
)) {
3698 *did_some_progress
= 1;
3701 * Help non-failing allocations by giving them access to memory
3704 if (gfp_mask
& __GFP_NOFAIL
)
3705 page
= __alloc_pages_cpuset_fallback(gfp_mask
, order
,
3706 ALLOC_NO_WATERMARKS
, ac
);
3709 mutex_unlock(&oom_lock
);
3714 * Maximum number of compaction retries wit a progress before OOM
3715 * killer is consider as the only way to move forward.
3717 #define MAX_COMPACT_RETRIES 16
3719 #ifdef CONFIG_COMPACTION
3720 /* Try memory compaction for high-order allocations before reclaim */
3721 static struct page
*
3722 __alloc_pages_direct_compact(gfp_t gfp_mask
, unsigned int order
,
3723 unsigned int alloc_flags
, const struct alloc_context
*ac
,
3724 enum compact_priority prio
, enum compact_result
*compact_result
)
3727 unsigned long pflags
;
3728 unsigned int noreclaim_flag
;
3733 psi_memstall_enter(&pflags
);
3734 noreclaim_flag
= memalloc_noreclaim_save();
3736 *compact_result
= try_to_compact_pages(gfp_mask
, order
, alloc_flags
, ac
,
3739 memalloc_noreclaim_restore(noreclaim_flag
);
3740 psi_memstall_leave(&pflags
);
3742 if (*compact_result
<= COMPACT_INACTIVE
)
3746 * At least in one zone compaction wasn't deferred or skipped, so let's
3747 * count a compaction stall
3749 count_vm_event(COMPACTSTALL
);
3751 page
= get_page_from_freelist(gfp_mask
, order
, alloc_flags
, ac
);
3754 struct zone
*zone
= page_zone(page
);
3756 zone
->compact_blockskip_flush
= false;
3757 compaction_defer_reset(zone
, order
, true);
3758 count_vm_event(COMPACTSUCCESS
);
3763 * It's bad if compaction run occurs and fails. The most likely reason
3764 * is that pages exist, but not enough to satisfy watermarks.
3766 count_vm_event(COMPACTFAIL
);
3774 should_compact_retry(struct alloc_context
*ac
, int order
, int alloc_flags
,
3775 enum compact_result compact_result
,
3776 enum compact_priority
*compact_priority
,
3777 int *compaction_retries
)
3779 int max_retries
= MAX_COMPACT_RETRIES
;
3782 int retries
= *compaction_retries
;
3783 enum compact_priority priority
= *compact_priority
;
3788 if (compaction_made_progress(compact_result
))
3789 (*compaction_retries
)++;
3792 * compaction considers all the zone as desperately out of memory
3793 * so it doesn't really make much sense to retry except when the
3794 * failure could be caused by insufficient priority
3796 if (compaction_failed(compact_result
))
3797 goto check_priority
;
3800 * make sure the compaction wasn't deferred or didn't bail out early
3801 * due to locks contention before we declare that we should give up.
3802 * But do not retry if the given zonelist is not suitable for
3805 if (compaction_withdrawn(compact_result
)) {
3806 ret
= compaction_zonelist_suitable(ac
, order
, alloc_flags
);
3811 * !costly requests are much more important than __GFP_RETRY_MAYFAIL
3812 * costly ones because they are de facto nofail and invoke OOM
3813 * killer to move on while costly can fail and users are ready
3814 * to cope with that. 1/4 retries is rather arbitrary but we
3815 * would need much more detailed feedback from compaction to
3816 * make a better decision.
3818 if (order
> PAGE_ALLOC_COSTLY_ORDER
)
3820 if (*compaction_retries
<= max_retries
) {
3826 * Make sure there are attempts at the highest priority if we exhausted
3827 * all retries or failed at the lower priorities.
3830 min_priority
= (order
> PAGE_ALLOC_COSTLY_ORDER
) ?
3831 MIN_COMPACT_COSTLY_PRIORITY
: MIN_COMPACT_PRIORITY
;
3833 if (*compact_priority
> min_priority
) {
3834 (*compact_priority
)--;
3835 *compaction_retries
= 0;
3839 trace_compact_retry(order
, priority
, compact_result
, retries
, max_retries
, ret
);
3843 static inline struct page
*
3844 __alloc_pages_direct_compact(gfp_t gfp_mask
, unsigned int order
,
3845 unsigned int alloc_flags
, const struct alloc_context
*ac
,
3846 enum compact_priority prio
, enum compact_result
*compact_result
)
3848 *compact_result
= COMPACT_SKIPPED
;
3853 should_compact_retry(struct alloc_context
*ac
, unsigned int order
, int alloc_flags
,
3854 enum compact_result compact_result
,
3855 enum compact_priority
*compact_priority
,
3856 int *compaction_retries
)
3861 if (!order
|| order
> PAGE_ALLOC_COSTLY_ORDER
)
3865 * There are setups with compaction disabled which would prefer to loop
3866 * inside the allocator rather than hit the oom killer prematurely.
3867 * Let's give them a good hope and keep retrying while the order-0
3868 * watermarks are OK.
3870 for_each_zone_zonelist_nodemask(zone
, z
, ac
->zonelist
, ac
->high_zoneidx
,
3872 if (zone_watermark_ok(zone
, 0, min_wmark_pages(zone
),
3873 ac_classzone_idx(ac
), alloc_flags
))
3878 #endif /* CONFIG_COMPACTION */
3880 #ifdef CONFIG_LOCKDEP
3881 static struct lockdep_map __fs_reclaim_map
=
3882 STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map
);
3884 static bool __need_fs_reclaim(gfp_t gfp_mask
)
3886 gfp_mask
= current_gfp_context(gfp_mask
);
3888 /* no reclaim without waiting on it */
3889 if (!(gfp_mask
& __GFP_DIRECT_RECLAIM
))
3892 /* this guy won't enter reclaim */
3893 if (current
->flags
& PF_MEMALLOC
)
3896 /* We're only interested __GFP_FS allocations for now */
3897 if (!(gfp_mask
& __GFP_FS
))
3900 if (gfp_mask
& __GFP_NOLOCKDEP
)
3906 void __fs_reclaim_acquire(void)
3908 lock_map_acquire(&__fs_reclaim_map
);
3911 void __fs_reclaim_release(void)
3913 lock_map_release(&__fs_reclaim_map
);
3916 void fs_reclaim_acquire(gfp_t gfp_mask
)
3918 if (__need_fs_reclaim(gfp_mask
))
3919 __fs_reclaim_acquire();
3921 EXPORT_SYMBOL_GPL(fs_reclaim_acquire
);
3923 void fs_reclaim_release(gfp_t gfp_mask
)
3925 if (__need_fs_reclaim(gfp_mask
))
3926 __fs_reclaim_release();
3928 EXPORT_SYMBOL_GPL(fs_reclaim_release
);
3931 /* Perform direct synchronous page reclaim */
3933 __perform_reclaim(gfp_t gfp_mask
, unsigned int order
,
3934 const struct alloc_context
*ac
)
3936 struct reclaim_state reclaim_state
;
3938 unsigned int noreclaim_flag
;
3939 unsigned long pflags
;
3943 /* We now go into synchronous reclaim */
3944 cpuset_memory_pressure_bump();
3945 psi_memstall_enter(&pflags
);
3946 fs_reclaim_acquire(gfp_mask
);
3947 noreclaim_flag
= memalloc_noreclaim_save();
3948 reclaim_state
.reclaimed_slab
= 0;
3949 current
->reclaim_state
= &reclaim_state
;
3951 progress
= try_to_free_pages(ac
->zonelist
, order
, gfp_mask
,
3954 current
->reclaim_state
= NULL
;
3955 memalloc_noreclaim_restore(noreclaim_flag
);
3956 fs_reclaim_release(gfp_mask
);
3957 psi_memstall_leave(&pflags
);
3964 /* The really slow allocator path where we enter direct reclaim */
3965 static inline struct page
*
3966 __alloc_pages_direct_reclaim(gfp_t gfp_mask
, unsigned int order
,
3967 unsigned int alloc_flags
, const struct alloc_context
*ac
,
3968 unsigned long *did_some_progress
)
3970 struct page
*page
= NULL
;
3971 bool drained
= false;
3973 *did_some_progress
= __perform_reclaim(gfp_mask
, order
, ac
);
3974 if (unlikely(!(*did_some_progress
)))
3978 page
= get_page_from_freelist(gfp_mask
, order
, alloc_flags
, ac
);
3981 * If an allocation failed after direct reclaim, it could be because
3982 * pages are pinned on the per-cpu lists or in high alloc reserves.
3983 * Shrink them them and try again
3985 if (!page
&& !drained
) {
3986 unreserve_highatomic_pageblock(ac
, false);
3987 drain_all_pages(NULL
);
3995 static void wake_all_kswapds(unsigned int order
, gfp_t gfp_mask
,
3996 const struct alloc_context
*ac
)
4000 pg_data_t
*last_pgdat
= NULL
;
4001 enum zone_type high_zoneidx
= ac
->high_zoneidx
;
4003 for_each_zone_zonelist_nodemask(zone
, z
, ac
->zonelist
, high_zoneidx
,
4005 if (last_pgdat
!= zone
->zone_pgdat
)
4006 wakeup_kswapd(zone
, gfp_mask
, order
, high_zoneidx
);
4007 last_pgdat
= zone
->zone_pgdat
;
4011 static inline unsigned int
4012 gfp_to_alloc_flags(gfp_t gfp_mask
)
4014 unsigned int alloc_flags
= ALLOC_WMARK_MIN
| ALLOC_CPUSET
;
4016 /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
4017 BUILD_BUG_ON(__GFP_HIGH
!= (__force gfp_t
) ALLOC_HIGH
);
4020 * The caller may dip into page reserves a bit more if the caller
4021 * cannot run direct reclaim, or if the caller has realtime scheduling
4022 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
4023 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
4025 alloc_flags
|= (__force
int) (gfp_mask
& __GFP_HIGH
);
4027 if (gfp_mask
& __GFP_ATOMIC
) {
4029 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4030 * if it can't schedule.
4032 if (!(gfp_mask
& __GFP_NOMEMALLOC
))
4033 alloc_flags
|= ALLOC_HARDER
;
4035 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
4036 * comment for __cpuset_node_allowed().
4038 alloc_flags
&= ~ALLOC_CPUSET
;
4039 } else if (unlikely(rt_task(current
)) && !in_interrupt())
4040 alloc_flags
|= ALLOC_HARDER
;
4042 if (gfp_mask
& __GFP_KSWAPD_RECLAIM
)
4043 alloc_flags
|= ALLOC_KSWAPD
;
4046 if (gfpflags_to_migratetype(gfp_mask
) == MIGRATE_MOVABLE
)
4047 alloc_flags
|= ALLOC_CMA
;
4052 static bool oom_reserves_allowed(struct task_struct
*tsk
)
4054 if (!tsk_is_oom_victim(tsk
))
4058 * !MMU doesn't have oom reaper so give access to memory reserves
4059 * only to the thread with TIF_MEMDIE set
4061 if (!IS_ENABLED(CONFIG_MMU
) && !test_thread_flag(TIF_MEMDIE
))
4068 * Distinguish requests which really need access to full memory
4069 * reserves from oom victims which can live with a portion of it
4071 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask
)
4073 if (unlikely(gfp_mask
& __GFP_NOMEMALLOC
))
4075 if (gfp_mask
& __GFP_MEMALLOC
)
4076 return ALLOC_NO_WATERMARKS
;
4077 if (in_serving_softirq() && (current
->flags
& PF_MEMALLOC
))
4078 return ALLOC_NO_WATERMARKS
;
4079 if (!in_interrupt()) {
4080 if (current
->flags
& PF_MEMALLOC
)
4081 return ALLOC_NO_WATERMARKS
;
4082 else if (oom_reserves_allowed(current
))
4089 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask
)
4091 return !!__gfp_pfmemalloc_flags(gfp_mask
);
4095 * Checks whether it makes sense to retry the reclaim to make a forward progress
4096 * for the given allocation request.
4098 * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4099 * without success, or when we couldn't even meet the watermark if we
4100 * reclaimed all remaining pages on the LRU lists.
4102 * Returns true if a retry is viable or false to enter the oom path.
4105 should_reclaim_retry(gfp_t gfp_mask
, unsigned order
,
4106 struct alloc_context
*ac
, int alloc_flags
,
4107 bool did_some_progress
, int *no_progress_loops
)
4114 * Costly allocations might have made a progress but this doesn't mean
4115 * their order will become available due to high fragmentation so
4116 * always increment the no progress counter for them
4118 if (did_some_progress
&& order
<= PAGE_ALLOC_COSTLY_ORDER
)
4119 *no_progress_loops
= 0;
4121 (*no_progress_loops
)++;
4124 * Make sure we converge to OOM if we cannot make any progress
4125 * several times in the row.
4127 if (*no_progress_loops
> MAX_RECLAIM_RETRIES
) {
4128 /* Before OOM, exhaust highatomic_reserve */
4129 return unreserve_highatomic_pageblock(ac
, true);
4133 * Keep reclaiming pages while there is a chance this will lead
4134 * somewhere. If none of the target zones can satisfy our allocation
4135 * request even if all reclaimable pages are considered then we are
4136 * screwed and have to go OOM.
4138 for_each_zone_zonelist_nodemask(zone
, z
, ac
->zonelist
, ac
->high_zoneidx
,
4140 unsigned long available
;
4141 unsigned long reclaimable
;
4142 unsigned long min_wmark
= min_wmark_pages(zone
);
4145 available
= reclaimable
= zone_reclaimable_pages(zone
);
4146 available
+= zone_page_state_snapshot(zone
, NR_FREE_PAGES
);
4149 * Would the allocation succeed if we reclaimed all
4150 * reclaimable pages?
4152 wmark
= __zone_watermark_ok(zone
, order
, min_wmark
,
4153 ac_classzone_idx(ac
), alloc_flags
, available
);
4154 trace_reclaim_retry_zone(z
, order
, reclaimable
,
4155 available
, min_wmark
, *no_progress_loops
, wmark
);
4158 * If we didn't make any progress and have a lot of
4159 * dirty + writeback pages then we should wait for
4160 * an IO to complete to slow down the reclaim and
4161 * prevent from pre mature OOM
4163 if (!did_some_progress
) {
4164 unsigned long write_pending
;
4166 write_pending
= zone_page_state_snapshot(zone
,
4167 NR_ZONE_WRITE_PENDING
);
4169 if (2 * write_pending
> reclaimable
) {
4170 congestion_wait(BLK_RW_ASYNC
, HZ
/10);
4182 * Memory allocation/reclaim might be called from a WQ context and the
4183 * current implementation of the WQ concurrency control doesn't
4184 * recognize that a particular WQ is congested if the worker thread is
4185 * looping without ever sleeping. Therefore we have to do a short sleep
4186 * here rather than calling cond_resched().
4188 if (current
->flags
& PF_WQ_WORKER
)
4189 schedule_timeout_uninterruptible(1);
4196 check_retry_cpuset(int cpuset_mems_cookie
, struct alloc_context
*ac
)
4199 * It's possible that cpuset's mems_allowed and the nodemask from
4200 * mempolicy don't intersect. This should be normally dealt with by
4201 * policy_nodemask(), but it's possible to race with cpuset update in
4202 * such a way the check therein was true, and then it became false
4203 * before we got our cpuset_mems_cookie here.
4204 * This assumes that for all allocations, ac->nodemask can come only
4205 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4206 * when it does not intersect with the cpuset restrictions) or the
4207 * caller can deal with a violated nodemask.
4209 if (cpusets_enabled() && ac
->nodemask
&&
4210 !cpuset_nodemask_valid_mems_allowed(ac
->nodemask
)) {
4211 ac
->nodemask
= NULL
;
4216 * When updating a task's mems_allowed or mempolicy nodemask, it is
4217 * possible to race with parallel threads in such a way that our
4218 * allocation can fail while the mask is being updated. If we are about
4219 * to fail, check if the cpuset changed during allocation and if so,
4222 if (read_mems_allowed_retry(cpuset_mems_cookie
))
4228 static inline struct page
*
4229 __alloc_pages_slowpath(gfp_t gfp_mask
, unsigned int order
,
4230 struct alloc_context
*ac
)
4232 bool can_direct_reclaim
= gfp_mask
& __GFP_DIRECT_RECLAIM
;
4233 const bool costly_order
= order
> PAGE_ALLOC_COSTLY_ORDER
;
4234 struct page
*page
= NULL
;
4235 unsigned int alloc_flags
;
4236 unsigned long did_some_progress
;
4237 enum compact_priority compact_priority
;
4238 enum compact_result compact_result
;
4239 int compaction_retries
;
4240 int no_progress_loops
;
4241 unsigned int cpuset_mems_cookie
;
4245 * We also sanity check to catch abuse of atomic reserves being used by
4246 * callers that are not in atomic context.
4248 if (WARN_ON_ONCE((gfp_mask
& (__GFP_ATOMIC
|__GFP_DIRECT_RECLAIM
)) ==
4249 (__GFP_ATOMIC
|__GFP_DIRECT_RECLAIM
)))
4250 gfp_mask
&= ~__GFP_ATOMIC
;
4253 compaction_retries
= 0;
4254 no_progress_loops
= 0;
4255 compact_priority
= DEF_COMPACT_PRIORITY
;
4256 cpuset_mems_cookie
= read_mems_allowed_begin();
4259 * The fast path uses conservative alloc_flags to succeed only until
4260 * kswapd needs to be woken up, and to avoid the cost of setting up
4261 * alloc_flags precisely. So we do that now.
4263 alloc_flags
= gfp_to_alloc_flags(gfp_mask
);
4266 * We need to recalculate the starting point for the zonelist iterator
4267 * because we might have used different nodemask in the fast path, or
4268 * there was a cpuset modification and we are retrying - otherwise we
4269 * could end up iterating over non-eligible zones endlessly.
4271 ac
->preferred_zoneref
= first_zones_zonelist(ac
->zonelist
,
4272 ac
->high_zoneidx
, ac
->nodemask
);
4273 if (!ac
->preferred_zoneref
->zone
)
4276 if (alloc_flags
& ALLOC_KSWAPD
)
4277 wake_all_kswapds(order
, gfp_mask
, ac
);
4280 * The adjusted alloc_flags might result in immediate success, so try
4283 page
= get_page_from_freelist(gfp_mask
, order
, alloc_flags
, ac
);
4288 * For costly allocations, try direct compaction first, as it's likely
4289 * that we have enough base pages and don't need to reclaim. For non-
4290 * movable high-order allocations, do that as well, as compaction will
4291 * try prevent permanent fragmentation by migrating from blocks of the
4293 * Don't try this for allocations that are allowed to ignore
4294 * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
4296 if (can_direct_reclaim
&&
4298 (order
> 0 && ac
->migratetype
!= MIGRATE_MOVABLE
))
4299 && !gfp_pfmemalloc_allowed(gfp_mask
)) {
4300 page
= __alloc_pages_direct_compact(gfp_mask
, order
,
4302 INIT_COMPACT_PRIORITY
,
4308 * Checks for costly allocations with __GFP_NORETRY, which
4309 * includes THP page fault allocations
4311 if (costly_order
&& (gfp_mask
& __GFP_NORETRY
)) {
4313 * If compaction is deferred for high-order allocations,
4314 * it is because sync compaction recently failed. If
4315 * this is the case and the caller requested a THP
4316 * allocation, we do not want to heavily disrupt the
4317 * system, so we fail the allocation instead of entering
4320 if (compact_result
== COMPACT_DEFERRED
)
4324 * Looks like reclaim/compaction is worth trying, but
4325 * sync compaction could be very expensive, so keep
4326 * using async compaction.
4328 compact_priority
= INIT_COMPACT_PRIORITY
;
4333 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4334 if (alloc_flags
& ALLOC_KSWAPD
)
4335 wake_all_kswapds(order
, gfp_mask
, ac
);
4337 reserve_flags
= __gfp_pfmemalloc_flags(gfp_mask
);
4339 alloc_flags
= reserve_flags
;
4342 * Reset the nodemask and zonelist iterators if memory policies can be
4343 * ignored. These allocations are high priority and system rather than
4346 if (!(alloc_flags
& ALLOC_CPUSET
) || reserve_flags
) {
4347 ac
->nodemask
= NULL
;
4348 ac
->preferred_zoneref
= first_zones_zonelist(ac
->zonelist
,
4349 ac
->high_zoneidx
, ac
->nodemask
);
4352 /* Attempt with potentially adjusted zonelist and alloc_flags */
4353 page
= get_page_from_freelist(gfp_mask
, order
, alloc_flags
, ac
);
4357 /* Caller is not willing to reclaim, we can't balance anything */
4358 if (!can_direct_reclaim
)
4361 /* Avoid recursion of direct reclaim */
4362 if (current
->flags
& PF_MEMALLOC
)
4365 /* Try direct reclaim and then allocating */
4366 page
= __alloc_pages_direct_reclaim(gfp_mask
, order
, alloc_flags
, ac
,
4367 &did_some_progress
);
4371 /* Try direct compaction and then allocating */
4372 page
= __alloc_pages_direct_compact(gfp_mask
, order
, alloc_flags
, ac
,
4373 compact_priority
, &compact_result
);
4377 /* Do not loop if specifically requested */
4378 if (gfp_mask
& __GFP_NORETRY
)
4382 * Do not retry costly high order allocations unless they are
4383 * __GFP_RETRY_MAYFAIL
4385 if (costly_order
&& !(gfp_mask
& __GFP_RETRY_MAYFAIL
))
4388 if (should_reclaim_retry(gfp_mask
, order
, ac
, alloc_flags
,
4389 did_some_progress
> 0, &no_progress_loops
))
4393 * It doesn't make any sense to retry for the compaction if the order-0
4394 * reclaim is not able to make any progress because the current
4395 * implementation of the compaction depends on the sufficient amount
4396 * of free memory (see __compaction_suitable)
4398 if (did_some_progress
> 0 &&
4399 should_compact_retry(ac
, order
, alloc_flags
,
4400 compact_result
, &compact_priority
,
4401 &compaction_retries
))
4405 /* Deal with possible cpuset update races before we start OOM killing */
4406 if (check_retry_cpuset(cpuset_mems_cookie
, ac
))
4409 /* Reclaim has failed us, start killing things */
4410 page
= __alloc_pages_may_oom(gfp_mask
, order
, ac
, &did_some_progress
);
4414 /* Avoid allocations with no watermarks from looping endlessly */
4415 if (tsk_is_oom_victim(current
) &&
4416 (alloc_flags
== ALLOC_OOM
||
4417 (gfp_mask
& __GFP_NOMEMALLOC
)))
4420 /* Retry as long as the OOM killer is making progress */
4421 if (did_some_progress
) {
4422 no_progress_loops
= 0;
4427 /* Deal with possible cpuset update races before we fail */
4428 if (check_retry_cpuset(cpuset_mems_cookie
, ac
))
4432 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
4435 if (gfp_mask
& __GFP_NOFAIL
) {
4437 * All existing users of the __GFP_NOFAIL are blockable, so warn
4438 * of any new users that actually require GFP_NOWAIT
4440 if (WARN_ON_ONCE(!can_direct_reclaim
))
4444 * PF_MEMALLOC request from this context is rather bizarre
4445 * because we cannot reclaim anything and only can loop waiting
4446 * for somebody to do a work for us
4448 WARN_ON_ONCE(current
->flags
& PF_MEMALLOC
);
4451 * non failing costly orders are a hard requirement which we
4452 * are not prepared for much so let's warn about these users
4453 * so that we can identify them and convert them to something
4456 WARN_ON_ONCE(order
> PAGE_ALLOC_COSTLY_ORDER
);
4459 * Help non-failing allocations by giving them access to memory
4460 * reserves but do not use ALLOC_NO_WATERMARKS because this
4461 * could deplete whole memory reserves which would just make
4462 * the situation worse
4464 page
= __alloc_pages_cpuset_fallback(gfp_mask
, order
, ALLOC_HARDER
, ac
);
4472 warn_alloc(gfp_mask
, ac
->nodemask
,
4473 "page allocation failure: order:%u", order
);
4478 static inline bool prepare_alloc_pages(gfp_t gfp_mask
, unsigned int order
,
4479 int preferred_nid
, nodemask_t
*nodemask
,
4480 struct alloc_context
*ac
, gfp_t
*alloc_mask
,
4481 unsigned int *alloc_flags
)
4483 ac
->high_zoneidx
= gfp_zone(gfp_mask
);
4484 ac
->zonelist
= node_zonelist(preferred_nid
, gfp_mask
);
4485 ac
->nodemask
= nodemask
;
4486 ac
->migratetype
= gfpflags_to_migratetype(gfp_mask
);
4488 if (cpusets_enabled()) {
4489 *alloc_mask
|= __GFP_HARDWALL
;
4491 ac
->nodemask
= &cpuset_current_mems_allowed
;
4493 *alloc_flags
|= ALLOC_CPUSET
;
4496 fs_reclaim_acquire(gfp_mask
);
4497 fs_reclaim_release(gfp_mask
);
4499 might_sleep_if(gfp_mask
& __GFP_DIRECT_RECLAIM
);
4501 if (should_fail_alloc_page(gfp_mask
, order
))
4504 if (IS_ENABLED(CONFIG_CMA
) && ac
->migratetype
== MIGRATE_MOVABLE
)
4505 *alloc_flags
|= ALLOC_CMA
;
4510 /* Determine whether to spread dirty pages and what the first usable zone */
4511 static inline void finalise_ac(gfp_t gfp_mask
, struct alloc_context
*ac
)
4513 /* Dirty zone balancing only done in the fast path */
4514 ac
->spread_dirty_pages
= (gfp_mask
& __GFP_WRITE
);
4517 * The preferred zone is used for statistics but crucially it is
4518 * also used as the starting point for the zonelist iterator. It
4519 * may get reset for allocations that ignore memory policies.
4521 ac
->preferred_zoneref
= first_zones_zonelist(ac
->zonelist
,
4522 ac
->high_zoneidx
, ac
->nodemask
);
4526 * This is the 'heart' of the zoned buddy allocator.
4529 __alloc_pages_nodemask(gfp_t gfp_mask
, unsigned int order
, int preferred_nid
,
4530 nodemask_t
*nodemask
)
4533 unsigned int alloc_flags
= ALLOC_WMARK_LOW
;
4534 gfp_t alloc_mask
; /* The gfp_t that was actually used for allocation */
4535 struct alloc_context ac
= { };
4538 * There are several places where we assume that the order value is sane
4539 * so bail out early if the request is out of bound.
4541 if (unlikely(order
>= MAX_ORDER
)) {
4542 WARN_ON_ONCE(!(gfp_mask
& __GFP_NOWARN
));
4546 gfp_mask
&= gfp_allowed_mask
;
4547 alloc_mask
= gfp_mask
;
4548 if (!prepare_alloc_pages(gfp_mask
, order
, preferred_nid
, nodemask
, &ac
, &alloc_mask
, &alloc_flags
))
4551 finalise_ac(gfp_mask
, &ac
);
4554 * Forbid the first pass from falling back to types that fragment
4555 * memory until all local zones are considered.
4557 alloc_flags
|= alloc_flags_nofragment(ac
.preferred_zoneref
->zone
, gfp_mask
);
4559 /* First allocation attempt */
4560 page
= get_page_from_freelist(alloc_mask
, order
, alloc_flags
, &ac
);
4565 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
4566 * resp. GFP_NOIO which has to be inherited for all allocation requests
4567 * from a particular context which has been marked by
4568 * memalloc_no{fs,io}_{save,restore}.
4570 alloc_mask
= current_gfp_context(gfp_mask
);
4571 ac
.spread_dirty_pages
= false;
4574 * Restore the original nodemask if it was potentially replaced with
4575 * &cpuset_current_mems_allowed to optimize the fast-path attempt.
4577 if (unlikely(ac
.nodemask
!= nodemask
))
4578 ac
.nodemask
= nodemask
;
4580 page
= __alloc_pages_slowpath(alloc_mask
, order
, &ac
);
4583 if (memcg_kmem_enabled() && (gfp_mask
& __GFP_ACCOUNT
) && page
&&
4584 unlikely(memcg_kmem_charge(page
, gfp_mask
, order
) != 0)) {
4585 __free_pages(page
, order
);
4589 trace_mm_page_alloc(page
, order
, alloc_mask
, ac
.migratetype
);
4593 EXPORT_SYMBOL(__alloc_pages_nodemask
);
4596 * Common helper functions. Never use with __GFP_HIGHMEM because the returned
4597 * address cannot represent highmem pages. Use alloc_pages and then kmap if
4598 * you need to access high mem.
4600 unsigned long __get_free_pages(gfp_t gfp_mask
, unsigned int order
)
4604 page
= alloc_pages(gfp_mask
& ~__GFP_HIGHMEM
, order
);
4607 return (unsigned long) page_address(page
);
4609 EXPORT_SYMBOL(__get_free_pages
);
4611 unsigned long get_zeroed_page(gfp_t gfp_mask
)
4613 return __get_free_pages(gfp_mask
| __GFP_ZERO
, 0);
4615 EXPORT_SYMBOL(get_zeroed_page
);
4617 static inline void free_the_page(struct page
*page
, unsigned int order
)
4619 if (order
== 0) /* Via pcp? */
4620 free_unref_page(page
);
4622 __free_pages_ok(page
, order
);
4625 void __free_pages(struct page
*page
, unsigned int order
)
4627 if (put_page_testzero(page
))
4628 free_the_page(page
, order
);
4630 EXPORT_SYMBOL(__free_pages
);
4632 void free_pages(unsigned long addr
, unsigned int order
)
4635 VM_BUG_ON(!virt_addr_valid((void *)addr
));
4636 __free_pages(virt_to_page((void *)addr
), order
);
4640 EXPORT_SYMBOL(free_pages
);
4644 * An arbitrary-length arbitrary-offset area of memory which resides
4645 * within a 0 or higher order page. Multiple fragments within that page
4646 * are individually refcounted, in the page's reference counter.
4648 * The page_frag functions below provide a simple allocation framework for
4649 * page fragments. This is used by the network stack and network device
4650 * drivers to provide a backing region of memory for use as either an
4651 * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
4653 static struct page
*__page_frag_cache_refill(struct page_frag_cache
*nc
,
4656 struct page
*page
= NULL
;
4657 gfp_t gfp
= gfp_mask
;
4659 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4660 gfp_mask
|= __GFP_COMP
| __GFP_NOWARN
| __GFP_NORETRY
|
4662 page
= alloc_pages_node(NUMA_NO_NODE
, gfp_mask
,
4663 PAGE_FRAG_CACHE_MAX_ORDER
);
4664 nc
->size
= page
? PAGE_FRAG_CACHE_MAX_SIZE
: PAGE_SIZE
;
4666 if (unlikely(!page
))
4667 page
= alloc_pages_node(NUMA_NO_NODE
, gfp
, 0);
4669 nc
->va
= page
? page_address(page
) : NULL
;
4674 void __page_frag_cache_drain(struct page
*page
, unsigned int count
)
4676 VM_BUG_ON_PAGE(page_ref_count(page
) == 0, page
);
4678 if (page_ref_sub_and_test(page
, count
))
4679 free_the_page(page
, compound_order(page
));
4681 EXPORT_SYMBOL(__page_frag_cache_drain
);
4683 void *page_frag_alloc(struct page_frag_cache
*nc
,
4684 unsigned int fragsz
, gfp_t gfp_mask
)
4686 unsigned int size
= PAGE_SIZE
;
4690 if (unlikely(!nc
->va
)) {
4692 page
= __page_frag_cache_refill(nc
, gfp_mask
);
4696 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4697 /* if size can vary use size else just use PAGE_SIZE */
4700 /* Even if we own the page, we do not use atomic_set().
4701 * This would break get_page_unless_zero() users.
4703 page_ref_add(page
, PAGE_FRAG_CACHE_MAX_SIZE
);
4705 /* reset page count bias and offset to start of new frag */
4706 nc
->pfmemalloc
= page_is_pfmemalloc(page
);
4707 nc
->pagecnt_bias
= PAGE_FRAG_CACHE_MAX_SIZE
+ 1;
4711 offset
= nc
->offset
- fragsz
;
4712 if (unlikely(offset
< 0)) {
4713 page
= virt_to_page(nc
->va
);
4715 if (!page_ref_sub_and_test(page
, nc
->pagecnt_bias
))
4718 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4719 /* if size can vary use size else just use PAGE_SIZE */
4722 /* OK, page count is 0, we can safely set it */
4723 set_page_count(page
, PAGE_FRAG_CACHE_MAX_SIZE
+ 1);
4725 /* reset page count bias and offset to start of new frag */
4726 nc
->pagecnt_bias
= PAGE_FRAG_CACHE_MAX_SIZE
+ 1;
4727 offset
= size
- fragsz
;
4731 nc
->offset
= offset
;
4733 return nc
->va
+ offset
;
4735 EXPORT_SYMBOL(page_frag_alloc
);
4738 * Frees a page fragment allocated out of either a compound or order 0 page.
4740 void page_frag_free(void *addr
)
4742 struct page
*page
= virt_to_head_page(addr
);
4744 if (unlikely(put_page_testzero(page
)))
4745 free_the_page(page
, compound_order(page
));
4747 EXPORT_SYMBOL(page_frag_free
);
4749 static void *make_alloc_exact(unsigned long addr
, unsigned int order
,
4753 unsigned long alloc_end
= addr
+ (PAGE_SIZE
<< order
);
4754 unsigned long used
= addr
+ PAGE_ALIGN(size
);
4756 split_page(virt_to_page((void *)addr
), order
);
4757 while (used
< alloc_end
) {
4762 return (void *)addr
;
4766 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
4767 * @size: the number of bytes to allocate
4768 * @gfp_mask: GFP flags for the allocation
4770 * This function is similar to alloc_pages(), except that it allocates the
4771 * minimum number of pages to satisfy the request. alloc_pages() can only
4772 * allocate memory in power-of-two pages.
4774 * This function is also limited by MAX_ORDER.
4776 * Memory allocated by this function must be released by free_pages_exact().
4778 void *alloc_pages_exact(size_t size
, gfp_t gfp_mask
)
4780 unsigned int order
= get_order(size
);
4783 addr
= __get_free_pages(gfp_mask
, order
);
4784 return make_alloc_exact(addr
, order
, size
);
4786 EXPORT_SYMBOL(alloc_pages_exact
);
4789 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
4791 * @nid: the preferred node ID where memory should be allocated
4792 * @size: the number of bytes to allocate
4793 * @gfp_mask: GFP flags for the allocation
4795 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
4798 void * __meminit
alloc_pages_exact_nid(int nid
, size_t size
, gfp_t gfp_mask
)
4800 unsigned int order
= get_order(size
);
4801 struct page
*p
= alloc_pages_node(nid
, gfp_mask
, order
);
4804 return make_alloc_exact((unsigned long)page_address(p
), order
, size
);
4808 * free_pages_exact - release memory allocated via alloc_pages_exact()
4809 * @virt: the value returned by alloc_pages_exact.
4810 * @size: size of allocation, same value as passed to alloc_pages_exact().
4812 * Release the memory allocated by a previous call to alloc_pages_exact.
4814 void free_pages_exact(void *virt
, size_t size
)
4816 unsigned long addr
= (unsigned long)virt
;
4817 unsigned long end
= addr
+ PAGE_ALIGN(size
);
4819 while (addr
< end
) {
4824 EXPORT_SYMBOL(free_pages_exact
);
4827 * nr_free_zone_pages - count number of pages beyond high watermark
4828 * @offset: The zone index of the highest zone
4830 * nr_free_zone_pages() counts the number of counts pages which are beyond the
4831 * high watermark within all zones at or below a given zone index. For each
4832 * zone, the number of pages is calculated as:
4834 * nr_free_zone_pages = managed_pages - high_pages
4836 static unsigned long nr_free_zone_pages(int offset
)
4841 /* Just pick one node, since fallback list is circular */
4842 unsigned long sum
= 0;
4844 struct zonelist
*zonelist
= node_zonelist(numa_node_id(), GFP_KERNEL
);
4846 for_each_zone_zonelist(zone
, z
, zonelist
, offset
) {
4847 unsigned long size
= zone_managed_pages(zone
);
4848 unsigned long high
= high_wmark_pages(zone
);
4857 * nr_free_buffer_pages - count number of pages beyond high watermark
4859 * nr_free_buffer_pages() counts the number of pages which are beyond the high
4860 * watermark within ZONE_DMA and ZONE_NORMAL.
4862 unsigned long nr_free_buffer_pages(void)
4864 return nr_free_zone_pages(gfp_zone(GFP_USER
));
4866 EXPORT_SYMBOL_GPL(nr_free_buffer_pages
);
4869 * nr_free_pagecache_pages - count number of pages beyond high watermark
4871 * nr_free_pagecache_pages() counts the number of pages which are beyond the
4872 * high watermark within all zones.
4874 unsigned long nr_free_pagecache_pages(void)
4876 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE
));
4879 static inline void show_node(struct zone
*zone
)
4881 if (IS_ENABLED(CONFIG_NUMA
))
4882 printk("Node %d ", zone_to_nid(zone
));
4885 long si_mem_available(void)
4888 unsigned long pagecache
;
4889 unsigned long wmark_low
= 0;
4890 unsigned long pages
[NR_LRU_LISTS
];
4891 unsigned long reclaimable
;
4895 for (lru
= LRU_BASE
; lru
< NR_LRU_LISTS
; lru
++)
4896 pages
[lru
] = global_node_page_state(NR_LRU_BASE
+ lru
);
4899 wmark_low
+= low_wmark_pages(zone
);
4902 * Estimate the amount of memory available for userspace allocations,
4903 * without causing swapping.
4905 available
= global_zone_page_state(NR_FREE_PAGES
) - totalreserve_pages
;
4908 * Not all the page cache can be freed, otherwise the system will
4909 * start swapping. Assume at least half of the page cache, or the
4910 * low watermark worth of cache, needs to stay.
4912 pagecache
= pages
[LRU_ACTIVE_FILE
] + pages
[LRU_INACTIVE_FILE
];
4913 pagecache
-= min(pagecache
/ 2, wmark_low
);
4914 available
+= pagecache
;
4917 * Part of the reclaimable slab and other kernel memory consists of
4918 * items that are in use, and cannot be freed. Cap this estimate at the
4921 reclaimable
= global_node_page_state(NR_SLAB_RECLAIMABLE
) +
4922 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE
);
4923 available
+= reclaimable
- min(reclaimable
/ 2, wmark_low
);
4929 EXPORT_SYMBOL_GPL(si_mem_available
);
4931 void si_meminfo(struct sysinfo
*val
)
4933 val
->totalram
= totalram_pages();
4934 val
->sharedram
= global_node_page_state(NR_SHMEM
);
4935 val
->freeram
= global_zone_page_state(NR_FREE_PAGES
);
4936 val
->bufferram
= nr_blockdev_pages();
4937 val
->totalhigh
= totalhigh_pages();
4938 val
->freehigh
= nr_free_highpages();
4939 val
->mem_unit
= PAGE_SIZE
;
4942 EXPORT_SYMBOL(si_meminfo
);
4945 void si_meminfo_node(struct sysinfo
*val
, int nid
)
4947 int zone_type
; /* needs to be signed */
4948 unsigned long managed_pages
= 0;
4949 unsigned long managed_highpages
= 0;
4950 unsigned long free_highpages
= 0;
4951 pg_data_t
*pgdat
= NODE_DATA(nid
);
4953 for (zone_type
= 0; zone_type
< MAX_NR_ZONES
; zone_type
++)
4954 managed_pages
+= zone_managed_pages(&pgdat
->node_zones
[zone_type
]);
4955 val
->totalram
= managed_pages
;
4956 val
->sharedram
= node_page_state(pgdat
, NR_SHMEM
);
4957 val
->freeram
= sum_zone_node_page_state(nid
, NR_FREE_PAGES
);
4958 #ifdef CONFIG_HIGHMEM
4959 for (zone_type
= 0; zone_type
< MAX_NR_ZONES
; zone_type
++) {
4960 struct zone
*zone
= &pgdat
->node_zones
[zone_type
];
4962 if (is_highmem(zone
)) {
4963 managed_highpages
+= zone_managed_pages(zone
);
4964 free_highpages
+= zone_page_state(zone
, NR_FREE_PAGES
);
4967 val
->totalhigh
= managed_highpages
;
4968 val
->freehigh
= free_highpages
;
4970 val
->totalhigh
= managed_highpages
;
4971 val
->freehigh
= free_highpages
;
4973 val
->mem_unit
= PAGE_SIZE
;
4978 * Determine whether the node should be displayed or not, depending on whether
4979 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
4981 static bool show_mem_node_skip(unsigned int flags
, int nid
, nodemask_t
*nodemask
)
4983 if (!(flags
& SHOW_MEM_FILTER_NODES
))
4987 * no node mask - aka implicit memory numa policy. Do not bother with
4988 * the synchronization - read_mems_allowed_begin - because we do not
4989 * have to be precise here.
4992 nodemask
= &cpuset_current_mems_allowed
;
4994 return !node_isset(nid
, *nodemask
);
4997 #define K(x) ((x) << (PAGE_SHIFT-10))
4999 static void show_migration_types(unsigned char type
)
5001 static const char types
[MIGRATE_TYPES
] = {
5002 [MIGRATE_UNMOVABLE
] = 'U',
5003 [MIGRATE_MOVABLE
] = 'M',
5004 [MIGRATE_RECLAIMABLE
] = 'E',
5005 [MIGRATE_HIGHATOMIC
] = 'H',
5007 [MIGRATE_CMA
] = 'C',
5009 #ifdef CONFIG_MEMORY_ISOLATION
5010 [MIGRATE_ISOLATE
] = 'I',
5013 char tmp
[MIGRATE_TYPES
+ 1];
5017 for (i
= 0; i
< MIGRATE_TYPES
; i
++) {
5018 if (type
& (1 << i
))
5023 printk(KERN_CONT
"(%s) ", tmp
);
5027 * Show free area list (used inside shift_scroll-lock stuff)
5028 * We also calculate the percentage fragmentation. We do this by counting the
5029 * memory on each free list with the exception of the first item on the list.
5032 * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
5035 void show_free_areas(unsigned int filter
, nodemask_t
*nodemask
)
5037 unsigned long free_pcp
= 0;
5042 for_each_populated_zone(zone
) {
5043 if (show_mem_node_skip(filter
, zone_to_nid(zone
), nodemask
))
5046 for_each_online_cpu(cpu
)
5047 free_pcp
+= per_cpu_ptr(zone
->pageset
, cpu
)->pcp
.count
;
5050 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
5051 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
5052 " unevictable:%lu dirty:%lu writeback:%lu unstable:%lu\n"
5053 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
5054 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
5055 " free:%lu free_pcp:%lu free_cma:%lu\n",
5056 global_node_page_state(NR_ACTIVE_ANON
),
5057 global_node_page_state(NR_INACTIVE_ANON
),
5058 global_node_page_state(NR_ISOLATED_ANON
),
5059 global_node_page_state(NR_ACTIVE_FILE
),
5060 global_node_page_state(NR_INACTIVE_FILE
),
5061 global_node_page_state(NR_ISOLATED_FILE
),
5062 global_node_page_state(NR_UNEVICTABLE
),
5063 global_node_page_state(NR_FILE_DIRTY
),
5064 global_node_page_state(NR_WRITEBACK
),
5065 global_node_page_state(NR_UNSTABLE_NFS
),
5066 global_node_page_state(NR_SLAB_RECLAIMABLE
),
5067 global_node_page_state(NR_SLAB_UNRECLAIMABLE
),
5068 global_node_page_state(NR_FILE_MAPPED
),
5069 global_node_page_state(NR_SHMEM
),
5070 global_zone_page_state(NR_PAGETABLE
),
5071 global_zone_page_state(NR_BOUNCE
),
5072 global_zone_page_state(NR_FREE_PAGES
),
5074 global_zone_page_state(NR_FREE_CMA_PAGES
));
5076 for_each_online_pgdat(pgdat
) {
5077 if (show_mem_node_skip(filter
, pgdat
->node_id
, nodemask
))
5081 " active_anon:%lukB"
5082 " inactive_anon:%lukB"
5083 " active_file:%lukB"
5084 " inactive_file:%lukB"
5085 " unevictable:%lukB"
5086 " isolated(anon):%lukB"
5087 " isolated(file):%lukB"
5092 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5094 " shmem_pmdmapped: %lukB"
5097 " writeback_tmp:%lukB"
5099 " all_unreclaimable? %s"
5102 K(node_page_state(pgdat
, NR_ACTIVE_ANON
)),
5103 K(node_page_state(pgdat
, NR_INACTIVE_ANON
)),
5104 K(node_page_state(pgdat
, NR_ACTIVE_FILE
)),
5105 K(node_page_state(pgdat
, NR_INACTIVE_FILE
)),
5106 K(node_page_state(pgdat
, NR_UNEVICTABLE
)),
5107 K(node_page_state(pgdat
, NR_ISOLATED_ANON
)),
5108 K(node_page_state(pgdat
, NR_ISOLATED_FILE
)),
5109 K(node_page_state(pgdat
, NR_FILE_MAPPED
)),
5110 K(node_page_state(pgdat
, NR_FILE_DIRTY
)),
5111 K(node_page_state(pgdat
, NR_WRITEBACK
)),
5112 K(node_page_state(pgdat
, NR_SHMEM
)),
5113 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5114 K(node_page_state(pgdat
, NR_SHMEM_THPS
) * HPAGE_PMD_NR
),
5115 K(node_page_state(pgdat
, NR_SHMEM_PMDMAPPED
)
5117 K(node_page_state(pgdat
, NR_ANON_THPS
) * HPAGE_PMD_NR
),
5119 K(node_page_state(pgdat
, NR_WRITEBACK_TEMP
)),
5120 K(node_page_state(pgdat
, NR_UNSTABLE_NFS
)),
5121 pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
?
5125 for_each_populated_zone(zone
) {
5128 if (show_mem_node_skip(filter
, zone_to_nid(zone
), nodemask
))
5132 for_each_online_cpu(cpu
)
5133 free_pcp
+= per_cpu_ptr(zone
->pageset
, cpu
)->pcp
.count
;
5142 " active_anon:%lukB"
5143 " inactive_anon:%lukB"
5144 " active_file:%lukB"
5145 " inactive_file:%lukB"
5146 " unevictable:%lukB"
5147 " writepending:%lukB"
5151 " kernel_stack:%lukB"
5159 K(zone_page_state(zone
, NR_FREE_PAGES
)),
5160 K(min_wmark_pages(zone
)),
5161 K(low_wmark_pages(zone
)),
5162 K(high_wmark_pages(zone
)),
5163 K(zone_page_state(zone
, NR_ZONE_ACTIVE_ANON
)),
5164 K(zone_page_state(zone
, NR_ZONE_INACTIVE_ANON
)),
5165 K(zone_page_state(zone
, NR_ZONE_ACTIVE_FILE
)),
5166 K(zone_page_state(zone
, NR_ZONE_INACTIVE_FILE
)),
5167 K(zone_page_state(zone
, NR_ZONE_UNEVICTABLE
)),
5168 K(zone_page_state(zone
, NR_ZONE_WRITE_PENDING
)),
5169 K(zone
->present_pages
),
5170 K(zone_managed_pages(zone
)),
5171 K(zone_page_state(zone
, NR_MLOCK
)),
5172 zone_page_state(zone
, NR_KERNEL_STACK_KB
),
5173 K(zone_page_state(zone
, NR_PAGETABLE
)),
5174 K(zone_page_state(zone
, NR_BOUNCE
)),
5176 K(this_cpu_read(zone
->pageset
->pcp
.count
)),
5177 K(zone_page_state(zone
, NR_FREE_CMA_PAGES
)));
5178 printk("lowmem_reserve[]:");
5179 for (i
= 0; i
< MAX_NR_ZONES
; i
++)
5180 printk(KERN_CONT
" %ld", zone
->lowmem_reserve
[i
]);
5181 printk(KERN_CONT
"\n");
5184 for_each_populated_zone(zone
) {
5186 unsigned long nr
[MAX_ORDER
], flags
, total
= 0;
5187 unsigned char types
[MAX_ORDER
];
5189 if (show_mem_node_skip(filter
, zone_to_nid(zone
), nodemask
))
5192 printk(KERN_CONT
"%s: ", zone
->name
);
5194 spin_lock_irqsave(&zone
->lock
, flags
);
5195 for (order
= 0; order
< MAX_ORDER
; order
++) {
5196 struct free_area
*area
= &zone
->free_area
[order
];
5199 nr
[order
] = area
->nr_free
;
5200 total
+= nr
[order
] << order
;
5203 for (type
= 0; type
< MIGRATE_TYPES
; type
++) {
5204 if (!list_empty(&area
->free_list
[type
]))
5205 types
[order
] |= 1 << type
;
5208 spin_unlock_irqrestore(&zone
->lock
, flags
);
5209 for (order
= 0; order
< MAX_ORDER
; order
++) {
5210 printk(KERN_CONT
"%lu*%lukB ",
5211 nr
[order
], K(1UL) << order
);
5213 show_migration_types(types
[order
]);
5215 printk(KERN_CONT
"= %lukB\n", K(total
));
5218 hugetlb_show_meminfo();
5220 printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES
));
5222 show_swap_cache_info();
5225 static void zoneref_set_zone(struct zone
*zone
, struct zoneref
*zoneref
)
5227 zoneref
->zone
= zone
;
5228 zoneref
->zone_idx
= zone_idx(zone
);
5232 * Builds allocation fallback zone lists.
5234 * Add all populated zones of a node to the zonelist.
5236 static int build_zonerefs_node(pg_data_t
*pgdat
, struct zoneref
*zonerefs
)
5239 enum zone_type zone_type
= MAX_NR_ZONES
;
5244 zone
= pgdat
->node_zones
+ zone_type
;
5245 if (managed_zone(zone
)) {
5246 zoneref_set_zone(zone
, &zonerefs
[nr_zones
++]);
5247 check_highest_zone(zone_type
);
5249 } while (zone_type
);
5256 static int __parse_numa_zonelist_order(char *s
)
5259 * We used to support different zonlists modes but they turned
5260 * out to be just not useful. Let's keep the warning in place
5261 * if somebody still use the cmd line parameter so that we do
5262 * not fail it silently
5264 if (!(*s
== 'd' || *s
== 'D' || *s
== 'n' || *s
== 'N')) {
5265 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s
);
5271 static __init
int setup_numa_zonelist_order(char *s
)
5276 return __parse_numa_zonelist_order(s
);
5278 early_param("numa_zonelist_order", setup_numa_zonelist_order
);
5280 char numa_zonelist_order
[] = "Node";
5283 * sysctl handler for numa_zonelist_order
5285 int numa_zonelist_order_handler(struct ctl_table
*table
, int write
,
5286 void __user
*buffer
, size_t *length
,
5293 return proc_dostring(table
, write
, buffer
, length
, ppos
);
5294 str
= memdup_user_nul(buffer
, 16);
5296 return PTR_ERR(str
);
5298 ret
= __parse_numa_zonelist_order(str
);
5304 #define MAX_NODE_LOAD (nr_online_nodes)
5305 static int node_load
[MAX_NUMNODES
];
5308 * find_next_best_node - find the next node that should appear in a given node's fallback list
5309 * @node: node whose fallback list we're appending
5310 * @used_node_mask: nodemask_t of already used nodes
5312 * We use a number of factors to determine which is the next node that should
5313 * appear on a given node's fallback list. The node should not have appeared
5314 * already in @node's fallback list, and it should be the next closest node
5315 * according to the distance array (which contains arbitrary distance values
5316 * from each node to each node in the system), and should also prefer nodes
5317 * with no CPUs, since presumably they'll have very little allocation pressure
5318 * on them otherwise.
5319 * It returns -1 if no node is found.
5321 static int find_next_best_node(int node
, nodemask_t
*used_node_mask
)
5324 int min_val
= INT_MAX
;
5325 int best_node
= NUMA_NO_NODE
;
5326 const struct cpumask
*tmp
= cpumask_of_node(0);
5328 /* Use the local node if we haven't already */
5329 if (!node_isset(node
, *used_node_mask
)) {
5330 node_set(node
, *used_node_mask
);
5334 for_each_node_state(n
, N_MEMORY
) {
5336 /* Don't want a node to appear more than once */
5337 if (node_isset(n
, *used_node_mask
))
5340 /* Use the distance array to find the distance */
5341 val
= node_distance(node
, n
);
5343 /* Penalize nodes under us ("prefer the next node") */
5346 /* Give preference to headless and unused nodes */
5347 tmp
= cpumask_of_node(n
);
5348 if (!cpumask_empty(tmp
))
5349 val
+= PENALTY_FOR_NODE_WITH_CPUS
;
5351 /* Slight preference for less loaded node */
5352 val
*= (MAX_NODE_LOAD
*MAX_NUMNODES
);
5353 val
+= node_load
[n
];
5355 if (val
< min_val
) {
5362 node_set(best_node
, *used_node_mask
);
5369 * Build zonelists ordered by node and zones within node.
5370 * This results in maximum locality--normal zone overflows into local
5371 * DMA zone, if any--but risks exhausting DMA zone.
5373 static void build_zonelists_in_node_order(pg_data_t
*pgdat
, int *node_order
,
5376 struct zoneref
*zonerefs
;
5379 zonerefs
= pgdat
->node_zonelists
[ZONELIST_FALLBACK
]._zonerefs
;
5381 for (i
= 0; i
< nr_nodes
; i
++) {
5384 pg_data_t
*node
= NODE_DATA(node_order
[i
]);
5386 nr_zones
= build_zonerefs_node(node
, zonerefs
);
5387 zonerefs
+= nr_zones
;
5389 zonerefs
->zone
= NULL
;
5390 zonerefs
->zone_idx
= 0;
5394 * Build gfp_thisnode zonelists
5396 static void build_thisnode_zonelists(pg_data_t
*pgdat
)
5398 struct zoneref
*zonerefs
;
5401 zonerefs
= pgdat
->node_zonelists
[ZONELIST_NOFALLBACK
]._zonerefs
;
5402 nr_zones
= build_zonerefs_node(pgdat
, zonerefs
);
5403 zonerefs
+= nr_zones
;
5404 zonerefs
->zone
= NULL
;
5405 zonerefs
->zone_idx
= 0;
5409 * Build zonelists ordered by zone and nodes within zones.
5410 * This results in conserving DMA zone[s] until all Normal memory is
5411 * exhausted, but results in overflowing to remote node while memory
5412 * may still exist in local DMA zone.
5415 static void build_zonelists(pg_data_t
*pgdat
)
5417 static int node_order
[MAX_NUMNODES
];
5418 int node
, load
, nr_nodes
= 0;
5419 nodemask_t used_mask
;
5420 int local_node
, prev_node
;
5422 /* NUMA-aware ordering of nodes */
5423 local_node
= pgdat
->node_id
;
5424 load
= nr_online_nodes
;
5425 prev_node
= local_node
;
5426 nodes_clear(used_mask
);
5428 memset(node_order
, 0, sizeof(node_order
));
5429 while ((node
= find_next_best_node(local_node
, &used_mask
)) >= 0) {
5431 * We don't want to pressure a particular node.
5432 * So adding penalty to the first node in same
5433 * distance group to make it round-robin.
5435 if (node_distance(local_node
, node
) !=
5436 node_distance(local_node
, prev_node
))
5437 node_load
[node
] = load
;
5439 node_order
[nr_nodes
++] = node
;
5444 build_zonelists_in_node_order(pgdat
, node_order
, nr_nodes
);
5445 build_thisnode_zonelists(pgdat
);
5448 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5450 * Return node id of node used for "local" allocations.
5451 * I.e., first node id of first zone in arg node's generic zonelist.
5452 * Used for initializing percpu 'numa_mem', which is used primarily
5453 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
5455 int local_memory_node(int node
)
5459 z
= first_zones_zonelist(node_zonelist(node
, GFP_KERNEL
),
5460 gfp_zone(GFP_KERNEL
),
5462 return zone_to_nid(z
->zone
);
5466 static void setup_min_unmapped_ratio(void);
5467 static void setup_min_slab_ratio(void);
5468 #else /* CONFIG_NUMA */
5470 static void build_zonelists(pg_data_t
*pgdat
)
5472 int node
, local_node
;
5473 struct zoneref
*zonerefs
;
5476 local_node
= pgdat
->node_id
;
5478 zonerefs
= pgdat
->node_zonelists
[ZONELIST_FALLBACK
]._zonerefs
;
5479 nr_zones
= build_zonerefs_node(pgdat
, zonerefs
);
5480 zonerefs
+= nr_zones
;
5483 * Now we build the zonelist so that it contains the zones
5484 * of all the other nodes.
5485 * We don't want to pressure a particular node, so when
5486 * building the zones for node N, we make sure that the
5487 * zones coming right after the local ones are those from
5488 * node N+1 (modulo N)
5490 for (node
= local_node
+ 1; node
< MAX_NUMNODES
; node
++) {
5491 if (!node_online(node
))
5493 nr_zones
= build_zonerefs_node(NODE_DATA(node
), zonerefs
);
5494 zonerefs
+= nr_zones
;
5496 for (node
= 0; node
< local_node
; node
++) {
5497 if (!node_online(node
))
5499 nr_zones
= build_zonerefs_node(NODE_DATA(node
), zonerefs
);
5500 zonerefs
+= nr_zones
;
5503 zonerefs
->zone
= NULL
;
5504 zonerefs
->zone_idx
= 0;
5507 #endif /* CONFIG_NUMA */
5510 * Boot pageset table. One per cpu which is going to be used for all
5511 * zones and all nodes. The parameters will be set in such a way
5512 * that an item put on a list will immediately be handed over to
5513 * the buddy list. This is safe since pageset manipulation is done
5514 * with interrupts disabled.
5516 * The boot_pagesets must be kept even after bootup is complete for
5517 * unused processors and/or zones. They do play a role for bootstrapping
5518 * hotplugged processors.
5520 * zoneinfo_show() and maybe other functions do
5521 * not check if the processor is online before following the pageset pointer.
5522 * Other parts of the kernel may not check if the zone is available.
5524 static void setup_pageset(struct per_cpu_pageset
*p
, unsigned long batch
);
5525 static DEFINE_PER_CPU(struct per_cpu_pageset
, boot_pageset
);
5526 static DEFINE_PER_CPU(struct per_cpu_nodestat
, boot_nodestats
);
5528 static void __build_all_zonelists(void *data
)
5531 int __maybe_unused cpu
;
5532 pg_data_t
*self
= data
;
5533 static DEFINE_SPINLOCK(lock
);
5538 memset(node_load
, 0, sizeof(node_load
));
5542 * This node is hotadded and no memory is yet present. So just
5543 * building zonelists is fine - no need to touch other nodes.
5545 if (self
&& !node_online(self
->node_id
)) {
5546 build_zonelists(self
);
5548 for_each_online_node(nid
) {
5549 pg_data_t
*pgdat
= NODE_DATA(nid
);
5551 build_zonelists(pgdat
);
5554 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5556 * We now know the "local memory node" for each node--
5557 * i.e., the node of the first zone in the generic zonelist.
5558 * Set up numa_mem percpu variable for on-line cpus. During
5559 * boot, only the boot cpu should be on-line; we'll init the
5560 * secondary cpus' numa_mem as they come on-line. During
5561 * node/memory hotplug, we'll fixup all on-line cpus.
5563 for_each_online_cpu(cpu
)
5564 set_cpu_numa_mem(cpu
, local_memory_node(cpu_to_node(cpu
)));
5571 static noinline
void __init
5572 build_all_zonelists_init(void)
5576 __build_all_zonelists(NULL
);
5579 * Initialize the boot_pagesets that are going to be used
5580 * for bootstrapping processors. The real pagesets for
5581 * each zone will be allocated later when the per cpu
5582 * allocator is available.
5584 * boot_pagesets are used also for bootstrapping offline
5585 * cpus if the system is already booted because the pagesets
5586 * are needed to initialize allocators on a specific cpu too.
5587 * F.e. the percpu allocator needs the page allocator which
5588 * needs the percpu allocator in order to allocate its pagesets
5589 * (a chicken-egg dilemma).
5591 for_each_possible_cpu(cpu
)
5592 setup_pageset(&per_cpu(boot_pageset
, cpu
), 0);
5594 mminit_verify_zonelist();
5595 cpuset_init_current_mems_allowed();
5599 * unless system_state == SYSTEM_BOOTING.
5601 * __ref due to call of __init annotated helper build_all_zonelists_init
5602 * [protected by SYSTEM_BOOTING].
5604 void __ref
build_all_zonelists(pg_data_t
*pgdat
)
5606 if (system_state
== SYSTEM_BOOTING
) {
5607 build_all_zonelists_init();
5609 __build_all_zonelists(pgdat
);
5610 /* cpuset refresh routine should be here */
5612 vm_total_pages
= nr_free_pagecache_pages();
5614 * Disable grouping by mobility if the number of pages in the
5615 * system is too low to allow the mechanism to work. It would be
5616 * more accurate, but expensive to check per-zone. This check is
5617 * made on memory-hotadd so a system can start with mobility
5618 * disabled and enable it later
5620 if (vm_total_pages
< (pageblock_nr_pages
* MIGRATE_TYPES
))
5621 page_group_by_mobility_disabled
= 1;
5623 page_group_by_mobility_disabled
= 0;
5625 pr_info("Built %i zonelists, mobility grouping %s. Total pages: %ld\n",
5627 page_group_by_mobility_disabled
? "off" : "on",
5630 pr_info("Policy zone: %s\n", zone_names
[policy_zone
]);
5634 /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
5635 static bool __meminit
5636 overlap_memmap_init(unsigned long zone
, unsigned long *pfn
)
5638 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5639 static struct memblock_region
*r
;
5641 if (mirrored_kernelcore
&& zone
== ZONE_MOVABLE
) {
5642 if (!r
|| *pfn
>= memblock_region_memory_end_pfn(r
)) {
5643 for_each_memblock(memory
, r
) {
5644 if (*pfn
< memblock_region_memory_end_pfn(r
))
5648 if (*pfn
>= memblock_region_memory_base_pfn(r
) &&
5649 memblock_is_mirror(r
)) {
5650 *pfn
= memblock_region_memory_end_pfn(r
);
5659 * Initially all pages are reserved - free ones are freed
5660 * up by memblock_free_all() once the early boot process is
5661 * done. Non-atomic initialization, single-pass.
5663 void __meminit
memmap_init_zone(unsigned long size
, int nid
, unsigned long zone
,
5664 unsigned long start_pfn
, enum memmap_context context
,
5665 struct vmem_altmap
*altmap
)
5667 unsigned long pfn
, end_pfn
= start_pfn
+ size
;
5670 if (highest_memmap_pfn
< end_pfn
- 1)
5671 highest_memmap_pfn
= end_pfn
- 1;
5673 #ifdef CONFIG_ZONE_DEVICE
5675 * Honor reservation requested by the driver for this ZONE_DEVICE
5676 * memory. We limit the total number of pages to initialize to just
5677 * those that might contain the memory mapping. We will defer the
5678 * ZONE_DEVICE page initialization until after we have released
5681 if (zone
== ZONE_DEVICE
) {
5685 if (start_pfn
== altmap
->base_pfn
)
5686 start_pfn
+= altmap
->reserve
;
5687 end_pfn
= altmap
->base_pfn
+ vmem_altmap_offset(altmap
);
5691 for (pfn
= start_pfn
; pfn
< end_pfn
; pfn
++) {
5693 * There can be holes in boot-time mem_map[]s handed to this
5694 * function. They do not exist on hotplugged memory.
5696 if (context
== MEMMAP_EARLY
) {
5697 if (!early_pfn_valid(pfn
))
5699 if (!early_pfn_in_nid(pfn
, nid
))
5701 if (overlap_memmap_init(zone
, &pfn
))
5703 if (defer_init(nid
, pfn
, end_pfn
))
5707 page
= pfn_to_page(pfn
);
5708 __init_single_page(page
, pfn
, zone
, nid
);
5709 if (context
== MEMMAP_HOTPLUG
)
5710 __SetPageReserved(page
);
5713 * Mark the block movable so that blocks are reserved for
5714 * movable at startup. This will force kernel allocations
5715 * to reserve their blocks rather than leaking throughout
5716 * the address space during boot when many long-lived
5717 * kernel allocations are made.
5719 * bitmap is created for zone's valid pfn range. but memmap
5720 * can be created for invalid pages (for alignment)
5721 * check here not to call set_pageblock_migratetype() against
5724 if (!(pfn
& (pageblock_nr_pages
- 1))) {
5725 set_pageblock_migratetype(page
, MIGRATE_MOVABLE
);
5731 #ifdef CONFIG_ZONE_DEVICE
5732 void __ref
memmap_init_zone_device(struct zone
*zone
,
5733 unsigned long start_pfn
,
5735 struct dev_pagemap
*pgmap
)
5737 unsigned long pfn
, end_pfn
= start_pfn
+ size
;
5738 struct pglist_data
*pgdat
= zone
->zone_pgdat
;
5739 unsigned long zone_idx
= zone_idx(zone
);
5740 unsigned long start
= jiffies
;
5741 int nid
= pgdat
->node_id
;
5743 if (WARN_ON_ONCE(!pgmap
|| !is_dev_zone(zone
)))
5747 * The call to memmap_init_zone should have already taken care
5748 * of the pages reserved for the memmap, so we can just jump to
5749 * the end of that region and start processing the device pages.
5751 if (pgmap
->altmap_valid
) {
5752 struct vmem_altmap
*altmap
= &pgmap
->altmap
;
5754 start_pfn
= altmap
->base_pfn
+ vmem_altmap_offset(altmap
);
5755 size
= end_pfn
- start_pfn
;
5758 for (pfn
= start_pfn
; pfn
< end_pfn
; pfn
++) {
5759 struct page
*page
= pfn_to_page(pfn
);
5761 __init_single_page(page
, pfn
, zone_idx
, nid
);
5764 * Mark page reserved as it will need to wait for onlining
5765 * phase for it to be fully associated with a zone.
5767 * We can use the non-atomic __set_bit operation for setting
5768 * the flag as we are still initializing the pages.
5770 __SetPageReserved(page
);
5773 * ZONE_DEVICE pages union ->lru with a ->pgmap back
5774 * pointer and hmm_data. It is a bug if a ZONE_DEVICE
5775 * page is ever freed or placed on a driver-private list.
5777 page
->pgmap
= pgmap
;
5781 * Mark the block movable so that blocks are reserved for
5782 * movable at startup. This will force kernel allocations
5783 * to reserve their blocks rather than leaking throughout
5784 * the address space during boot when many long-lived
5785 * kernel allocations are made.
5787 * bitmap is created for zone's valid pfn range. but memmap
5788 * can be created for invalid pages (for alignment)
5789 * check here not to call set_pageblock_migratetype() against
5792 * Please note that MEMMAP_HOTPLUG path doesn't clear memmap
5793 * because this is done early in sparse_add_one_section
5795 if (!(pfn
& (pageblock_nr_pages
- 1))) {
5796 set_pageblock_migratetype(page
, MIGRATE_MOVABLE
);
5801 pr_info("%s initialised, %lu pages in %ums\n", dev_name(pgmap
->dev
),
5802 size
, jiffies_to_msecs(jiffies
- start
));
5806 static void __meminit
zone_init_free_lists(struct zone
*zone
)
5808 unsigned int order
, t
;
5809 for_each_migratetype_order(order
, t
) {
5810 INIT_LIST_HEAD(&zone
->free_area
[order
].free_list
[t
]);
5811 zone
->free_area
[order
].nr_free
= 0;
5815 void __meminit __weak
memmap_init(unsigned long size
, int nid
,
5816 unsigned long zone
, unsigned long start_pfn
)
5818 memmap_init_zone(size
, nid
, zone
, start_pfn
, MEMMAP_EARLY
, NULL
);
5821 static int zone_batchsize(struct zone
*zone
)
5827 * The per-cpu-pages pools are set to around 1000th of the
5830 batch
= zone_managed_pages(zone
) / 1024;
5831 /* But no more than a meg. */
5832 if (batch
* PAGE_SIZE
> 1024 * 1024)
5833 batch
= (1024 * 1024) / PAGE_SIZE
;
5834 batch
/= 4; /* We effectively *= 4 below */
5839 * Clamp the batch to a 2^n - 1 value. Having a power
5840 * of 2 value was found to be more likely to have
5841 * suboptimal cache aliasing properties in some cases.
5843 * For example if 2 tasks are alternately allocating
5844 * batches of pages, one task can end up with a lot
5845 * of pages of one half of the possible page colors
5846 * and the other with pages of the other colors.
5848 batch
= rounddown_pow_of_two(batch
+ batch
/2) - 1;
5853 /* The deferral and batching of frees should be suppressed under NOMMU
5856 * The problem is that NOMMU needs to be able to allocate large chunks
5857 * of contiguous memory as there's no hardware page translation to
5858 * assemble apparent contiguous memory from discontiguous pages.
5860 * Queueing large contiguous runs of pages for batching, however,
5861 * causes the pages to actually be freed in smaller chunks. As there
5862 * can be a significant delay between the individual batches being
5863 * recycled, this leads to the once large chunks of space being
5864 * fragmented and becoming unavailable for high-order allocations.
5871 * pcp->high and pcp->batch values are related and dependent on one another:
5872 * ->batch must never be higher then ->high.
5873 * The following function updates them in a safe manner without read side
5876 * Any new users of pcp->batch and pcp->high should ensure they can cope with
5877 * those fields changing asynchronously (acording the the above rule).
5879 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
5880 * outside of boot time (or some other assurance that no concurrent updaters
5883 static void pageset_update(struct per_cpu_pages
*pcp
, unsigned long high
,
5884 unsigned long batch
)
5886 /* start with a fail safe value for batch */
5890 /* Update high, then batch, in order */
5897 /* a companion to pageset_set_high() */
5898 static void pageset_set_batch(struct per_cpu_pageset
*p
, unsigned long batch
)
5900 pageset_update(&p
->pcp
, 6 * batch
, max(1UL, 1 * batch
));
5903 static void pageset_init(struct per_cpu_pageset
*p
)
5905 struct per_cpu_pages
*pcp
;
5908 memset(p
, 0, sizeof(*p
));
5911 for (migratetype
= 0; migratetype
< MIGRATE_PCPTYPES
; migratetype
++)
5912 INIT_LIST_HEAD(&pcp
->lists
[migratetype
]);
5915 static void setup_pageset(struct per_cpu_pageset
*p
, unsigned long batch
)
5918 pageset_set_batch(p
, batch
);
5922 * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
5923 * to the value high for the pageset p.
5925 static void pageset_set_high(struct per_cpu_pageset
*p
,
5928 unsigned long batch
= max(1UL, high
/ 4);
5929 if ((high
/ 4) > (PAGE_SHIFT
* 8))
5930 batch
= PAGE_SHIFT
* 8;
5932 pageset_update(&p
->pcp
, high
, batch
);
5935 static void pageset_set_high_and_batch(struct zone
*zone
,
5936 struct per_cpu_pageset
*pcp
)
5938 if (percpu_pagelist_fraction
)
5939 pageset_set_high(pcp
,
5940 (zone_managed_pages(zone
) /
5941 percpu_pagelist_fraction
));
5943 pageset_set_batch(pcp
, zone_batchsize(zone
));
5946 static void __meminit
zone_pageset_init(struct zone
*zone
, int cpu
)
5948 struct per_cpu_pageset
*pcp
= per_cpu_ptr(zone
->pageset
, cpu
);
5951 pageset_set_high_and_batch(zone
, pcp
);
5954 void __meminit
setup_zone_pageset(struct zone
*zone
)
5957 zone
->pageset
= alloc_percpu(struct per_cpu_pageset
);
5958 for_each_possible_cpu(cpu
)
5959 zone_pageset_init(zone
, cpu
);
5963 * Allocate per cpu pagesets and initialize them.
5964 * Before this call only boot pagesets were available.
5966 void __init
setup_per_cpu_pageset(void)
5968 struct pglist_data
*pgdat
;
5971 for_each_populated_zone(zone
)
5972 setup_zone_pageset(zone
);
5974 for_each_online_pgdat(pgdat
)
5975 pgdat
->per_cpu_nodestats
=
5976 alloc_percpu(struct per_cpu_nodestat
);
5979 static __meminit
void zone_pcp_init(struct zone
*zone
)
5982 * per cpu subsystem is not up at this point. The following code
5983 * relies on the ability of the linker to provide the
5984 * offset of a (static) per cpu variable into the per cpu area.
5986 zone
->pageset
= &boot_pageset
;
5988 if (populated_zone(zone
))
5989 printk(KERN_DEBUG
" %s zone: %lu pages, LIFO batch:%u\n",
5990 zone
->name
, zone
->present_pages
,
5991 zone_batchsize(zone
));
5994 void __meminit
init_currently_empty_zone(struct zone
*zone
,
5995 unsigned long zone_start_pfn
,
5998 struct pglist_data
*pgdat
= zone
->zone_pgdat
;
5999 int zone_idx
= zone_idx(zone
) + 1;
6001 if (zone_idx
> pgdat
->nr_zones
)
6002 pgdat
->nr_zones
= zone_idx
;
6004 zone
->zone_start_pfn
= zone_start_pfn
;
6006 mminit_dprintk(MMINIT_TRACE
, "memmap_init",
6007 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
6009 (unsigned long)zone_idx(zone
),
6010 zone_start_pfn
, (zone_start_pfn
+ size
));
6012 zone_init_free_lists(zone
);
6013 zone
->initialized
= 1;
6016 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6017 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
6020 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
6022 int __meminit
__early_pfn_to_nid(unsigned long pfn
,
6023 struct mminit_pfnnid_cache
*state
)
6025 unsigned long start_pfn
, end_pfn
;
6028 if (state
->last_start
<= pfn
&& pfn
< state
->last_end
)
6029 return state
->last_nid
;
6031 nid
= memblock_search_pfn_nid(pfn
, &start_pfn
, &end_pfn
);
6033 state
->last_start
= start_pfn
;
6034 state
->last_end
= end_pfn
;
6035 state
->last_nid
= nid
;
6040 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
6043 * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
6044 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
6045 * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
6047 * If an architecture guarantees that all ranges registered contain no holes
6048 * and may be freed, this this function may be used instead of calling
6049 * memblock_free_early_nid() manually.
6051 void __init
free_bootmem_with_active_regions(int nid
, unsigned long max_low_pfn
)
6053 unsigned long start_pfn
, end_pfn
;
6056 for_each_mem_pfn_range(i
, nid
, &start_pfn
, &end_pfn
, &this_nid
) {
6057 start_pfn
= min(start_pfn
, max_low_pfn
);
6058 end_pfn
= min(end_pfn
, max_low_pfn
);
6060 if (start_pfn
< end_pfn
)
6061 memblock_free_early_nid(PFN_PHYS(start_pfn
),
6062 (end_pfn
- start_pfn
) << PAGE_SHIFT
,
6068 * sparse_memory_present_with_active_regions - Call memory_present for each active range
6069 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
6071 * If an architecture guarantees that all ranges registered contain no holes and may
6072 * be freed, this function may be used instead of calling memory_present() manually.
6074 void __init
sparse_memory_present_with_active_regions(int nid
)
6076 unsigned long start_pfn
, end_pfn
;
6079 for_each_mem_pfn_range(i
, nid
, &start_pfn
, &end_pfn
, &this_nid
)
6080 memory_present(this_nid
, start_pfn
, end_pfn
);
6084 * get_pfn_range_for_nid - Return the start and end page frames for a node
6085 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
6086 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
6087 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
6089 * It returns the start and end page frame of a node based on information
6090 * provided by memblock_set_node(). If called for a node
6091 * with no available memory, a warning is printed and the start and end
6094 void __init
get_pfn_range_for_nid(unsigned int nid
,
6095 unsigned long *start_pfn
, unsigned long *end_pfn
)
6097 unsigned long this_start_pfn
, this_end_pfn
;
6103 for_each_mem_pfn_range(i
, nid
, &this_start_pfn
, &this_end_pfn
, NULL
) {
6104 *start_pfn
= min(*start_pfn
, this_start_pfn
);
6105 *end_pfn
= max(*end_pfn
, this_end_pfn
);
6108 if (*start_pfn
== -1UL)
6113 * This finds a zone that can be used for ZONE_MOVABLE pages. The
6114 * assumption is made that zones within a node are ordered in monotonic
6115 * increasing memory addresses so that the "highest" populated zone is used
6117 static void __init
find_usable_zone_for_movable(void)
6120 for (zone_index
= MAX_NR_ZONES
- 1; zone_index
>= 0; zone_index
--) {
6121 if (zone_index
== ZONE_MOVABLE
)
6124 if (arch_zone_highest_possible_pfn
[zone_index
] >
6125 arch_zone_lowest_possible_pfn
[zone_index
])
6129 VM_BUG_ON(zone_index
== -1);
6130 movable_zone
= zone_index
;
6134 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
6135 * because it is sized independent of architecture. Unlike the other zones,
6136 * the starting point for ZONE_MOVABLE is not fixed. It may be different
6137 * in each node depending on the size of each node and how evenly kernelcore
6138 * is distributed. This helper function adjusts the zone ranges
6139 * provided by the architecture for a given node by using the end of the
6140 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
6141 * zones within a node are in order of monotonic increases memory addresses
6143 static void __init
adjust_zone_range_for_zone_movable(int nid
,
6144 unsigned long zone_type
,
6145 unsigned long node_start_pfn
,
6146 unsigned long node_end_pfn
,
6147 unsigned long *zone_start_pfn
,
6148 unsigned long *zone_end_pfn
)
6150 /* Only adjust if ZONE_MOVABLE is on this node */
6151 if (zone_movable_pfn
[nid
]) {
6152 /* Size ZONE_MOVABLE */
6153 if (zone_type
== ZONE_MOVABLE
) {
6154 *zone_start_pfn
= zone_movable_pfn
[nid
];
6155 *zone_end_pfn
= min(node_end_pfn
,
6156 arch_zone_highest_possible_pfn
[movable_zone
]);
6158 /* Adjust for ZONE_MOVABLE starting within this range */
6159 } else if (!mirrored_kernelcore
&&
6160 *zone_start_pfn
< zone_movable_pfn
[nid
] &&
6161 *zone_end_pfn
> zone_movable_pfn
[nid
]) {
6162 *zone_end_pfn
= zone_movable_pfn
[nid
];
6164 /* Check if this whole range is within ZONE_MOVABLE */
6165 } else if (*zone_start_pfn
>= zone_movable_pfn
[nid
])
6166 *zone_start_pfn
= *zone_end_pfn
;
6171 * Return the number of pages a zone spans in a node, including holes
6172 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
6174 static unsigned long __init
zone_spanned_pages_in_node(int nid
,
6175 unsigned long zone_type
,
6176 unsigned long node_start_pfn
,
6177 unsigned long node_end_pfn
,
6178 unsigned long *zone_start_pfn
,
6179 unsigned long *zone_end_pfn
,
6180 unsigned long *ignored
)
6182 /* When hotadd a new node from cpu_up(), the node should be empty */
6183 if (!node_start_pfn
&& !node_end_pfn
)
6186 /* Get the start and end of the zone */
6187 *zone_start_pfn
= arch_zone_lowest_possible_pfn
[zone_type
];
6188 *zone_end_pfn
= arch_zone_highest_possible_pfn
[zone_type
];
6189 adjust_zone_range_for_zone_movable(nid
, zone_type
,
6190 node_start_pfn
, node_end_pfn
,
6191 zone_start_pfn
, zone_end_pfn
);
6193 /* Check that this node has pages within the zone's required range */
6194 if (*zone_end_pfn
< node_start_pfn
|| *zone_start_pfn
> node_end_pfn
)
6197 /* Move the zone boundaries inside the node if necessary */
6198 *zone_end_pfn
= min(*zone_end_pfn
, node_end_pfn
);
6199 *zone_start_pfn
= max(*zone_start_pfn
, node_start_pfn
);
6201 /* Return the spanned pages */
6202 return *zone_end_pfn
- *zone_start_pfn
;
6206 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
6207 * then all holes in the requested range will be accounted for.
6209 unsigned long __init
__absent_pages_in_range(int nid
,
6210 unsigned long range_start_pfn
,
6211 unsigned long range_end_pfn
)
6213 unsigned long nr_absent
= range_end_pfn
- range_start_pfn
;
6214 unsigned long start_pfn
, end_pfn
;
6217 for_each_mem_pfn_range(i
, nid
, &start_pfn
, &end_pfn
, NULL
) {
6218 start_pfn
= clamp(start_pfn
, range_start_pfn
, range_end_pfn
);
6219 end_pfn
= clamp(end_pfn
, range_start_pfn
, range_end_pfn
);
6220 nr_absent
-= end_pfn
- start_pfn
;
6226 * absent_pages_in_range - Return number of page frames in holes within a range
6227 * @start_pfn: The start PFN to start searching for holes
6228 * @end_pfn: The end PFN to stop searching for holes
6230 * It returns the number of pages frames in memory holes within a range.
6232 unsigned long __init
absent_pages_in_range(unsigned long start_pfn
,
6233 unsigned long end_pfn
)
6235 return __absent_pages_in_range(MAX_NUMNODES
, start_pfn
, end_pfn
);
6238 /* Return the number of page frames in holes in a zone on a node */
6239 static unsigned long __init
zone_absent_pages_in_node(int nid
,
6240 unsigned long zone_type
,
6241 unsigned long node_start_pfn
,
6242 unsigned long node_end_pfn
,
6243 unsigned long *ignored
)
6245 unsigned long zone_low
= arch_zone_lowest_possible_pfn
[zone_type
];
6246 unsigned long zone_high
= arch_zone_highest_possible_pfn
[zone_type
];
6247 unsigned long zone_start_pfn
, zone_end_pfn
;
6248 unsigned long nr_absent
;
6250 /* When hotadd a new node from cpu_up(), the node should be empty */
6251 if (!node_start_pfn
&& !node_end_pfn
)
6254 zone_start_pfn
= clamp(node_start_pfn
, zone_low
, zone_high
);
6255 zone_end_pfn
= clamp(node_end_pfn
, zone_low
, zone_high
);
6257 adjust_zone_range_for_zone_movable(nid
, zone_type
,
6258 node_start_pfn
, node_end_pfn
,
6259 &zone_start_pfn
, &zone_end_pfn
);
6260 nr_absent
= __absent_pages_in_range(nid
, zone_start_pfn
, zone_end_pfn
);
6263 * ZONE_MOVABLE handling.
6264 * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
6267 if (mirrored_kernelcore
&& zone_movable_pfn
[nid
]) {
6268 unsigned long start_pfn
, end_pfn
;
6269 struct memblock_region
*r
;
6271 for_each_memblock(memory
, r
) {
6272 start_pfn
= clamp(memblock_region_memory_base_pfn(r
),
6273 zone_start_pfn
, zone_end_pfn
);
6274 end_pfn
= clamp(memblock_region_memory_end_pfn(r
),
6275 zone_start_pfn
, zone_end_pfn
);
6277 if (zone_type
== ZONE_MOVABLE
&&
6278 memblock_is_mirror(r
))
6279 nr_absent
+= end_pfn
- start_pfn
;
6281 if (zone_type
== ZONE_NORMAL
&&
6282 !memblock_is_mirror(r
))
6283 nr_absent
+= end_pfn
- start_pfn
;
6290 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6291 static inline unsigned long __init
zone_spanned_pages_in_node(int nid
,
6292 unsigned long zone_type
,
6293 unsigned long node_start_pfn
,
6294 unsigned long node_end_pfn
,
6295 unsigned long *zone_start_pfn
,
6296 unsigned long *zone_end_pfn
,
6297 unsigned long *zones_size
)
6301 *zone_start_pfn
= node_start_pfn
;
6302 for (zone
= 0; zone
< zone_type
; zone
++)
6303 *zone_start_pfn
+= zones_size
[zone
];
6305 *zone_end_pfn
= *zone_start_pfn
+ zones_size
[zone_type
];
6307 return zones_size
[zone_type
];
6310 static inline unsigned long __init
zone_absent_pages_in_node(int nid
,
6311 unsigned long zone_type
,
6312 unsigned long node_start_pfn
,
6313 unsigned long node_end_pfn
,
6314 unsigned long *zholes_size
)
6319 return zholes_size
[zone_type
];
6322 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6324 static void __init
calculate_node_totalpages(struct pglist_data
*pgdat
,
6325 unsigned long node_start_pfn
,
6326 unsigned long node_end_pfn
,
6327 unsigned long *zones_size
,
6328 unsigned long *zholes_size
)
6330 unsigned long realtotalpages
= 0, totalpages
= 0;
6333 for (i
= 0; i
< MAX_NR_ZONES
; i
++) {
6334 struct zone
*zone
= pgdat
->node_zones
+ i
;
6335 unsigned long zone_start_pfn
, zone_end_pfn
;
6336 unsigned long size
, real_size
;
6338 size
= zone_spanned_pages_in_node(pgdat
->node_id
, i
,
6344 real_size
= size
- zone_absent_pages_in_node(pgdat
->node_id
, i
,
6345 node_start_pfn
, node_end_pfn
,
6348 zone
->zone_start_pfn
= zone_start_pfn
;
6350 zone
->zone_start_pfn
= 0;
6351 zone
->spanned_pages
= size
;
6352 zone
->present_pages
= real_size
;
6355 realtotalpages
+= real_size
;
6358 pgdat
->node_spanned_pages
= totalpages
;
6359 pgdat
->node_present_pages
= realtotalpages
;
6360 printk(KERN_DEBUG
"On node %d totalpages: %lu\n", pgdat
->node_id
,
6364 #ifndef CONFIG_SPARSEMEM
6366 * Calculate the size of the zone->blockflags rounded to an unsigned long
6367 * Start by making sure zonesize is a multiple of pageblock_order by rounding
6368 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
6369 * round what is now in bits to nearest long in bits, then return it in
6372 static unsigned long __init
usemap_size(unsigned long zone_start_pfn
, unsigned long zonesize
)
6374 unsigned long usemapsize
;
6376 zonesize
+= zone_start_pfn
& (pageblock_nr_pages
-1);
6377 usemapsize
= roundup(zonesize
, pageblock_nr_pages
);
6378 usemapsize
= usemapsize
>> pageblock_order
;
6379 usemapsize
*= NR_PAGEBLOCK_BITS
;
6380 usemapsize
= roundup(usemapsize
, 8 * sizeof(unsigned long));
6382 return usemapsize
/ 8;
6385 static void __ref
setup_usemap(struct pglist_data
*pgdat
,
6387 unsigned long zone_start_pfn
,
6388 unsigned long zonesize
)
6390 unsigned long usemapsize
= usemap_size(zone_start_pfn
, zonesize
);
6391 zone
->pageblock_flags
= NULL
;
6393 zone
->pageblock_flags
=
6394 memblock_alloc_node_nopanic(usemapsize
,
6398 static inline void setup_usemap(struct pglist_data
*pgdat
, struct zone
*zone
,
6399 unsigned long zone_start_pfn
, unsigned long zonesize
) {}
6400 #endif /* CONFIG_SPARSEMEM */
6402 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
6404 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
6405 void __init
set_pageblock_order(void)
6409 /* Check that pageblock_nr_pages has not already been setup */
6410 if (pageblock_order
)
6413 if (HPAGE_SHIFT
> PAGE_SHIFT
)
6414 order
= HUGETLB_PAGE_ORDER
;
6416 order
= MAX_ORDER
- 1;
6419 * Assume the largest contiguous order of interest is a huge page.
6420 * This value may be variable depending on boot parameters on IA64 and
6423 pageblock_order
= order
;
6425 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6428 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
6429 * is unused as pageblock_order is set at compile-time. See
6430 * include/linux/pageblock-flags.h for the values of pageblock_order based on
6433 void __init
set_pageblock_order(void)
6437 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6439 static unsigned long __init
calc_memmap_size(unsigned long spanned_pages
,
6440 unsigned long present_pages
)
6442 unsigned long pages
= spanned_pages
;
6445 * Provide a more accurate estimation if there are holes within
6446 * the zone and SPARSEMEM is in use. If there are holes within the
6447 * zone, each populated memory region may cost us one or two extra
6448 * memmap pages due to alignment because memmap pages for each
6449 * populated regions may not be naturally aligned on page boundary.
6450 * So the (present_pages >> 4) heuristic is a tradeoff for that.
6452 if (spanned_pages
> present_pages
+ (present_pages
>> 4) &&
6453 IS_ENABLED(CONFIG_SPARSEMEM
))
6454 pages
= present_pages
;
6456 return PAGE_ALIGN(pages
* sizeof(struct page
)) >> PAGE_SHIFT
;
6459 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6460 static void pgdat_init_split_queue(struct pglist_data
*pgdat
)
6462 spin_lock_init(&pgdat
->split_queue_lock
);
6463 INIT_LIST_HEAD(&pgdat
->split_queue
);
6464 pgdat
->split_queue_len
= 0;
6467 static void pgdat_init_split_queue(struct pglist_data
*pgdat
) {}
6470 #ifdef CONFIG_COMPACTION
6471 static void pgdat_init_kcompactd(struct pglist_data
*pgdat
)
6473 init_waitqueue_head(&pgdat
->kcompactd_wait
);
6476 static void pgdat_init_kcompactd(struct pglist_data
*pgdat
) {}
6479 static void __meminit
pgdat_init_internals(struct pglist_data
*pgdat
)
6481 pgdat_resize_init(pgdat
);
6483 pgdat_init_split_queue(pgdat
);
6484 pgdat_init_kcompactd(pgdat
);
6486 init_waitqueue_head(&pgdat
->kswapd_wait
);
6487 init_waitqueue_head(&pgdat
->pfmemalloc_wait
);
6489 pgdat_page_ext_init(pgdat
);
6490 spin_lock_init(&pgdat
->lru_lock
);
6491 lruvec_init(node_lruvec(pgdat
));
6494 static void __meminit
zone_init_internals(struct zone
*zone
, enum zone_type idx
, int nid
,
6495 unsigned long remaining_pages
)
6497 atomic_long_set(&zone
->managed_pages
, remaining_pages
);
6498 zone_set_nid(zone
, nid
);
6499 zone
->name
= zone_names
[idx
];
6500 zone
->zone_pgdat
= NODE_DATA(nid
);
6501 spin_lock_init(&zone
->lock
);
6502 zone_seqlock_init(zone
);
6503 zone_pcp_init(zone
);
6507 * Set up the zone data structures
6508 * - init pgdat internals
6509 * - init all zones belonging to this node
6511 * NOTE: this function is only called during memory hotplug
6513 #ifdef CONFIG_MEMORY_HOTPLUG
6514 void __ref
free_area_init_core_hotplug(int nid
)
6517 pg_data_t
*pgdat
= NODE_DATA(nid
);
6519 pgdat_init_internals(pgdat
);
6520 for (z
= 0; z
< MAX_NR_ZONES
; z
++)
6521 zone_init_internals(&pgdat
->node_zones
[z
], z
, nid
, 0);
6526 * Set up the zone data structures:
6527 * - mark all pages reserved
6528 * - mark all memory queues empty
6529 * - clear the memory bitmaps
6531 * NOTE: pgdat should get zeroed by caller.
6532 * NOTE: this function is only called during early init.
6534 static void __init
free_area_init_core(struct pglist_data
*pgdat
)
6537 int nid
= pgdat
->node_id
;
6539 pgdat_init_internals(pgdat
);
6540 pgdat
->per_cpu_nodestats
= &boot_nodestats
;
6542 for (j
= 0; j
< MAX_NR_ZONES
; j
++) {
6543 struct zone
*zone
= pgdat
->node_zones
+ j
;
6544 unsigned long size
, freesize
, memmap_pages
;
6545 unsigned long zone_start_pfn
= zone
->zone_start_pfn
;
6547 size
= zone
->spanned_pages
;
6548 freesize
= zone
->present_pages
;
6551 * Adjust freesize so that it accounts for how much memory
6552 * is used by this zone for memmap. This affects the watermark
6553 * and per-cpu initialisations
6555 memmap_pages
= calc_memmap_size(size
, freesize
);
6556 if (!is_highmem_idx(j
)) {
6557 if (freesize
>= memmap_pages
) {
6558 freesize
-= memmap_pages
;
6561 " %s zone: %lu pages used for memmap\n",
6562 zone_names
[j
], memmap_pages
);
6564 pr_warn(" %s zone: %lu pages exceeds freesize %lu\n",
6565 zone_names
[j
], memmap_pages
, freesize
);
6568 /* Account for reserved pages */
6569 if (j
== 0 && freesize
> dma_reserve
) {
6570 freesize
-= dma_reserve
;
6571 printk(KERN_DEBUG
" %s zone: %lu pages reserved\n",
6572 zone_names
[0], dma_reserve
);
6575 if (!is_highmem_idx(j
))
6576 nr_kernel_pages
+= freesize
;
6577 /* Charge for highmem memmap if there are enough kernel pages */
6578 else if (nr_kernel_pages
> memmap_pages
* 2)
6579 nr_kernel_pages
-= memmap_pages
;
6580 nr_all_pages
+= freesize
;
6583 * Set an approximate value for lowmem here, it will be adjusted
6584 * when the bootmem allocator frees pages into the buddy system.
6585 * And all highmem pages will be managed by the buddy system.
6587 zone_init_internals(zone
, j
, nid
, freesize
);
6592 set_pageblock_order();
6593 setup_usemap(pgdat
, zone
, zone_start_pfn
, size
);
6594 init_currently_empty_zone(zone
, zone_start_pfn
, size
);
6595 memmap_init(size
, nid
, j
, zone_start_pfn
);
6599 #ifdef CONFIG_FLAT_NODE_MEM_MAP
6600 static void __ref
alloc_node_mem_map(struct pglist_data
*pgdat
)
6602 unsigned long __maybe_unused start
= 0;
6603 unsigned long __maybe_unused offset
= 0;
6605 /* Skip empty nodes */
6606 if (!pgdat
->node_spanned_pages
)
6609 start
= pgdat
->node_start_pfn
& ~(MAX_ORDER_NR_PAGES
- 1);
6610 offset
= pgdat
->node_start_pfn
- start
;
6611 /* ia64 gets its own node_mem_map, before this, without bootmem */
6612 if (!pgdat
->node_mem_map
) {
6613 unsigned long size
, end
;
6617 * The zone's endpoints aren't required to be MAX_ORDER
6618 * aligned but the node_mem_map endpoints must be in order
6619 * for the buddy allocator to function correctly.
6621 end
= pgdat_end_pfn(pgdat
);
6622 end
= ALIGN(end
, MAX_ORDER_NR_PAGES
);
6623 size
= (end
- start
) * sizeof(struct page
);
6624 map
= memblock_alloc_node_nopanic(size
, pgdat
->node_id
);
6625 pgdat
->node_mem_map
= map
+ offset
;
6627 pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
6628 __func__
, pgdat
->node_id
, (unsigned long)pgdat
,
6629 (unsigned long)pgdat
->node_mem_map
);
6630 #ifndef CONFIG_NEED_MULTIPLE_NODES
6632 * With no DISCONTIG, the global mem_map is just set as node 0's
6634 if (pgdat
== NODE_DATA(0)) {
6635 mem_map
= NODE_DATA(0)->node_mem_map
;
6636 #if defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) || defined(CONFIG_FLATMEM)
6637 if (page_to_pfn(mem_map
) != pgdat
->node_start_pfn
)
6639 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6644 static void __ref
alloc_node_mem_map(struct pglist_data
*pgdat
) { }
6645 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
6647 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
6648 static inline void pgdat_set_deferred_range(pg_data_t
*pgdat
)
6650 pgdat
->first_deferred_pfn
= ULONG_MAX
;
6653 static inline void pgdat_set_deferred_range(pg_data_t
*pgdat
) {}
6656 void __init
free_area_init_node(int nid
, unsigned long *zones_size
,
6657 unsigned long node_start_pfn
,
6658 unsigned long *zholes_size
)
6660 pg_data_t
*pgdat
= NODE_DATA(nid
);
6661 unsigned long start_pfn
= 0;
6662 unsigned long end_pfn
= 0;
6664 /* pg_data_t should be reset to zero when it's allocated */
6665 WARN_ON(pgdat
->nr_zones
|| pgdat
->kswapd_classzone_idx
);
6667 pgdat
->node_id
= nid
;
6668 pgdat
->node_start_pfn
= node_start_pfn
;
6669 pgdat
->per_cpu_nodestats
= NULL
;
6670 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6671 get_pfn_range_for_nid(nid
, &start_pfn
, &end_pfn
);
6672 pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid
,
6673 (u64
)start_pfn
<< PAGE_SHIFT
,
6674 end_pfn
? ((u64
)end_pfn
<< PAGE_SHIFT
) - 1 : 0);
6676 start_pfn
= node_start_pfn
;
6678 calculate_node_totalpages(pgdat
, start_pfn
, end_pfn
,
6679 zones_size
, zholes_size
);
6681 alloc_node_mem_map(pgdat
);
6682 pgdat_set_deferred_range(pgdat
);
6684 free_area_init_core(pgdat
);
6687 #if !defined(CONFIG_FLAT_NODE_MEM_MAP)
6689 * Zero all valid struct pages in range [spfn, epfn), return number of struct
6692 static u64
zero_pfn_range(unsigned long spfn
, unsigned long epfn
)
6697 for (pfn
= spfn
; pfn
< epfn
; pfn
++) {
6698 if (!pfn_valid(ALIGN_DOWN(pfn
, pageblock_nr_pages
))) {
6699 pfn
= ALIGN_DOWN(pfn
, pageblock_nr_pages
)
6700 + pageblock_nr_pages
- 1;
6703 mm_zero_struct_page(pfn_to_page(pfn
));
6711 * Only struct pages that are backed by physical memory are zeroed and
6712 * initialized by going through __init_single_page(). But, there are some
6713 * struct pages which are reserved in memblock allocator and their fields
6714 * may be accessed (for example page_to_pfn() on some configuration accesses
6715 * flags). We must explicitly zero those struct pages.
6717 * This function also addresses a similar issue where struct pages are left
6718 * uninitialized because the physical address range is not covered by
6719 * memblock.memory or memblock.reserved. That could happen when memblock
6720 * layout is manually configured via memmap=.
6722 void __init
zero_resv_unavail(void)
6724 phys_addr_t start
, end
;
6726 phys_addr_t next
= 0;
6729 * Loop through unavailable ranges not covered by memblock.memory.
6732 for_each_mem_range(i
, &memblock
.memory
, NULL
,
6733 NUMA_NO_NODE
, MEMBLOCK_NONE
, &start
, &end
, NULL
) {
6735 pgcnt
+= zero_pfn_range(PFN_DOWN(next
), PFN_UP(start
));
6738 pgcnt
+= zero_pfn_range(PFN_DOWN(next
), max_pfn
);
6741 * Struct pages that do not have backing memory. This could be because
6742 * firmware is using some of this memory, or for some other reasons.
6745 pr_info("Zeroed struct page in unavailable ranges: %lld pages", pgcnt
);
6747 #endif /* !CONFIG_FLAT_NODE_MEM_MAP */
6749 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6751 #if MAX_NUMNODES > 1
6753 * Figure out the number of possible node ids.
6755 void __init
setup_nr_node_ids(void)
6757 unsigned int highest
;
6759 highest
= find_last_bit(node_possible_map
.bits
, MAX_NUMNODES
);
6760 nr_node_ids
= highest
+ 1;
6765 * node_map_pfn_alignment - determine the maximum internode alignment
6767 * This function should be called after node map is populated and sorted.
6768 * It calculates the maximum power of two alignment which can distinguish
6771 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
6772 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
6773 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
6774 * shifted, 1GiB is enough and this function will indicate so.
6776 * This is used to test whether pfn -> nid mapping of the chosen memory
6777 * model has fine enough granularity to avoid incorrect mapping for the
6778 * populated node map.
6780 * Returns the determined alignment in pfn's. 0 if there is no alignment
6781 * requirement (single node).
6783 unsigned long __init
node_map_pfn_alignment(void)
6785 unsigned long accl_mask
= 0, last_end
= 0;
6786 unsigned long start
, end
, mask
;
6790 for_each_mem_pfn_range(i
, MAX_NUMNODES
, &start
, &end
, &nid
) {
6791 if (!start
|| last_nid
< 0 || last_nid
== nid
) {
6798 * Start with a mask granular enough to pin-point to the
6799 * start pfn and tick off bits one-by-one until it becomes
6800 * too coarse to separate the current node from the last.
6802 mask
= ~((1 << __ffs(start
)) - 1);
6803 while (mask
&& last_end
<= (start
& (mask
<< 1)))
6806 /* accumulate all internode masks */
6810 /* convert mask to number of pages */
6811 return ~accl_mask
+ 1;
6814 /* Find the lowest pfn for a node */
6815 static unsigned long __init
find_min_pfn_for_node(int nid
)
6817 unsigned long min_pfn
= ULONG_MAX
;
6818 unsigned long start_pfn
;
6821 for_each_mem_pfn_range(i
, nid
, &start_pfn
, NULL
, NULL
)
6822 min_pfn
= min(min_pfn
, start_pfn
);
6824 if (min_pfn
== ULONG_MAX
) {
6825 pr_warn("Could not find start_pfn for node %d\n", nid
);
6833 * find_min_pfn_with_active_regions - Find the minimum PFN registered
6835 * It returns the minimum PFN based on information provided via
6836 * memblock_set_node().
6838 unsigned long __init
find_min_pfn_with_active_regions(void)
6840 return find_min_pfn_for_node(MAX_NUMNODES
);
6844 * early_calculate_totalpages()
6845 * Sum pages in active regions for movable zone.
6846 * Populate N_MEMORY for calculating usable_nodes.
6848 static unsigned long __init
early_calculate_totalpages(void)
6850 unsigned long totalpages
= 0;
6851 unsigned long start_pfn
, end_pfn
;
6854 for_each_mem_pfn_range(i
, MAX_NUMNODES
, &start_pfn
, &end_pfn
, &nid
) {
6855 unsigned long pages
= end_pfn
- start_pfn
;
6857 totalpages
+= pages
;
6859 node_set_state(nid
, N_MEMORY
);
6865 * Find the PFN the Movable zone begins in each node. Kernel memory
6866 * is spread evenly between nodes as long as the nodes have enough
6867 * memory. When they don't, some nodes will have more kernelcore than
6870 static void __init
find_zone_movable_pfns_for_nodes(void)
6873 unsigned long usable_startpfn
;
6874 unsigned long kernelcore_node
, kernelcore_remaining
;
6875 /* save the state before borrow the nodemask */
6876 nodemask_t saved_node_state
= node_states
[N_MEMORY
];
6877 unsigned long totalpages
= early_calculate_totalpages();
6878 int usable_nodes
= nodes_weight(node_states
[N_MEMORY
]);
6879 struct memblock_region
*r
;
6881 /* Need to find movable_zone earlier when movable_node is specified. */
6882 find_usable_zone_for_movable();
6885 * If movable_node is specified, ignore kernelcore and movablecore
6888 if (movable_node_is_enabled()) {
6889 for_each_memblock(memory
, r
) {
6890 if (!memblock_is_hotpluggable(r
))
6895 usable_startpfn
= PFN_DOWN(r
->base
);
6896 zone_movable_pfn
[nid
] = zone_movable_pfn
[nid
] ?
6897 min(usable_startpfn
, zone_movable_pfn
[nid
]) :
6905 * If kernelcore=mirror is specified, ignore movablecore option
6907 if (mirrored_kernelcore
) {
6908 bool mem_below_4gb_not_mirrored
= false;
6910 for_each_memblock(memory
, r
) {
6911 if (memblock_is_mirror(r
))
6916 usable_startpfn
= memblock_region_memory_base_pfn(r
);
6918 if (usable_startpfn
< 0x100000) {
6919 mem_below_4gb_not_mirrored
= true;
6923 zone_movable_pfn
[nid
] = zone_movable_pfn
[nid
] ?
6924 min(usable_startpfn
, zone_movable_pfn
[nid
]) :
6928 if (mem_below_4gb_not_mirrored
)
6929 pr_warn("This configuration results in unmirrored kernel memory.");
6935 * If kernelcore=nn% or movablecore=nn% was specified, calculate the
6936 * amount of necessary memory.
6938 if (required_kernelcore_percent
)
6939 required_kernelcore
= (totalpages
* 100 * required_kernelcore_percent
) /
6941 if (required_movablecore_percent
)
6942 required_movablecore
= (totalpages
* 100 * required_movablecore_percent
) /
6946 * If movablecore= was specified, calculate what size of
6947 * kernelcore that corresponds so that memory usable for
6948 * any allocation type is evenly spread. If both kernelcore
6949 * and movablecore are specified, then the value of kernelcore
6950 * will be used for required_kernelcore if it's greater than
6951 * what movablecore would have allowed.
6953 if (required_movablecore
) {
6954 unsigned long corepages
;
6957 * Round-up so that ZONE_MOVABLE is at least as large as what
6958 * was requested by the user
6960 required_movablecore
=
6961 roundup(required_movablecore
, MAX_ORDER_NR_PAGES
);
6962 required_movablecore
= min(totalpages
, required_movablecore
);
6963 corepages
= totalpages
- required_movablecore
;
6965 required_kernelcore
= max(required_kernelcore
, corepages
);
6969 * If kernelcore was not specified or kernelcore size is larger
6970 * than totalpages, there is no ZONE_MOVABLE.
6972 if (!required_kernelcore
|| required_kernelcore
>= totalpages
)
6975 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
6976 usable_startpfn
= arch_zone_lowest_possible_pfn
[movable_zone
];
6979 /* Spread kernelcore memory as evenly as possible throughout nodes */
6980 kernelcore_node
= required_kernelcore
/ usable_nodes
;
6981 for_each_node_state(nid
, N_MEMORY
) {
6982 unsigned long start_pfn
, end_pfn
;
6985 * Recalculate kernelcore_node if the division per node
6986 * now exceeds what is necessary to satisfy the requested
6987 * amount of memory for the kernel
6989 if (required_kernelcore
< kernelcore_node
)
6990 kernelcore_node
= required_kernelcore
/ usable_nodes
;
6993 * As the map is walked, we track how much memory is usable
6994 * by the kernel using kernelcore_remaining. When it is
6995 * 0, the rest of the node is usable by ZONE_MOVABLE
6997 kernelcore_remaining
= kernelcore_node
;
6999 /* Go through each range of PFNs within this node */
7000 for_each_mem_pfn_range(i
, nid
, &start_pfn
, &end_pfn
, NULL
) {
7001 unsigned long size_pages
;
7003 start_pfn
= max(start_pfn
, zone_movable_pfn
[nid
]);
7004 if (start_pfn
>= end_pfn
)
7007 /* Account for what is only usable for kernelcore */
7008 if (start_pfn
< usable_startpfn
) {
7009 unsigned long kernel_pages
;
7010 kernel_pages
= min(end_pfn
, usable_startpfn
)
7013 kernelcore_remaining
-= min(kernel_pages
,
7014 kernelcore_remaining
);
7015 required_kernelcore
-= min(kernel_pages
,
7016 required_kernelcore
);
7018 /* Continue if range is now fully accounted */
7019 if (end_pfn
<= usable_startpfn
) {
7022 * Push zone_movable_pfn to the end so
7023 * that if we have to rebalance
7024 * kernelcore across nodes, we will
7025 * not double account here
7027 zone_movable_pfn
[nid
] = end_pfn
;
7030 start_pfn
= usable_startpfn
;
7034 * The usable PFN range for ZONE_MOVABLE is from
7035 * start_pfn->end_pfn. Calculate size_pages as the
7036 * number of pages used as kernelcore
7038 size_pages
= end_pfn
- start_pfn
;
7039 if (size_pages
> kernelcore_remaining
)
7040 size_pages
= kernelcore_remaining
;
7041 zone_movable_pfn
[nid
] = start_pfn
+ size_pages
;
7044 * Some kernelcore has been met, update counts and
7045 * break if the kernelcore for this node has been
7048 required_kernelcore
-= min(required_kernelcore
,
7050 kernelcore_remaining
-= size_pages
;
7051 if (!kernelcore_remaining
)
7057 * If there is still required_kernelcore, we do another pass with one
7058 * less node in the count. This will push zone_movable_pfn[nid] further
7059 * along on the nodes that still have memory until kernelcore is
7063 if (usable_nodes
&& required_kernelcore
> usable_nodes
)
7067 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
7068 for (nid
= 0; nid
< MAX_NUMNODES
; nid
++)
7069 zone_movable_pfn
[nid
] =
7070 roundup(zone_movable_pfn
[nid
], MAX_ORDER_NR_PAGES
);
7073 /* restore the node_state */
7074 node_states
[N_MEMORY
] = saved_node_state
;
7077 /* Any regular or high memory on that node ? */
7078 static void check_for_memory(pg_data_t
*pgdat
, int nid
)
7080 enum zone_type zone_type
;
7082 for (zone_type
= 0; zone_type
<= ZONE_MOVABLE
- 1; zone_type
++) {
7083 struct zone
*zone
= &pgdat
->node_zones
[zone_type
];
7084 if (populated_zone(zone
)) {
7085 if (IS_ENABLED(CONFIG_HIGHMEM
))
7086 node_set_state(nid
, N_HIGH_MEMORY
);
7087 if (zone_type
<= ZONE_NORMAL
)
7088 node_set_state(nid
, N_NORMAL_MEMORY
);
7095 * free_area_init_nodes - Initialise all pg_data_t and zone data
7096 * @max_zone_pfn: an array of max PFNs for each zone
7098 * This will call free_area_init_node() for each active node in the system.
7099 * Using the page ranges provided by memblock_set_node(), the size of each
7100 * zone in each node and their holes is calculated. If the maximum PFN
7101 * between two adjacent zones match, it is assumed that the zone is empty.
7102 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
7103 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
7104 * starts where the previous one ended. For example, ZONE_DMA32 starts
7105 * at arch_max_dma_pfn.
7107 void __init
free_area_init_nodes(unsigned long *max_zone_pfn
)
7109 unsigned long start_pfn
, end_pfn
;
7112 /* Record where the zone boundaries are */
7113 memset(arch_zone_lowest_possible_pfn
, 0,
7114 sizeof(arch_zone_lowest_possible_pfn
));
7115 memset(arch_zone_highest_possible_pfn
, 0,
7116 sizeof(arch_zone_highest_possible_pfn
));
7118 start_pfn
= find_min_pfn_with_active_regions();
7120 for (i
= 0; i
< MAX_NR_ZONES
; i
++) {
7121 if (i
== ZONE_MOVABLE
)
7124 end_pfn
= max(max_zone_pfn
[i
], start_pfn
);
7125 arch_zone_lowest_possible_pfn
[i
] = start_pfn
;
7126 arch_zone_highest_possible_pfn
[i
] = end_pfn
;
7128 start_pfn
= end_pfn
;
7131 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
7132 memset(zone_movable_pfn
, 0, sizeof(zone_movable_pfn
));
7133 find_zone_movable_pfns_for_nodes();
7135 /* Print out the zone ranges */
7136 pr_info("Zone ranges:\n");
7137 for (i
= 0; i
< MAX_NR_ZONES
; i
++) {
7138 if (i
== ZONE_MOVABLE
)
7140 pr_info(" %-8s ", zone_names
[i
]);
7141 if (arch_zone_lowest_possible_pfn
[i
] ==
7142 arch_zone_highest_possible_pfn
[i
])
7145 pr_cont("[mem %#018Lx-%#018Lx]\n",
7146 (u64
)arch_zone_lowest_possible_pfn
[i
]
7148 ((u64
)arch_zone_highest_possible_pfn
[i
]
7149 << PAGE_SHIFT
) - 1);
7152 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
7153 pr_info("Movable zone start for each node\n");
7154 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
7155 if (zone_movable_pfn
[i
])
7156 pr_info(" Node %d: %#018Lx\n", i
,
7157 (u64
)zone_movable_pfn
[i
] << PAGE_SHIFT
);
7160 /* Print out the early node map */
7161 pr_info("Early memory node ranges\n");
7162 for_each_mem_pfn_range(i
, MAX_NUMNODES
, &start_pfn
, &end_pfn
, &nid
)
7163 pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid
,
7164 (u64
)start_pfn
<< PAGE_SHIFT
,
7165 ((u64
)end_pfn
<< PAGE_SHIFT
) - 1);
7167 /* Initialise every node */
7168 mminit_verify_pageflags_layout();
7169 setup_nr_node_ids();
7170 zero_resv_unavail();
7171 for_each_online_node(nid
) {
7172 pg_data_t
*pgdat
= NODE_DATA(nid
);
7173 free_area_init_node(nid
, NULL
,
7174 find_min_pfn_for_node(nid
), NULL
);
7176 /* Any memory on that node */
7177 if (pgdat
->node_present_pages
)
7178 node_set_state(nid
, N_MEMORY
);
7179 check_for_memory(pgdat
, nid
);
7183 static int __init
cmdline_parse_core(char *p
, unsigned long *core
,
7184 unsigned long *percent
)
7186 unsigned long long coremem
;
7192 /* Value may be a percentage of total memory, otherwise bytes */
7193 coremem
= simple_strtoull(p
, &endptr
, 0);
7194 if (*endptr
== '%') {
7195 /* Paranoid check for percent values greater than 100 */
7196 WARN_ON(coremem
> 100);
7200 coremem
= memparse(p
, &p
);
7201 /* Paranoid check that UL is enough for the coremem value */
7202 WARN_ON((coremem
>> PAGE_SHIFT
) > ULONG_MAX
);
7204 *core
= coremem
>> PAGE_SHIFT
;
7211 * kernelcore=size sets the amount of memory for use for allocations that
7212 * cannot be reclaimed or migrated.
7214 static int __init
cmdline_parse_kernelcore(char *p
)
7216 /* parse kernelcore=mirror */
7217 if (parse_option_str(p
, "mirror")) {
7218 mirrored_kernelcore
= true;
7222 return cmdline_parse_core(p
, &required_kernelcore
,
7223 &required_kernelcore_percent
);
7227 * movablecore=size sets the amount of memory for use for allocations that
7228 * can be reclaimed or migrated.
7230 static int __init
cmdline_parse_movablecore(char *p
)
7232 return cmdline_parse_core(p
, &required_movablecore
,
7233 &required_movablecore_percent
);
7236 early_param("kernelcore", cmdline_parse_kernelcore
);
7237 early_param("movablecore", cmdline_parse_movablecore
);
7239 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
7241 void adjust_managed_page_count(struct page
*page
, long count
)
7243 atomic_long_add(count
, &page_zone(page
)->managed_pages
);
7244 totalram_pages_add(count
);
7245 #ifdef CONFIG_HIGHMEM
7246 if (PageHighMem(page
))
7247 totalhigh_pages_add(count
);
7250 EXPORT_SYMBOL(adjust_managed_page_count
);
7252 unsigned long free_reserved_area(void *start
, void *end
, int poison
, const char *s
)
7255 unsigned long pages
= 0;
7257 start
= (void *)PAGE_ALIGN((unsigned long)start
);
7258 end
= (void *)((unsigned long)end
& PAGE_MASK
);
7259 for (pos
= start
; pos
< end
; pos
+= PAGE_SIZE
, pages
++) {
7260 struct page
*page
= virt_to_page(pos
);
7261 void *direct_map_addr
;
7264 * 'direct_map_addr' might be different from 'pos'
7265 * because some architectures' virt_to_page()
7266 * work with aliases. Getting the direct map
7267 * address ensures that we get a _writeable_
7268 * alias for the memset().
7270 direct_map_addr
= page_address(page
);
7271 if ((unsigned int)poison
<= 0xFF)
7272 memset(direct_map_addr
, poison
, PAGE_SIZE
);
7274 free_reserved_page(page
);
7278 pr_info("Freeing %s memory: %ldK\n",
7279 s
, pages
<< (PAGE_SHIFT
- 10));
7283 EXPORT_SYMBOL(free_reserved_area
);
7285 #ifdef CONFIG_HIGHMEM
7286 void free_highmem_page(struct page
*page
)
7288 __free_reserved_page(page
);
7289 totalram_pages_inc();
7290 atomic_long_inc(&page_zone(page
)->managed_pages
);
7291 totalhigh_pages_inc();
7296 void __init
mem_init_print_info(const char *str
)
7298 unsigned long physpages
, codesize
, datasize
, rosize
, bss_size
;
7299 unsigned long init_code_size
, init_data_size
;
7301 physpages
= get_num_physpages();
7302 codesize
= _etext
- _stext
;
7303 datasize
= _edata
- _sdata
;
7304 rosize
= __end_rodata
- __start_rodata
;
7305 bss_size
= __bss_stop
- __bss_start
;
7306 init_data_size
= __init_end
- __init_begin
;
7307 init_code_size
= _einittext
- _sinittext
;
7310 * Detect special cases and adjust section sizes accordingly:
7311 * 1) .init.* may be embedded into .data sections
7312 * 2) .init.text.* may be out of [__init_begin, __init_end],
7313 * please refer to arch/tile/kernel/vmlinux.lds.S.
7314 * 3) .rodata.* may be embedded into .text or .data sections.
7316 #define adj_init_size(start, end, size, pos, adj) \
7318 if (start <= pos && pos < end && size > adj) \
7322 adj_init_size(__init_begin
, __init_end
, init_data_size
,
7323 _sinittext
, init_code_size
);
7324 adj_init_size(_stext
, _etext
, codesize
, _sinittext
, init_code_size
);
7325 adj_init_size(_sdata
, _edata
, datasize
, __init_begin
, init_data_size
);
7326 adj_init_size(_stext
, _etext
, codesize
, __start_rodata
, rosize
);
7327 adj_init_size(_sdata
, _edata
, datasize
, __start_rodata
, rosize
);
7329 #undef adj_init_size
7331 pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
7332 #ifdef CONFIG_HIGHMEM
7336 nr_free_pages() << (PAGE_SHIFT
- 10),
7337 physpages
<< (PAGE_SHIFT
- 10),
7338 codesize
>> 10, datasize
>> 10, rosize
>> 10,
7339 (init_data_size
+ init_code_size
) >> 10, bss_size
>> 10,
7340 (physpages
- totalram_pages() - totalcma_pages
) << (PAGE_SHIFT
- 10),
7341 totalcma_pages
<< (PAGE_SHIFT
- 10),
7342 #ifdef CONFIG_HIGHMEM
7343 totalhigh_pages() << (PAGE_SHIFT
- 10),
7345 str
? ", " : "", str
? str
: "");
7349 * set_dma_reserve - set the specified number of pages reserved in the first zone
7350 * @new_dma_reserve: The number of pages to mark reserved
7352 * The per-cpu batchsize and zone watermarks are determined by managed_pages.
7353 * In the DMA zone, a significant percentage may be consumed by kernel image
7354 * and other unfreeable allocations which can skew the watermarks badly. This
7355 * function may optionally be used to account for unfreeable pages in the
7356 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
7357 * smaller per-cpu batchsize.
7359 void __init
set_dma_reserve(unsigned long new_dma_reserve
)
7361 dma_reserve
= new_dma_reserve
;
7364 void __init
free_area_init(unsigned long *zones_size
)
7366 zero_resv_unavail();
7367 free_area_init_node(0, zones_size
,
7368 __pa(PAGE_OFFSET
) >> PAGE_SHIFT
, NULL
);
7371 static int page_alloc_cpu_dead(unsigned int cpu
)
7374 lru_add_drain_cpu(cpu
);
7378 * Spill the event counters of the dead processor
7379 * into the current processors event counters.
7380 * This artificially elevates the count of the current
7383 vm_events_fold_cpu(cpu
);
7386 * Zero the differential counters of the dead processor
7387 * so that the vm statistics are consistent.
7389 * This is only okay since the processor is dead and cannot
7390 * race with what we are doing.
7392 cpu_vm_stats_fold(cpu
);
7396 void __init
page_alloc_init(void)
7400 ret
= cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC_DEAD
,
7401 "mm/page_alloc:dead", NULL
,
7402 page_alloc_cpu_dead
);
7407 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
7408 * or min_free_kbytes changes.
7410 static void calculate_totalreserve_pages(void)
7412 struct pglist_data
*pgdat
;
7413 unsigned long reserve_pages
= 0;
7414 enum zone_type i
, j
;
7416 for_each_online_pgdat(pgdat
) {
7418 pgdat
->totalreserve_pages
= 0;
7420 for (i
= 0; i
< MAX_NR_ZONES
; i
++) {
7421 struct zone
*zone
= pgdat
->node_zones
+ i
;
7423 unsigned long managed_pages
= zone_managed_pages(zone
);
7425 /* Find valid and maximum lowmem_reserve in the zone */
7426 for (j
= i
; j
< MAX_NR_ZONES
; j
++) {
7427 if (zone
->lowmem_reserve
[j
] > max
)
7428 max
= zone
->lowmem_reserve
[j
];
7431 /* we treat the high watermark as reserved pages. */
7432 max
+= high_wmark_pages(zone
);
7434 if (max
> managed_pages
)
7435 max
= managed_pages
;
7437 pgdat
->totalreserve_pages
+= max
;
7439 reserve_pages
+= max
;
7442 totalreserve_pages
= reserve_pages
;
7446 * setup_per_zone_lowmem_reserve - called whenever
7447 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
7448 * has a correct pages reserved value, so an adequate number of
7449 * pages are left in the zone after a successful __alloc_pages().
7451 static void setup_per_zone_lowmem_reserve(void)
7453 struct pglist_data
*pgdat
;
7454 enum zone_type j
, idx
;
7456 for_each_online_pgdat(pgdat
) {
7457 for (j
= 0; j
< MAX_NR_ZONES
; j
++) {
7458 struct zone
*zone
= pgdat
->node_zones
+ j
;
7459 unsigned long managed_pages
= zone_managed_pages(zone
);
7461 zone
->lowmem_reserve
[j
] = 0;
7465 struct zone
*lower_zone
;
7468 lower_zone
= pgdat
->node_zones
+ idx
;
7470 if (sysctl_lowmem_reserve_ratio
[idx
] < 1) {
7471 sysctl_lowmem_reserve_ratio
[idx
] = 0;
7472 lower_zone
->lowmem_reserve
[j
] = 0;
7474 lower_zone
->lowmem_reserve
[j
] =
7475 managed_pages
/ sysctl_lowmem_reserve_ratio
[idx
];
7477 managed_pages
+= zone_managed_pages(lower_zone
);
7482 /* update totalreserve_pages */
7483 calculate_totalreserve_pages();
7486 static void __setup_per_zone_wmarks(void)
7488 unsigned long pages_min
= min_free_kbytes
>> (PAGE_SHIFT
- 10);
7489 unsigned long lowmem_pages
= 0;
7491 unsigned long flags
;
7493 /* Calculate total number of !ZONE_HIGHMEM pages */
7494 for_each_zone(zone
) {
7495 if (!is_highmem(zone
))
7496 lowmem_pages
+= zone_managed_pages(zone
);
7499 for_each_zone(zone
) {
7502 spin_lock_irqsave(&zone
->lock
, flags
);
7503 tmp
= (u64
)pages_min
* zone_managed_pages(zone
);
7504 do_div(tmp
, lowmem_pages
);
7505 if (is_highmem(zone
)) {
7507 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
7508 * need highmem pages, so cap pages_min to a small
7511 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
7512 * deltas control asynch page reclaim, and so should
7513 * not be capped for highmem.
7515 unsigned long min_pages
;
7517 min_pages
= zone_managed_pages(zone
) / 1024;
7518 min_pages
= clamp(min_pages
, SWAP_CLUSTER_MAX
, 128UL);
7519 zone
->_watermark
[WMARK_MIN
] = min_pages
;
7522 * If it's a lowmem zone, reserve a number of pages
7523 * proportionate to the zone's size.
7525 zone
->_watermark
[WMARK_MIN
] = tmp
;
7529 * Set the kswapd watermarks distance according to the
7530 * scale factor in proportion to available memory, but
7531 * ensure a minimum size on small systems.
7533 tmp
= max_t(u64
, tmp
>> 2,
7534 mult_frac(zone_managed_pages(zone
),
7535 watermark_scale_factor
, 10000));
7537 zone
->_watermark
[WMARK_LOW
] = min_wmark_pages(zone
) + tmp
;
7538 zone
->_watermark
[WMARK_HIGH
] = min_wmark_pages(zone
) + tmp
* 2;
7539 zone
->watermark_boost
= 0;
7541 spin_unlock_irqrestore(&zone
->lock
, flags
);
7544 /* update totalreserve_pages */
7545 calculate_totalreserve_pages();
7549 * setup_per_zone_wmarks - called when min_free_kbytes changes
7550 * or when memory is hot-{added|removed}
7552 * Ensures that the watermark[min,low,high] values for each zone are set
7553 * correctly with respect to min_free_kbytes.
7555 void setup_per_zone_wmarks(void)
7557 static DEFINE_SPINLOCK(lock
);
7560 __setup_per_zone_wmarks();
7565 * Initialise min_free_kbytes.
7567 * For small machines we want it small (128k min). For large machines
7568 * we want it large (64MB max). But it is not linear, because network
7569 * bandwidth does not increase linearly with machine size. We use
7571 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
7572 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
7588 int __meminit
init_per_zone_wmark_min(void)
7590 unsigned long lowmem_kbytes
;
7591 int new_min_free_kbytes
;
7593 lowmem_kbytes
= nr_free_buffer_pages() * (PAGE_SIZE
>> 10);
7594 new_min_free_kbytes
= int_sqrt(lowmem_kbytes
* 16);
7596 if (new_min_free_kbytes
> user_min_free_kbytes
) {
7597 min_free_kbytes
= new_min_free_kbytes
;
7598 if (min_free_kbytes
< 128)
7599 min_free_kbytes
= 128;
7600 if (min_free_kbytes
> 65536)
7601 min_free_kbytes
= 65536;
7603 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
7604 new_min_free_kbytes
, user_min_free_kbytes
);
7606 setup_per_zone_wmarks();
7607 refresh_zone_stat_thresholds();
7608 setup_per_zone_lowmem_reserve();
7611 setup_min_unmapped_ratio();
7612 setup_min_slab_ratio();
7617 core_initcall(init_per_zone_wmark_min
)
7620 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
7621 * that we can call two helper functions whenever min_free_kbytes
7624 int min_free_kbytes_sysctl_handler(struct ctl_table
*table
, int write
,
7625 void __user
*buffer
, size_t *length
, loff_t
*ppos
)
7629 rc
= proc_dointvec_minmax(table
, write
, buffer
, length
, ppos
);
7634 user_min_free_kbytes
= min_free_kbytes
;
7635 setup_per_zone_wmarks();
7640 int watermark_boost_factor_sysctl_handler(struct ctl_table
*table
, int write
,
7641 void __user
*buffer
, size_t *length
, loff_t
*ppos
)
7645 rc
= proc_dointvec_minmax(table
, write
, buffer
, length
, ppos
);
7652 int watermark_scale_factor_sysctl_handler(struct ctl_table
*table
, int write
,
7653 void __user
*buffer
, size_t *length
, loff_t
*ppos
)
7657 rc
= proc_dointvec_minmax(table
, write
, buffer
, length
, ppos
);
7662 setup_per_zone_wmarks();
7668 static void setup_min_unmapped_ratio(void)
7673 for_each_online_pgdat(pgdat
)
7674 pgdat
->min_unmapped_pages
= 0;
7677 zone
->zone_pgdat
->min_unmapped_pages
+= (zone_managed_pages(zone
) *
7678 sysctl_min_unmapped_ratio
) / 100;
7682 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table
*table
, int write
,
7683 void __user
*buffer
, size_t *length
, loff_t
*ppos
)
7687 rc
= proc_dointvec_minmax(table
, write
, buffer
, length
, ppos
);
7691 setup_min_unmapped_ratio();
7696 static void setup_min_slab_ratio(void)
7701 for_each_online_pgdat(pgdat
)
7702 pgdat
->min_slab_pages
= 0;
7705 zone
->zone_pgdat
->min_slab_pages
+= (zone_managed_pages(zone
) *
7706 sysctl_min_slab_ratio
) / 100;
7709 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table
*table
, int write
,
7710 void __user
*buffer
, size_t *length
, loff_t
*ppos
)
7714 rc
= proc_dointvec_minmax(table
, write
, buffer
, length
, ppos
);
7718 setup_min_slab_ratio();
7725 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
7726 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
7727 * whenever sysctl_lowmem_reserve_ratio changes.
7729 * The reserve ratio obviously has absolutely no relation with the
7730 * minimum watermarks. The lowmem reserve ratio can only make sense
7731 * if in function of the boot time zone sizes.
7733 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table
*table
, int write
,
7734 void __user
*buffer
, size_t *length
, loff_t
*ppos
)
7736 proc_dointvec_minmax(table
, write
, buffer
, length
, ppos
);
7737 setup_per_zone_lowmem_reserve();
7742 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
7743 * cpu. It is the fraction of total pages in each zone that a hot per cpu
7744 * pagelist can have before it gets flushed back to buddy allocator.
7746 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table
*table
, int write
,
7747 void __user
*buffer
, size_t *length
, loff_t
*ppos
)
7750 int old_percpu_pagelist_fraction
;
7753 mutex_lock(&pcp_batch_high_lock
);
7754 old_percpu_pagelist_fraction
= percpu_pagelist_fraction
;
7756 ret
= proc_dointvec_minmax(table
, write
, buffer
, length
, ppos
);
7757 if (!write
|| ret
< 0)
7760 /* Sanity checking to avoid pcp imbalance */
7761 if (percpu_pagelist_fraction
&&
7762 percpu_pagelist_fraction
< MIN_PERCPU_PAGELIST_FRACTION
) {
7763 percpu_pagelist_fraction
= old_percpu_pagelist_fraction
;
7769 if (percpu_pagelist_fraction
== old_percpu_pagelist_fraction
)
7772 for_each_populated_zone(zone
) {
7775 for_each_possible_cpu(cpu
)
7776 pageset_set_high_and_batch(zone
,
7777 per_cpu_ptr(zone
->pageset
, cpu
));
7780 mutex_unlock(&pcp_batch_high_lock
);
7785 int hashdist
= HASHDIST_DEFAULT
;
7787 static int __init
set_hashdist(char *str
)
7791 hashdist
= simple_strtoul(str
, &str
, 0);
7794 __setup("hashdist=", set_hashdist
);
7797 #ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES
7799 * Returns the number of pages that arch has reserved but
7800 * is not known to alloc_large_system_hash().
7802 static unsigned long __init
arch_reserved_kernel_pages(void)
7809 * Adaptive scale is meant to reduce sizes of hash tables on large memory
7810 * machines. As memory size is increased the scale is also increased but at
7811 * slower pace. Starting from ADAPT_SCALE_BASE (64G), every time memory
7812 * quadruples the scale is increased by one, which means the size of hash table
7813 * only doubles, instead of quadrupling as well.
7814 * Because 32-bit systems cannot have large physical memory, where this scaling
7815 * makes sense, it is disabled on such platforms.
7817 #if __BITS_PER_LONG > 32
7818 #define ADAPT_SCALE_BASE (64ul << 30)
7819 #define ADAPT_SCALE_SHIFT 2
7820 #define ADAPT_SCALE_NPAGES (ADAPT_SCALE_BASE >> PAGE_SHIFT)
7824 * allocate a large system hash table from bootmem
7825 * - it is assumed that the hash table must contain an exact power-of-2
7826 * quantity of entries
7827 * - limit is the number of hash buckets, not the total allocation size
7829 void *__init
alloc_large_system_hash(const char *tablename
,
7830 unsigned long bucketsize
,
7831 unsigned long numentries
,
7834 unsigned int *_hash_shift
,
7835 unsigned int *_hash_mask
,
7836 unsigned long low_limit
,
7837 unsigned long high_limit
)
7839 unsigned long long max
= high_limit
;
7840 unsigned long log2qty
, size
;
7844 /* allow the kernel cmdline to have a say */
7846 /* round applicable memory size up to nearest megabyte */
7847 numentries
= nr_kernel_pages
;
7848 numentries
-= arch_reserved_kernel_pages();
7850 /* It isn't necessary when PAGE_SIZE >= 1MB */
7851 if (PAGE_SHIFT
< 20)
7852 numentries
= round_up(numentries
, (1<<20)/PAGE_SIZE
);
7854 #if __BITS_PER_LONG > 32
7856 unsigned long adapt
;
7858 for (adapt
= ADAPT_SCALE_NPAGES
; adapt
< numentries
;
7859 adapt
<<= ADAPT_SCALE_SHIFT
)
7864 /* limit to 1 bucket per 2^scale bytes of low memory */
7865 if (scale
> PAGE_SHIFT
)
7866 numentries
>>= (scale
- PAGE_SHIFT
);
7868 numentries
<<= (PAGE_SHIFT
- scale
);
7870 /* Make sure we've got at least a 0-order allocation.. */
7871 if (unlikely(flags
& HASH_SMALL
)) {
7872 /* Makes no sense without HASH_EARLY */
7873 WARN_ON(!(flags
& HASH_EARLY
));
7874 if (!(numentries
>> *_hash_shift
)) {
7875 numentries
= 1UL << *_hash_shift
;
7876 BUG_ON(!numentries
);
7878 } else if (unlikely((numentries
* bucketsize
) < PAGE_SIZE
))
7879 numentries
= PAGE_SIZE
/ bucketsize
;
7881 numentries
= roundup_pow_of_two(numentries
);
7883 /* limit allocation size to 1/16 total memory by default */
7885 max
= ((unsigned long long)nr_all_pages
<< PAGE_SHIFT
) >> 4;
7886 do_div(max
, bucketsize
);
7888 max
= min(max
, 0x80000000ULL
);
7890 if (numentries
< low_limit
)
7891 numentries
= low_limit
;
7892 if (numentries
> max
)
7895 log2qty
= ilog2(numentries
);
7897 gfp_flags
= (flags
& HASH_ZERO
) ? GFP_ATOMIC
| __GFP_ZERO
: GFP_ATOMIC
;
7899 size
= bucketsize
<< log2qty
;
7900 if (flags
& HASH_EARLY
) {
7901 if (flags
& HASH_ZERO
)
7902 table
= memblock_alloc_nopanic(size
,
7905 table
= memblock_alloc_raw(size
,
7907 } else if (hashdist
) {
7908 table
= __vmalloc(size
, gfp_flags
, PAGE_KERNEL
);
7911 * If bucketsize is not a power-of-two, we may free
7912 * some pages at the end of hash table which
7913 * alloc_pages_exact() automatically does
7915 if (get_order(size
) < MAX_ORDER
) {
7916 table
= alloc_pages_exact(size
, gfp_flags
);
7917 kmemleak_alloc(table
, size
, 1, gfp_flags
);
7920 } while (!table
&& size
> PAGE_SIZE
&& --log2qty
);
7923 panic("Failed to allocate %s hash table\n", tablename
);
7925 pr_info("%s hash table entries: %ld (order: %d, %lu bytes)\n",
7926 tablename
, 1UL << log2qty
, ilog2(size
) - PAGE_SHIFT
, size
);
7929 *_hash_shift
= log2qty
;
7931 *_hash_mask
= (1 << log2qty
) - 1;
7937 * This function checks whether pageblock includes unmovable pages or not.
7938 * If @count is not zero, it is okay to include less @count unmovable pages
7940 * PageLRU check without isolation or lru_lock could race so that
7941 * MIGRATE_MOVABLE block might include unmovable pages. And __PageMovable
7942 * check without lock_page also may miss some movable non-lru pages at
7943 * race condition. So you can't expect this function should be exact.
7945 bool has_unmovable_pages(struct zone
*zone
, struct page
*page
, int count
,
7946 int migratetype
, int flags
)
7948 unsigned long found
;
7949 unsigned long iter
= 0;
7950 unsigned long pfn
= page_to_pfn(page
);
7951 const char *reason
= "unmovable page";
7954 * TODO we could make this much more efficient by not checking every
7955 * page in the range if we know all of them are in MOVABLE_ZONE and
7956 * that the movable zone guarantees that pages are migratable but
7957 * the later is not the case right now unfortunatelly. E.g. movablecore
7958 * can still lead to having bootmem allocations in zone_movable.
7961 if (is_migrate_cma_page(page
)) {
7963 * CMA allocations (alloc_contig_range) really need to mark
7964 * isolate CMA pageblocks even when they are not movable in fact
7965 * so consider them movable here.
7967 if (is_migrate_cma(migratetype
))
7970 reason
= "CMA page";
7974 for (found
= 0; iter
< pageblock_nr_pages
; iter
++) {
7975 unsigned long check
= pfn
+ iter
;
7977 if (!pfn_valid_within(check
))
7980 page
= pfn_to_page(check
);
7982 if (PageReserved(page
))
7986 * If the zone is movable and we have ruled out all reserved
7987 * pages then it should be reasonably safe to assume the rest
7990 if (zone_idx(zone
) == ZONE_MOVABLE
)
7994 * Hugepages are not in LRU lists, but they're movable.
7995 * We need not scan over tail pages bacause we don't
7996 * handle each tail page individually in migration.
7998 if (PageHuge(page
)) {
7999 struct page
*head
= compound_head(page
);
8000 unsigned int skip_pages
;
8002 if (!hugepage_migration_supported(page_hstate(head
)))
8005 skip_pages
= (1 << compound_order(head
)) - (page
- head
);
8006 iter
+= skip_pages
- 1;
8011 * We can't use page_count without pin a page
8012 * because another CPU can free compound page.
8013 * This check already skips compound tails of THP
8014 * because their page->_refcount is zero at all time.
8016 if (!page_ref_count(page
)) {
8017 if (PageBuddy(page
))
8018 iter
+= (1 << page_order(page
)) - 1;
8023 * The HWPoisoned page may be not in buddy system, and
8024 * page_count() is not 0.
8026 if ((flags
& SKIP_HWPOISON
) && PageHWPoison(page
))
8029 if (__PageMovable(page
))
8035 * If there are RECLAIMABLE pages, we need to check
8036 * it. But now, memory offline itself doesn't call
8037 * shrink_node_slabs() and it still to be fixed.
8040 * If the page is not RAM, page_count()should be 0.
8041 * we don't need more check. This is an _used_ not-movable page.
8043 * The problematic thing here is PG_reserved pages. PG_reserved
8044 * is set to both of a memory hole page and a _used_ kernel
8052 WARN_ON_ONCE(zone_idx(zone
) == ZONE_MOVABLE
);
8053 if (flags
& REPORT_FAILURE
)
8054 dump_page(pfn_to_page(pfn
+ iter
), reason
);
8058 #if (defined(CONFIG_MEMORY_ISOLATION) && defined(CONFIG_COMPACTION)) || defined(CONFIG_CMA)
8060 static unsigned long pfn_max_align_down(unsigned long pfn
)
8062 return pfn
& ~(max_t(unsigned long, MAX_ORDER_NR_PAGES
,
8063 pageblock_nr_pages
) - 1);
8066 static unsigned long pfn_max_align_up(unsigned long pfn
)
8068 return ALIGN(pfn
, max_t(unsigned long, MAX_ORDER_NR_PAGES
,
8069 pageblock_nr_pages
));
8072 /* [start, end) must belong to a single zone. */
8073 static int __alloc_contig_migrate_range(struct compact_control
*cc
,
8074 unsigned long start
, unsigned long end
)
8076 /* This function is based on compact_zone() from compaction.c. */
8077 unsigned long nr_reclaimed
;
8078 unsigned long pfn
= start
;
8079 unsigned int tries
= 0;
8084 while (pfn
< end
|| !list_empty(&cc
->migratepages
)) {
8085 if (fatal_signal_pending(current
)) {
8090 if (list_empty(&cc
->migratepages
)) {
8091 cc
->nr_migratepages
= 0;
8092 pfn
= isolate_migratepages_range(cc
, pfn
, end
);
8098 } else if (++tries
== 5) {
8099 ret
= ret
< 0 ? ret
: -EBUSY
;
8103 nr_reclaimed
= reclaim_clean_pages_from_list(cc
->zone
,
8105 cc
->nr_migratepages
-= nr_reclaimed
;
8107 ret
= migrate_pages(&cc
->migratepages
, alloc_migrate_target
,
8108 NULL
, 0, cc
->mode
, MR_CONTIG_RANGE
);
8111 putback_movable_pages(&cc
->migratepages
);
8118 * alloc_contig_range() -- tries to allocate given range of pages
8119 * @start: start PFN to allocate
8120 * @end: one-past-the-last PFN to allocate
8121 * @migratetype: migratetype of the underlaying pageblocks (either
8122 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
8123 * in range must have the same migratetype and it must
8124 * be either of the two.
8125 * @gfp_mask: GFP mask to use during compaction
8127 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
8128 * aligned. The PFN range must belong to a single zone.
8130 * The first thing this routine does is attempt to MIGRATE_ISOLATE all
8131 * pageblocks in the range. Once isolated, the pageblocks should not
8132 * be modified by others.
8134 * Returns zero on success or negative error code. On success all
8135 * pages which PFN is in [start, end) are allocated for the caller and
8136 * need to be freed with free_contig_range().
8138 int alloc_contig_range(unsigned long start
, unsigned long end
,
8139 unsigned migratetype
, gfp_t gfp_mask
)
8141 unsigned long outer_start
, outer_end
;
8145 struct compact_control cc
= {
8146 .nr_migratepages
= 0,
8148 .zone
= page_zone(pfn_to_page(start
)),
8149 .mode
= MIGRATE_SYNC
,
8150 .ignore_skip_hint
= true,
8151 .no_set_skip_hint
= true,
8152 .gfp_mask
= current_gfp_context(gfp_mask
),
8154 INIT_LIST_HEAD(&cc
.migratepages
);
8157 * What we do here is we mark all pageblocks in range as
8158 * MIGRATE_ISOLATE. Because pageblock and max order pages may
8159 * have different sizes, and due to the way page allocator
8160 * work, we align the range to biggest of the two pages so
8161 * that page allocator won't try to merge buddies from
8162 * different pageblocks and change MIGRATE_ISOLATE to some
8163 * other migration type.
8165 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
8166 * migrate the pages from an unaligned range (ie. pages that
8167 * we are interested in). This will put all the pages in
8168 * range back to page allocator as MIGRATE_ISOLATE.
8170 * When this is done, we take the pages in range from page
8171 * allocator removing them from the buddy system. This way
8172 * page allocator will never consider using them.
8174 * This lets us mark the pageblocks back as
8175 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
8176 * aligned range but not in the unaligned, original range are
8177 * put back to page allocator so that buddy can use them.
8180 ret
= start_isolate_page_range(pfn_max_align_down(start
),
8181 pfn_max_align_up(end
), migratetype
, 0);
8186 * In case of -EBUSY, we'd like to know which page causes problem.
8187 * So, just fall through. test_pages_isolated() has a tracepoint
8188 * which will report the busy page.
8190 * It is possible that busy pages could become available before
8191 * the call to test_pages_isolated, and the range will actually be
8192 * allocated. So, if we fall through be sure to clear ret so that
8193 * -EBUSY is not accidentally used or returned to caller.
8195 ret
= __alloc_contig_migrate_range(&cc
, start
, end
);
8196 if (ret
&& ret
!= -EBUSY
)
8201 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
8202 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
8203 * more, all pages in [start, end) are free in page allocator.
8204 * What we are going to do is to allocate all pages from
8205 * [start, end) (that is remove them from page allocator).
8207 * The only problem is that pages at the beginning and at the
8208 * end of interesting range may be not aligned with pages that
8209 * page allocator holds, ie. they can be part of higher order
8210 * pages. Because of this, we reserve the bigger range and
8211 * once this is done free the pages we are not interested in.
8213 * We don't have to hold zone->lock here because the pages are
8214 * isolated thus they won't get removed from buddy.
8217 lru_add_drain_all();
8218 drain_all_pages(cc
.zone
);
8221 outer_start
= start
;
8222 while (!PageBuddy(pfn_to_page(outer_start
))) {
8223 if (++order
>= MAX_ORDER
) {
8224 outer_start
= start
;
8227 outer_start
&= ~0UL << order
;
8230 if (outer_start
!= start
) {
8231 order
= page_order(pfn_to_page(outer_start
));
8234 * outer_start page could be small order buddy page and
8235 * it doesn't include start page. Adjust outer_start
8236 * in this case to report failed page properly
8237 * on tracepoint in test_pages_isolated()
8239 if (outer_start
+ (1UL << order
) <= start
)
8240 outer_start
= start
;
8243 /* Make sure the range is really isolated. */
8244 if (test_pages_isolated(outer_start
, end
, false)) {
8245 pr_info_ratelimited("%s: [%lx, %lx) PFNs busy\n",
8246 __func__
, outer_start
, end
);
8251 /* Grab isolated pages from freelists. */
8252 outer_end
= isolate_freepages_range(&cc
, outer_start
, end
);
8258 /* Free head and tail (if any) */
8259 if (start
!= outer_start
)
8260 free_contig_range(outer_start
, start
- outer_start
);
8261 if (end
!= outer_end
)
8262 free_contig_range(end
, outer_end
- end
);
8265 undo_isolate_page_range(pfn_max_align_down(start
),
8266 pfn_max_align_up(end
), migratetype
);
8270 void free_contig_range(unsigned long pfn
, unsigned nr_pages
)
8272 unsigned int count
= 0;
8274 for (; nr_pages
--; pfn
++) {
8275 struct page
*page
= pfn_to_page(pfn
);
8277 count
+= page_count(page
) != 1;
8280 WARN(count
!= 0, "%d pages are still in use!\n", count
);
8284 #ifdef CONFIG_MEMORY_HOTPLUG
8286 * The zone indicated has a new number of managed_pages; batch sizes and percpu
8287 * page high values need to be recalulated.
8289 void __meminit
zone_pcp_update(struct zone
*zone
)
8292 mutex_lock(&pcp_batch_high_lock
);
8293 for_each_possible_cpu(cpu
)
8294 pageset_set_high_and_batch(zone
,
8295 per_cpu_ptr(zone
->pageset
, cpu
));
8296 mutex_unlock(&pcp_batch_high_lock
);
8300 void zone_pcp_reset(struct zone
*zone
)
8302 unsigned long flags
;
8304 struct per_cpu_pageset
*pset
;
8306 /* avoid races with drain_pages() */
8307 local_irq_save(flags
);
8308 if (zone
->pageset
!= &boot_pageset
) {
8309 for_each_online_cpu(cpu
) {
8310 pset
= per_cpu_ptr(zone
->pageset
, cpu
);
8311 drain_zonestat(zone
, pset
);
8313 free_percpu(zone
->pageset
);
8314 zone
->pageset
= &boot_pageset
;
8316 local_irq_restore(flags
);
8319 #ifdef CONFIG_MEMORY_HOTREMOVE
8321 * All pages in the range must be in a single zone and isolated
8322 * before calling this.
8325 __offline_isolated_pages(unsigned long start_pfn
, unsigned long end_pfn
)
8329 unsigned int order
, i
;
8331 unsigned long flags
;
8332 /* find the first valid pfn */
8333 for (pfn
= start_pfn
; pfn
< end_pfn
; pfn
++)
8338 offline_mem_sections(pfn
, end_pfn
);
8339 zone
= page_zone(pfn_to_page(pfn
));
8340 spin_lock_irqsave(&zone
->lock
, flags
);
8342 while (pfn
< end_pfn
) {
8343 if (!pfn_valid(pfn
)) {
8347 page
= pfn_to_page(pfn
);
8349 * The HWPoisoned page may be not in buddy system, and
8350 * page_count() is not 0.
8352 if (unlikely(!PageBuddy(page
) && PageHWPoison(page
))) {
8354 SetPageReserved(page
);
8358 BUG_ON(page_count(page
));
8359 BUG_ON(!PageBuddy(page
));
8360 order
= page_order(page
);
8361 #ifdef CONFIG_DEBUG_VM
8362 pr_info("remove from free list %lx %d %lx\n",
8363 pfn
, 1 << order
, end_pfn
);
8365 list_del(&page
->lru
);
8366 rmv_page_order(page
);
8367 zone
->free_area
[order
].nr_free
--;
8368 for (i
= 0; i
< (1 << order
); i
++)
8369 SetPageReserved((page
+i
));
8370 pfn
+= (1 << order
);
8372 spin_unlock_irqrestore(&zone
->lock
, flags
);
8376 bool is_free_buddy_page(struct page
*page
)
8378 struct zone
*zone
= page_zone(page
);
8379 unsigned long pfn
= page_to_pfn(page
);
8380 unsigned long flags
;
8383 spin_lock_irqsave(&zone
->lock
, flags
);
8384 for (order
= 0; order
< MAX_ORDER
; order
++) {
8385 struct page
*page_head
= page
- (pfn
& ((1 << order
) - 1));
8387 if (PageBuddy(page_head
) && page_order(page_head
) >= order
)
8390 spin_unlock_irqrestore(&zone
->lock
, flags
);
8392 return order
< MAX_ORDER
;
8395 #ifdef CONFIG_MEMORY_FAILURE
8397 * Set PG_hwpoison flag if a given page is confirmed to be a free page. This
8398 * test is performed under the zone lock to prevent a race against page
8401 bool set_hwpoison_free_buddy_page(struct page
*page
)
8403 struct zone
*zone
= page_zone(page
);
8404 unsigned long pfn
= page_to_pfn(page
);
8405 unsigned long flags
;
8407 bool hwpoisoned
= false;
8409 spin_lock_irqsave(&zone
->lock
, flags
);
8410 for (order
= 0; order
< MAX_ORDER
; order
++) {
8411 struct page
*page_head
= page
- (pfn
& ((1 << order
) - 1));
8413 if (PageBuddy(page_head
) && page_order(page_head
) >= order
) {
8414 if (!TestSetPageHWPoison(page
))
8419 spin_unlock_irqrestore(&zone
->lock
, flags
);