Linux 5.7.7
[linux/fpc-iii.git] / mm / page_alloc.c
blobd0c0d9364aa6d7fa9748ecff30e2ca07b1126807
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * linux/mm/page_alloc.c
5 * Manages the free list, the system allocates free pages here.
6 * Note that kmalloc() lives in slab.c
8 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
9 * Swap reorganised 29.12.95, Stephen Tweedie
10 * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
11 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
12 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
13 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000
14 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
15 * (lots of bits borrowed from Ingo Molnar & Andrew Morton)
18 #include <linux/stddef.h>
19 #include <linux/mm.h>
20 #include <linux/highmem.h>
21 #include <linux/swap.h>
22 #include <linux/interrupt.h>
23 #include <linux/pagemap.h>
24 #include <linux/jiffies.h>
25 #include <linux/memblock.h>
26 #include <linux/compiler.h>
27 #include <linux/kernel.h>
28 #include <linux/kasan.h>
29 #include <linux/module.h>
30 #include <linux/suspend.h>
31 #include <linux/pagevec.h>
32 #include <linux/blkdev.h>
33 #include <linux/slab.h>
34 #include <linux/ratelimit.h>
35 #include <linux/oom.h>
36 #include <linux/topology.h>
37 #include <linux/sysctl.h>
38 #include <linux/cpu.h>
39 #include <linux/cpuset.h>
40 #include <linux/memory_hotplug.h>
41 #include <linux/nodemask.h>
42 #include <linux/vmalloc.h>
43 #include <linux/vmstat.h>
44 #include <linux/mempolicy.h>
45 #include <linux/memremap.h>
46 #include <linux/stop_machine.h>
47 #include <linux/random.h>
48 #include <linux/sort.h>
49 #include <linux/pfn.h>
50 #include <linux/backing-dev.h>
51 #include <linux/fault-inject.h>
52 #include <linux/page-isolation.h>
53 #include <linux/debugobjects.h>
54 #include <linux/kmemleak.h>
55 #include <linux/compaction.h>
56 #include <trace/events/kmem.h>
57 #include <trace/events/oom.h>
58 #include <linux/prefetch.h>
59 #include <linux/mm_inline.h>
60 #include <linux/migrate.h>
61 #include <linux/hugetlb.h>
62 #include <linux/sched/rt.h>
63 #include <linux/sched/mm.h>
64 #include <linux/page_owner.h>
65 #include <linux/kthread.h>
66 #include <linux/memcontrol.h>
67 #include <linux/ftrace.h>
68 #include <linux/lockdep.h>
69 #include <linux/nmi.h>
70 #include <linux/psi.h>
72 #include <asm/sections.h>
73 #include <asm/tlbflush.h>
74 #include <asm/div64.h>
75 #include "internal.h"
76 #include "shuffle.h"
77 #include "page_reporting.h"
79 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
80 static DEFINE_MUTEX(pcp_batch_high_lock);
81 #define MIN_PERCPU_PAGELIST_FRACTION (8)
83 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
84 DEFINE_PER_CPU(int, numa_node);
85 EXPORT_PER_CPU_SYMBOL(numa_node);
86 #endif
88 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
90 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
92 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
93 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
94 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
95 * defined in <linux/topology.h>.
97 DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
98 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
99 #endif
101 /* work_structs for global per-cpu drains */
102 struct pcpu_drain {
103 struct zone *zone;
104 struct work_struct work;
106 static DEFINE_MUTEX(pcpu_drain_mutex);
107 static DEFINE_PER_CPU(struct pcpu_drain, pcpu_drain);
109 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
110 volatile unsigned long latent_entropy __latent_entropy;
111 EXPORT_SYMBOL(latent_entropy);
112 #endif
115 * Array of node states.
117 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
118 [N_POSSIBLE] = NODE_MASK_ALL,
119 [N_ONLINE] = { { [0] = 1UL } },
120 #ifndef CONFIG_NUMA
121 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
122 #ifdef CONFIG_HIGHMEM
123 [N_HIGH_MEMORY] = { { [0] = 1UL } },
124 #endif
125 [N_MEMORY] = { { [0] = 1UL } },
126 [N_CPU] = { { [0] = 1UL } },
127 #endif /* NUMA */
129 EXPORT_SYMBOL(node_states);
131 atomic_long_t _totalram_pages __read_mostly;
132 EXPORT_SYMBOL(_totalram_pages);
133 unsigned long totalreserve_pages __read_mostly;
134 unsigned long totalcma_pages __read_mostly;
136 int percpu_pagelist_fraction;
137 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
138 #ifdef CONFIG_INIT_ON_ALLOC_DEFAULT_ON
139 DEFINE_STATIC_KEY_TRUE(init_on_alloc);
140 #else
141 DEFINE_STATIC_KEY_FALSE(init_on_alloc);
142 #endif
143 EXPORT_SYMBOL(init_on_alloc);
145 #ifdef CONFIG_INIT_ON_FREE_DEFAULT_ON
146 DEFINE_STATIC_KEY_TRUE(init_on_free);
147 #else
148 DEFINE_STATIC_KEY_FALSE(init_on_free);
149 #endif
150 EXPORT_SYMBOL(init_on_free);
152 static int __init early_init_on_alloc(char *buf)
154 int ret;
155 bool bool_result;
157 if (!buf)
158 return -EINVAL;
159 ret = kstrtobool(buf, &bool_result);
160 if (bool_result && page_poisoning_enabled())
161 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, will take precedence over init_on_alloc\n");
162 if (bool_result)
163 static_branch_enable(&init_on_alloc);
164 else
165 static_branch_disable(&init_on_alloc);
166 return ret;
168 early_param("init_on_alloc", early_init_on_alloc);
170 static int __init early_init_on_free(char *buf)
172 int ret;
173 bool bool_result;
175 if (!buf)
176 return -EINVAL;
177 ret = kstrtobool(buf, &bool_result);
178 if (bool_result && page_poisoning_enabled())
179 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, will take precedence over init_on_free\n");
180 if (bool_result)
181 static_branch_enable(&init_on_free);
182 else
183 static_branch_disable(&init_on_free);
184 return ret;
186 early_param("init_on_free", early_init_on_free);
189 * A cached value of the page's pageblock's migratetype, used when the page is
190 * put on a pcplist. Used to avoid the pageblock migratetype lookup when
191 * freeing from pcplists in most cases, at the cost of possibly becoming stale.
192 * Also the migratetype set in the page does not necessarily match the pcplist
193 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
194 * other index - this ensures that it will be put on the correct CMA freelist.
196 static inline int get_pcppage_migratetype(struct page *page)
198 return page->index;
201 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
203 page->index = migratetype;
206 #ifdef CONFIG_PM_SLEEP
208 * The following functions are used by the suspend/hibernate code to temporarily
209 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
210 * while devices are suspended. To avoid races with the suspend/hibernate code,
211 * they should always be called with system_transition_mutex held
212 * (gfp_allowed_mask also should only be modified with system_transition_mutex
213 * held, unless the suspend/hibernate code is guaranteed not to run in parallel
214 * with that modification).
217 static gfp_t saved_gfp_mask;
219 void pm_restore_gfp_mask(void)
221 WARN_ON(!mutex_is_locked(&system_transition_mutex));
222 if (saved_gfp_mask) {
223 gfp_allowed_mask = saved_gfp_mask;
224 saved_gfp_mask = 0;
228 void pm_restrict_gfp_mask(void)
230 WARN_ON(!mutex_is_locked(&system_transition_mutex));
231 WARN_ON(saved_gfp_mask);
232 saved_gfp_mask = gfp_allowed_mask;
233 gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
236 bool pm_suspended_storage(void)
238 if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
239 return false;
240 return true;
242 #endif /* CONFIG_PM_SLEEP */
244 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
245 unsigned int pageblock_order __read_mostly;
246 #endif
248 static void __free_pages_ok(struct page *page, unsigned int order);
251 * results with 256, 32 in the lowmem_reserve sysctl:
252 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
253 * 1G machine -> (16M dma, 784M normal, 224M high)
254 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
255 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
256 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
258 * TBD: should special case ZONE_DMA32 machines here - in those we normally
259 * don't need any ZONE_NORMAL reservation
261 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
262 #ifdef CONFIG_ZONE_DMA
263 [ZONE_DMA] = 256,
264 #endif
265 #ifdef CONFIG_ZONE_DMA32
266 [ZONE_DMA32] = 256,
267 #endif
268 [ZONE_NORMAL] = 32,
269 #ifdef CONFIG_HIGHMEM
270 [ZONE_HIGHMEM] = 0,
271 #endif
272 [ZONE_MOVABLE] = 0,
275 static char * const zone_names[MAX_NR_ZONES] = {
276 #ifdef CONFIG_ZONE_DMA
277 "DMA",
278 #endif
279 #ifdef CONFIG_ZONE_DMA32
280 "DMA32",
281 #endif
282 "Normal",
283 #ifdef CONFIG_HIGHMEM
284 "HighMem",
285 #endif
286 "Movable",
287 #ifdef CONFIG_ZONE_DEVICE
288 "Device",
289 #endif
292 const char * const migratetype_names[MIGRATE_TYPES] = {
293 "Unmovable",
294 "Movable",
295 "Reclaimable",
296 "HighAtomic",
297 #ifdef CONFIG_CMA
298 "CMA",
299 #endif
300 #ifdef CONFIG_MEMORY_ISOLATION
301 "Isolate",
302 #endif
305 compound_page_dtor * const compound_page_dtors[] = {
306 NULL,
307 free_compound_page,
308 #ifdef CONFIG_HUGETLB_PAGE
309 free_huge_page,
310 #endif
311 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
312 free_transhuge_page,
313 #endif
316 int min_free_kbytes = 1024;
317 int user_min_free_kbytes = -1;
318 #ifdef CONFIG_DISCONTIGMEM
320 * DiscontigMem defines memory ranges as separate pg_data_t even if the ranges
321 * are not on separate NUMA nodes. Functionally this works but with
322 * watermark_boost_factor, it can reclaim prematurely as the ranges can be
323 * quite small. By default, do not boost watermarks on discontigmem as in
324 * many cases very high-order allocations like THP are likely to be
325 * unsupported and the premature reclaim offsets the advantage of long-term
326 * fragmentation avoidance.
328 int watermark_boost_factor __read_mostly;
329 #else
330 int watermark_boost_factor __read_mostly = 15000;
331 #endif
332 int watermark_scale_factor = 10;
334 static unsigned long nr_kernel_pages __initdata;
335 static unsigned long nr_all_pages __initdata;
336 static unsigned long dma_reserve __initdata;
338 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
339 static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata;
340 static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata;
341 static unsigned long required_kernelcore __initdata;
342 static unsigned long required_kernelcore_percent __initdata;
343 static unsigned long required_movablecore __initdata;
344 static unsigned long required_movablecore_percent __initdata;
345 static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata;
346 static bool mirrored_kernelcore __meminitdata;
348 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
349 int movable_zone;
350 EXPORT_SYMBOL(movable_zone);
351 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
353 #if MAX_NUMNODES > 1
354 unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
355 unsigned int nr_online_nodes __read_mostly = 1;
356 EXPORT_SYMBOL(nr_node_ids);
357 EXPORT_SYMBOL(nr_online_nodes);
358 #endif
360 int page_group_by_mobility_disabled __read_mostly;
362 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
364 * During boot we initialize deferred pages on-demand, as needed, but once
365 * page_alloc_init_late() has finished, the deferred pages are all initialized,
366 * and we can permanently disable that path.
368 static DEFINE_STATIC_KEY_TRUE(deferred_pages);
371 * Calling kasan_free_pages() only after deferred memory initialization
372 * has completed. Poisoning pages during deferred memory init will greatly
373 * lengthen the process and cause problem in large memory systems as the
374 * deferred pages initialization is done with interrupt disabled.
376 * Assuming that there will be no reference to those newly initialized
377 * pages before they are ever allocated, this should have no effect on
378 * KASAN memory tracking as the poison will be properly inserted at page
379 * allocation time. The only corner case is when pages are allocated by
380 * on-demand allocation and then freed again before the deferred pages
381 * initialization is done, but this is not likely to happen.
383 static inline void kasan_free_nondeferred_pages(struct page *page, int order)
385 if (!static_branch_unlikely(&deferred_pages))
386 kasan_free_pages(page, order);
389 /* Returns true if the struct page for the pfn is uninitialised */
390 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
392 int nid = early_pfn_to_nid(pfn);
394 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
395 return true;
397 return false;
401 * Returns true when the remaining initialisation should be deferred until
402 * later in the boot cycle when it can be parallelised.
404 static bool __meminit
405 defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
407 static unsigned long prev_end_pfn, nr_initialised;
410 * prev_end_pfn static that contains the end of previous zone
411 * No need to protect because called very early in boot before smp_init.
413 if (prev_end_pfn != end_pfn) {
414 prev_end_pfn = end_pfn;
415 nr_initialised = 0;
418 /* Always populate low zones for address-constrained allocations */
419 if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
420 return false;
423 * We start only with one section of pages, more pages are added as
424 * needed until the rest of deferred pages are initialized.
426 nr_initialised++;
427 if ((nr_initialised > PAGES_PER_SECTION) &&
428 (pfn & (PAGES_PER_SECTION - 1)) == 0) {
429 NODE_DATA(nid)->first_deferred_pfn = pfn;
430 return true;
432 return false;
434 #else
435 #define kasan_free_nondeferred_pages(p, o) kasan_free_pages(p, o)
437 static inline bool early_page_uninitialised(unsigned long pfn)
439 return false;
442 static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
444 return false;
446 #endif
448 /* Return a pointer to the bitmap storing bits affecting a block of pages */
449 static inline unsigned long *get_pageblock_bitmap(struct page *page,
450 unsigned long pfn)
452 #ifdef CONFIG_SPARSEMEM
453 return section_to_usemap(__pfn_to_section(pfn));
454 #else
455 return page_zone(page)->pageblock_flags;
456 #endif /* CONFIG_SPARSEMEM */
459 static inline int pfn_to_bitidx(struct page *page, unsigned long pfn)
461 #ifdef CONFIG_SPARSEMEM
462 pfn &= (PAGES_PER_SECTION-1);
463 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
464 #else
465 pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
466 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
467 #endif /* CONFIG_SPARSEMEM */
471 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
472 * @page: The page within the block of interest
473 * @pfn: The target page frame number
474 * @end_bitidx: The last bit of interest to retrieve
475 * @mask: mask of bits that the caller is interested in
477 * Return: pageblock_bits flags
479 static __always_inline unsigned long __get_pfnblock_flags_mask(struct page *page,
480 unsigned long pfn,
481 unsigned long end_bitidx,
482 unsigned long mask)
484 unsigned long *bitmap;
485 unsigned long bitidx, word_bitidx;
486 unsigned long word;
488 bitmap = get_pageblock_bitmap(page, pfn);
489 bitidx = pfn_to_bitidx(page, pfn);
490 word_bitidx = bitidx / BITS_PER_LONG;
491 bitidx &= (BITS_PER_LONG-1);
493 word = bitmap[word_bitidx];
494 bitidx += end_bitidx;
495 return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
498 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
499 unsigned long end_bitidx,
500 unsigned long mask)
502 return __get_pfnblock_flags_mask(page, pfn, end_bitidx, mask);
505 static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn)
507 return __get_pfnblock_flags_mask(page, pfn, PB_migrate_end, MIGRATETYPE_MASK);
511 * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
512 * @page: The page within the block of interest
513 * @flags: The flags to set
514 * @pfn: The target page frame number
515 * @end_bitidx: The last bit of interest
516 * @mask: mask of bits that the caller is interested in
518 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
519 unsigned long pfn,
520 unsigned long end_bitidx,
521 unsigned long mask)
523 unsigned long *bitmap;
524 unsigned long bitidx, word_bitidx;
525 unsigned long old_word, word;
527 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
528 BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits));
530 bitmap = get_pageblock_bitmap(page, pfn);
531 bitidx = pfn_to_bitidx(page, pfn);
532 word_bitidx = bitidx / BITS_PER_LONG;
533 bitidx &= (BITS_PER_LONG-1);
535 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
537 bitidx += end_bitidx;
538 mask <<= (BITS_PER_LONG - bitidx - 1);
539 flags <<= (BITS_PER_LONG - bitidx - 1);
541 word = READ_ONCE(bitmap[word_bitidx]);
542 for (;;) {
543 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
544 if (word == old_word)
545 break;
546 word = old_word;
550 void set_pageblock_migratetype(struct page *page, int migratetype)
552 if (unlikely(page_group_by_mobility_disabled &&
553 migratetype < MIGRATE_PCPTYPES))
554 migratetype = MIGRATE_UNMOVABLE;
556 set_pageblock_flags_group(page, (unsigned long)migratetype,
557 PB_migrate, PB_migrate_end);
560 #ifdef CONFIG_DEBUG_VM
561 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
563 int ret = 0;
564 unsigned seq;
565 unsigned long pfn = page_to_pfn(page);
566 unsigned long sp, start_pfn;
568 do {
569 seq = zone_span_seqbegin(zone);
570 start_pfn = zone->zone_start_pfn;
571 sp = zone->spanned_pages;
572 if (!zone_spans_pfn(zone, pfn))
573 ret = 1;
574 } while (zone_span_seqretry(zone, seq));
576 if (ret)
577 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
578 pfn, zone_to_nid(zone), zone->name,
579 start_pfn, start_pfn + sp);
581 return ret;
584 static int page_is_consistent(struct zone *zone, struct page *page)
586 if (!pfn_valid_within(page_to_pfn(page)))
587 return 0;
588 if (zone != page_zone(page))
589 return 0;
591 return 1;
594 * Temporary debugging check for pages not lying within a given zone.
596 static int __maybe_unused bad_range(struct zone *zone, struct page *page)
598 if (page_outside_zone_boundaries(zone, page))
599 return 1;
600 if (!page_is_consistent(zone, page))
601 return 1;
603 return 0;
605 #else
606 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
608 return 0;
610 #endif
612 static void bad_page(struct page *page, const char *reason,
613 unsigned long bad_flags)
615 static unsigned long resume;
616 static unsigned long nr_shown;
617 static unsigned long nr_unshown;
620 * Allow a burst of 60 reports, then keep quiet for that minute;
621 * or allow a steady drip of one report per second.
623 if (nr_shown == 60) {
624 if (time_before(jiffies, resume)) {
625 nr_unshown++;
626 goto out;
628 if (nr_unshown) {
629 pr_alert(
630 "BUG: Bad page state: %lu messages suppressed\n",
631 nr_unshown);
632 nr_unshown = 0;
634 nr_shown = 0;
636 if (nr_shown++ == 0)
637 resume = jiffies + 60 * HZ;
639 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
640 current->comm, page_to_pfn(page));
641 __dump_page(page, reason);
642 bad_flags &= page->flags;
643 if (bad_flags)
644 pr_alert("bad because of flags: %#lx(%pGp)\n",
645 bad_flags, &bad_flags);
646 dump_page_owner(page);
648 print_modules();
649 dump_stack();
650 out:
651 /* Leave bad fields for debug, except PageBuddy could make trouble */
652 page_mapcount_reset(page); /* remove PageBuddy */
653 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
657 * Higher-order pages are called "compound pages". They are structured thusly:
659 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
661 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
662 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
664 * The first tail page's ->compound_dtor holds the offset in array of compound
665 * page destructors. See compound_page_dtors.
667 * The first tail page's ->compound_order holds the order of allocation.
668 * This usage means that zero-order pages may not be compound.
671 void free_compound_page(struct page *page)
673 mem_cgroup_uncharge(page);
674 __free_pages_ok(page, compound_order(page));
677 void prep_compound_page(struct page *page, unsigned int order)
679 int i;
680 int nr_pages = 1 << order;
682 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
683 set_compound_order(page, order);
684 __SetPageHead(page);
685 for (i = 1; i < nr_pages; i++) {
686 struct page *p = page + i;
687 set_page_count(p, 0);
688 p->mapping = TAIL_MAPPING;
689 set_compound_head(p, page);
691 atomic_set(compound_mapcount_ptr(page), -1);
692 if (hpage_pincount_available(page))
693 atomic_set(compound_pincount_ptr(page), 0);
696 #ifdef CONFIG_DEBUG_PAGEALLOC
697 unsigned int _debug_guardpage_minorder;
699 bool _debug_pagealloc_enabled_early __read_mostly
700 = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
701 EXPORT_SYMBOL(_debug_pagealloc_enabled_early);
702 DEFINE_STATIC_KEY_FALSE(_debug_pagealloc_enabled);
703 EXPORT_SYMBOL(_debug_pagealloc_enabled);
705 DEFINE_STATIC_KEY_FALSE(_debug_guardpage_enabled);
707 static int __init early_debug_pagealloc(char *buf)
709 return kstrtobool(buf, &_debug_pagealloc_enabled_early);
711 early_param("debug_pagealloc", early_debug_pagealloc);
713 void init_debug_pagealloc(void)
715 if (!debug_pagealloc_enabled())
716 return;
718 static_branch_enable(&_debug_pagealloc_enabled);
720 if (!debug_guardpage_minorder())
721 return;
723 static_branch_enable(&_debug_guardpage_enabled);
726 static int __init debug_guardpage_minorder_setup(char *buf)
728 unsigned long res;
730 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
731 pr_err("Bad debug_guardpage_minorder value\n");
732 return 0;
734 _debug_guardpage_minorder = res;
735 pr_info("Setting debug_guardpage_minorder to %lu\n", res);
736 return 0;
738 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
740 static inline bool set_page_guard(struct zone *zone, struct page *page,
741 unsigned int order, int migratetype)
743 if (!debug_guardpage_enabled())
744 return false;
746 if (order >= debug_guardpage_minorder())
747 return false;
749 __SetPageGuard(page);
750 INIT_LIST_HEAD(&page->lru);
751 set_page_private(page, order);
752 /* Guard pages are not available for any usage */
753 __mod_zone_freepage_state(zone, -(1 << order), migratetype);
755 return true;
758 static inline void clear_page_guard(struct zone *zone, struct page *page,
759 unsigned int order, int migratetype)
761 if (!debug_guardpage_enabled())
762 return;
764 __ClearPageGuard(page);
766 set_page_private(page, 0);
767 if (!is_migrate_isolate(migratetype))
768 __mod_zone_freepage_state(zone, (1 << order), migratetype);
770 #else
771 static inline bool set_page_guard(struct zone *zone, struct page *page,
772 unsigned int order, int migratetype) { return false; }
773 static inline void clear_page_guard(struct zone *zone, struct page *page,
774 unsigned int order, int migratetype) {}
775 #endif
777 static inline void set_page_order(struct page *page, unsigned int order)
779 set_page_private(page, order);
780 __SetPageBuddy(page);
784 * This function checks whether a page is free && is the buddy
785 * we can coalesce a page and its buddy if
786 * (a) the buddy is not in a hole (check before calling!) &&
787 * (b) the buddy is in the buddy system &&
788 * (c) a page and its buddy have the same order &&
789 * (d) a page and its buddy are in the same zone.
791 * For recording whether a page is in the buddy system, we set PageBuddy.
792 * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
794 * For recording page's order, we use page_private(page).
796 static inline bool page_is_buddy(struct page *page, struct page *buddy,
797 unsigned int order)
799 if (!page_is_guard(buddy) && !PageBuddy(buddy))
800 return false;
802 if (page_order(buddy) != order)
803 return false;
806 * zone check is done late to avoid uselessly calculating
807 * zone/node ids for pages that could never merge.
809 if (page_zone_id(page) != page_zone_id(buddy))
810 return false;
812 VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
814 return true;
817 #ifdef CONFIG_COMPACTION
818 static inline struct capture_control *task_capc(struct zone *zone)
820 struct capture_control *capc = current->capture_control;
822 return capc &&
823 !(current->flags & PF_KTHREAD) &&
824 !capc->page &&
825 capc->cc->zone == zone &&
826 capc->cc->direct_compaction ? capc : NULL;
829 static inline bool
830 compaction_capture(struct capture_control *capc, struct page *page,
831 int order, int migratetype)
833 if (!capc || order != capc->cc->order)
834 return false;
836 /* Do not accidentally pollute CMA or isolated regions*/
837 if (is_migrate_cma(migratetype) ||
838 is_migrate_isolate(migratetype))
839 return false;
842 * Do not let lower order allocations polluate a movable pageblock.
843 * This might let an unmovable request use a reclaimable pageblock
844 * and vice-versa but no more than normal fallback logic which can
845 * have trouble finding a high-order free page.
847 if (order < pageblock_order && migratetype == MIGRATE_MOVABLE)
848 return false;
850 capc->page = page;
851 return true;
854 #else
855 static inline struct capture_control *task_capc(struct zone *zone)
857 return NULL;
860 static inline bool
861 compaction_capture(struct capture_control *capc, struct page *page,
862 int order, int migratetype)
864 return false;
866 #endif /* CONFIG_COMPACTION */
868 /* Used for pages not on another list */
869 static inline void add_to_free_list(struct page *page, struct zone *zone,
870 unsigned int order, int migratetype)
872 struct free_area *area = &zone->free_area[order];
874 list_add(&page->lru, &area->free_list[migratetype]);
875 area->nr_free++;
878 /* Used for pages not on another list */
879 static inline void add_to_free_list_tail(struct page *page, struct zone *zone,
880 unsigned int order, int migratetype)
882 struct free_area *area = &zone->free_area[order];
884 list_add_tail(&page->lru, &area->free_list[migratetype]);
885 area->nr_free++;
888 /* Used for pages which are on another list */
889 static inline void move_to_free_list(struct page *page, struct zone *zone,
890 unsigned int order, int migratetype)
892 struct free_area *area = &zone->free_area[order];
894 list_move(&page->lru, &area->free_list[migratetype]);
897 static inline void del_page_from_free_list(struct page *page, struct zone *zone,
898 unsigned int order)
900 /* clear reported state and update reported page count */
901 if (page_reported(page))
902 __ClearPageReported(page);
904 list_del(&page->lru);
905 __ClearPageBuddy(page);
906 set_page_private(page, 0);
907 zone->free_area[order].nr_free--;
911 * If this is not the largest possible page, check if the buddy
912 * of the next-highest order is free. If it is, it's possible
913 * that pages are being freed that will coalesce soon. In case,
914 * that is happening, add the free page to the tail of the list
915 * so it's less likely to be used soon and more likely to be merged
916 * as a higher order page
918 static inline bool
919 buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
920 struct page *page, unsigned int order)
922 struct page *higher_page, *higher_buddy;
923 unsigned long combined_pfn;
925 if (order >= MAX_ORDER - 2)
926 return false;
928 if (!pfn_valid_within(buddy_pfn))
929 return false;
931 combined_pfn = buddy_pfn & pfn;
932 higher_page = page + (combined_pfn - pfn);
933 buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
934 higher_buddy = higher_page + (buddy_pfn - combined_pfn);
936 return pfn_valid_within(buddy_pfn) &&
937 page_is_buddy(higher_page, higher_buddy, order + 1);
941 * Freeing function for a buddy system allocator.
943 * The concept of a buddy system is to maintain direct-mapped table
944 * (containing bit values) for memory blocks of various "orders".
945 * The bottom level table contains the map for the smallest allocatable
946 * units of memory (here, pages), and each level above it describes
947 * pairs of units from the levels below, hence, "buddies".
948 * At a high level, all that happens here is marking the table entry
949 * at the bottom level available, and propagating the changes upward
950 * as necessary, plus some accounting needed to play nicely with other
951 * parts of the VM system.
952 * At each level, we keep a list of pages, which are heads of continuous
953 * free pages of length of (1 << order) and marked with PageBuddy.
954 * Page's order is recorded in page_private(page) field.
955 * So when we are allocating or freeing one, we can derive the state of the
956 * other. That is, if we allocate a small block, and both were
957 * free, the remainder of the region must be split into blocks.
958 * If a block is freed, and its buddy is also free, then this
959 * triggers coalescing into a block of larger size.
961 * -- nyc
964 static inline void __free_one_page(struct page *page,
965 unsigned long pfn,
966 struct zone *zone, unsigned int order,
967 int migratetype, bool report)
969 struct capture_control *capc = task_capc(zone);
970 unsigned long uninitialized_var(buddy_pfn);
971 unsigned long combined_pfn;
972 unsigned int max_order;
973 struct page *buddy;
974 bool to_tail;
976 max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
978 VM_BUG_ON(!zone_is_initialized(zone));
979 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
981 VM_BUG_ON(migratetype == -1);
982 if (likely(!is_migrate_isolate(migratetype)))
983 __mod_zone_freepage_state(zone, 1 << order, migratetype);
985 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
986 VM_BUG_ON_PAGE(bad_range(zone, page), page);
988 continue_merging:
989 while (order < max_order - 1) {
990 if (compaction_capture(capc, page, order, migratetype)) {
991 __mod_zone_freepage_state(zone, -(1 << order),
992 migratetype);
993 return;
995 buddy_pfn = __find_buddy_pfn(pfn, order);
996 buddy = page + (buddy_pfn - pfn);
998 if (!pfn_valid_within(buddy_pfn))
999 goto done_merging;
1000 if (!page_is_buddy(page, buddy, order))
1001 goto done_merging;
1003 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
1004 * merge with it and move up one order.
1006 if (page_is_guard(buddy))
1007 clear_page_guard(zone, buddy, order, migratetype);
1008 else
1009 del_page_from_free_list(buddy, zone, order);
1010 combined_pfn = buddy_pfn & pfn;
1011 page = page + (combined_pfn - pfn);
1012 pfn = combined_pfn;
1013 order++;
1015 if (max_order < MAX_ORDER) {
1016 /* If we are here, it means order is >= pageblock_order.
1017 * We want to prevent merge between freepages on isolate
1018 * pageblock and normal pageblock. Without this, pageblock
1019 * isolation could cause incorrect freepage or CMA accounting.
1021 * We don't want to hit this code for the more frequent
1022 * low-order merging.
1024 if (unlikely(has_isolate_pageblock(zone))) {
1025 int buddy_mt;
1027 buddy_pfn = __find_buddy_pfn(pfn, order);
1028 buddy = page + (buddy_pfn - pfn);
1029 buddy_mt = get_pageblock_migratetype(buddy);
1031 if (migratetype != buddy_mt
1032 && (is_migrate_isolate(migratetype) ||
1033 is_migrate_isolate(buddy_mt)))
1034 goto done_merging;
1036 max_order++;
1037 goto continue_merging;
1040 done_merging:
1041 set_page_order(page, order);
1043 if (is_shuffle_order(order))
1044 to_tail = shuffle_pick_tail();
1045 else
1046 to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
1048 if (to_tail)
1049 add_to_free_list_tail(page, zone, order, migratetype);
1050 else
1051 add_to_free_list(page, zone, order, migratetype);
1053 /* Notify page reporting subsystem of freed page */
1054 if (report)
1055 page_reporting_notify_free(order);
1059 * A bad page could be due to a number of fields. Instead of multiple branches,
1060 * try and check multiple fields with one check. The caller must do a detailed
1061 * check if necessary.
1063 static inline bool page_expected_state(struct page *page,
1064 unsigned long check_flags)
1066 if (unlikely(atomic_read(&page->_mapcount) != -1))
1067 return false;
1069 if (unlikely((unsigned long)page->mapping |
1070 page_ref_count(page) |
1071 #ifdef CONFIG_MEMCG
1072 (unsigned long)page->mem_cgroup |
1073 #endif
1074 (page->flags & check_flags)))
1075 return false;
1077 return true;
1080 static void free_pages_check_bad(struct page *page)
1082 const char *bad_reason;
1083 unsigned long bad_flags;
1085 bad_reason = NULL;
1086 bad_flags = 0;
1088 if (unlikely(atomic_read(&page->_mapcount) != -1))
1089 bad_reason = "nonzero mapcount";
1090 if (unlikely(page->mapping != NULL))
1091 bad_reason = "non-NULL mapping";
1092 if (unlikely(page_ref_count(page) != 0))
1093 bad_reason = "nonzero _refcount";
1094 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
1095 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
1096 bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
1098 #ifdef CONFIG_MEMCG
1099 if (unlikely(page->mem_cgroup))
1100 bad_reason = "page still charged to cgroup";
1101 #endif
1102 bad_page(page, bad_reason, bad_flags);
1105 static inline int free_pages_check(struct page *page)
1107 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
1108 return 0;
1110 /* Something has gone sideways, find it */
1111 free_pages_check_bad(page);
1112 return 1;
1115 static int free_tail_pages_check(struct page *head_page, struct page *page)
1117 int ret = 1;
1120 * We rely page->lru.next never has bit 0 set, unless the page
1121 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
1123 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
1125 if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
1126 ret = 0;
1127 goto out;
1129 switch (page - head_page) {
1130 case 1:
1131 /* the first tail page: ->mapping may be compound_mapcount() */
1132 if (unlikely(compound_mapcount(page))) {
1133 bad_page(page, "nonzero compound_mapcount", 0);
1134 goto out;
1136 break;
1137 case 2:
1139 * the second tail page: ->mapping is
1140 * deferred_list.next -- ignore value.
1142 break;
1143 default:
1144 if (page->mapping != TAIL_MAPPING) {
1145 bad_page(page, "corrupted mapping in tail page", 0);
1146 goto out;
1148 break;
1150 if (unlikely(!PageTail(page))) {
1151 bad_page(page, "PageTail not set", 0);
1152 goto out;
1154 if (unlikely(compound_head(page) != head_page)) {
1155 bad_page(page, "compound_head not consistent", 0);
1156 goto out;
1158 ret = 0;
1159 out:
1160 page->mapping = NULL;
1161 clear_compound_head(page);
1162 return ret;
1165 static void kernel_init_free_pages(struct page *page, int numpages)
1167 int i;
1169 for (i = 0; i < numpages; i++)
1170 clear_highpage(page + i);
1173 static __always_inline bool free_pages_prepare(struct page *page,
1174 unsigned int order, bool check_free)
1176 int bad = 0;
1178 VM_BUG_ON_PAGE(PageTail(page), page);
1180 trace_mm_page_free(page, order);
1183 * Check tail pages before head page information is cleared to
1184 * avoid checking PageCompound for order-0 pages.
1186 if (unlikely(order)) {
1187 bool compound = PageCompound(page);
1188 int i;
1190 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1192 if (compound)
1193 ClearPageDoubleMap(page);
1194 for (i = 1; i < (1 << order); i++) {
1195 if (compound)
1196 bad += free_tail_pages_check(page, page + i);
1197 if (unlikely(free_pages_check(page + i))) {
1198 bad++;
1199 continue;
1201 (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1204 if (PageMappingFlags(page))
1205 page->mapping = NULL;
1206 if (memcg_kmem_enabled() && PageKmemcg(page))
1207 __memcg_kmem_uncharge_page(page, order);
1208 if (check_free)
1209 bad += free_pages_check(page);
1210 if (bad)
1211 return false;
1213 page_cpupid_reset_last(page);
1214 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1215 reset_page_owner(page, order);
1217 if (!PageHighMem(page)) {
1218 debug_check_no_locks_freed(page_address(page),
1219 PAGE_SIZE << order);
1220 debug_check_no_obj_freed(page_address(page),
1221 PAGE_SIZE << order);
1223 if (want_init_on_free())
1224 kernel_init_free_pages(page, 1 << order);
1226 kernel_poison_pages(page, 1 << order, 0);
1228 * arch_free_page() can make the page's contents inaccessible. s390
1229 * does this. So nothing which can access the page's contents should
1230 * happen after this.
1232 arch_free_page(page, order);
1234 if (debug_pagealloc_enabled_static())
1235 kernel_map_pages(page, 1 << order, 0);
1237 kasan_free_nondeferred_pages(page, order);
1239 return true;
1242 #ifdef CONFIG_DEBUG_VM
1244 * With DEBUG_VM enabled, order-0 pages are checked immediately when being freed
1245 * to pcp lists. With debug_pagealloc also enabled, they are also rechecked when
1246 * moved from pcp lists to free lists.
1248 static bool free_pcp_prepare(struct page *page)
1250 return free_pages_prepare(page, 0, true);
1253 static bool bulkfree_pcp_prepare(struct page *page)
1255 if (debug_pagealloc_enabled_static())
1256 return free_pages_check(page);
1257 else
1258 return false;
1260 #else
1262 * With DEBUG_VM disabled, order-0 pages being freed are checked only when
1263 * moving from pcp lists to free list in order to reduce overhead. With
1264 * debug_pagealloc enabled, they are checked also immediately when being freed
1265 * to the pcp lists.
1267 static bool free_pcp_prepare(struct page *page)
1269 if (debug_pagealloc_enabled_static())
1270 return free_pages_prepare(page, 0, true);
1271 else
1272 return free_pages_prepare(page, 0, false);
1275 static bool bulkfree_pcp_prepare(struct page *page)
1277 return free_pages_check(page);
1279 #endif /* CONFIG_DEBUG_VM */
1281 static inline void prefetch_buddy(struct page *page)
1283 unsigned long pfn = page_to_pfn(page);
1284 unsigned long buddy_pfn = __find_buddy_pfn(pfn, 0);
1285 struct page *buddy = page + (buddy_pfn - pfn);
1287 prefetch(buddy);
1291 * Frees a number of pages from the PCP lists
1292 * Assumes all pages on list are in same zone, and of same order.
1293 * count is the number of pages to free.
1295 * If the zone was previously in an "all pages pinned" state then look to
1296 * see if this freeing clears that state.
1298 * And clear the zone's pages_scanned counter, to hold off the "all pages are
1299 * pinned" detection logic.
1301 static void free_pcppages_bulk(struct zone *zone, int count,
1302 struct per_cpu_pages *pcp)
1304 int migratetype = 0;
1305 int batch_free = 0;
1306 int prefetch_nr = 0;
1307 bool isolated_pageblocks;
1308 struct page *page, *tmp;
1309 LIST_HEAD(head);
1311 while (count) {
1312 struct list_head *list;
1315 * Remove pages from lists in a round-robin fashion. A
1316 * batch_free count is maintained that is incremented when an
1317 * empty list is encountered. This is so more pages are freed
1318 * off fuller lists instead of spinning excessively around empty
1319 * lists
1321 do {
1322 batch_free++;
1323 if (++migratetype == MIGRATE_PCPTYPES)
1324 migratetype = 0;
1325 list = &pcp->lists[migratetype];
1326 } while (list_empty(list));
1328 /* This is the only non-empty list. Free them all. */
1329 if (batch_free == MIGRATE_PCPTYPES)
1330 batch_free = count;
1332 do {
1333 page = list_last_entry(list, struct page, lru);
1334 /* must delete to avoid corrupting pcp list */
1335 list_del(&page->lru);
1336 pcp->count--;
1338 if (bulkfree_pcp_prepare(page))
1339 continue;
1341 list_add_tail(&page->lru, &head);
1344 * We are going to put the page back to the global
1345 * pool, prefetch its buddy to speed up later access
1346 * under zone->lock. It is believed the overhead of
1347 * an additional test and calculating buddy_pfn here
1348 * can be offset by reduced memory latency later. To
1349 * avoid excessive prefetching due to large count, only
1350 * prefetch buddy for the first pcp->batch nr of pages.
1352 if (prefetch_nr++ < pcp->batch)
1353 prefetch_buddy(page);
1354 } while (--count && --batch_free && !list_empty(list));
1357 spin_lock(&zone->lock);
1358 isolated_pageblocks = has_isolate_pageblock(zone);
1361 * Use safe version since after __free_one_page(),
1362 * page->lru.next will not point to original list.
1364 list_for_each_entry_safe(page, tmp, &head, lru) {
1365 int mt = get_pcppage_migratetype(page);
1366 /* MIGRATE_ISOLATE page should not go to pcplists */
1367 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1368 /* Pageblock could have been isolated meanwhile */
1369 if (unlikely(isolated_pageblocks))
1370 mt = get_pageblock_migratetype(page);
1372 __free_one_page(page, page_to_pfn(page), zone, 0, mt, true);
1373 trace_mm_page_pcpu_drain(page, 0, mt);
1375 spin_unlock(&zone->lock);
1378 static void free_one_page(struct zone *zone,
1379 struct page *page, unsigned long pfn,
1380 unsigned int order,
1381 int migratetype)
1383 spin_lock(&zone->lock);
1384 if (unlikely(has_isolate_pageblock(zone) ||
1385 is_migrate_isolate(migratetype))) {
1386 migratetype = get_pfnblock_migratetype(page, pfn);
1388 __free_one_page(page, pfn, zone, order, migratetype, true);
1389 spin_unlock(&zone->lock);
1392 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
1393 unsigned long zone, int nid)
1395 mm_zero_struct_page(page);
1396 set_page_links(page, zone, nid, pfn);
1397 init_page_count(page);
1398 page_mapcount_reset(page);
1399 page_cpupid_reset_last(page);
1400 page_kasan_tag_reset(page);
1402 INIT_LIST_HEAD(&page->lru);
1403 #ifdef WANT_PAGE_VIRTUAL
1404 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1405 if (!is_highmem_idx(zone))
1406 set_page_address(page, __va(pfn << PAGE_SHIFT));
1407 #endif
1410 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1411 static void __meminit init_reserved_page(unsigned long pfn)
1413 pg_data_t *pgdat;
1414 int nid, zid;
1416 if (!early_page_uninitialised(pfn))
1417 return;
1419 nid = early_pfn_to_nid(pfn);
1420 pgdat = NODE_DATA(nid);
1422 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1423 struct zone *zone = &pgdat->node_zones[zid];
1425 if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
1426 break;
1428 __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
1430 #else
1431 static inline void init_reserved_page(unsigned long pfn)
1434 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1437 * Initialised pages do not have PageReserved set. This function is
1438 * called for each range allocated by the bootmem allocator and
1439 * marks the pages PageReserved. The remaining valid pages are later
1440 * sent to the buddy page allocator.
1442 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1444 unsigned long start_pfn = PFN_DOWN(start);
1445 unsigned long end_pfn = PFN_UP(end);
1447 for (; start_pfn < end_pfn; start_pfn++) {
1448 if (pfn_valid(start_pfn)) {
1449 struct page *page = pfn_to_page(start_pfn);
1451 init_reserved_page(start_pfn);
1453 /* Avoid false-positive PageTail() */
1454 INIT_LIST_HEAD(&page->lru);
1457 * no need for atomic set_bit because the struct
1458 * page is not visible yet so nobody should
1459 * access it yet.
1461 __SetPageReserved(page);
1466 static void __free_pages_ok(struct page *page, unsigned int order)
1468 unsigned long flags;
1469 int migratetype;
1470 unsigned long pfn = page_to_pfn(page);
1472 if (!free_pages_prepare(page, order, true))
1473 return;
1475 migratetype = get_pfnblock_migratetype(page, pfn);
1476 local_irq_save(flags);
1477 __count_vm_events(PGFREE, 1 << order);
1478 free_one_page(page_zone(page), page, pfn, order, migratetype);
1479 local_irq_restore(flags);
1482 void __free_pages_core(struct page *page, unsigned int order)
1484 unsigned int nr_pages = 1 << order;
1485 struct page *p = page;
1486 unsigned int loop;
1488 prefetchw(p);
1489 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1490 prefetchw(p + 1);
1491 __ClearPageReserved(p);
1492 set_page_count(p, 0);
1494 __ClearPageReserved(p);
1495 set_page_count(p, 0);
1497 atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
1498 set_page_refcounted(page);
1499 __free_pages(page, order);
1502 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1503 defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1505 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1507 int __meminit early_pfn_to_nid(unsigned long pfn)
1509 static DEFINE_SPINLOCK(early_pfn_lock);
1510 int nid;
1512 spin_lock(&early_pfn_lock);
1513 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1514 if (nid < 0)
1515 nid = first_online_node;
1516 spin_unlock(&early_pfn_lock);
1518 return nid;
1520 #endif
1522 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1523 /* Only safe to use early in boot when initialisation is single-threaded */
1524 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1526 int nid;
1528 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1529 if (nid >= 0 && nid != node)
1530 return false;
1531 return true;
1534 #else
1535 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1537 return true;
1539 #endif
1542 void __init memblock_free_pages(struct page *page, unsigned long pfn,
1543 unsigned int order)
1545 if (early_page_uninitialised(pfn))
1546 return;
1547 __free_pages_core(page, order);
1551 * Check that the whole (or subset of) a pageblock given by the interval of
1552 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1553 * with the migration of free compaction scanner. The scanners then need to
1554 * use only pfn_valid_within() check for arches that allow holes within
1555 * pageblocks.
1557 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1559 * It's possible on some configurations to have a setup like node0 node1 node0
1560 * i.e. it's possible that all pages within a zones range of pages do not
1561 * belong to a single zone. We assume that a border between node0 and node1
1562 * can occur within a single pageblock, but not a node0 node1 node0
1563 * interleaving within a single pageblock. It is therefore sufficient to check
1564 * the first and last page of a pageblock and avoid checking each individual
1565 * page in a pageblock.
1567 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1568 unsigned long end_pfn, struct zone *zone)
1570 struct page *start_page;
1571 struct page *end_page;
1573 /* end_pfn is one past the range we are checking */
1574 end_pfn--;
1576 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1577 return NULL;
1579 start_page = pfn_to_online_page(start_pfn);
1580 if (!start_page)
1581 return NULL;
1583 if (page_zone(start_page) != zone)
1584 return NULL;
1586 end_page = pfn_to_page(end_pfn);
1588 /* This gives a shorter code than deriving page_zone(end_page) */
1589 if (page_zone_id(start_page) != page_zone_id(end_page))
1590 return NULL;
1592 return start_page;
1595 void set_zone_contiguous(struct zone *zone)
1597 unsigned long block_start_pfn = zone->zone_start_pfn;
1598 unsigned long block_end_pfn;
1600 block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1601 for (; block_start_pfn < zone_end_pfn(zone);
1602 block_start_pfn = block_end_pfn,
1603 block_end_pfn += pageblock_nr_pages) {
1605 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1607 if (!__pageblock_pfn_to_page(block_start_pfn,
1608 block_end_pfn, zone))
1609 return;
1610 cond_resched();
1613 /* We confirm that there is no hole */
1614 zone->contiguous = true;
1617 void clear_zone_contiguous(struct zone *zone)
1619 zone->contiguous = false;
1622 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1623 static void __init deferred_free_range(unsigned long pfn,
1624 unsigned long nr_pages)
1626 struct page *page;
1627 unsigned long i;
1629 if (!nr_pages)
1630 return;
1632 page = pfn_to_page(pfn);
1634 /* Free a large naturally-aligned chunk if possible */
1635 if (nr_pages == pageblock_nr_pages &&
1636 (pfn & (pageblock_nr_pages - 1)) == 0) {
1637 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1638 __free_pages_core(page, pageblock_order);
1639 return;
1642 for (i = 0; i < nr_pages; i++, page++, pfn++) {
1643 if ((pfn & (pageblock_nr_pages - 1)) == 0)
1644 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1645 __free_pages_core(page, 0);
1649 /* Completion tracking for deferred_init_memmap() threads */
1650 static atomic_t pgdat_init_n_undone __initdata;
1651 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1653 static inline void __init pgdat_init_report_one_done(void)
1655 if (atomic_dec_and_test(&pgdat_init_n_undone))
1656 complete(&pgdat_init_all_done_comp);
1660 * Returns true if page needs to be initialized or freed to buddy allocator.
1662 * First we check if pfn is valid on architectures where it is possible to have
1663 * holes within pageblock_nr_pages. On systems where it is not possible, this
1664 * function is optimized out.
1666 * Then, we check if a current large page is valid by only checking the validity
1667 * of the head pfn.
1669 static inline bool __init deferred_pfn_valid(unsigned long pfn)
1671 if (!pfn_valid_within(pfn))
1672 return false;
1673 if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1674 return false;
1675 return true;
1679 * Free pages to buddy allocator. Try to free aligned pages in
1680 * pageblock_nr_pages sizes.
1682 static void __init deferred_free_pages(unsigned long pfn,
1683 unsigned long end_pfn)
1685 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1686 unsigned long nr_free = 0;
1688 for (; pfn < end_pfn; pfn++) {
1689 if (!deferred_pfn_valid(pfn)) {
1690 deferred_free_range(pfn - nr_free, nr_free);
1691 nr_free = 0;
1692 } else if (!(pfn & nr_pgmask)) {
1693 deferred_free_range(pfn - nr_free, nr_free);
1694 nr_free = 1;
1695 } else {
1696 nr_free++;
1699 /* Free the last block of pages to allocator */
1700 deferred_free_range(pfn - nr_free, nr_free);
1704 * Initialize struct pages. We minimize pfn page lookups and scheduler checks
1705 * by performing it only once every pageblock_nr_pages.
1706 * Return number of pages initialized.
1708 static unsigned long __init deferred_init_pages(struct zone *zone,
1709 unsigned long pfn,
1710 unsigned long end_pfn)
1712 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1713 int nid = zone_to_nid(zone);
1714 unsigned long nr_pages = 0;
1715 int zid = zone_idx(zone);
1716 struct page *page = NULL;
1718 for (; pfn < end_pfn; pfn++) {
1719 if (!deferred_pfn_valid(pfn)) {
1720 page = NULL;
1721 continue;
1722 } else if (!page || !(pfn & nr_pgmask)) {
1723 page = pfn_to_page(pfn);
1724 } else {
1725 page++;
1727 __init_single_page(page, pfn, zid, nid);
1728 nr_pages++;
1730 return (nr_pages);
1734 * This function is meant to pre-load the iterator for the zone init.
1735 * Specifically it walks through the ranges until we are caught up to the
1736 * first_init_pfn value and exits there. If we never encounter the value we
1737 * return false indicating there are no valid ranges left.
1739 static bool __init
1740 deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone,
1741 unsigned long *spfn, unsigned long *epfn,
1742 unsigned long first_init_pfn)
1744 u64 j;
1747 * Start out by walking through the ranges in this zone that have
1748 * already been initialized. We don't need to do anything with them
1749 * so we just need to flush them out of the system.
1751 for_each_free_mem_pfn_range_in_zone(j, zone, spfn, epfn) {
1752 if (*epfn <= first_init_pfn)
1753 continue;
1754 if (*spfn < first_init_pfn)
1755 *spfn = first_init_pfn;
1756 *i = j;
1757 return true;
1760 return false;
1764 * Initialize and free pages. We do it in two loops: first we initialize
1765 * struct page, then free to buddy allocator, because while we are
1766 * freeing pages we can access pages that are ahead (computing buddy
1767 * page in __free_one_page()).
1769 * In order to try and keep some memory in the cache we have the loop
1770 * broken along max page order boundaries. This way we will not cause
1771 * any issues with the buddy page computation.
1773 static unsigned long __init
1774 deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn,
1775 unsigned long *end_pfn)
1777 unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES);
1778 unsigned long spfn = *start_pfn, epfn = *end_pfn;
1779 unsigned long nr_pages = 0;
1780 u64 j = *i;
1782 /* First we loop through and initialize the page values */
1783 for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) {
1784 unsigned long t;
1786 if (mo_pfn <= *start_pfn)
1787 break;
1789 t = min(mo_pfn, *end_pfn);
1790 nr_pages += deferred_init_pages(zone, *start_pfn, t);
1792 if (mo_pfn < *end_pfn) {
1793 *start_pfn = mo_pfn;
1794 break;
1798 /* Reset values and now loop through freeing pages as needed */
1799 swap(j, *i);
1801 for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) {
1802 unsigned long t;
1804 if (mo_pfn <= spfn)
1805 break;
1807 t = min(mo_pfn, epfn);
1808 deferred_free_pages(spfn, t);
1810 if (mo_pfn <= epfn)
1811 break;
1814 return nr_pages;
1817 /* Initialise remaining memory on a node */
1818 static int __init deferred_init_memmap(void *data)
1820 pg_data_t *pgdat = data;
1821 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1822 unsigned long spfn = 0, epfn = 0, nr_pages = 0;
1823 unsigned long first_init_pfn, flags;
1824 unsigned long start = jiffies;
1825 struct zone *zone;
1826 int zid;
1827 u64 i;
1829 /* Bind memory initialisation thread to a local node if possible */
1830 if (!cpumask_empty(cpumask))
1831 set_cpus_allowed_ptr(current, cpumask);
1833 pgdat_resize_lock(pgdat, &flags);
1834 first_init_pfn = pgdat->first_deferred_pfn;
1835 if (first_init_pfn == ULONG_MAX) {
1836 pgdat_resize_unlock(pgdat, &flags);
1837 pgdat_init_report_one_done();
1838 return 0;
1841 /* Sanity check boundaries */
1842 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1843 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1844 pgdat->first_deferred_pfn = ULONG_MAX;
1847 * Once we unlock here, the zone cannot be grown anymore, thus if an
1848 * interrupt thread must allocate this early in boot, zone must be
1849 * pre-grown prior to start of deferred page initialization.
1851 pgdat_resize_unlock(pgdat, &flags);
1853 /* Only the highest zone is deferred so find it */
1854 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1855 zone = pgdat->node_zones + zid;
1856 if (first_init_pfn < zone_end_pfn(zone))
1857 break;
1860 /* If the zone is empty somebody else may have cleared out the zone */
1861 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
1862 first_init_pfn))
1863 goto zone_empty;
1866 * Initialize and free pages in MAX_ORDER sized increments so
1867 * that we can avoid introducing any issues with the buddy
1868 * allocator.
1870 while (spfn < epfn) {
1871 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
1872 cond_resched();
1874 zone_empty:
1875 /* Sanity check that the next zone really is unpopulated */
1876 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1878 pr_info("node %d initialised, %lu pages in %ums\n",
1879 pgdat->node_id, nr_pages, jiffies_to_msecs(jiffies - start));
1881 pgdat_init_report_one_done();
1882 return 0;
1886 * If this zone has deferred pages, try to grow it by initializing enough
1887 * deferred pages to satisfy the allocation specified by order, rounded up to
1888 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
1889 * of SECTION_SIZE bytes by initializing struct pages in increments of
1890 * PAGES_PER_SECTION * sizeof(struct page) bytes.
1892 * Return true when zone was grown, otherwise return false. We return true even
1893 * when we grow less than requested, to let the caller decide if there are
1894 * enough pages to satisfy the allocation.
1896 * Note: We use noinline because this function is needed only during boot, and
1897 * it is called from a __ref function _deferred_grow_zone. This way we are
1898 * making sure that it is not inlined into permanent text section.
1900 static noinline bool __init
1901 deferred_grow_zone(struct zone *zone, unsigned int order)
1903 unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
1904 pg_data_t *pgdat = zone->zone_pgdat;
1905 unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
1906 unsigned long spfn, epfn, flags;
1907 unsigned long nr_pages = 0;
1908 u64 i;
1910 /* Only the last zone may have deferred pages */
1911 if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
1912 return false;
1914 pgdat_resize_lock(pgdat, &flags);
1917 * If someone grew this zone while we were waiting for spinlock, return
1918 * true, as there might be enough pages already.
1920 if (first_deferred_pfn != pgdat->first_deferred_pfn) {
1921 pgdat_resize_unlock(pgdat, &flags);
1922 return true;
1925 /* If the zone is empty somebody else may have cleared out the zone */
1926 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
1927 first_deferred_pfn)) {
1928 pgdat->first_deferred_pfn = ULONG_MAX;
1929 pgdat_resize_unlock(pgdat, &flags);
1930 /* Retry only once. */
1931 return first_deferred_pfn != ULONG_MAX;
1935 * Initialize and free pages in MAX_ORDER sized increments so
1936 * that we can avoid introducing any issues with the buddy
1937 * allocator.
1939 while (spfn < epfn) {
1940 /* update our first deferred PFN for this section */
1941 first_deferred_pfn = spfn;
1943 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
1944 touch_nmi_watchdog();
1946 /* We should only stop along section boundaries */
1947 if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION)
1948 continue;
1950 /* If our quota has been met we can stop here */
1951 if (nr_pages >= nr_pages_needed)
1952 break;
1955 pgdat->first_deferred_pfn = spfn;
1956 pgdat_resize_unlock(pgdat, &flags);
1958 return nr_pages > 0;
1962 * deferred_grow_zone() is __init, but it is called from
1963 * get_page_from_freelist() during early boot until deferred_pages permanently
1964 * disables this call. This is why we have refdata wrapper to avoid warning,
1965 * and to ensure that the function body gets unloaded.
1967 static bool __ref
1968 _deferred_grow_zone(struct zone *zone, unsigned int order)
1970 return deferred_grow_zone(zone, order);
1973 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1975 void __init page_alloc_init_late(void)
1977 struct zone *zone;
1978 int nid;
1980 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1982 /* There will be num_node_state(N_MEMORY) threads */
1983 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1984 for_each_node_state(nid, N_MEMORY) {
1985 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1988 /* Block until all are initialised */
1989 wait_for_completion(&pgdat_init_all_done_comp);
1992 * The number of managed pages has changed due to the initialisation
1993 * so the pcpu batch and high limits needs to be updated or the limits
1994 * will be artificially small.
1996 for_each_populated_zone(zone)
1997 zone_pcp_update(zone);
2000 * We initialized the rest of the deferred pages. Permanently disable
2001 * on-demand struct page initialization.
2003 static_branch_disable(&deferred_pages);
2005 /* Reinit limits that are based on free pages after the kernel is up */
2006 files_maxfiles_init();
2007 #endif
2009 /* Discard memblock private memory */
2010 memblock_discard();
2012 for_each_node_state(nid, N_MEMORY)
2013 shuffle_free_memory(NODE_DATA(nid));
2015 for_each_populated_zone(zone)
2016 set_zone_contiguous(zone);
2019 #ifdef CONFIG_CMA
2020 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
2021 void __init init_cma_reserved_pageblock(struct page *page)
2023 unsigned i = pageblock_nr_pages;
2024 struct page *p = page;
2026 do {
2027 __ClearPageReserved(p);
2028 set_page_count(p, 0);
2029 } while (++p, --i);
2031 set_pageblock_migratetype(page, MIGRATE_CMA);
2033 if (pageblock_order >= MAX_ORDER) {
2034 i = pageblock_nr_pages;
2035 p = page;
2036 do {
2037 set_page_refcounted(p);
2038 __free_pages(p, MAX_ORDER - 1);
2039 p += MAX_ORDER_NR_PAGES;
2040 } while (i -= MAX_ORDER_NR_PAGES);
2041 } else {
2042 set_page_refcounted(page);
2043 __free_pages(page, pageblock_order);
2046 adjust_managed_page_count(page, pageblock_nr_pages);
2048 #endif
2051 * The order of subdivision here is critical for the IO subsystem.
2052 * Please do not alter this order without good reasons and regression
2053 * testing. Specifically, as large blocks of memory are subdivided,
2054 * the order in which smaller blocks are delivered depends on the order
2055 * they're subdivided in this function. This is the primary factor
2056 * influencing the order in which pages are delivered to the IO
2057 * subsystem according to empirical testing, and this is also justified
2058 * by considering the behavior of a buddy system containing a single
2059 * large block of memory acted on by a series of small allocations.
2060 * This behavior is a critical factor in sglist merging's success.
2062 * -- nyc
2064 static inline void expand(struct zone *zone, struct page *page,
2065 int low, int high, int migratetype)
2067 unsigned long size = 1 << high;
2069 while (high > low) {
2070 high--;
2071 size >>= 1;
2072 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
2075 * Mark as guard pages (or page), that will allow to
2076 * merge back to allocator when buddy will be freed.
2077 * Corresponding page table entries will not be touched,
2078 * pages will stay not present in virtual address space
2080 if (set_page_guard(zone, &page[size], high, migratetype))
2081 continue;
2083 add_to_free_list(&page[size], zone, high, migratetype);
2084 set_page_order(&page[size], high);
2088 static void check_new_page_bad(struct page *page)
2090 const char *bad_reason = NULL;
2091 unsigned long bad_flags = 0;
2093 if (unlikely(atomic_read(&page->_mapcount) != -1))
2094 bad_reason = "nonzero mapcount";
2095 if (unlikely(page->mapping != NULL))
2096 bad_reason = "non-NULL mapping";
2097 if (unlikely(page_ref_count(page) != 0))
2098 bad_reason = "nonzero _refcount";
2099 if (unlikely(page->flags & __PG_HWPOISON)) {
2100 bad_reason = "HWPoisoned (hardware-corrupted)";
2101 bad_flags = __PG_HWPOISON;
2102 /* Don't complain about hwpoisoned pages */
2103 page_mapcount_reset(page); /* remove PageBuddy */
2104 return;
2106 if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
2107 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
2108 bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
2110 #ifdef CONFIG_MEMCG
2111 if (unlikely(page->mem_cgroup))
2112 bad_reason = "page still charged to cgroup";
2113 #endif
2114 bad_page(page, bad_reason, bad_flags);
2118 * This page is about to be returned from the page allocator
2120 static inline int check_new_page(struct page *page)
2122 if (likely(page_expected_state(page,
2123 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
2124 return 0;
2126 check_new_page_bad(page);
2127 return 1;
2130 static inline bool free_pages_prezeroed(void)
2132 return (IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) &&
2133 page_poisoning_enabled()) || want_init_on_free();
2136 #ifdef CONFIG_DEBUG_VM
2138 * With DEBUG_VM enabled, order-0 pages are checked for expected state when
2139 * being allocated from pcp lists. With debug_pagealloc also enabled, they are
2140 * also checked when pcp lists are refilled from the free lists.
2142 static inline bool check_pcp_refill(struct page *page)
2144 if (debug_pagealloc_enabled_static())
2145 return check_new_page(page);
2146 else
2147 return false;
2150 static inline bool check_new_pcp(struct page *page)
2152 return check_new_page(page);
2154 #else
2156 * With DEBUG_VM disabled, free order-0 pages are checked for expected state
2157 * when pcp lists are being refilled from the free lists. With debug_pagealloc
2158 * enabled, they are also checked when being allocated from the pcp lists.
2160 static inline bool check_pcp_refill(struct page *page)
2162 return check_new_page(page);
2164 static inline bool check_new_pcp(struct page *page)
2166 if (debug_pagealloc_enabled_static())
2167 return check_new_page(page);
2168 else
2169 return false;
2171 #endif /* CONFIG_DEBUG_VM */
2173 static bool check_new_pages(struct page *page, unsigned int order)
2175 int i;
2176 for (i = 0; i < (1 << order); i++) {
2177 struct page *p = page + i;
2179 if (unlikely(check_new_page(p)))
2180 return true;
2183 return false;
2186 inline void post_alloc_hook(struct page *page, unsigned int order,
2187 gfp_t gfp_flags)
2189 set_page_private(page, 0);
2190 set_page_refcounted(page);
2192 arch_alloc_page(page, order);
2193 if (debug_pagealloc_enabled_static())
2194 kernel_map_pages(page, 1 << order, 1);
2195 kasan_alloc_pages(page, order);
2196 kernel_poison_pages(page, 1 << order, 1);
2197 set_page_owner(page, order, gfp_flags);
2200 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
2201 unsigned int alloc_flags)
2203 post_alloc_hook(page, order, gfp_flags);
2205 if (!free_pages_prezeroed() && want_init_on_alloc(gfp_flags))
2206 kernel_init_free_pages(page, 1 << order);
2208 if (order && (gfp_flags & __GFP_COMP))
2209 prep_compound_page(page, order);
2212 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
2213 * allocate the page. The expectation is that the caller is taking
2214 * steps that will free more memory. The caller should avoid the page
2215 * being used for !PFMEMALLOC purposes.
2217 if (alloc_flags & ALLOC_NO_WATERMARKS)
2218 set_page_pfmemalloc(page);
2219 else
2220 clear_page_pfmemalloc(page);
2224 * Go through the free lists for the given migratetype and remove
2225 * the smallest available page from the freelists
2227 static __always_inline
2228 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
2229 int migratetype)
2231 unsigned int current_order;
2232 struct free_area *area;
2233 struct page *page;
2235 /* Find a page of the appropriate size in the preferred list */
2236 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
2237 area = &(zone->free_area[current_order]);
2238 page = get_page_from_free_area(area, migratetype);
2239 if (!page)
2240 continue;
2241 del_page_from_free_list(page, zone, current_order);
2242 expand(zone, page, order, current_order, migratetype);
2243 set_pcppage_migratetype(page, migratetype);
2244 return page;
2247 return NULL;
2252 * This array describes the order lists are fallen back to when
2253 * the free lists for the desirable migrate type are depleted
2255 static int fallbacks[MIGRATE_TYPES][4] = {
2256 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2257 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
2258 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
2259 #ifdef CONFIG_CMA
2260 [MIGRATE_CMA] = { MIGRATE_TYPES }, /* Never used */
2261 #endif
2262 #ifdef CONFIG_MEMORY_ISOLATION
2263 [MIGRATE_ISOLATE] = { MIGRATE_TYPES }, /* Never used */
2264 #endif
2267 #ifdef CONFIG_CMA
2268 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2269 unsigned int order)
2271 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
2273 #else
2274 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2275 unsigned int order) { return NULL; }
2276 #endif
2279 * Move the free pages in a range to the free lists of the requested type.
2280 * Note that start_page and end_pages are not aligned on a pageblock
2281 * boundary. If alignment is required, use move_freepages_block()
2283 static int move_freepages(struct zone *zone,
2284 struct page *start_page, struct page *end_page,
2285 int migratetype, int *num_movable)
2287 struct page *page;
2288 unsigned int order;
2289 int pages_moved = 0;
2291 for (page = start_page; page <= end_page;) {
2292 if (!pfn_valid_within(page_to_pfn(page))) {
2293 page++;
2294 continue;
2297 if (!PageBuddy(page)) {
2299 * We assume that pages that could be isolated for
2300 * migration are movable. But we don't actually try
2301 * isolating, as that would be expensive.
2303 if (num_movable &&
2304 (PageLRU(page) || __PageMovable(page)))
2305 (*num_movable)++;
2307 page++;
2308 continue;
2311 /* Make sure we are not inadvertently changing nodes */
2312 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2313 VM_BUG_ON_PAGE(page_zone(page) != zone, page);
2315 order = page_order(page);
2316 move_to_free_list(page, zone, order, migratetype);
2317 page += 1 << order;
2318 pages_moved += 1 << order;
2321 return pages_moved;
2324 int move_freepages_block(struct zone *zone, struct page *page,
2325 int migratetype, int *num_movable)
2327 unsigned long start_pfn, end_pfn;
2328 struct page *start_page, *end_page;
2330 if (num_movable)
2331 *num_movable = 0;
2333 start_pfn = page_to_pfn(page);
2334 start_pfn = start_pfn & ~(pageblock_nr_pages-1);
2335 start_page = pfn_to_page(start_pfn);
2336 end_page = start_page + pageblock_nr_pages - 1;
2337 end_pfn = start_pfn + pageblock_nr_pages - 1;
2339 /* Do not cross zone boundaries */
2340 if (!zone_spans_pfn(zone, start_pfn))
2341 start_page = page;
2342 if (!zone_spans_pfn(zone, end_pfn))
2343 return 0;
2345 return move_freepages(zone, start_page, end_page, migratetype,
2346 num_movable);
2349 static void change_pageblock_range(struct page *pageblock_page,
2350 int start_order, int migratetype)
2352 int nr_pageblocks = 1 << (start_order - pageblock_order);
2354 while (nr_pageblocks--) {
2355 set_pageblock_migratetype(pageblock_page, migratetype);
2356 pageblock_page += pageblock_nr_pages;
2361 * When we are falling back to another migratetype during allocation, try to
2362 * steal extra free pages from the same pageblocks to satisfy further
2363 * allocations, instead of polluting multiple pageblocks.
2365 * If we are stealing a relatively large buddy page, it is likely there will
2366 * be more free pages in the pageblock, so try to steal them all. For
2367 * reclaimable and unmovable allocations, we steal regardless of page size,
2368 * as fragmentation caused by those allocations polluting movable pageblocks
2369 * is worse than movable allocations stealing from unmovable and reclaimable
2370 * pageblocks.
2372 static bool can_steal_fallback(unsigned int order, int start_mt)
2375 * Leaving this order check is intended, although there is
2376 * relaxed order check in next check. The reason is that
2377 * we can actually steal whole pageblock if this condition met,
2378 * but, below check doesn't guarantee it and that is just heuristic
2379 * so could be changed anytime.
2381 if (order >= pageblock_order)
2382 return true;
2384 if (order >= pageblock_order / 2 ||
2385 start_mt == MIGRATE_RECLAIMABLE ||
2386 start_mt == MIGRATE_UNMOVABLE ||
2387 page_group_by_mobility_disabled)
2388 return true;
2390 return false;
2393 static inline void boost_watermark(struct zone *zone)
2395 unsigned long max_boost;
2397 if (!watermark_boost_factor)
2398 return;
2400 * Don't bother in zones that are unlikely to produce results.
2401 * On small machines, including kdump capture kernels running
2402 * in a small area, boosting the watermark can cause an out of
2403 * memory situation immediately.
2405 if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
2406 return;
2408 max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
2409 watermark_boost_factor, 10000);
2412 * high watermark may be uninitialised if fragmentation occurs
2413 * very early in boot so do not boost. We do not fall
2414 * through and boost by pageblock_nr_pages as failing
2415 * allocations that early means that reclaim is not going
2416 * to help and it may even be impossible to reclaim the
2417 * boosted watermark resulting in a hang.
2419 if (!max_boost)
2420 return;
2422 max_boost = max(pageblock_nr_pages, max_boost);
2424 zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
2425 max_boost);
2429 * This function implements actual steal behaviour. If order is large enough,
2430 * we can steal whole pageblock. If not, we first move freepages in this
2431 * pageblock to our migratetype and determine how many already-allocated pages
2432 * are there in the pageblock with a compatible migratetype. If at least half
2433 * of pages are free or compatible, we can change migratetype of the pageblock
2434 * itself, so pages freed in the future will be put on the correct free list.
2436 static void steal_suitable_fallback(struct zone *zone, struct page *page,
2437 unsigned int alloc_flags, int start_type, bool whole_block)
2439 unsigned int current_order = page_order(page);
2440 int free_pages, movable_pages, alike_pages;
2441 int old_block_type;
2443 old_block_type = get_pageblock_migratetype(page);
2446 * This can happen due to races and we want to prevent broken
2447 * highatomic accounting.
2449 if (is_migrate_highatomic(old_block_type))
2450 goto single_page;
2452 /* Take ownership for orders >= pageblock_order */
2453 if (current_order >= pageblock_order) {
2454 change_pageblock_range(page, current_order, start_type);
2455 goto single_page;
2459 * Boost watermarks to increase reclaim pressure to reduce the
2460 * likelihood of future fallbacks. Wake kswapd now as the node
2461 * may be balanced overall and kswapd will not wake naturally.
2463 boost_watermark(zone);
2464 if (alloc_flags & ALLOC_KSWAPD)
2465 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
2467 /* We are not allowed to try stealing from the whole block */
2468 if (!whole_block)
2469 goto single_page;
2471 free_pages = move_freepages_block(zone, page, start_type,
2472 &movable_pages);
2474 * Determine how many pages are compatible with our allocation.
2475 * For movable allocation, it's the number of movable pages which
2476 * we just obtained. For other types it's a bit more tricky.
2478 if (start_type == MIGRATE_MOVABLE) {
2479 alike_pages = movable_pages;
2480 } else {
2482 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2483 * to MOVABLE pageblock, consider all non-movable pages as
2484 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2485 * vice versa, be conservative since we can't distinguish the
2486 * exact migratetype of non-movable pages.
2488 if (old_block_type == MIGRATE_MOVABLE)
2489 alike_pages = pageblock_nr_pages
2490 - (free_pages + movable_pages);
2491 else
2492 alike_pages = 0;
2495 /* moving whole block can fail due to zone boundary conditions */
2496 if (!free_pages)
2497 goto single_page;
2500 * If a sufficient number of pages in the block are either free or of
2501 * comparable migratability as our allocation, claim the whole block.
2503 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2504 page_group_by_mobility_disabled)
2505 set_pageblock_migratetype(page, start_type);
2507 return;
2509 single_page:
2510 move_to_free_list(page, zone, current_order, start_type);
2514 * Check whether there is a suitable fallback freepage with requested order.
2515 * If only_stealable is true, this function returns fallback_mt only if
2516 * we can steal other freepages all together. This would help to reduce
2517 * fragmentation due to mixed migratetype pages in one pageblock.
2519 int find_suitable_fallback(struct free_area *area, unsigned int order,
2520 int migratetype, bool only_stealable, bool *can_steal)
2522 int i;
2523 int fallback_mt;
2525 if (area->nr_free == 0)
2526 return -1;
2528 *can_steal = false;
2529 for (i = 0;; i++) {
2530 fallback_mt = fallbacks[migratetype][i];
2531 if (fallback_mt == MIGRATE_TYPES)
2532 break;
2534 if (free_area_empty(area, fallback_mt))
2535 continue;
2537 if (can_steal_fallback(order, migratetype))
2538 *can_steal = true;
2540 if (!only_stealable)
2541 return fallback_mt;
2543 if (*can_steal)
2544 return fallback_mt;
2547 return -1;
2551 * Reserve a pageblock for exclusive use of high-order atomic allocations if
2552 * there are no empty page blocks that contain a page with a suitable order
2554 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2555 unsigned int alloc_order)
2557 int mt;
2558 unsigned long max_managed, flags;
2561 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2562 * Check is race-prone but harmless.
2564 max_managed = (zone_managed_pages(zone) / 100) + pageblock_nr_pages;
2565 if (zone->nr_reserved_highatomic >= max_managed)
2566 return;
2568 spin_lock_irqsave(&zone->lock, flags);
2570 /* Recheck the nr_reserved_highatomic limit under the lock */
2571 if (zone->nr_reserved_highatomic >= max_managed)
2572 goto out_unlock;
2574 /* Yoink! */
2575 mt = get_pageblock_migratetype(page);
2576 if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
2577 && !is_migrate_cma(mt)) {
2578 zone->nr_reserved_highatomic += pageblock_nr_pages;
2579 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
2580 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
2583 out_unlock:
2584 spin_unlock_irqrestore(&zone->lock, flags);
2588 * Used when an allocation is about to fail under memory pressure. This
2589 * potentially hurts the reliability of high-order allocations when under
2590 * intense memory pressure but failed atomic allocations should be easier
2591 * to recover from than an OOM.
2593 * If @force is true, try to unreserve a pageblock even though highatomic
2594 * pageblock is exhausted.
2596 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2597 bool force)
2599 struct zonelist *zonelist = ac->zonelist;
2600 unsigned long flags;
2601 struct zoneref *z;
2602 struct zone *zone;
2603 struct page *page;
2604 int order;
2605 bool ret;
2607 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2608 ac->nodemask) {
2610 * Preserve at least one pageblock unless memory pressure
2611 * is really high.
2613 if (!force && zone->nr_reserved_highatomic <=
2614 pageblock_nr_pages)
2615 continue;
2617 spin_lock_irqsave(&zone->lock, flags);
2618 for (order = 0; order < MAX_ORDER; order++) {
2619 struct free_area *area = &(zone->free_area[order]);
2621 page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
2622 if (!page)
2623 continue;
2626 * In page freeing path, migratetype change is racy so
2627 * we can counter several free pages in a pageblock
2628 * in this loop althoug we changed the pageblock type
2629 * from highatomic to ac->migratetype. So we should
2630 * adjust the count once.
2632 if (is_migrate_highatomic_page(page)) {
2634 * It should never happen but changes to
2635 * locking could inadvertently allow a per-cpu
2636 * drain to add pages to MIGRATE_HIGHATOMIC
2637 * while unreserving so be safe and watch for
2638 * underflows.
2640 zone->nr_reserved_highatomic -= min(
2641 pageblock_nr_pages,
2642 zone->nr_reserved_highatomic);
2646 * Convert to ac->migratetype and avoid the normal
2647 * pageblock stealing heuristics. Minimally, the caller
2648 * is doing the work and needs the pages. More
2649 * importantly, if the block was always converted to
2650 * MIGRATE_UNMOVABLE or another type then the number
2651 * of pageblocks that cannot be completely freed
2652 * may increase.
2654 set_pageblock_migratetype(page, ac->migratetype);
2655 ret = move_freepages_block(zone, page, ac->migratetype,
2656 NULL);
2657 if (ret) {
2658 spin_unlock_irqrestore(&zone->lock, flags);
2659 return ret;
2662 spin_unlock_irqrestore(&zone->lock, flags);
2665 return false;
2669 * Try finding a free buddy page on the fallback list and put it on the free
2670 * list of requested migratetype, possibly along with other pages from the same
2671 * block, depending on fragmentation avoidance heuristics. Returns true if
2672 * fallback was found so that __rmqueue_smallest() can grab it.
2674 * The use of signed ints for order and current_order is a deliberate
2675 * deviation from the rest of this file, to make the for loop
2676 * condition simpler.
2678 static __always_inline bool
2679 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype,
2680 unsigned int alloc_flags)
2682 struct free_area *area;
2683 int current_order;
2684 int min_order = order;
2685 struct page *page;
2686 int fallback_mt;
2687 bool can_steal;
2690 * Do not steal pages from freelists belonging to other pageblocks
2691 * i.e. orders < pageblock_order. If there are no local zones free,
2692 * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2694 if (alloc_flags & ALLOC_NOFRAGMENT)
2695 min_order = pageblock_order;
2698 * Find the largest available free page in the other list. This roughly
2699 * approximates finding the pageblock with the most free pages, which
2700 * would be too costly to do exactly.
2702 for (current_order = MAX_ORDER - 1; current_order >= min_order;
2703 --current_order) {
2704 area = &(zone->free_area[current_order]);
2705 fallback_mt = find_suitable_fallback(area, current_order,
2706 start_migratetype, false, &can_steal);
2707 if (fallback_mt == -1)
2708 continue;
2711 * We cannot steal all free pages from the pageblock and the
2712 * requested migratetype is movable. In that case it's better to
2713 * steal and split the smallest available page instead of the
2714 * largest available page, because even if the next movable
2715 * allocation falls back into a different pageblock than this
2716 * one, it won't cause permanent fragmentation.
2718 if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2719 && current_order > order)
2720 goto find_smallest;
2722 goto do_steal;
2725 return false;
2727 find_smallest:
2728 for (current_order = order; current_order < MAX_ORDER;
2729 current_order++) {
2730 area = &(zone->free_area[current_order]);
2731 fallback_mt = find_suitable_fallback(area, current_order,
2732 start_migratetype, false, &can_steal);
2733 if (fallback_mt != -1)
2734 break;
2738 * This should not happen - we already found a suitable fallback
2739 * when looking for the largest page.
2741 VM_BUG_ON(current_order == MAX_ORDER);
2743 do_steal:
2744 page = get_page_from_free_area(area, fallback_mt);
2746 steal_suitable_fallback(zone, page, alloc_flags, start_migratetype,
2747 can_steal);
2749 trace_mm_page_alloc_extfrag(page, order, current_order,
2750 start_migratetype, fallback_mt);
2752 return true;
2757 * Do the hard work of removing an element from the buddy allocator.
2758 * Call me with the zone->lock already held.
2760 static __always_inline struct page *
2761 __rmqueue(struct zone *zone, unsigned int order, int migratetype,
2762 unsigned int alloc_flags)
2764 struct page *page;
2766 retry:
2767 page = __rmqueue_smallest(zone, order, migratetype);
2768 if (unlikely(!page)) {
2769 if (migratetype == MIGRATE_MOVABLE)
2770 page = __rmqueue_cma_fallback(zone, order);
2772 if (!page && __rmqueue_fallback(zone, order, migratetype,
2773 alloc_flags))
2774 goto retry;
2777 trace_mm_page_alloc_zone_locked(page, order, migratetype);
2778 return page;
2782 * Obtain a specified number of elements from the buddy allocator, all under
2783 * a single hold of the lock, for efficiency. Add them to the supplied list.
2784 * Returns the number of new pages which were placed at *list.
2786 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2787 unsigned long count, struct list_head *list,
2788 int migratetype, unsigned int alloc_flags)
2790 int i, alloced = 0;
2792 spin_lock(&zone->lock);
2793 for (i = 0; i < count; ++i) {
2794 struct page *page = __rmqueue(zone, order, migratetype,
2795 alloc_flags);
2796 if (unlikely(page == NULL))
2797 break;
2799 if (unlikely(check_pcp_refill(page)))
2800 continue;
2803 * Split buddy pages returned by expand() are received here in
2804 * physical page order. The page is added to the tail of
2805 * caller's list. From the callers perspective, the linked list
2806 * is ordered by page number under some conditions. This is
2807 * useful for IO devices that can forward direction from the
2808 * head, thus also in the physical page order. This is useful
2809 * for IO devices that can merge IO requests if the physical
2810 * pages are ordered properly.
2812 list_add_tail(&page->lru, list);
2813 alloced++;
2814 if (is_migrate_cma(get_pcppage_migratetype(page)))
2815 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
2816 -(1 << order));
2820 * i pages were removed from the buddy list even if some leak due
2821 * to check_pcp_refill failing so adjust NR_FREE_PAGES based
2822 * on i. Do not confuse with 'alloced' which is the number of
2823 * pages added to the pcp list.
2825 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
2826 spin_unlock(&zone->lock);
2827 return alloced;
2830 #ifdef CONFIG_NUMA
2832 * Called from the vmstat counter updater to drain pagesets of this
2833 * currently executing processor on remote nodes after they have
2834 * expired.
2836 * Note that this function must be called with the thread pinned to
2837 * a single processor.
2839 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2841 unsigned long flags;
2842 int to_drain, batch;
2844 local_irq_save(flags);
2845 batch = READ_ONCE(pcp->batch);
2846 to_drain = min(pcp->count, batch);
2847 if (to_drain > 0)
2848 free_pcppages_bulk(zone, to_drain, pcp);
2849 local_irq_restore(flags);
2851 #endif
2854 * Drain pcplists of the indicated processor and zone.
2856 * The processor must either be the current processor and the
2857 * thread pinned to the current processor or a processor that
2858 * is not online.
2860 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2862 unsigned long flags;
2863 struct per_cpu_pageset *pset;
2864 struct per_cpu_pages *pcp;
2866 local_irq_save(flags);
2867 pset = per_cpu_ptr(zone->pageset, cpu);
2869 pcp = &pset->pcp;
2870 if (pcp->count)
2871 free_pcppages_bulk(zone, pcp->count, pcp);
2872 local_irq_restore(flags);
2876 * Drain pcplists of all zones on the indicated processor.
2878 * The processor must either be the current processor and the
2879 * thread pinned to the current processor or a processor that
2880 * is not online.
2882 static void drain_pages(unsigned int cpu)
2884 struct zone *zone;
2886 for_each_populated_zone(zone) {
2887 drain_pages_zone(cpu, zone);
2892 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2894 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2895 * the single zone's pages.
2897 void drain_local_pages(struct zone *zone)
2899 int cpu = smp_processor_id();
2901 if (zone)
2902 drain_pages_zone(cpu, zone);
2903 else
2904 drain_pages(cpu);
2907 static void drain_local_pages_wq(struct work_struct *work)
2909 struct pcpu_drain *drain;
2911 drain = container_of(work, struct pcpu_drain, work);
2914 * drain_all_pages doesn't use proper cpu hotplug protection so
2915 * we can race with cpu offline when the WQ can move this from
2916 * a cpu pinned worker to an unbound one. We can operate on a different
2917 * cpu which is allright but we also have to make sure to not move to
2918 * a different one.
2920 preempt_disable();
2921 drain_local_pages(drain->zone);
2922 preempt_enable();
2926 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2928 * When zone parameter is non-NULL, spill just the single zone's pages.
2930 * Note that this can be extremely slow as the draining happens in a workqueue.
2932 void drain_all_pages(struct zone *zone)
2934 int cpu;
2937 * Allocate in the BSS so we wont require allocation in
2938 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2940 static cpumask_t cpus_with_pcps;
2943 * Make sure nobody triggers this path before mm_percpu_wq is fully
2944 * initialized.
2946 if (WARN_ON_ONCE(!mm_percpu_wq))
2947 return;
2950 * Do not drain if one is already in progress unless it's specific to
2951 * a zone. Such callers are primarily CMA and memory hotplug and need
2952 * the drain to be complete when the call returns.
2954 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
2955 if (!zone)
2956 return;
2957 mutex_lock(&pcpu_drain_mutex);
2961 * We don't care about racing with CPU hotplug event
2962 * as offline notification will cause the notified
2963 * cpu to drain that CPU pcps and on_each_cpu_mask
2964 * disables preemption as part of its processing
2966 for_each_online_cpu(cpu) {
2967 struct per_cpu_pageset *pcp;
2968 struct zone *z;
2969 bool has_pcps = false;
2971 if (zone) {
2972 pcp = per_cpu_ptr(zone->pageset, cpu);
2973 if (pcp->pcp.count)
2974 has_pcps = true;
2975 } else {
2976 for_each_populated_zone(z) {
2977 pcp = per_cpu_ptr(z->pageset, cpu);
2978 if (pcp->pcp.count) {
2979 has_pcps = true;
2980 break;
2985 if (has_pcps)
2986 cpumask_set_cpu(cpu, &cpus_with_pcps);
2987 else
2988 cpumask_clear_cpu(cpu, &cpus_with_pcps);
2991 for_each_cpu(cpu, &cpus_with_pcps) {
2992 struct pcpu_drain *drain = per_cpu_ptr(&pcpu_drain, cpu);
2994 drain->zone = zone;
2995 INIT_WORK(&drain->work, drain_local_pages_wq);
2996 queue_work_on(cpu, mm_percpu_wq, &drain->work);
2998 for_each_cpu(cpu, &cpus_with_pcps)
2999 flush_work(&per_cpu_ptr(&pcpu_drain, cpu)->work);
3001 mutex_unlock(&pcpu_drain_mutex);
3004 #ifdef CONFIG_HIBERNATION
3007 * Touch the watchdog for every WD_PAGE_COUNT pages.
3009 #define WD_PAGE_COUNT (128*1024)
3011 void mark_free_pages(struct zone *zone)
3013 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
3014 unsigned long flags;
3015 unsigned int order, t;
3016 struct page *page;
3018 if (zone_is_empty(zone))
3019 return;
3021 spin_lock_irqsave(&zone->lock, flags);
3023 max_zone_pfn = zone_end_pfn(zone);
3024 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
3025 if (pfn_valid(pfn)) {
3026 page = pfn_to_page(pfn);
3028 if (!--page_count) {
3029 touch_nmi_watchdog();
3030 page_count = WD_PAGE_COUNT;
3033 if (page_zone(page) != zone)
3034 continue;
3036 if (!swsusp_page_is_forbidden(page))
3037 swsusp_unset_page_free(page);
3040 for_each_migratetype_order(order, t) {
3041 list_for_each_entry(page,
3042 &zone->free_area[order].free_list[t], lru) {
3043 unsigned long i;
3045 pfn = page_to_pfn(page);
3046 for (i = 0; i < (1UL << order); i++) {
3047 if (!--page_count) {
3048 touch_nmi_watchdog();
3049 page_count = WD_PAGE_COUNT;
3051 swsusp_set_page_free(pfn_to_page(pfn + i));
3055 spin_unlock_irqrestore(&zone->lock, flags);
3057 #endif /* CONFIG_PM */
3059 static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
3061 int migratetype;
3063 if (!free_pcp_prepare(page))
3064 return false;
3066 migratetype = get_pfnblock_migratetype(page, pfn);
3067 set_pcppage_migratetype(page, migratetype);
3068 return true;
3071 static void free_unref_page_commit(struct page *page, unsigned long pfn)
3073 struct zone *zone = page_zone(page);
3074 struct per_cpu_pages *pcp;
3075 int migratetype;
3077 migratetype = get_pcppage_migratetype(page);
3078 __count_vm_event(PGFREE);
3081 * We only track unmovable, reclaimable and movable on pcp lists.
3082 * Free ISOLATE pages back to the allocator because they are being
3083 * offlined but treat HIGHATOMIC as movable pages so we can get those
3084 * areas back if necessary. Otherwise, we may have to free
3085 * excessively into the page allocator
3087 if (migratetype >= MIGRATE_PCPTYPES) {
3088 if (unlikely(is_migrate_isolate(migratetype))) {
3089 free_one_page(zone, page, pfn, 0, migratetype);
3090 return;
3092 migratetype = MIGRATE_MOVABLE;
3095 pcp = &this_cpu_ptr(zone->pageset)->pcp;
3096 list_add(&page->lru, &pcp->lists[migratetype]);
3097 pcp->count++;
3098 if (pcp->count >= pcp->high) {
3099 unsigned long batch = READ_ONCE(pcp->batch);
3100 free_pcppages_bulk(zone, batch, pcp);
3105 * Free a 0-order page
3107 void free_unref_page(struct page *page)
3109 unsigned long flags;
3110 unsigned long pfn = page_to_pfn(page);
3112 if (!free_unref_page_prepare(page, pfn))
3113 return;
3115 local_irq_save(flags);
3116 free_unref_page_commit(page, pfn);
3117 local_irq_restore(flags);
3121 * Free a list of 0-order pages
3123 void free_unref_page_list(struct list_head *list)
3125 struct page *page, *next;
3126 unsigned long flags, pfn;
3127 int batch_count = 0;
3129 /* Prepare pages for freeing */
3130 list_for_each_entry_safe(page, next, list, lru) {
3131 pfn = page_to_pfn(page);
3132 if (!free_unref_page_prepare(page, pfn))
3133 list_del(&page->lru);
3134 set_page_private(page, pfn);
3137 local_irq_save(flags);
3138 list_for_each_entry_safe(page, next, list, lru) {
3139 unsigned long pfn = page_private(page);
3141 set_page_private(page, 0);
3142 trace_mm_page_free_batched(page);
3143 free_unref_page_commit(page, pfn);
3146 * Guard against excessive IRQ disabled times when we get
3147 * a large list of pages to free.
3149 if (++batch_count == SWAP_CLUSTER_MAX) {
3150 local_irq_restore(flags);
3151 batch_count = 0;
3152 local_irq_save(flags);
3155 local_irq_restore(flags);
3159 * split_page takes a non-compound higher-order page, and splits it into
3160 * n (1<<order) sub-pages: page[0..n]
3161 * Each sub-page must be freed individually.
3163 * Note: this is probably too low level an operation for use in drivers.
3164 * Please consult with lkml before using this in your driver.
3166 void split_page(struct page *page, unsigned int order)
3168 int i;
3170 VM_BUG_ON_PAGE(PageCompound(page), page);
3171 VM_BUG_ON_PAGE(!page_count(page), page);
3173 for (i = 1; i < (1 << order); i++)
3174 set_page_refcounted(page + i);
3175 split_page_owner(page, order);
3177 EXPORT_SYMBOL_GPL(split_page);
3179 int __isolate_free_page(struct page *page, unsigned int order)
3181 unsigned long watermark;
3182 struct zone *zone;
3183 int mt;
3185 BUG_ON(!PageBuddy(page));
3187 zone = page_zone(page);
3188 mt = get_pageblock_migratetype(page);
3190 if (!is_migrate_isolate(mt)) {
3192 * Obey watermarks as if the page was being allocated. We can
3193 * emulate a high-order watermark check with a raised order-0
3194 * watermark, because we already know our high-order page
3195 * exists.
3197 watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
3198 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
3199 return 0;
3201 __mod_zone_freepage_state(zone, -(1UL << order), mt);
3204 /* Remove page from free list */
3206 del_page_from_free_list(page, zone, order);
3209 * Set the pageblock if the isolated page is at least half of a
3210 * pageblock
3212 if (order >= pageblock_order - 1) {
3213 struct page *endpage = page + (1 << order) - 1;
3214 for (; page < endpage; page += pageblock_nr_pages) {
3215 int mt = get_pageblock_migratetype(page);
3216 if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
3217 && !is_migrate_highatomic(mt))
3218 set_pageblock_migratetype(page,
3219 MIGRATE_MOVABLE);
3224 return 1UL << order;
3228 * __putback_isolated_page - Return a now-isolated page back where we got it
3229 * @page: Page that was isolated
3230 * @order: Order of the isolated page
3231 * @mt: The page's pageblock's migratetype
3233 * This function is meant to return a page pulled from the free lists via
3234 * __isolate_free_page back to the free lists they were pulled from.
3236 void __putback_isolated_page(struct page *page, unsigned int order, int mt)
3238 struct zone *zone = page_zone(page);
3240 /* zone lock should be held when this function is called */
3241 lockdep_assert_held(&zone->lock);
3243 /* Return isolated page to tail of freelist. */
3244 __free_one_page(page, page_to_pfn(page), zone, order, mt, false);
3248 * Update NUMA hit/miss statistics
3250 * Must be called with interrupts disabled.
3252 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z)
3254 #ifdef CONFIG_NUMA
3255 enum numa_stat_item local_stat = NUMA_LOCAL;
3257 /* skip numa counters update if numa stats is disabled */
3258 if (!static_branch_likely(&vm_numa_stat_key))
3259 return;
3261 if (zone_to_nid(z) != numa_node_id())
3262 local_stat = NUMA_OTHER;
3264 if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3265 __inc_numa_state(z, NUMA_HIT);
3266 else {
3267 __inc_numa_state(z, NUMA_MISS);
3268 __inc_numa_state(preferred_zone, NUMA_FOREIGN);
3270 __inc_numa_state(z, local_stat);
3271 #endif
3274 /* Remove page from the per-cpu list, caller must protect the list */
3275 static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
3276 unsigned int alloc_flags,
3277 struct per_cpu_pages *pcp,
3278 struct list_head *list)
3280 struct page *page;
3282 do {
3283 if (list_empty(list)) {
3284 pcp->count += rmqueue_bulk(zone, 0,
3285 pcp->batch, list,
3286 migratetype, alloc_flags);
3287 if (unlikely(list_empty(list)))
3288 return NULL;
3291 page = list_first_entry(list, struct page, lru);
3292 list_del(&page->lru);
3293 pcp->count--;
3294 } while (check_new_pcp(page));
3296 return page;
3299 /* Lock and remove page from the per-cpu list */
3300 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
3301 struct zone *zone, gfp_t gfp_flags,
3302 int migratetype, unsigned int alloc_flags)
3304 struct per_cpu_pages *pcp;
3305 struct list_head *list;
3306 struct page *page;
3307 unsigned long flags;
3309 local_irq_save(flags);
3310 pcp = &this_cpu_ptr(zone->pageset)->pcp;
3311 list = &pcp->lists[migratetype];
3312 page = __rmqueue_pcplist(zone, migratetype, alloc_flags, pcp, list);
3313 if (page) {
3314 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1);
3315 zone_statistics(preferred_zone, zone);
3317 local_irq_restore(flags);
3318 return page;
3322 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
3324 static inline
3325 struct page *rmqueue(struct zone *preferred_zone,
3326 struct zone *zone, unsigned int order,
3327 gfp_t gfp_flags, unsigned int alloc_flags,
3328 int migratetype)
3330 unsigned long flags;
3331 struct page *page;
3333 if (likely(order == 0)) {
3334 page = rmqueue_pcplist(preferred_zone, zone, gfp_flags,
3335 migratetype, alloc_flags);
3336 goto out;
3340 * We most definitely don't want callers attempting to
3341 * allocate greater than order-1 page units with __GFP_NOFAIL.
3343 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
3344 spin_lock_irqsave(&zone->lock, flags);
3346 do {
3347 page = NULL;
3348 if (alloc_flags & ALLOC_HARDER) {
3349 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3350 if (page)
3351 trace_mm_page_alloc_zone_locked(page, order, migratetype);
3353 if (!page)
3354 page = __rmqueue(zone, order, migratetype, alloc_flags);
3355 } while (page && check_new_pages(page, order));
3356 spin_unlock(&zone->lock);
3357 if (!page)
3358 goto failed;
3359 __mod_zone_freepage_state(zone, -(1 << order),
3360 get_pcppage_migratetype(page));
3362 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3363 zone_statistics(preferred_zone, zone);
3364 local_irq_restore(flags);
3366 out:
3367 /* Separate test+clear to avoid unnecessary atomics */
3368 if (test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags)) {
3369 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3370 wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3373 VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3374 return page;
3376 failed:
3377 local_irq_restore(flags);
3378 return NULL;
3381 #ifdef CONFIG_FAIL_PAGE_ALLOC
3383 static struct {
3384 struct fault_attr attr;
3386 bool ignore_gfp_highmem;
3387 bool ignore_gfp_reclaim;
3388 u32 min_order;
3389 } fail_page_alloc = {
3390 .attr = FAULT_ATTR_INITIALIZER,
3391 .ignore_gfp_reclaim = true,
3392 .ignore_gfp_highmem = true,
3393 .min_order = 1,
3396 static int __init setup_fail_page_alloc(char *str)
3398 return setup_fault_attr(&fail_page_alloc.attr, str);
3400 __setup("fail_page_alloc=", setup_fail_page_alloc);
3402 static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3404 if (order < fail_page_alloc.min_order)
3405 return false;
3406 if (gfp_mask & __GFP_NOFAIL)
3407 return false;
3408 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3409 return false;
3410 if (fail_page_alloc.ignore_gfp_reclaim &&
3411 (gfp_mask & __GFP_DIRECT_RECLAIM))
3412 return false;
3414 return should_fail(&fail_page_alloc.attr, 1 << order);
3417 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3419 static int __init fail_page_alloc_debugfs(void)
3421 umode_t mode = S_IFREG | 0600;
3422 struct dentry *dir;
3424 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3425 &fail_page_alloc.attr);
3427 debugfs_create_bool("ignore-gfp-wait", mode, dir,
3428 &fail_page_alloc.ignore_gfp_reclaim);
3429 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3430 &fail_page_alloc.ignore_gfp_highmem);
3431 debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order);
3433 return 0;
3436 late_initcall(fail_page_alloc_debugfs);
3438 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3440 #else /* CONFIG_FAIL_PAGE_ALLOC */
3442 static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3444 return false;
3447 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3449 static noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3451 return __should_fail_alloc_page(gfp_mask, order);
3453 ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE);
3456 * Return true if free base pages are above 'mark'. For high-order checks it
3457 * will return true of the order-0 watermark is reached and there is at least
3458 * one free page of a suitable size. Checking now avoids taking the zone lock
3459 * to check in the allocation paths if no pages are free.
3461 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3462 int classzone_idx, unsigned int alloc_flags,
3463 long free_pages)
3465 long min = mark;
3466 int o;
3467 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3469 /* free_pages may go negative - that's OK */
3470 free_pages -= (1 << order) - 1;
3472 if (alloc_flags & ALLOC_HIGH)
3473 min -= min / 2;
3476 * If the caller does not have rights to ALLOC_HARDER then subtract
3477 * the high-atomic reserves. This will over-estimate the size of the
3478 * atomic reserve but it avoids a search.
3480 if (likely(!alloc_harder)) {
3481 free_pages -= z->nr_reserved_highatomic;
3482 } else {
3484 * OOM victims can try even harder than normal ALLOC_HARDER
3485 * users on the grounds that it's definitely going to be in
3486 * the exit path shortly and free memory. Any allocation it
3487 * makes during the free path will be small and short-lived.
3489 if (alloc_flags & ALLOC_OOM)
3490 min -= min / 2;
3491 else
3492 min -= min / 4;
3496 #ifdef CONFIG_CMA
3497 /* If allocation can't use CMA areas don't use free CMA pages */
3498 if (!(alloc_flags & ALLOC_CMA))
3499 free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
3500 #endif
3503 * Check watermarks for an order-0 allocation request. If these
3504 * are not met, then a high-order request also cannot go ahead
3505 * even if a suitable page happened to be free.
3507 if (free_pages <= min + z->lowmem_reserve[classzone_idx])
3508 return false;
3510 /* If this is an order-0 request then the watermark is fine */
3511 if (!order)
3512 return true;
3514 /* For a high-order request, check at least one suitable page is free */
3515 for (o = order; o < MAX_ORDER; o++) {
3516 struct free_area *area = &z->free_area[o];
3517 int mt;
3519 if (!area->nr_free)
3520 continue;
3522 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3523 if (!free_area_empty(area, mt))
3524 return true;
3527 #ifdef CONFIG_CMA
3528 if ((alloc_flags & ALLOC_CMA) &&
3529 !free_area_empty(area, MIGRATE_CMA)) {
3530 return true;
3532 #endif
3533 if (alloc_harder && !free_area_empty(area, MIGRATE_HIGHATOMIC))
3534 return true;
3536 return false;
3539 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3540 int classzone_idx, unsigned int alloc_flags)
3542 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3543 zone_page_state(z, NR_FREE_PAGES));
3546 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3547 unsigned long mark, int classzone_idx, unsigned int alloc_flags)
3549 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3550 long cma_pages = 0;
3552 #ifdef CONFIG_CMA
3553 /* If allocation can't use CMA areas don't use free CMA pages */
3554 if (!(alloc_flags & ALLOC_CMA))
3555 cma_pages = zone_page_state(z, NR_FREE_CMA_PAGES);
3556 #endif
3559 * Fast check for order-0 only. If this fails then the reserves
3560 * need to be calculated. There is a corner case where the check
3561 * passes but only the high-order atomic reserve are free. If
3562 * the caller is !atomic then it'll uselessly search the free
3563 * list. That corner case is then slower but it is harmless.
3565 if (!order && (free_pages - cma_pages) > mark + z->lowmem_reserve[classzone_idx])
3566 return true;
3568 return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3569 free_pages);
3572 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3573 unsigned long mark, int classzone_idx)
3575 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3577 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3578 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3580 return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
3581 free_pages);
3584 #ifdef CONFIG_NUMA
3585 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3587 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3588 node_reclaim_distance;
3590 #else /* CONFIG_NUMA */
3591 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3593 return true;
3595 #endif /* CONFIG_NUMA */
3598 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3599 * fragmentation is subtle. If the preferred zone was HIGHMEM then
3600 * premature use of a lower zone may cause lowmem pressure problems that
3601 * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3602 * probably too small. It only makes sense to spread allocations to avoid
3603 * fragmentation between the Normal and DMA32 zones.
3605 static inline unsigned int
3606 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3608 unsigned int alloc_flags;
3611 * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
3612 * to save a branch.
3614 alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
3616 #ifdef CONFIG_ZONE_DMA32
3617 if (!zone)
3618 return alloc_flags;
3620 if (zone_idx(zone) != ZONE_NORMAL)
3621 return alloc_flags;
3624 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3625 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3626 * on UMA that if Normal is populated then so is DMA32.
3628 BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3629 if (nr_online_nodes > 1 && !populated_zone(--zone))
3630 return alloc_flags;
3632 alloc_flags |= ALLOC_NOFRAGMENT;
3633 #endif /* CONFIG_ZONE_DMA32 */
3634 return alloc_flags;
3638 * get_page_from_freelist goes through the zonelist trying to allocate
3639 * a page.
3641 static struct page *
3642 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3643 const struct alloc_context *ac)
3645 struct zoneref *z;
3646 struct zone *zone;
3647 struct pglist_data *last_pgdat_dirty_limit = NULL;
3648 bool no_fallback;
3650 retry:
3652 * Scan zonelist, looking for a zone with enough free.
3653 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3655 no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3656 z = ac->preferred_zoneref;
3657 for_next_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
3658 ac->nodemask) {
3659 struct page *page;
3660 unsigned long mark;
3662 if (cpusets_enabled() &&
3663 (alloc_flags & ALLOC_CPUSET) &&
3664 !__cpuset_zone_allowed(zone, gfp_mask))
3665 continue;
3667 * When allocating a page cache page for writing, we
3668 * want to get it from a node that is within its dirty
3669 * limit, such that no single node holds more than its
3670 * proportional share of globally allowed dirty pages.
3671 * The dirty limits take into account the node's
3672 * lowmem reserves and high watermark so that kswapd
3673 * should be able to balance it without having to
3674 * write pages from its LRU list.
3676 * XXX: For now, allow allocations to potentially
3677 * exceed the per-node dirty limit in the slowpath
3678 * (spread_dirty_pages unset) before going into reclaim,
3679 * which is important when on a NUMA setup the allowed
3680 * nodes are together not big enough to reach the
3681 * global limit. The proper fix for these situations
3682 * will require awareness of nodes in the
3683 * dirty-throttling and the flusher threads.
3685 if (ac->spread_dirty_pages) {
3686 if (last_pgdat_dirty_limit == zone->zone_pgdat)
3687 continue;
3689 if (!node_dirty_ok(zone->zone_pgdat)) {
3690 last_pgdat_dirty_limit = zone->zone_pgdat;
3691 continue;
3695 if (no_fallback && nr_online_nodes > 1 &&
3696 zone != ac->preferred_zoneref->zone) {
3697 int local_nid;
3700 * If moving to a remote node, retry but allow
3701 * fragmenting fallbacks. Locality is more important
3702 * than fragmentation avoidance.
3704 local_nid = zone_to_nid(ac->preferred_zoneref->zone);
3705 if (zone_to_nid(zone) != local_nid) {
3706 alloc_flags &= ~ALLOC_NOFRAGMENT;
3707 goto retry;
3711 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
3712 if (!zone_watermark_fast(zone, order, mark,
3713 ac_classzone_idx(ac), alloc_flags)) {
3714 int ret;
3716 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3718 * Watermark failed for this zone, but see if we can
3719 * grow this zone if it contains deferred pages.
3721 if (static_branch_unlikely(&deferred_pages)) {
3722 if (_deferred_grow_zone(zone, order))
3723 goto try_this_zone;
3725 #endif
3726 /* Checked here to keep the fast path fast */
3727 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3728 if (alloc_flags & ALLOC_NO_WATERMARKS)
3729 goto try_this_zone;
3731 if (node_reclaim_mode == 0 ||
3732 !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
3733 continue;
3735 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3736 switch (ret) {
3737 case NODE_RECLAIM_NOSCAN:
3738 /* did not scan */
3739 continue;
3740 case NODE_RECLAIM_FULL:
3741 /* scanned but unreclaimable */
3742 continue;
3743 default:
3744 /* did we reclaim enough */
3745 if (zone_watermark_ok(zone, order, mark,
3746 ac_classzone_idx(ac), alloc_flags))
3747 goto try_this_zone;
3749 continue;
3753 try_this_zone:
3754 page = rmqueue(ac->preferred_zoneref->zone, zone, order,
3755 gfp_mask, alloc_flags, ac->migratetype);
3756 if (page) {
3757 prep_new_page(page, order, gfp_mask, alloc_flags);
3760 * If this is a high-order atomic allocation then check
3761 * if the pageblock should be reserved for the future
3763 if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
3764 reserve_highatomic_pageblock(page, zone, order);
3766 return page;
3767 } else {
3768 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3769 /* Try again if zone has deferred pages */
3770 if (static_branch_unlikely(&deferred_pages)) {
3771 if (_deferred_grow_zone(zone, order))
3772 goto try_this_zone;
3774 #endif
3779 * It's possible on a UMA machine to get through all zones that are
3780 * fragmented. If avoiding fragmentation, reset and try again.
3782 if (no_fallback) {
3783 alloc_flags &= ~ALLOC_NOFRAGMENT;
3784 goto retry;
3787 return NULL;
3790 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
3792 unsigned int filter = SHOW_MEM_FILTER_NODES;
3795 * This documents exceptions given to allocations in certain
3796 * contexts that are allowed to allocate outside current's set
3797 * of allowed nodes.
3799 if (!(gfp_mask & __GFP_NOMEMALLOC))
3800 if (tsk_is_oom_victim(current) ||
3801 (current->flags & (PF_MEMALLOC | PF_EXITING)))
3802 filter &= ~SHOW_MEM_FILTER_NODES;
3803 if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
3804 filter &= ~SHOW_MEM_FILTER_NODES;
3806 show_mem(filter, nodemask);
3809 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
3811 struct va_format vaf;
3812 va_list args;
3813 static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
3815 if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs))
3816 return;
3818 va_start(args, fmt);
3819 vaf.fmt = fmt;
3820 vaf.va = &args;
3821 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
3822 current->comm, &vaf, gfp_mask, &gfp_mask,
3823 nodemask_pr_args(nodemask));
3824 va_end(args);
3826 cpuset_print_current_mems_allowed();
3827 pr_cont("\n");
3828 dump_stack();
3829 warn_alloc_show_mem(gfp_mask, nodemask);
3832 static inline struct page *
3833 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
3834 unsigned int alloc_flags,
3835 const struct alloc_context *ac)
3837 struct page *page;
3839 page = get_page_from_freelist(gfp_mask, order,
3840 alloc_flags|ALLOC_CPUSET, ac);
3842 * fallback to ignore cpuset restriction if our nodes
3843 * are depleted
3845 if (!page)
3846 page = get_page_from_freelist(gfp_mask, order,
3847 alloc_flags, ac);
3849 return page;
3852 static inline struct page *
3853 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
3854 const struct alloc_context *ac, unsigned long *did_some_progress)
3856 struct oom_control oc = {
3857 .zonelist = ac->zonelist,
3858 .nodemask = ac->nodemask,
3859 .memcg = NULL,
3860 .gfp_mask = gfp_mask,
3861 .order = order,
3863 struct page *page;
3865 *did_some_progress = 0;
3868 * Acquire the oom lock. If that fails, somebody else is
3869 * making progress for us.
3871 if (!mutex_trylock(&oom_lock)) {
3872 *did_some_progress = 1;
3873 schedule_timeout_uninterruptible(1);
3874 return NULL;
3878 * Go through the zonelist yet one more time, keep very high watermark
3879 * here, this is only to catch a parallel oom killing, we must fail if
3880 * we're still under heavy pressure. But make sure that this reclaim
3881 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
3882 * allocation which will never fail due to oom_lock already held.
3884 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
3885 ~__GFP_DIRECT_RECLAIM, order,
3886 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
3887 if (page)
3888 goto out;
3890 /* Coredumps can quickly deplete all memory reserves */
3891 if (current->flags & PF_DUMPCORE)
3892 goto out;
3893 /* The OOM killer will not help higher order allocs */
3894 if (order > PAGE_ALLOC_COSTLY_ORDER)
3895 goto out;
3897 * We have already exhausted all our reclaim opportunities without any
3898 * success so it is time to admit defeat. We will skip the OOM killer
3899 * because it is very likely that the caller has a more reasonable
3900 * fallback than shooting a random task.
3902 if (gfp_mask & __GFP_RETRY_MAYFAIL)
3903 goto out;
3904 /* The OOM killer does not needlessly kill tasks for lowmem */
3905 if (ac->high_zoneidx < ZONE_NORMAL)
3906 goto out;
3907 if (pm_suspended_storage())
3908 goto out;
3910 * XXX: GFP_NOFS allocations should rather fail than rely on
3911 * other request to make a forward progress.
3912 * We are in an unfortunate situation where out_of_memory cannot
3913 * do much for this context but let's try it to at least get
3914 * access to memory reserved if the current task is killed (see
3915 * out_of_memory). Once filesystems are ready to handle allocation
3916 * failures more gracefully we should just bail out here.
3919 /* The OOM killer may not free memory on a specific node */
3920 if (gfp_mask & __GFP_THISNODE)
3921 goto out;
3923 /* Exhausted what can be done so it's blame time */
3924 if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
3925 *did_some_progress = 1;
3928 * Help non-failing allocations by giving them access to memory
3929 * reserves
3931 if (gfp_mask & __GFP_NOFAIL)
3932 page = __alloc_pages_cpuset_fallback(gfp_mask, order,
3933 ALLOC_NO_WATERMARKS, ac);
3935 out:
3936 mutex_unlock(&oom_lock);
3937 return page;
3941 * Maximum number of compaction retries wit a progress before OOM
3942 * killer is consider as the only way to move forward.
3944 #define MAX_COMPACT_RETRIES 16
3946 #ifdef CONFIG_COMPACTION
3947 /* Try memory compaction for high-order allocations before reclaim */
3948 static struct page *
3949 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
3950 unsigned int alloc_flags, const struct alloc_context *ac,
3951 enum compact_priority prio, enum compact_result *compact_result)
3953 struct page *page = NULL;
3954 unsigned long pflags;
3955 unsigned int noreclaim_flag;
3957 if (!order)
3958 return NULL;
3960 psi_memstall_enter(&pflags);
3961 noreclaim_flag = memalloc_noreclaim_save();
3963 *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
3964 prio, &page);
3966 memalloc_noreclaim_restore(noreclaim_flag);
3967 psi_memstall_leave(&pflags);
3970 * At least in one zone compaction wasn't deferred or skipped, so let's
3971 * count a compaction stall
3973 count_vm_event(COMPACTSTALL);
3975 /* Prep a captured page if available */
3976 if (page)
3977 prep_new_page(page, order, gfp_mask, alloc_flags);
3979 /* Try get a page from the freelist if available */
3980 if (!page)
3981 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
3983 if (page) {
3984 struct zone *zone = page_zone(page);
3986 zone->compact_blockskip_flush = false;
3987 compaction_defer_reset(zone, order, true);
3988 count_vm_event(COMPACTSUCCESS);
3989 return page;
3993 * It's bad if compaction run occurs and fails. The most likely reason
3994 * is that pages exist, but not enough to satisfy watermarks.
3996 count_vm_event(COMPACTFAIL);
3998 cond_resched();
4000 return NULL;
4003 static inline bool
4004 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
4005 enum compact_result compact_result,
4006 enum compact_priority *compact_priority,
4007 int *compaction_retries)
4009 int max_retries = MAX_COMPACT_RETRIES;
4010 int min_priority;
4011 bool ret = false;
4012 int retries = *compaction_retries;
4013 enum compact_priority priority = *compact_priority;
4015 if (!order)
4016 return false;
4018 if (compaction_made_progress(compact_result))
4019 (*compaction_retries)++;
4022 * compaction considers all the zone as desperately out of memory
4023 * so it doesn't really make much sense to retry except when the
4024 * failure could be caused by insufficient priority
4026 if (compaction_failed(compact_result))
4027 goto check_priority;
4030 * compaction was skipped because there are not enough order-0 pages
4031 * to work with, so we retry only if it looks like reclaim can help.
4033 if (compaction_needs_reclaim(compact_result)) {
4034 ret = compaction_zonelist_suitable(ac, order, alloc_flags);
4035 goto out;
4039 * make sure the compaction wasn't deferred or didn't bail out early
4040 * due to locks contention before we declare that we should give up.
4041 * But the next retry should use a higher priority if allowed, so
4042 * we don't just keep bailing out endlessly.
4044 if (compaction_withdrawn(compact_result)) {
4045 goto check_priority;
4049 * !costly requests are much more important than __GFP_RETRY_MAYFAIL
4050 * costly ones because they are de facto nofail and invoke OOM
4051 * killer to move on while costly can fail and users are ready
4052 * to cope with that. 1/4 retries is rather arbitrary but we
4053 * would need much more detailed feedback from compaction to
4054 * make a better decision.
4056 if (order > PAGE_ALLOC_COSTLY_ORDER)
4057 max_retries /= 4;
4058 if (*compaction_retries <= max_retries) {
4059 ret = true;
4060 goto out;
4064 * Make sure there are attempts at the highest priority if we exhausted
4065 * all retries or failed at the lower priorities.
4067 check_priority:
4068 min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
4069 MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
4071 if (*compact_priority > min_priority) {
4072 (*compact_priority)--;
4073 *compaction_retries = 0;
4074 ret = true;
4076 out:
4077 trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
4078 return ret;
4080 #else
4081 static inline struct page *
4082 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4083 unsigned int alloc_flags, const struct alloc_context *ac,
4084 enum compact_priority prio, enum compact_result *compact_result)
4086 *compact_result = COMPACT_SKIPPED;
4087 return NULL;
4090 static inline bool
4091 should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
4092 enum compact_result compact_result,
4093 enum compact_priority *compact_priority,
4094 int *compaction_retries)
4096 struct zone *zone;
4097 struct zoneref *z;
4099 if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
4100 return false;
4103 * There are setups with compaction disabled which would prefer to loop
4104 * inside the allocator rather than hit the oom killer prematurely.
4105 * Let's give them a good hope and keep retrying while the order-0
4106 * watermarks are OK.
4108 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
4109 ac->nodemask) {
4110 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
4111 ac_classzone_idx(ac), alloc_flags))
4112 return true;
4114 return false;
4116 #endif /* CONFIG_COMPACTION */
4118 #ifdef CONFIG_LOCKDEP
4119 static struct lockdep_map __fs_reclaim_map =
4120 STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
4122 static bool __need_fs_reclaim(gfp_t gfp_mask)
4124 gfp_mask = current_gfp_context(gfp_mask);
4126 /* no reclaim without waiting on it */
4127 if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
4128 return false;
4130 /* this guy won't enter reclaim */
4131 if (current->flags & PF_MEMALLOC)
4132 return false;
4134 /* We're only interested __GFP_FS allocations for now */
4135 if (!(gfp_mask & __GFP_FS))
4136 return false;
4138 if (gfp_mask & __GFP_NOLOCKDEP)
4139 return false;
4141 return true;
4144 void __fs_reclaim_acquire(void)
4146 lock_map_acquire(&__fs_reclaim_map);
4149 void __fs_reclaim_release(void)
4151 lock_map_release(&__fs_reclaim_map);
4154 void fs_reclaim_acquire(gfp_t gfp_mask)
4156 if (__need_fs_reclaim(gfp_mask))
4157 __fs_reclaim_acquire();
4159 EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
4161 void fs_reclaim_release(gfp_t gfp_mask)
4163 if (__need_fs_reclaim(gfp_mask))
4164 __fs_reclaim_release();
4166 EXPORT_SYMBOL_GPL(fs_reclaim_release);
4167 #endif
4169 /* Perform direct synchronous page reclaim */
4170 static int
4171 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
4172 const struct alloc_context *ac)
4174 int progress;
4175 unsigned int noreclaim_flag;
4176 unsigned long pflags;
4178 cond_resched();
4180 /* We now go into synchronous reclaim */
4181 cpuset_memory_pressure_bump();
4182 psi_memstall_enter(&pflags);
4183 fs_reclaim_acquire(gfp_mask);
4184 noreclaim_flag = memalloc_noreclaim_save();
4186 progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
4187 ac->nodemask);
4189 memalloc_noreclaim_restore(noreclaim_flag);
4190 fs_reclaim_release(gfp_mask);
4191 psi_memstall_leave(&pflags);
4193 cond_resched();
4195 return progress;
4198 /* The really slow allocator path where we enter direct reclaim */
4199 static inline struct page *
4200 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
4201 unsigned int alloc_flags, const struct alloc_context *ac,
4202 unsigned long *did_some_progress)
4204 struct page *page = NULL;
4205 bool drained = false;
4207 *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
4208 if (unlikely(!(*did_some_progress)))
4209 return NULL;
4211 retry:
4212 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4215 * If an allocation failed after direct reclaim, it could be because
4216 * pages are pinned on the per-cpu lists or in high alloc reserves.
4217 * Shrink them them and try again
4219 if (!page && !drained) {
4220 unreserve_highatomic_pageblock(ac, false);
4221 drain_all_pages(NULL);
4222 drained = true;
4223 goto retry;
4226 return page;
4229 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
4230 const struct alloc_context *ac)
4232 struct zoneref *z;
4233 struct zone *zone;
4234 pg_data_t *last_pgdat = NULL;
4235 enum zone_type high_zoneidx = ac->high_zoneidx;
4237 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, high_zoneidx,
4238 ac->nodemask) {
4239 if (last_pgdat != zone->zone_pgdat)
4240 wakeup_kswapd(zone, gfp_mask, order, high_zoneidx);
4241 last_pgdat = zone->zone_pgdat;
4245 static inline unsigned int
4246 gfp_to_alloc_flags(gfp_t gfp_mask)
4248 unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
4251 * __GFP_HIGH is assumed to be the same as ALLOC_HIGH
4252 * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
4253 * to save two branches.
4255 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
4256 BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD);
4259 * The caller may dip into page reserves a bit more if the caller
4260 * cannot run direct reclaim, or if the caller has realtime scheduling
4261 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
4262 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
4264 alloc_flags |= (__force int)
4265 (gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM));
4267 if (gfp_mask & __GFP_ATOMIC) {
4269 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4270 * if it can't schedule.
4272 if (!(gfp_mask & __GFP_NOMEMALLOC))
4273 alloc_flags |= ALLOC_HARDER;
4275 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
4276 * comment for __cpuset_node_allowed().
4278 alloc_flags &= ~ALLOC_CPUSET;
4279 } else if (unlikely(rt_task(current)) && !in_interrupt())
4280 alloc_flags |= ALLOC_HARDER;
4282 #ifdef CONFIG_CMA
4283 if (gfpflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
4284 alloc_flags |= ALLOC_CMA;
4285 #endif
4286 return alloc_flags;
4289 static bool oom_reserves_allowed(struct task_struct *tsk)
4291 if (!tsk_is_oom_victim(tsk))
4292 return false;
4295 * !MMU doesn't have oom reaper so give access to memory reserves
4296 * only to the thread with TIF_MEMDIE set
4298 if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
4299 return false;
4301 return true;
4305 * Distinguish requests which really need access to full memory
4306 * reserves from oom victims which can live with a portion of it
4308 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4310 if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4311 return 0;
4312 if (gfp_mask & __GFP_MEMALLOC)
4313 return ALLOC_NO_WATERMARKS;
4314 if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
4315 return ALLOC_NO_WATERMARKS;
4316 if (!in_interrupt()) {
4317 if (current->flags & PF_MEMALLOC)
4318 return ALLOC_NO_WATERMARKS;
4319 else if (oom_reserves_allowed(current))
4320 return ALLOC_OOM;
4323 return 0;
4326 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4328 return !!__gfp_pfmemalloc_flags(gfp_mask);
4332 * Checks whether it makes sense to retry the reclaim to make a forward progress
4333 * for the given allocation request.
4335 * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4336 * without success, or when we couldn't even meet the watermark if we
4337 * reclaimed all remaining pages on the LRU lists.
4339 * Returns true if a retry is viable or false to enter the oom path.
4341 static inline bool
4342 should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4343 struct alloc_context *ac, int alloc_flags,
4344 bool did_some_progress, int *no_progress_loops)
4346 struct zone *zone;
4347 struct zoneref *z;
4348 bool ret = false;
4351 * Costly allocations might have made a progress but this doesn't mean
4352 * their order will become available due to high fragmentation so
4353 * always increment the no progress counter for them
4355 if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4356 *no_progress_loops = 0;
4357 else
4358 (*no_progress_loops)++;
4361 * Make sure we converge to OOM if we cannot make any progress
4362 * several times in the row.
4364 if (*no_progress_loops > MAX_RECLAIM_RETRIES) {
4365 /* Before OOM, exhaust highatomic_reserve */
4366 return unreserve_highatomic_pageblock(ac, true);
4370 * Keep reclaiming pages while there is a chance this will lead
4371 * somewhere. If none of the target zones can satisfy our allocation
4372 * request even if all reclaimable pages are considered then we are
4373 * screwed and have to go OOM.
4375 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
4376 ac->nodemask) {
4377 unsigned long available;
4378 unsigned long reclaimable;
4379 unsigned long min_wmark = min_wmark_pages(zone);
4380 bool wmark;
4382 available = reclaimable = zone_reclaimable_pages(zone);
4383 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
4386 * Would the allocation succeed if we reclaimed all
4387 * reclaimable pages?
4389 wmark = __zone_watermark_ok(zone, order, min_wmark,
4390 ac_classzone_idx(ac), alloc_flags, available);
4391 trace_reclaim_retry_zone(z, order, reclaimable,
4392 available, min_wmark, *no_progress_loops, wmark);
4393 if (wmark) {
4395 * If we didn't make any progress and have a lot of
4396 * dirty + writeback pages then we should wait for
4397 * an IO to complete to slow down the reclaim and
4398 * prevent from pre mature OOM
4400 if (!did_some_progress) {
4401 unsigned long write_pending;
4403 write_pending = zone_page_state_snapshot(zone,
4404 NR_ZONE_WRITE_PENDING);
4406 if (2 * write_pending > reclaimable) {
4407 congestion_wait(BLK_RW_ASYNC, HZ/10);
4408 return true;
4412 ret = true;
4413 goto out;
4417 out:
4419 * Memory allocation/reclaim might be called from a WQ context and the
4420 * current implementation of the WQ concurrency control doesn't
4421 * recognize that a particular WQ is congested if the worker thread is
4422 * looping without ever sleeping. Therefore we have to do a short sleep
4423 * here rather than calling cond_resched().
4425 if (current->flags & PF_WQ_WORKER)
4426 schedule_timeout_uninterruptible(1);
4427 else
4428 cond_resched();
4429 return ret;
4432 static inline bool
4433 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4436 * It's possible that cpuset's mems_allowed and the nodemask from
4437 * mempolicy don't intersect. This should be normally dealt with by
4438 * policy_nodemask(), but it's possible to race with cpuset update in
4439 * such a way the check therein was true, and then it became false
4440 * before we got our cpuset_mems_cookie here.
4441 * This assumes that for all allocations, ac->nodemask can come only
4442 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4443 * when it does not intersect with the cpuset restrictions) or the
4444 * caller can deal with a violated nodemask.
4446 if (cpusets_enabled() && ac->nodemask &&
4447 !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4448 ac->nodemask = NULL;
4449 return true;
4453 * When updating a task's mems_allowed or mempolicy nodemask, it is
4454 * possible to race with parallel threads in such a way that our
4455 * allocation can fail while the mask is being updated. If we are about
4456 * to fail, check if the cpuset changed during allocation and if so,
4457 * retry.
4459 if (read_mems_allowed_retry(cpuset_mems_cookie))
4460 return true;
4462 return false;
4465 static inline struct page *
4466 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
4467 struct alloc_context *ac)
4469 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
4470 const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
4471 struct page *page = NULL;
4472 unsigned int alloc_flags;
4473 unsigned long did_some_progress;
4474 enum compact_priority compact_priority;
4475 enum compact_result compact_result;
4476 int compaction_retries;
4477 int no_progress_loops;
4478 unsigned int cpuset_mems_cookie;
4479 int reserve_flags;
4482 * We also sanity check to catch abuse of atomic reserves being used by
4483 * callers that are not in atomic context.
4485 if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
4486 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
4487 gfp_mask &= ~__GFP_ATOMIC;
4489 retry_cpuset:
4490 compaction_retries = 0;
4491 no_progress_loops = 0;
4492 compact_priority = DEF_COMPACT_PRIORITY;
4493 cpuset_mems_cookie = read_mems_allowed_begin();
4496 * The fast path uses conservative alloc_flags to succeed only until
4497 * kswapd needs to be woken up, and to avoid the cost of setting up
4498 * alloc_flags precisely. So we do that now.
4500 alloc_flags = gfp_to_alloc_flags(gfp_mask);
4503 * We need to recalculate the starting point for the zonelist iterator
4504 * because we might have used different nodemask in the fast path, or
4505 * there was a cpuset modification and we are retrying - otherwise we
4506 * could end up iterating over non-eligible zones endlessly.
4508 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4509 ac->high_zoneidx, ac->nodemask);
4510 if (!ac->preferred_zoneref->zone)
4511 goto nopage;
4513 if (alloc_flags & ALLOC_KSWAPD)
4514 wake_all_kswapds(order, gfp_mask, ac);
4517 * The adjusted alloc_flags might result in immediate success, so try
4518 * that first
4520 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4521 if (page)
4522 goto got_pg;
4525 * For costly allocations, try direct compaction first, as it's likely
4526 * that we have enough base pages and don't need to reclaim. For non-
4527 * movable high-order allocations, do that as well, as compaction will
4528 * try prevent permanent fragmentation by migrating from blocks of the
4529 * same migratetype.
4530 * Don't try this for allocations that are allowed to ignore
4531 * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
4533 if (can_direct_reclaim &&
4534 (costly_order ||
4535 (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
4536 && !gfp_pfmemalloc_allowed(gfp_mask)) {
4537 page = __alloc_pages_direct_compact(gfp_mask, order,
4538 alloc_flags, ac,
4539 INIT_COMPACT_PRIORITY,
4540 &compact_result);
4541 if (page)
4542 goto got_pg;
4545 * Checks for costly allocations with __GFP_NORETRY, which
4546 * includes some THP page fault allocations
4548 if (costly_order && (gfp_mask & __GFP_NORETRY)) {
4550 * If allocating entire pageblock(s) and compaction
4551 * failed because all zones are below low watermarks
4552 * or is prohibited because it recently failed at this
4553 * order, fail immediately unless the allocator has
4554 * requested compaction and reclaim retry.
4556 * Reclaim is
4557 * - potentially very expensive because zones are far
4558 * below their low watermarks or this is part of very
4559 * bursty high order allocations,
4560 * - not guaranteed to help because isolate_freepages()
4561 * may not iterate over freed pages as part of its
4562 * linear scan, and
4563 * - unlikely to make entire pageblocks free on its
4564 * own.
4566 if (compact_result == COMPACT_SKIPPED ||
4567 compact_result == COMPACT_DEFERRED)
4568 goto nopage;
4571 * Looks like reclaim/compaction is worth trying, but
4572 * sync compaction could be very expensive, so keep
4573 * using async compaction.
4575 compact_priority = INIT_COMPACT_PRIORITY;
4579 retry:
4580 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4581 if (alloc_flags & ALLOC_KSWAPD)
4582 wake_all_kswapds(order, gfp_mask, ac);
4584 reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
4585 if (reserve_flags)
4586 alloc_flags = reserve_flags;
4589 * Reset the nodemask and zonelist iterators if memory policies can be
4590 * ignored. These allocations are high priority and system rather than
4591 * user oriented.
4593 if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
4594 ac->nodemask = NULL;
4595 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4596 ac->high_zoneidx, ac->nodemask);
4599 /* Attempt with potentially adjusted zonelist and alloc_flags */
4600 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4601 if (page)
4602 goto got_pg;
4604 /* Caller is not willing to reclaim, we can't balance anything */
4605 if (!can_direct_reclaim)
4606 goto nopage;
4608 /* Avoid recursion of direct reclaim */
4609 if (current->flags & PF_MEMALLOC)
4610 goto nopage;
4612 /* Try direct reclaim and then allocating */
4613 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
4614 &did_some_progress);
4615 if (page)
4616 goto got_pg;
4618 /* Try direct compaction and then allocating */
4619 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
4620 compact_priority, &compact_result);
4621 if (page)
4622 goto got_pg;
4624 /* Do not loop if specifically requested */
4625 if (gfp_mask & __GFP_NORETRY)
4626 goto nopage;
4629 * Do not retry costly high order allocations unless they are
4630 * __GFP_RETRY_MAYFAIL
4632 if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL))
4633 goto nopage;
4635 if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
4636 did_some_progress > 0, &no_progress_loops))
4637 goto retry;
4640 * It doesn't make any sense to retry for the compaction if the order-0
4641 * reclaim is not able to make any progress because the current
4642 * implementation of the compaction depends on the sufficient amount
4643 * of free memory (see __compaction_suitable)
4645 if (did_some_progress > 0 &&
4646 should_compact_retry(ac, order, alloc_flags,
4647 compact_result, &compact_priority,
4648 &compaction_retries))
4649 goto retry;
4652 /* Deal with possible cpuset update races before we start OOM killing */
4653 if (check_retry_cpuset(cpuset_mems_cookie, ac))
4654 goto retry_cpuset;
4656 /* Reclaim has failed us, start killing things */
4657 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
4658 if (page)
4659 goto got_pg;
4661 /* Avoid allocations with no watermarks from looping endlessly */
4662 if (tsk_is_oom_victim(current) &&
4663 (alloc_flags == ALLOC_OOM ||
4664 (gfp_mask & __GFP_NOMEMALLOC)))
4665 goto nopage;
4667 /* Retry as long as the OOM killer is making progress */
4668 if (did_some_progress) {
4669 no_progress_loops = 0;
4670 goto retry;
4673 nopage:
4674 /* Deal with possible cpuset update races before we fail */
4675 if (check_retry_cpuset(cpuset_mems_cookie, ac))
4676 goto retry_cpuset;
4679 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
4680 * we always retry
4682 if (gfp_mask & __GFP_NOFAIL) {
4684 * All existing users of the __GFP_NOFAIL are blockable, so warn
4685 * of any new users that actually require GFP_NOWAIT
4687 if (WARN_ON_ONCE(!can_direct_reclaim))
4688 goto fail;
4691 * PF_MEMALLOC request from this context is rather bizarre
4692 * because we cannot reclaim anything and only can loop waiting
4693 * for somebody to do a work for us
4695 WARN_ON_ONCE(current->flags & PF_MEMALLOC);
4698 * non failing costly orders are a hard requirement which we
4699 * are not prepared for much so let's warn about these users
4700 * so that we can identify them and convert them to something
4701 * else.
4703 WARN_ON_ONCE(order > PAGE_ALLOC_COSTLY_ORDER);
4706 * Help non-failing allocations by giving them access to memory
4707 * reserves but do not use ALLOC_NO_WATERMARKS because this
4708 * could deplete whole memory reserves which would just make
4709 * the situation worse
4711 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac);
4712 if (page)
4713 goto got_pg;
4715 cond_resched();
4716 goto retry;
4718 fail:
4719 warn_alloc(gfp_mask, ac->nodemask,
4720 "page allocation failure: order:%u", order);
4721 got_pg:
4722 return page;
4725 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
4726 int preferred_nid, nodemask_t *nodemask,
4727 struct alloc_context *ac, gfp_t *alloc_mask,
4728 unsigned int *alloc_flags)
4730 ac->high_zoneidx = gfp_zone(gfp_mask);
4731 ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
4732 ac->nodemask = nodemask;
4733 ac->migratetype = gfpflags_to_migratetype(gfp_mask);
4735 if (cpusets_enabled()) {
4736 *alloc_mask |= __GFP_HARDWALL;
4737 if (!ac->nodemask)
4738 ac->nodemask = &cpuset_current_mems_allowed;
4739 else
4740 *alloc_flags |= ALLOC_CPUSET;
4743 fs_reclaim_acquire(gfp_mask);
4744 fs_reclaim_release(gfp_mask);
4746 might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
4748 if (should_fail_alloc_page(gfp_mask, order))
4749 return false;
4751 if (IS_ENABLED(CONFIG_CMA) && ac->migratetype == MIGRATE_MOVABLE)
4752 *alloc_flags |= ALLOC_CMA;
4754 return true;
4757 /* Determine whether to spread dirty pages and what the first usable zone */
4758 static inline void finalise_ac(gfp_t gfp_mask, struct alloc_context *ac)
4760 /* Dirty zone balancing only done in the fast path */
4761 ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
4764 * The preferred zone is used for statistics but crucially it is
4765 * also used as the starting point for the zonelist iterator. It
4766 * may get reset for allocations that ignore memory policies.
4768 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4769 ac->high_zoneidx, ac->nodemask);
4773 * This is the 'heart' of the zoned buddy allocator.
4775 struct page *
4776 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order, int preferred_nid,
4777 nodemask_t *nodemask)
4779 struct page *page;
4780 unsigned int alloc_flags = ALLOC_WMARK_LOW;
4781 gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
4782 struct alloc_context ac = { };
4785 * There are several places where we assume that the order value is sane
4786 * so bail out early if the request is out of bound.
4788 if (unlikely(order >= MAX_ORDER)) {
4789 WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
4790 return NULL;
4793 gfp_mask &= gfp_allowed_mask;
4794 alloc_mask = gfp_mask;
4795 if (!prepare_alloc_pages(gfp_mask, order, preferred_nid, nodemask, &ac, &alloc_mask, &alloc_flags))
4796 return NULL;
4798 finalise_ac(gfp_mask, &ac);
4801 * Forbid the first pass from falling back to types that fragment
4802 * memory until all local zones are considered.
4804 alloc_flags |= alloc_flags_nofragment(ac.preferred_zoneref->zone, gfp_mask);
4806 /* First allocation attempt */
4807 page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
4808 if (likely(page))
4809 goto out;
4812 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
4813 * resp. GFP_NOIO which has to be inherited for all allocation requests
4814 * from a particular context which has been marked by
4815 * memalloc_no{fs,io}_{save,restore}.
4817 alloc_mask = current_gfp_context(gfp_mask);
4818 ac.spread_dirty_pages = false;
4821 * Restore the original nodemask if it was potentially replaced with
4822 * &cpuset_current_mems_allowed to optimize the fast-path attempt.
4824 ac.nodemask = nodemask;
4826 page = __alloc_pages_slowpath(alloc_mask, order, &ac);
4828 out:
4829 if (memcg_kmem_enabled() && (gfp_mask & __GFP_ACCOUNT) && page &&
4830 unlikely(__memcg_kmem_charge_page(page, gfp_mask, order) != 0)) {
4831 __free_pages(page, order);
4832 page = NULL;
4835 trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
4837 return page;
4839 EXPORT_SYMBOL(__alloc_pages_nodemask);
4842 * Common helper functions. Never use with __GFP_HIGHMEM because the returned
4843 * address cannot represent highmem pages. Use alloc_pages and then kmap if
4844 * you need to access high mem.
4846 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
4848 struct page *page;
4850 page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order);
4851 if (!page)
4852 return 0;
4853 return (unsigned long) page_address(page);
4855 EXPORT_SYMBOL(__get_free_pages);
4857 unsigned long get_zeroed_page(gfp_t gfp_mask)
4859 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
4861 EXPORT_SYMBOL(get_zeroed_page);
4863 static inline void free_the_page(struct page *page, unsigned int order)
4865 if (order == 0) /* Via pcp? */
4866 free_unref_page(page);
4867 else
4868 __free_pages_ok(page, order);
4871 void __free_pages(struct page *page, unsigned int order)
4873 if (put_page_testzero(page))
4874 free_the_page(page, order);
4876 EXPORT_SYMBOL(__free_pages);
4878 void free_pages(unsigned long addr, unsigned int order)
4880 if (addr != 0) {
4881 VM_BUG_ON(!virt_addr_valid((void *)addr));
4882 __free_pages(virt_to_page((void *)addr), order);
4886 EXPORT_SYMBOL(free_pages);
4889 * Page Fragment:
4890 * An arbitrary-length arbitrary-offset area of memory which resides
4891 * within a 0 or higher order page. Multiple fragments within that page
4892 * are individually refcounted, in the page's reference counter.
4894 * The page_frag functions below provide a simple allocation framework for
4895 * page fragments. This is used by the network stack and network device
4896 * drivers to provide a backing region of memory for use as either an
4897 * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
4899 static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
4900 gfp_t gfp_mask)
4902 struct page *page = NULL;
4903 gfp_t gfp = gfp_mask;
4905 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4906 gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
4907 __GFP_NOMEMALLOC;
4908 page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
4909 PAGE_FRAG_CACHE_MAX_ORDER);
4910 nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
4911 #endif
4912 if (unlikely(!page))
4913 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
4915 nc->va = page ? page_address(page) : NULL;
4917 return page;
4920 void __page_frag_cache_drain(struct page *page, unsigned int count)
4922 VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
4924 if (page_ref_sub_and_test(page, count))
4925 free_the_page(page, compound_order(page));
4927 EXPORT_SYMBOL(__page_frag_cache_drain);
4929 void *page_frag_alloc(struct page_frag_cache *nc,
4930 unsigned int fragsz, gfp_t gfp_mask)
4932 unsigned int size = PAGE_SIZE;
4933 struct page *page;
4934 int offset;
4936 if (unlikely(!nc->va)) {
4937 refill:
4938 page = __page_frag_cache_refill(nc, gfp_mask);
4939 if (!page)
4940 return NULL;
4942 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4943 /* if size can vary use size else just use PAGE_SIZE */
4944 size = nc->size;
4945 #endif
4946 /* Even if we own the page, we do not use atomic_set().
4947 * This would break get_page_unless_zero() users.
4949 page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
4951 /* reset page count bias and offset to start of new frag */
4952 nc->pfmemalloc = page_is_pfmemalloc(page);
4953 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
4954 nc->offset = size;
4957 offset = nc->offset - fragsz;
4958 if (unlikely(offset < 0)) {
4959 page = virt_to_page(nc->va);
4961 if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
4962 goto refill;
4964 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4965 /* if size can vary use size else just use PAGE_SIZE */
4966 size = nc->size;
4967 #endif
4968 /* OK, page count is 0, we can safely set it */
4969 set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
4971 /* reset page count bias and offset to start of new frag */
4972 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
4973 offset = size - fragsz;
4976 nc->pagecnt_bias--;
4977 nc->offset = offset;
4979 return nc->va + offset;
4981 EXPORT_SYMBOL(page_frag_alloc);
4984 * Frees a page fragment allocated out of either a compound or order 0 page.
4986 void page_frag_free(void *addr)
4988 struct page *page = virt_to_head_page(addr);
4990 if (unlikely(put_page_testzero(page)))
4991 free_the_page(page, compound_order(page));
4993 EXPORT_SYMBOL(page_frag_free);
4995 static void *make_alloc_exact(unsigned long addr, unsigned int order,
4996 size_t size)
4998 if (addr) {
4999 unsigned long alloc_end = addr + (PAGE_SIZE << order);
5000 unsigned long used = addr + PAGE_ALIGN(size);
5002 split_page(virt_to_page((void *)addr), order);
5003 while (used < alloc_end) {
5004 free_page(used);
5005 used += PAGE_SIZE;
5008 return (void *)addr;
5012 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
5013 * @size: the number of bytes to allocate
5014 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5016 * This function is similar to alloc_pages(), except that it allocates the
5017 * minimum number of pages to satisfy the request. alloc_pages() can only
5018 * allocate memory in power-of-two pages.
5020 * This function is also limited by MAX_ORDER.
5022 * Memory allocated by this function must be released by free_pages_exact().
5024 * Return: pointer to the allocated area or %NULL in case of error.
5026 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
5028 unsigned int order = get_order(size);
5029 unsigned long addr;
5031 if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
5032 gfp_mask &= ~__GFP_COMP;
5034 addr = __get_free_pages(gfp_mask, order);
5035 return make_alloc_exact(addr, order, size);
5037 EXPORT_SYMBOL(alloc_pages_exact);
5040 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
5041 * pages on a node.
5042 * @nid: the preferred node ID where memory should be allocated
5043 * @size: the number of bytes to allocate
5044 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5046 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
5047 * back.
5049 * Return: pointer to the allocated area or %NULL in case of error.
5051 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
5053 unsigned int order = get_order(size);
5054 struct page *p;
5056 if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
5057 gfp_mask &= ~__GFP_COMP;
5059 p = alloc_pages_node(nid, gfp_mask, order);
5060 if (!p)
5061 return NULL;
5062 return make_alloc_exact((unsigned long)page_address(p), order, size);
5066 * free_pages_exact - release memory allocated via alloc_pages_exact()
5067 * @virt: the value returned by alloc_pages_exact.
5068 * @size: size of allocation, same value as passed to alloc_pages_exact().
5070 * Release the memory allocated by a previous call to alloc_pages_exact.
5072 void free_pages_exact(void *virt, size_t size)
5074 unsigned long addr = (unsigned long)virt;
5075 unsigned long end = addr + PAGE_ALIGN(size);
5077 while (addr < end) {
5078 free_page(addr);
5079 addr += PAGE_SIZE;
5082 EXPORT_SYMBOL(free_pages_exact);
5085 * nr_free_zone_pages - count number of pages beyond high watermark
5086 * @offset: The zone index of the highest zone
5088 * nr_free_zone_pages() counts the number of pages which are beyond the
5089 * high watermark within all zones at or below a given zone index. For each
5090 * zone, the number of pages is calculated as:
5092 * nr_free_zone_pages = managed_pages - high_pages
5094 * Return: number of pages beyond high watermark.
5096 static unsigned long nr_free_zone_pages(int offset)
5098 struct zoneref *z;
5099 struct zone *zone;
5101 /* Just pick one node, since fallback list is circular */
5102 unsigned long sum = 0;
5104 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
5106 for_each_zone_zonelist(zone, z, zonelist, offset) {
5107 unsigned long size = zone_managed_pages(zone);
5108 unsigned long high = high_wmark_pages(zone);
5109 if (size > high)
5110 sum += size - high;
5113 return sum;
5117 * nr_free_buffer_pages - count number of pages beyond high watermark
5119 * nr_free_buffer_pages() counts the number of pages which are beyond the high
5120 * watermark within ZONE_DMA and ZONE_NORMAL.
5122 * Return: number of pages beyond high watermark within ZONE_DMA and
5123 * ZONE_NORMAL.
5125 unsigned long nr_free_buffer_pages(void)
5127 return nr_free_zone_pages(gfp_zone(GFP_USER));
5129 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
5132 * nr_free_pagecache_pages - count number of pages beyond high watermark
5134 * nr_free_pagecache_pages() counts the number of pages which are beyond the
5135 * high watermark within all zones.
5137 * Return: number of pages beyond high watermark within all zones.
5139 unsigned long nr_free_pagecache_pages(void)
5141 return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
5144 static inline void show_node(struct zone *zone)
5146 if (IS_ENABLED(CONFIG_NUMA))
5147 printk("Node %d ", zone_to_nid(zone));
5150 long si_mem_available(void)
5152 long available;
5153 unsigned long pagecache;
5154 unsigned long wmark_low = 0;
5155 unsigned long pages[NR_LRU_LISTS];
5156 unsigned long reclaimable;
5157 struct zone *zone;
5158 int lru;
5160 for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
5161 pages[lru] = global_node_page_state(NR_LRU_BASE + lru);
5163 for_each_zone(zone)
5164 wmark_low += low_wmark_pages(zone);
5167 * Estimate the amount of memory available for userspace allocations,
5168 * without causing swapping.
5170 available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages;
5173 * Not all the page cache can be freed, otherwise the system will
5174 * start swapping. Assume at least half of the page cache, or the
5175 * low watermark worth of cache, needs to stay.
5177 pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
5178 pagecache -= min(pagecache / 2, wmark_low);
5179 available += pagecache;
5182 * Part of the reclaimable slab and other kernel memory consists of
5183 * items that are in use, and cannot be freed. Cap this estimate at the
5184 * low watermark.
5186 reclaimable = global_node_page_state(NR_SLAB_RECLAIMABLE) +
5187 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE);
5188 available += reclaimable - min(reclaimable / 2, wmark_low);
5190 if (available < 0)
5191 available = 0;
5192 return available;
5194 EXPORT_SYMBOL_GPL(si_mem_available);
5196 void si_meminfo(struct sysinfo *val)
5198 val->totalram = totalram_pages();
5199 val->sharedram = global_node_page_state(NR_SHMEM);
5200 val->freeram = global_zone_page_state(NR_FREE_PAGES);
5201 val->bufferram = nr_blockdev_pages();
5202 val->totalhigh = totalhigh_pages();
5203 val->freehigh = nr_free_highpages();
5204 val->mem_unit = PAGE_SIZE;
5207 EXPORT_SYMBOL(si_meminfo);
5209 #ifdef CONFIG_NUMA
5210 void si_meminfo_node(struct sysinfo *val, int nid)
5212 int zone_type; /* needs to be signed */
5213 unsigned long managed_pages = 0;
5214 unsigned long managed_highpages = 0;
5215 unsigned long free_highpages = 0;
5216 pg_data_t *pgdat = NODE_DATA(nid);
5218 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
5219 managed_pages += zone_managed_pages(&pgdat->node_zones[zone_type]);
5220 val->totalram = managed_pages;
5221 val->sharedram = node_page_state(pgdat, NR_SHMEM);
5222 val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES);
5223 #ifdef CONFIG_HIGHMEM
5224 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
5225 struct zone *zone = &pgdat->node_zones[zone_type];
5227 if (is_highmem(zone)) {
5228 managed_highpages += zone_managed_pages(zone);
5229 free_highpages += zone_page_state(zone, NR_FREE_PAGES);
5232 val->totalhigh = managed_highpages;
5233 val->freehigh = free_highpages;
5234 #else
5235 val->totalhigh = managed_highpages;
5236 val->freehigh = free_highpages;
5237 #endif
5238 val->mem_unit = PAGE_SIZE;
5240 #endif
5243 * Determine whether the node should be displayed or not, depending on whether
5244 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
5246 static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask)
5248 if (!(flags & SHOW_MEM_FILTER_NODES))
5249 return false;
5252 * no node mask - aka implicit memory numa policy. Do not bother with
5253 * the synchronization - read_mems_allowed_begin - because we do not
5254 * have to be precise here.
5256 if (!nodemask)
5257 nodemask = &cpuset_current_mems_allowed;
5259 return !node_isset(nid, *nodemask);
5262 #define K(x) ((x) << (PAGE_SHIFT-10))
5264 static void show_migration_types(unsigned char type)
5266 static const char types[MIGRATE_TYPES] = {
5267 [MIGRATE_UNMOVABLE] = 'U',
5268 [MIGRATE_MOVABLE] = 'M',
5269 [MIGRATE_RECLAIMABLE] = 'E',
5270 [MIGRATE_HIGHATOMIC] = 'H',
5271 #ifdef CONFIG_CMA
5272 [MIGRATE_CMA] = 'C',
5273 #endif
5274 #ifdef CONFIG_MEMORY_ISOLATION
5275 [MIGRATE_ISOLATE] = 'I',
5276 #endif
5278 char tmp[MIGRATE_TYPES + 1];
5279 char *p = tmp;
5280 int i;
5282 for (i = 0; i < MIGRATE_TYPES; i++) {
5283 if (type & (1 << i))
5284 *p++ = types[i];
5287 *p = '\0';
5288 printk(KERN_CONT "(%s) ", tmp);
5292 * Show free area list (used inside shift_scroll-lock stuff)
5293 * We also calculate the percentage fragmentation. We do this by counting the
5294 * memory on each free list with the exception of the first item on the list.
5296 * Bits in @filter:
5297 * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
5298 * cpuset.
5300 void show_free_areas(unsigned int filter, nodemask_t *nodemask)
5302 unsigned long free_pcp = 0;
5303 int cpu;
5304 struct zone *zone;
5305 pg_data_t *pgdat;
5307 for_each_populated_zone(zone) {
5308 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5309 continue;
5311 for_each_online_cpu(cpu)
5312 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5315 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
5316 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
5317 " unevictable:%lu dirty:%lu writeback:%lu unstable:%lu\n"
5318 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
5319 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
5320 " free:%lu free_pcp:%lu free_cma:%lu\n",
5321 global_node_page_state(NR_ACTIVE_ANON),
5322 global_node_page_state(NR_INACTIVE_ANON),
5323 global_node_page_state(NR_ISOLATED_ANON),
5324 global_node_page_state(NR_ACTIVE_FILE),
5325 global_node_page_state(NR_INACTIVE_FILE),
5326 global_node_page_state(NR_ISOLATED_FILE),
5327 global_node_page_state(NR_UNEVICTABLE),
5328 global_node_page_state(NR_FILE_DIRTY),
5329 global_node_page_state(NR_WRITEBACK),
5330 global_node_page_state(NR_UNSTABLE_NFS),
5331 global_node_page_state(NR_SLAB_RECLAIMABLE),
5332 global_node_page_state(NR_SLAB_UNRECLAIMABLE),
5333 global_node_page_state(NR_FILE_MAPPED),
5334 global_node_page_state(NR_SHMEM),
5335 global_zone_page_state(NR_PAGETABLE),
5336 global_zone_page_state(NR_BOUNCE),
5337 global_zone_page_state(NR_FREE_PAGES),
5338 free_pcp,
5339 global_zone_page_state(NR_FREE_CMA_PAGES));
5341 for_each_online_pgdat(pgdat) {
5342 if (show_mem_node_skip(filter, pgdat->node_id, nodemask))
5343 continue;
5345 printk("Node %d"
5346 " active_anon:%lukB"
5347 " inactive_anon:%lukB"
5348 " active_file:%lukB"
5349 " inactive_file:%lukB"
5350 " unevictable:%lukB"
5351 " isolated(anon):%lukB"
5352 " isolated(file):%lukB"
5353 " mapped:%lukB"
5354 " dirty:%lukB"
5355 " writeback:%lukB"
5356 " shmem:%lukB"
5357 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5358 " shmem_thp: %lukB"
5359 " shmem_pmdmapped: %lukB"
5360 " anon_thp: %lukB"
5361 #endif
5362 " writeback_tmp:%lukB"
5363 " unstable:%lukB"
5364 " all_unreclaimable? %s"
5365 "\n",
5366 pgdat->node_id,
5367 K(node_page_state(pgdat, NR_ACTIVE_ANON)),
5368 K(node_page_state(pgdat, NR_INACTIVE_ANON)),
5369 K(node_page_state(pgdat, NR_ACTIVE_FILE)),
5370 K(node_page_state(pgdat, NR_INACTIVE_FILE)),
5371 K(node_page_state(pgdat, NR_UNEVICTABLE)),
5372 K(node_page_state(pgdat, NR_ISOLATED_ANON)),
5373 K(node_page_state(pgdat, NR_ISOLATED_FILE)),
5374 K(node_page_state(pgdat, NR_FILE_MAPPED)),
5375 K(node_page_state(pgdat, NR_FILE_DIRTY)),
5376 K(node_page_state(pgdat, NR_WRITEBACK)),
5377 K(node_page_state(pgdat, NR_SHMEM)),
5378 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5379 K(node_page_state(pgdat, NR_SHMEM_THPS) * HPAGE_PMD_NR),
5380 K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED)
5381 * HPAGE_PMD_NR),
5382 K(node_page_state(pgdat, NR_ANON_THPS) * HPAGE_PMD_NR),
5383 #endif
5384 K(node_page_state(pgdat, NR_WRITEBACK_TEMP)),
5385 K(node_page_state(pgdat, NR_UNSTABLE_NFS)),
5386 pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ?
5387 "yes" : "no");
5390 for_each_populated_zone(zone) {
5391 int i;
5393 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5394 continue;
5396 free_pcp = 0;
5397 for_each_online_cpu(cpu)
5398 free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5400 show_node(zone);
5401 printk(KERN_CONT
5402 "%s"
5403 " free:%lukB"
5404 " min:%lukB"
5405 " low:%lukB"
5406 " high:%lukB"
5407 " reserved_highatomic:%luKB"
5408 " active_anon:%lukB"
5409 " inactive_anon:%lukB"
5410 " active_file:%lukB"
5411 " inactive_file:%lukB"
5412 " unevictable:%lukB"
5413 " writepending:%lukB"
5414 " present:%lukB"
5415 " managed:%lukB"
5416 " mlocked:%lukB"
5417 " kernel_stack:%lukB"
5418 " pagetables:%lukB"
5419 " bounce:%lukB"
5420 " free_pcp:%lukB"
5421 " local_pcp:%ukB"
5422 " free_cma:%lukB"
5423 "\n",
5424 zone->name,
5425 K(zone_page_state(zone, NR_FREE_PAGES)),
5426 K(min_wmark_pages(zone)),
5427 K(low_wmark_pages(zone)),
5428 K(high_wmark_pages(zone)),
5429 K(zone->nr_reserved_highatomic),
5430 K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)),
5431 K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)),
5432 K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)),
5433 K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)),
5434 K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)),
5435 K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)),
5436 K(zone->present_pages),
5437 K(zone_managed_pages(zone)),
5438 K(zone_page_state(zone, NR_MLOCK)),
5439 zone_page_state(zone, NR_KERNEL_STACK_KB),
5440 K(zone_page_state(zone, NR_PAGETABLE)),
5441 K(zone_page_state(zone, NR_BOUNCE)),
5442 K(free_pcp),
5443 K(this_cpu_read(zone->pageset->pcp.count)),
5444 K(zone_page_state(zone, NR_FREE_CMA_PAGES)));
5445 printk("lowmem_reserve[]:");
5446 for (i = 0; i < MAX_NR_ZONES; i++)
5447 printk(KERN_CONT " %ld", zone->lowmem_reserve[i]);
5448 printk(KERN_CONT "\n");
5451 for_each_populated_zone(zone) {
5452 unsigned int order;
5453 unsigned long nr[MAX_ORDER], flags, total = 0;
5454 unsigned char types[MAX_ORDER];
5456 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5457 continue;
5458 show_node(zone);
5459 printk(KERN_CONT "%s: ", zone->name);
5461 spin_lock_irqsave(&zone->lock, flags);
5462 for (order = 0; order < MAX_ORDER; order++) {
5463 struct free_area *area = &zone->free_area[order];
5464 int type;
5466 nr[order] = area->nr_free;
5467 total += nr[order] << order;
5469 types[order] = 0;
5470 for (type = 0; type < MIGRATE_TYPES; type++) {
5471 if (!free_area_empty(area, type))
5472 types[order] |= 1 << type;
5475 spin_unlock_irqrestore(&zone->lock, flags);
5476 for (order = 0; order < MAX_ORDER; order++) {
5477 printk(KERN_CONT "%lu*%lukB ",
5478 nr[order], K(1UL) << order);
5479 if (nr[order])
5480 show_migration_types(types[order]);
5482 printk(KERN_CONT "= %lukB\n", K(total));
5485 hugetlb_show_meminfo();
5487 printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES));
5489 show_swap_cache_info();
5492 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
5494 zoneref->zone = zone;
5495 zoneref->zone_idx = zone_idx(zone);
5499 * Builds allocation fallback zone lists.
5501 * Add all populated zones of a node to the zonelist.
5503 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
5505 struct zone *zone;
5506 enum zone_type zone_type = MAX_NR_ZONES;
5507 int nr_zones = 0;
5509 do {
5510 zone_type--;
5511 zone = pgdat->node_zones + zone_type;
5512 if (managed_zone(zone)) {
5513 zoneref_set_zone(zone, &zonerefs[nr_zones++]);
5514 check_highest_zone(zone_type);
5516 } while (zone_type);
5518 return nr_zones;
5521 #ifdef CONFIG_NUMA
5523 static int __parse_numa_zonelist_order(char *s)
5526 * We used to support different zonlists modes but they turned
5527 * out to be just not useful. Let's keep the warning in place
5528 * if somebody still use the cmd line parameter so that we do
5529 * not fail it silently
5531 if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
5532 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s);
5533 return -EINVAL;
5535 return 0;
5538 static __init int setup_numa_zonelist_order(char *s)
5540 if (!s)
5541 return 0;
5543 return __parse_numa_zonelist_order(s);
5545 early_param("numa_zonelist_order", setup_numa_zonelist_order);
5547 char numa_zonelist_order[] = "Node";
5550 * sysctl handler for numa_zonelist_order
5552 int numa_zonelist_order_handler(struct ctl_table *table, int write,
5553 void __user *buffer, size_t *length,
5554 loff_t *ppos)
5556 char *str;
5557 int ret;
5559 if (!write)
5560 return proc_dostring(table, write, buffer, length, ppos);
5561 str = memdup_user_nul(buffer, 16);
5562 if (IS_ERR(str))
5563 return PTR_ERR(str);
5565 ret = __parse_numa_zonelist_order(str);
5566 kfree(str);
5567 return ret;
5571 #define MAX_NODE_LOAD (nr_online_nodes)
5572 static int node_load[MAX_NUMNODES];
5575 * find_next_best_node - find the next node that should appear in a given node's fallback list
5576 * @node: node whose fallback list we're appending
5577 * @used_node_mask: nodemask_t of already used nodes
5579 * We use a number of factors to determine which is the next node that should
5580 * appear on a given node's fallback list. The node should not have appeared
5581 * already in @node's fallback list, and it should be the next closest node
5582 * according to the distance array (which contains arbitrary distance values
5583 * from each node to each node in the system), and should also prefer nodes
5584 * with no CPUs, since presumably they'll have very little allocation pressure
5585 * on them otherwise.
5587 * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
5589 static int find_next_best_node(int node, nodemask_t *used_node_mask)
5591 int n, val;
5592 int min_val = INT_MAX;
5593 int best_node = NUMA_NO_NODE;
5594 const struct cpumask *tmp = cpumask_of_node(0);
5596 /* Use the local node if we haven't already */
5597 if (!node_isset(node, *used_node_mask)) {
5598 node_set(node, *used_node_mask);
5599 return node;
5602 for_each_node_state(n, N_MEMORY) {
5604 /* Don't want a node to appear more than once */
5605 if (node_isset(n, *used_node_mask))
5606 continue;
5608 /* Use the distance array to find the distance */
5609 val = node_distance(node, n);
5611 /* Penalize nodes under us ("prefer the next node") */
5612 val += (n < node);
5614 /* Give preference to headless and unused nodes */
5615 tmp = cpumask_of_node(n);
5616 if (!cpumask_empty(tmp))
5617 val += PENALTY_FOR_NODE_WITH_CPUS;
5619 /* Slight preference for less loaded node */
5620 val *= (MAX_NODE_LOAD*MAX_NUMNODES);
5621 val += node_load[n];
5623 if (val < min_val) {
5624 min_val = val;
5625 best_node = n;
5629 if (best_node >= 0)
5630 node_set(best_node, *used_node_mask);
5632 return best_node;
5637 * Build zonelists ordered by node and zones within node.
5638 * This results in maximum locality--normal zone overflows into local
5639 * DMA zone, if any--but risks exhausting DMA zone.
5641 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
5642 unsigned nr_nodes)
5644 struct zoneref *zonerefs;
5645 int i;
5647 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5649 for (i = 0; i < nr_nodes; i++) {
5650 int nr_zones;
5652 pg_data_t *node = NODE_DATA(node_order[i]);
5654 nr_zones = build_zonerefs_node(node, zonerefs);
5655 zonerefs += nr_zones;
5657 zonerefs->zone = NULL;
5658 zonerefs->zone_idx = 0;
5662 * Build gfp_thisnode zonelists
5664 static void build_thisnode_zonelists(pg_data_t *pgdat)
5666 struct zoneref *zonerefs;
5667 int nr_zones;
5669 zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
5670 nr_zones = build_zonerefs_node(pgdat, zonerefs);
5671 zonerefs += nr_zones;
5672 zonerefs->zone = NULL;
5673 zonerefs->zone_idx = 0;
5677 * Build zonelists ordered by zone and nodes within zones.
5678 * This results in conserving DMA zone[s] until all Normal memory is
5679 * exhausted, but results in overflowing to remote node while memory
5680 * may still exist in local DMA zone.
5683 static void build_zonelists(pg_data_t *pgdat)
5685 static int node_order[MAX_NUMNODES];
5686 int node, load, nr_nodes = 0;
5687 nodemask_t used_mask;
5688 int local_node, prev_node;
5690 /* NUMA-aware ordering of nodes */
5691 local_node = pgdat->node_id;
5692 load = nr_online_nodes;
5693 prev_node = local_node;
5694 nodes_clear(used_mask);
5696 memset(node_order, 0, sizeof(node_order));
5697 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
5699 * We don't want to pressure a particular node.
5700 * So adding penalty to the first node in same
5701 * distance group to make it round-robin.
5703 if (node_distance(local_node, node) !=
5704 node_distance(local_node, prev_node))
5705 node_load[node] = load;
5707 node_order[nr_nodes++] = node;
5708 prev_node = node;
5709 load--;
5712 build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
5713 build_thisnode_zonelists(pgdat);
5716 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5718 * Return node id of node used for "local" allocations.
5719 * I.e., first node id of first zone in arg node's generic zonelist.
5720 * Used for initializing percpu 'numa_mem', which is used primarily
5721 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
5723 int local_memory_node(int node)
5725 struct zoneref *z;
5727 z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
5728 gfp_zone(GFP_KERNEL),
5729 NULL);
5730 return zone_to_nid(z->zone);
5732 #endif
5734 static void setup_min_unmapped_ratio(void);
5735 static void setup_min_slab_ratio(void);
5736 #else /* CONFIG_NUMA */
5738 static void build_zonelists(pg_data_t *pgdat)
5740 int node, local_node;
5741 struct zoneref *zonerefs;
5742 int nr_zones;
5744 local_node = pgdat->node_id;
5746 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5747 nr_zones = build_zonerefs_node(pgdat, zonerefs);
5748 zonerefs += nr_zones;
5751 * Now we build the zonelist so that it contains the zones
5752 * of all the other nodes.
5753 * We don't want to pressure a particular node, so when
5754 * building the zones for node N, we make sure that the
5755 * zones coming right after the local ones are those from
5756 * node N+1 (modulo N)
5758 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
5759 if (!node_online(node))
5760 continue;
5761 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
5762 zonerefs += nr_zones;
5764 for (node = 0; node < local_node; node++) {
5765 if (!node_online(node))
5766 continue;
5767 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
5768 zonerefs += nr_zones;
5771 zonerefs->zone = NULL;
5772 zonerefs->zone_idx = 0;
5775 #endif /* CONFIG_NUMA */
5778 * Boot pageset table. One per cpu which is going to be used for all
5779 * zones and all nodes. The parameters will be set in such a way
5780 * that an item put on a list will immediately be handed over to
5781 * the buddy list. This is safe since pageset manipulation is done
5782 * with interrupts disabled.
5784 * The boot_pagesets must be kept even after bootup is complete for
5785 * unused processors and/or zones. They do play a role for bootstrapping
5786 * hotplugged processors.
5788 * zoneinfo_show() and maybe other functions do
5789 * not check if the processor is online before following the pageset pointer.
5790 * Other parts of the kernel may not check if the zone is available.
5792 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
5793 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
5794 static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
5796 static void __build_all_zonelists(void *data)
5798 int nid;
5799 int __maybe_unused cpu;
5800 pg_data_t *self = data;
5801 static DEFINE_SPINLOCK(lock);
5803 spin_lock(&lock);
5805 #ifdef CONFIG_NUMA
5806 memset(node_load, 0, sizeof(node_load));
5807 #endif
5810 * This node is hotadded and no memory is yet present. So just
5811 * building zonelists is fine - no need to touch other nodes.
5813 if (self && !node_online(self->node_id)) {
5814 build_zonelists(self);
5815 } else {
5816 for_each_online_node(nid) {
5817 pg_data_t *pgdat = NODE_DATA(nid);
5819 build_zonelists(pgdat);
5822 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5824 * We now know the "local memory node" for each node--
5825 * i.e., the node of the first zone in the generic zonelist.
5826 * Set up numa_mem percpu variable for on-line cpus. During
5827 * boot, only the boot cpu should be on-line; we'll init the
5828 * secondary cpus' numa_mem as they come on-line. During
5829 * node/memory hotplug, we'll fixup all on-line cpus.
5831 for_each_online_cpu(cpu)
5832 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
5833 #endif
5836 spin_unlock(&lock);
5839 static noinline void __init
5840 build_all_zonelists_init(void)
5842 int cpu;
5844 __build_all_zonelists(NULL);
5847 * Initialize the boot_pagesets that are going to be used
5848 * for bootstrapping processors. The real pagesets for
5849 * each zone will be allocated later when the per cpu
5850 * allocator is available.
5852 * boot_pagesets are used also for bootstrapping offline
5853 * cpus if the system is already booted because the pagesets
5854 * are needed to initialize allocators on a specific cpu too.
5855 * F.e. the percpu allocator needs the page allocator which
5856 * needs the percpu allocator in order to allocate its pagesets
5857 * (a chicken-egg dilemma).
5859 for_each_possible_cpu(cpu)
5860 setup_pageset(&per_cpu(boot_pageset, cpu), 0);
5862 mminit_verify_zonelist();
5863 cpuset_init_current_mems_allowed();
5867 * unless system_state == SYSTEM_BOOTING.
5869 * __ref due to call of __init annotated helper build_all_zonelists_init
5870 * [protected by SYSTEM_BOOTING].
5872 void __ref build_all_zonelists(pg_data_t *pgdat)
5874 if (system_state == SYSTEM_BOOTING) {
5875 build_all_zonelists_init();
5876 } else {
5877 __build_all_zonelists(pgdat);
5878 /* cpuset refresh routine should be here */
5880 vm_total_pages = nr_free_pagecache_pages();
5882 * Disable grouping by mobility if the number of pages in the
5883 * system is too low to allow the mechanism to work. It would be
5884 * more accurate, but expensive to check per-zone. This check is
5885 * made on memory-hotadd so a system can start with mobility
5886 * disabled and enable it later
5888 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
5889 page_group_by_mobility_disabled = 1;
5890 else
5891 page_group_by_mobility_disabled = 0;
5893 pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n",
5894 nr_online_nodes,
5895 page_group_by_mobility_disabled ? "off" : "on",
5896 vm_total_pages);
5897 #ifdef CONFIG_NUMA
5898 pr_info("Policy zone: %s\n", zone_names[policy_zone]);
5899 #endif
5902 /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
5903 static bool __meminit
5904 overlap_memmap_init(unsigned long zone, unsigned long *pfn)
5906 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5907 static struct memblock_region *r;
5909 if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
5910 if (!r || *pfn >= memblock_region_memory_end_pfn(r)) {
5911 for_each_memblock(memory, r) {
5912 if (*pfn < memblock_region_memory_end_pfn(r))
5913 break;
5916 if (*pfn >= memblock_region_memory_base_pfn(r) &&
5917 memblock_is_mirror(r)) {
5918 *pfn = memblock_region_memory_end_pfn(r);
5919 return true;
5922 #endif
5923 return false;
5926 #ifdef CONFIG_SPARSEMEM
5927 /* Skip PFNs that belong to non-present sections */
5928 static inline __meminit unsigned long next_pfn(unsigned long pfn)
5930 const unsigned long section_nr = pfn_to_section_nr(++pfn);
5932 if (present_section_nr(section_nr))
5933 return pfn;
5934 return section_nr_to_pfn(next_present_section_nr(section_nr));
5936 #else
5937 static inline __meminit unsigned long next_pfn(unsigned long pfn)
5939 return pfn++;
5941 #endif
5944 * Initially all pages are reserved - free ones are freed
5945 * up by memblock_free_all() once the early boot process is
5946 * done. Non-atomic initialization, single-pass.
5948 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
5949 unsigned long start_pfn, enum memmap_context context,
5950 struct vmem_altmap *altmap)
5952 unsigned long pfn, end_pfn = start_pfn + size;
5953 struct page *page;
5955 if (highest_memmap_pfn < end_pfn - 1)
5956 highest_memmap_pfn = end_pfn - 1;
5958 #ifdef CONFIG_ZONE_DEVICE
5960 * Honor reservation requested by the driver for this ZONE_DEVICE
5961 * memory. We limit the total number of pages to initialize to just
5962 * those that might contain the memory mapping. We will defer the
5963 * ZONE_DEVICE page initialization until after we have released
5964 * the hotplug lock.
5966 if (zone == ZONE_DEVICE) {
5967 if (!altmap)
5968 return;
5970 if (start_pfn == altmap->base_pfn)
5971 start_pfn += altmap->reserve;
5972 end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
5974 #endif
5976 for (pfn = start_pfn; pfn < end_pfn; ) {
5978 * There can be holes in boot-time mem_map[]s handed to this
5979 * function. They do not exist on hotplugged memory.
5981 if (context == MEMMAP_EARLY) {
5982 if (!early_pfn_valid(pfn)) {
5983 pfn = next_pfn(pfn);
5984 continue;
5986 if (!early_pfn_in_nid(pfn, nid)) {
5987 pfn++;
5988 continue;
5990 if (overlap_memmap_init(zone, &pfn))
5991 continue;
5992 if (defer_init(nid, pfn, end_pfn))
5993 break;
5996 page = pfn_to_page(pfn);
5997 __init_single_page(page, pfn, zone, nid);
5998 if (context == MEMMAP_HOTPLUG)
5999 __SetPageReserved(page);
6002 * Mark the block movable so that blocks are reserved for
6003 * movable at startup. This will force kernel allocations
6004 * to reserve their blocks rather than leaking throughout
6005 * the address space during boot when many long-lived
6006 * kernel allocations are made.
6008 * bitmap is created for zone's valid pfn range. but memmap
6009 * can be created for invalid pages (for alignment)
6010 * check here not to call set_pageblock_migratetype() against
6011 * pfn out of zone.
6013 if (!(pfn & (pageblock_nr_pages - 1))) {
6014 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
6015 cond_resched();
6017 pfn++;
6021 #ifdef CONFIG_ZONE_DEVICE
6022 void __ref memmap_init_zone_device(struct zone *zone,
6023 unsigned long start_pfn,
6024 unsigned long nr_pages,
6025 struct dev_pagemap *pgmap)
6027 unsigned long pfn, end_pfn = start_pfn + nr_pages;
6028 struct pglist_data *pgdat = zone->zone_pgdat;
6029 struct vmem_altmap *altmap = pgmap_altmap(pgmap);
6030 unsigned long zone_idx = zone_idx(zone);
6031 unsigned long start = jiffies;
6032 int nid = pgdat->node_id;
6034 if (WARN_ON_ONCE(!pgmap || zone_idx(zone) != ZONE_DEVICE))
6035 return;
6038 * The call to memmap_init_zone should have already taken care
6039 * of the pages reserved for the memmap, so we can just jump to
6040 * the end of that region and start processing the device pages.
6042 if (altmap) {
6043 start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
6044 nr_pages = end_pfn - start_pfn;
6047 for (pfn = start_pfn; pfn < end_pfn; pfn++) {
6048 struct page *page = pfn_to_page(pfn);
6050 __init_single_page(page, pfn, zone_idx, nid);
6053 * Mark page reserved as it will need to wait for onlining
6054 * phase for it to be fully associated with a zone.
6056 * We can use the non-atomic __set_bit operation for setting
6057 * the flag as we are still initializing the pages.
6059 __SetPageReserved(page);
6062 * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer
6063 * and zone_device_data. It is a bug if a ZONE_DEVICE page is
6064 * ever freed or placed on a driver-private list.
6066 page->pgmap = pgmap;
6067 page->zone_device_data = NULL;
6070 * Mark the block movable so that blocks are reserved for
6071 * movable at startup. This will force kernel allocations
6072 * to reserve their blocks rather than leaking throughout
6073 * the address space during boot when many long-lived
6074 * kernel allocations are made.
6076 * bitmap is created for zone's valid pfn range. but memmap
6077 * can be created for invalid pages (for alignment)
6078 * check here not to call set_pageblock_migratetype() against
6079 * pfn out of zone.
6081 * Please note that MEMMAP_HOTPLUG path doesn't clear memmap
6082 * because this is done early in section_activate()
6084 if (!(pfn & (pageblock_nr_pages - 1))) {
6085 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
6086 cond_resched();
6090 pr_info("%s initialised %lu pages in %ums\n", __func__,
6091 nr_pages, jiffies_to_msecs(jiffies - start));
6094 #endif
6095 static void __meminit zone_init_free_lists(struct zone *zone)
6097 unsigned int order, t;
6098 for_each_migratetype_order(order, t) {
6099 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
6100 zone->free_area[order].nr_free = 0;
6104 void __meminit __weak memmap_init(unsigned long size, int nid,
6105 unsigned long zone, unsigned long start_pfn)
6107 memmap_init_zone(size, nid, zone, start_pfn, MEMMAP_EARLY, NULL);
6110 static int zone_batchsize(struct zone *zone)
6112 #ifdef CONFIG_MMU
6113 int batch;
6116 * The per-cpu-pages pools are set to around 1000th of the
6117 * size of the zone.
6119 batch = zone_managed_pages(zone) / 1024;
6120 /* But no more than a meg. */
6121 if (batch * PAGE_SIZE > 1024 * 1024)
6122 batch = (1024 * 1024) / PAGE_SIZE;
6123 batch /= 4; /* We effectively *= 4 below */
6124 if (batch < 1)
6125 batch = 1;
6128 * Clamp the batch to a 2^n - 1 value. Having a power
6129 * of 2 value was found to be more likely to have
6130 * suboptimal cache aliasing properties in some cases.
6132 * For example if 2 tasks are alternately allocating
6133 * batches of pages, one task can end up with a lot
6134 * of pages of one half of the possible page colors
6135 * and the other with pages of the other colors.
6137 batch = rounddown_pow_of_two(batch + batch/2) - 1;
6139 return batch;
6141 #else
6142 /* The deferral and batching of frees should be suppressed under NOMMU
6143 * conditions.
6145 * The problem is that NOMMU needs to be able to allocate large chunks
6146 * of contiguous memory as there's no hardware page translation to
6147 * assemble apparent contiguous memory from discontiguous pages.
6149 * Queueing large contiguous runs of pages for batching, however,
6150 * causes the pages to actually be freed in smaller chunks. As there
6151 * can be a significant delay between the individual batches being
6152 * recycled, this leads to the once large chunks of space being
6153 * fragmented and becoming unavailable for high-order allocations.
6155 return 0;
6156 #endif
6160 * pcp->high and pcp->batch values are related and dependent on one another:
6161 * ->batch must never be higher then ->high.
6162 * The following function updates them in a safe manner without read side
6163 * locking.
6165 * Any new users of pcp->batch and pcp->high should ensure they can cope with
6166 * those fields changing asynchronously (acording the the above rule).
6168 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
6169 * outside of boot time (or some other assurance that no concurrent updaters
6170 * exist).
6172 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
6173 unsigned long batch)
6175 /* start with a fail safe value for batch */
6176 pcp->batch = 1;
6177 smp_wmb();
6179 /* Update high, then batch, in order */
6180 pcp->high = high;
6181 smp_wmb();
6183 pcp->batch = batch;
6186 /* a companion to pageset_set_high() */
6187 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
6189 pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
6192 static void pageset_init(struct per_cpu_pageset *p)
6194 struct per_cpu_pages *pcp;
6195 int migratetype;
6197 memset(p, 0, sizeof(*p));
6199 pcp = &p->pcp;
6200 for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
6201 INIT_LIST_HEAD(&pcp->lists[migratetype]);
6204 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
6206 pageset_init(p);
6207 pageset_set_batch(p, batch);
6211 * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
6212 * to the value high for the pageset p.
6214 static void pageset_set_high(struct per_cpu_pageset *p,
6215 unsigned long high)
6217 unsigned long batch = max(1UL, high / 4);
6218 if ((high / 4) > (PAGE_SHIFT * 8))
6219 batch = PAGE_SHIFT * 8;
6221 pageset_update(&p->pcp, high, batch);
6224 static void pageset_set_high_and_batch(struct zone *zone,
6225 struct per_cpu_pageset *pcp)
6227 if (percpu_pagelist_fraction)
6228 pageset_set_high(pcp,
6229 (zone_managed_pages(zone) /
6230 percpu_pagelist_fraction));
6231 else
6232 pageset_set_batch(pcp, zone_batchsize(zone));
6235 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
6237 struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
6239 pageset_init(pcp);
6240 pageset_set_high_and_batch(zone, pcp);
6243 void __meminit setup_zone_pageset(struct zone *zone)
6245 int cpu;
6246 zone->pageset = alloc_percpu(struct per_cpu_pageset);
6247 for_each_possible_cpu(cpu)
6248 zone_pageset_init(zone, cpu);
6252 * Allocate per cpu pagesets and initialize them.
6253 * Before this call only boot pagesets were available.
6255 void __init setup_per_cpu_pageset(void)
6257 struct pglist_data *pgdat;
6258 struct zone *zone;
6260 for_each_populated_zone(zone)
6261 setup_zone_pageset(zone);
6263 for_each_online_pgdat(pgdat)
6264 pgdat->per_cpu_nodestats =
6265 alloc_percpu(struct per_cpu_nodestat);
6268 static __meminit void zone_pcp_init(struct zone *zone)
6271 * per cpu subsystem is not up at this point. The following code
6272 * relies on the ability of the linker to provide the
6273 * offset of a (static) per cpu variable into the per cpu area.
6275 zone->pageset = &boot_pageset;
6277 if (populated_zone(zone))
6278 printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n",
6279 zone->name, zone->present_pages,
6280 zone_batchsize(zone));
6283 void __meminit init_currently_empty_zone(struct zone *zone,
6284 unsigned long zone_start_pfn,
6285 unsigned long size)
6287 struct pglist_data *pgdat = zone->zone_pgdat;
6288 int zone_idx = zone_idx(zone) + 1;
6290 if (zone_idx > pgdat->nr_zones)
6291 pgdat->nr_zones = zone_idx;
6293 zone->zone_start_pfn = zone_start_pfn;
6295 mminit_dprintk(MMINIT_TRACE, "memmap_init",
6296 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
6297 pgdat->node_id,
6298 (unsigned long)zone_idx(zone),
6299 zone_start_pfn, (zone_start_pfn + size));
6301 zone_init_free_lists(zone);
6302 zone->initialized = 1;
6305 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6306 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
6309 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
6311 int __meminit __early_pfn_to_nid(unsigned long pfn,
6312 struct mminit_pfnnid_cache *state)
6314 unsigned long start_pfn, end_pfn;
6315 int nid;
6317 if (state->last_start <= pfn && pfn < state->last_end)
6318 return state->last_nid;
6320 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
6321 if (nid != NUMA_NO_NODE) {
6322 state->last_start = start_pfn;
6323 state->last_end = end_pfn;
6324 state->last_nid = nid;
6327 return nid;
6329 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
6332 * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
6333 * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
6334 * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
6336 * If an architecture guarantees that all ranges registered contain no holes
6337 * and may be freed, this this function may be used instead of calling
6338 * memblock_free_early_nid() manually.
6340 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
6342 unsigned long start_pfn, end_pfn;
6343 int i, this_nid;
6345 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
6346 start_pfn = min(start_pfn, max_low_pfn);
6347 end_pfn = min(end_pfn, max_low_pfn);
6349 if (start_pfn < end_pfn)
6350 memblock_free_early_nid(PFN_PHYS(start_pfn),
6351 (end_pfn - start_pfn) << PAGE_SHIFT,
6352 this_nid);
6357 * sparse_memory_present_with_active_regions - Call memory_present for each active range
6358 * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
6360 * If an architecture guarantees that all ranges registered contain no holes and may
6361 * be freed, this function may be used instead of calling memory_present() manually.
6363 void __init sparse_memory_present_with_active_regions(int nid)
6365 unsigned long start_pfn, end_pfn;
6366 int i, this_nid;
6368 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
6369 memory_present(this_nid, start_pfn, end_pfn);
6373 * get_pfn_range_for_nid - Return the start and end page frames for a node
6374 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
6375 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
6376 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
6378 * It returns the start and end page frame of a node based on information
6379 * provided by memblock_set_node(). If called for a node
6380 * with no available memory, a warning is printed and the start and end
6381 * PFNs will be 0.
6383 void __init get_pfn_range_for_nid(unsigned int nid,
6384 unsigned long *start_pfn, unsigned long *end_pfn)
6386 unsigned long this_start_pfn, this_end_pfn;
6387 int i;
6389 *start_pfn = -1UL;
6390 *end_pfn = 0;
6392 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
6393 *start_pfn = min(*start_pfn, this_start_pfn);
6394 *end_pfn = max(*end_pfn, this_end_pfn);
6397 if (*start_pfn == -1UL)
6398 *start_pfn = 0;
6402 * This finds a zone that can be used for ZONE_MOVABLE pages. The
6403 * assumption is made that zones within a node are ordered in monotonic
6404 * increasing memory addresses so that the "highest" populated zone is used
6406 static void __init find_usable_zone_for_movable(void)
6408 int zone_index;
6409 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
6410 if (zone_index == ZONE_MOVABLE)
6411 continue;
6413 if (arch_zone_highest_possible_pfn[zone_index] >
6414 arch_zone_lowest_possible_pfn[zone_index])
6415 break;
6418 VM_BUG_ON(zone_index == -1);
6419 movable_zone = zone_index;
6423 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
6424 * because it is sized independent of architecture. Unlike the other zones,
6425 * the starting point for ZONE_MOVABLE is not fixed. It may be different
6426 * in each node depending on the size of each node and how evenly kernelcore
6427 * is distributed. This helper function adjusts the zone ranges
6428 * provided by the architecture for a given node by using the end of the
6429 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
6430 * zones within a node are in order of monotonic increases memory addresses
6432 static void __init adjust_zone_range_for_zone_movable(int nid,
6433 unsigned long zone_type,
6434 unsigned long node_start_pfn,
6435 unsigned long node_end_pfn,
6436 unsigned long *zone_start_pfn,
6437 unsigned long *zone_end_pfn)
6439 /* Only adjust if ZONE_MOVABLE is on this node */
6440 if (zone_movable_pfn[nid]) {
6441 /* Size ZONE_MOVABLE */
6442 if (zone_type == ZONE_MOVABLE) {
6443 *zone_start_pfn = zone_movable_pfn[nid];
6444 *zone_end_pfn = min(node_end_pfn,
6445 arch_zone_highest_possible_pfn[movable_zone]);
6447 /* Adjust for ZONE_MOVABLE starting within this range */
6448 } else if (!mirrored_kernelcore &&
6449 *zone_start_pfn < zone_movable_pfn[nid] &&
6450 *zone_end_pfn > zone_movable_pfn[nid]) {
6451 *zone_end_pfn = zone_movable_pfn[nid];
6453 /* Check if this whole range is within ZONE_MOVABLE */
6454 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
6455 *zone_start_pfn = *zone_end_pfn;
6460 * Return the number of pages a zone spans in a node, including holes
6461 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
6463 static unsigned long __init zone_spanned_pages_in_node(int nid,
6464 unsigned long zone_type,
6465 unsigned long node_start_pfn,
6466 unsigned long node_end_pfn,
6467 unsigned long *zone_start_pfn,
6468 unsigned long *zone_end_pfn,
6469 unsigned long *ignored)
6471 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
6472 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
6473 /* When hotadd a new node from cpu_up(), the node should be empty */
6474 if (!node_start_pfn && !node_end_pfn)
6475 return 0;
6477 /* Get the start and end of the zone */
6478 *zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
6479 *zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
6480 adjust_zone_range_for_zone_movable(nid, zone_type,
6481 node_start_pfn, node_end_pfn,
6482 zone_start_pfn, zone_end_pfn);
6484 /* Check that this node has pages within the zone's required range */
6485 if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
6486 return 0;
6488 /* Move the zone boundaries inside the node if necessary */
6489 *zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
6490 *zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
6492 /* Return the spanned pages */
6493 return *zone_end_pfn - *zone_start_pfn;
6497 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
6498 * then all holes in the requested range will be accounted for.
6500 unsigned long __init __absent_pages_in_range(int nid,
6501 unsigned long range_start_pfn,
6502 unsigned long range_end_pfn)
6504 unsigned long nr_absent = range_end_pfn - range_start_pfn;
6505 unsigned long start_pfn, end_pfn;
6506 int i;
6508 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
6509 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
6510 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
6511 nr_absent -= end_pfn - start_pfn;
6513 return nr_absent;
6517 * absent_pages_in_range - Return number of page frames in holes within a range
6518 * @start_pfn: The start PFN to start searching for holes
6519 * @end_pfn: The end PFN to stop searching for holes
6521 * Return: the number of pages frames in memory holes within a range.
6523 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
6524 unsigned long end_pfn)
6526 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
6529 /* Return the number of page frames in holes in a zone on a node */
6530 static unsigned long __init zone_absent_pages_in_node(int nid,
6531 unsigned long zone_type,
6532 unsigned long node_start_pfn,
6533 unsigned long node_end_pfn,
6534 unsigned long *ignored)
6536 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
6537 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
6538 unsigned long zone_start_pfn, zone_end_pfn;
6539 unsigned long nr_absent;
6541 /* When hotadd a new node from cpu_up(), the node should be empty */
6542 if (!node_start_pfn && !node_end_pfn)
6543 return 0;
6545 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
6546 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
6548 adjust_zone_range_for_zone_movable(nid, zone_type,
6549 node_start_pfn, node_end_pfn,
6550 &zone_start_pfn, &zone_end_pfn);
6551 nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
6554 * ZONE_MOVABLE handling.
6555 * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
6556 * and vice versa.
6558 if (mirrored_kernelcore && zone_movable_pfn[nid]) {
6559 unsigned long start_pfn, end_pfn;
6560 struct memblock_region *r;
6562 for_each_memblock(memory, r) {
6563 start_pfn = clamp(memblock_region_memory_base_pfn(r),
6564 zone_start_pfn, zone_end_pfn);
6565 end_pfn = clamp(memblock_region_memory_end_pfn(r),
6566 zone_start_pfn, zone_end_pfn);
6568 if (zone_type == ZONE_MOVABLE &&
6569 memblock_is_mirror(r))
6570 nr_absent += end_pfn - start_pfn;
6572 if (zone_type == ZONE_NORMAL &&
6573 !memblock_is_mirror(r))
6574 nr_absent += end_pfn - start_pfn;
6578 return nr_absent;
6581 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6582 static inline unsigned long __init zone_spanned_pages_in_node(int nid,
6583 unsigned long zone_type,
6584 unsigned long node_start_pfn,
6585 unsigned long node_end_pfn,
6586 unsigned long *zone_start_pfn,
6587 unsigned long *zone_end_pfn,
6588 unsigned long *zones_size)
6590 unsigned int zone;
6592 *zone_start_pfn = node_start_pfn;
6593 for (zone = 0; zone < zone_type; zone++)
6594 *zone_start_pfn += zones_size[zone];
6596 *zone_end_pfn = *zone_start_pfn + zones_size[zone_type];
6598 return zones_size[zone_type];
6601 static inline unsigned long __init zone_absent_pages_in_node(int nid,
6602 unsigned long zone_type,
6603 unsigned long node_start_pfn,
6604 unsigned long node_end_pfn,
6605 unsigned long *zholes_size)
6607 if (!zholes_size)
6608 return 0;
6610 return zholes_size[zone_type];
6613 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6615 static void __init calculate_node_totalpages(struct pglist_data *pgdat,
6616 unsigned long node_start_pfn,
6617 unsigned long node_end_pfn,
6618 unsigned long *zones_size,
6619 unsigned long *zholes_size)
6621 unsigned long realtotalpages = 0, totalpages = 0;
6622 enum zone_type i;
6624 for (i = 0; i < MAX_NR_ZONES; i++) {
6625 struct zone *zone = pgdat->node_zones + i;
6626 unsigned long zone_start_pfn, zone_end_pfn;
6627 unsigned long size, real_size;
6629 size = zone_spanned_pages_in_node(pgdat->node_id, i,
6630 node_start_pfn,
6631 node_end_pfn,
6632 &zone_start_pfn,
6633 &zone_end_pfn,
6634 zones_size);
6635 real_size = size - zone_absent_pages_in_node(pgdat->node_id, i,
6636 node_start_pfn, node_end_pfn,
6637 zholes_size);
6638 if (size)
6639 zone->zone_start_pfn = zone_start_pfn;
6640 else
6641 zone->zone_start_pfn = 0;
6642 zone->spanned_pages = size;
6643 zone->present_pages = real_size;
6645 totalpages += size;
6646 realtotalpages += real_size;
6649 pgdat->node_spanned_pages = totalpages;
6650 pgdat->node_present_pages = realtotalpages;
6651 printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
6652 realtotalpages);
6655 #ifndef CONFIG_SPARSEMEM
6657 * Calculate the size of the zone->blockflags rounded to an unsigned long
6658 * Start by making sure zonesize is a multiple of pageblock_order by rounding
6659 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
6660 * round what is now in bits to nearest long in bits, then return it in
6661 * bytes.
6663 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
6665 unsigned long usemapsize;
6667 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
6668 usemapsize = roundup(zonesize, pageblock_nr_pages);
6669 usemapsize = usemapsize >> pageblock_order;
6670 usemapsize *= NR_PAGEBLOCK_BITS;
6671 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
6673 return usemapsize / 8;
6676 static void __ref setup_usemap(struct pglist_data *pgdat,
6677 struct zone *zone,
6678 unsigned long zone_start_pfn,
6679 unsigned long zonesize)
6681 unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
6682 zone->pageblock_flags = NULL;
6683 if (usemapsize) {
6684 zone->pageblock_flags =
6685 memblock_alloc_node(usemapsize, SMP_CACHE_BYTES,
6686 pgdat->node_id);
6687 if (!zone->pageblock_flags)
6688 panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n",
6689 usemapsize, zone->name, pgdat->node_id);
6692 #else
6693 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
6694 unsigned long zone_start_pfn, unsigned long zonesize) {}
6695 #endif /* CONFIG_SPARSEMEM */
6697 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
6699 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
6700 void __init set_pageblock_order(void)
6702 unsigned int order;
6704 /* Check that pageblock_nr_pages has not already been setup */
6705 if (pageblock_order)
6706 return;
6708 if (HPAGE_SHIFT > PAGE_SHIFT)
6709 order = HUGETLB_PAGE_ORDER;
6710 else
6711 order = MAX_ORDER - 1;
6714 * Assume the largest contiguous order of interest is a huge page.
6715 * This value may be variable depending on boot parameters on IA64 and
6716 * powerpc.
6718 pageblock_order = order;
6720 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6723 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
6724 * is unused as pageblock_order is set at compile-time. See
6725 * include/linux/pageblock-flags.h for the values of pageblock_order based on
6726 * the kernel config
6728 void __init set_pageblock_order(void)
6732 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6734 static unsigned long __init calc_memmap_size(unsigned long spanned_pages,
6735 unsigned long present_pages)
6737 unsigned long pages = spanned_pages;
6740 * Provide a more accurate estimation if there are holes within
6741 * the zone and SPARSEMEM is in use. If there are holes within the
6742 * zone, each populated memory region may cost us one or two extra
6743 * memmap pages due to alignment because memmap pages for each
6744 * populated regions may not be naturally aligned on page boundary.
6745 * So the (present_pages >> 4) heuristic is a tradeoff for that.
6747 if (spanned_pages > present_pages + (present_pages >> 4) &&
6748 IS_ENABLED(CONFIG_SPARSEMEM))
6749 pages = present_pages;
6751 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
6754 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
6755 static void pgdat_init_split_queue(struct pglist_data *pgdat)
6757 struct deferred_split *ds_queue = &pgdat->deferred_split_queue;
6759 spin_lock_init(&ds_queue->split_queue_lock);
6760 INIT_LIST_HEAD(&ds_queue->split_queue);
6761 ds_queue->split_queue_len = 0;
6763 #else
6764 static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
6765 #endif
6767 #ifdef CONFIG_COMPACTION
6768 static void pgdat_init_kcompactd(struct pglist_data *pgdat)
6770 init_waitqueue_head(&pgdat->kcompactd_wait);
6772 #else
6773 static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
6774 #endif
6776 static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
6778 pgdat_resize_init(pgdat);
6780 pgdat_init_split_queue(pgdat);
6781 pgdat_init_kcompactd(pgdat);
6783 init_waitqueue_head(&pgdat->kswapd_wait);
6784 init_waitqueue_head(&pgdat->pfmemalloc_wait);
6786 pgdat_page_ext_init(pgdat);
6787 spin_lock_init(&pgdat->lru_lock);
6788 lruvec_init(&pgdat->__lruvec);
6791 static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
6792 unsigned long remaining_pages)
6794 atomic_long_set(&zone->managed_pages, remaining_pages);
6795 zone_set_nid(zone, nid);
6796 zone->name = zone_names[idx];
6797 zone->zone_pgdat = NODE_DATA(nid);
6798 spin_lock_init(&zone->lock);
6799 zone_seqlock_init(zone);
6800 zone_pcp_init(zone);
6804 * Set up the zone data structures
6805 * - init pgdat internals
6806 * - init all zones belonging to this node
6808 * NOTE: this function is only called during memory hotplug
6810 #ifdef CONFIG_MEMORY_HOTPLUG
6811 void __ref free_area_init_core_hotplug(int nid)
6813 enum zone_type z;
6814 pg_data_t *pgdat = NODE_DATA(nid);
6816 pgdat_init_internals(pgdat);
6817 for (z = 0; z < MAX_NR_ZONES; z++)
6818 zone_init_internals(&pgdat->node_zones[z], z, nid, 0);
6820 #endif
6823 * Set up the zone data structures:
6824 * - mark all pages reserved
6825 * - mark all memory queues empty
6826 * - clear the memory bitmaps
6828 * NOTE: pgdat should get zeroed by caller.
6829 * NOTE: this function is only called during early init.
6831 static void __init free_area_init_core(struct pglist_data *pgdat)
6833 enum zone_type j;
6834 int nid = pgdat->node_id;
6836 pgdat_init_internals(pgdat);
6837 pgdat->per_cpu_nodestats = &boot_nodestats;
6839 for (j = 0; j < MAX_NR_ZONES; j++) {
6840 struct zone *zone = pgdat->node_zones + j;
6841 unsigned long size, freesize, memmap_pages;
6842 unsigned long zone_start_pfn = zone->zone_start_pfn;
6844 size = zone->spanned_pages;
6845 freesize = zone->present_pages;
6848 * Adjust freesize so that it accounts for how much memory
6849 * is used by this zone for memmap. This affects the watermark
6850 * and per-cpu initialisations
6852 memmap_pages = calc_memmap_size(size, freesize);
6853 if (!is_highmem_idx(j)) {
6854 if (freesize >= memmap_pages) {
6855 freesize -= memmap_pages;
6856 if (memmap_pages)
6857 printk(KERN_DEBUG
6858 " %s zone: %lu pages used for memmap\n",
6859 zone_names[j], memmap_pages);
6860 } else
6861 pr_warn(" %s zone: %lu pages exceeds freesize %lu\n",
6862 zone_names[j], memmap_pages, freesize);
6865 /* Account for reserved pages */
6866 if (j == 0 && freesize > dma_reserve) {
6867 freesize -= dma_reserve;
6868 printk(KERN_DEBUG " %s zone: %lu pages reserved\n",
6869 zone_names[0], dma_reserve);
6872 if (!is_highmem_idx(j))
6873 nr_kernel_pages += freesize;
6874 /* Charge for highmem memmap if there are enough kernel pages */
6875 else if (nr_kernel_pages > memmap_pages * 2)
6876 nr_kernel_pages -= memmap_pages;
6877 nr_all_pages += freesize;
6880 * Set an approximate value for lowmem here, it will be adjusted
6881 * when the bootmem allocator frees pages into the buddy system.
6882 * And all highmem pages will be managed by the buddy system.
6884 zone_init_internals(zone, j, nid, freesize);
6886 if (!size)
6887 continue;
6889 set_pageblock_order();
6890 setup_usemap(pgdat, zone, zone_start_pfn, size);
6891 init_currently_empty_zone(zone, zone_start_pfn, size);
6892 memmap_init(size, nid, j, zone_start_pfn);
6896 #ifdef CONFIG_FLAT_NODE_MEM_MAP
6897 static void __ref alloc_node_mem_map(struct pglist_data *pgdat)
6899 unsigned long __maybe_unused start = 0;
6900 unsigned long __maybe_unused offset = 0;
6902 /* Skip empty nodes */
6903 if (!pgdat->node_spanned_pages)
6904 return;
6906 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
6907 offset = pgdat->node_start_pfn - start;
6908 /* ia64 gets its own node_mem_map, before this, without bootmem */
6909 if (!pgdat->node_mem_map) {
6910 unsigned long size, end;
6911 struct page *map;
6914 * The zone's endpoints aren't required to be MAX_ORDER
6915 * aligned but the node_mem_map endpoints must be in order
6916 * for the buddy allocator to function correctly.
6918 end = pgdat_end_pfn(pgdat);
6919 end = ALIGN(end, MAX_ORDER_NR_PAGES);
6920 size = (end - start) * sizeof(struct page);
6921 map = memblock_alloc_node(size, SMP_CACHE_BYTES,
6922 pgdat->node_id);
6923 if (!map)
6924 panic("Failed to allocate %ld bytes for node %d memory map\n",
6925 size, pgdat->node_id);
6926 pgdat->node_mem_map = map + offset;
6928 pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
6929 __func__, pgdat->node_id, (unsigned long)pgdat,
6930 (unsigned long)pgdat->node_mem_map);
6931 #ifndef CONFIG_NEED_MULTIPLE_NODES
6933 * With no DISCONTIG, the global mem_map is just set as node 0's
6935 if (pgdat == NODE_DATA(0)) {
6936 mem_map = NODE_DATA(0)->node_mem_map;
6937 #if defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) || defined(CONFIG_FLATMEM)
6938 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
6939 mem_map -= offset;
6940 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6942 #endif
6944 #else
6945 static void __ref alloc_node_mem_map(struct pglist_data *pgdat) { }
6946 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
6948 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
6949 static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
6951 pgdat->first_deferred_pfn = ULONG_MAX;
6953 #else
6954 static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
6955 #endif
6957 void __init free_area_init_node(int nid, unsigned long *zones_size,
6958 unsigned long node_start_pfn,
6959 unsigned long *zholes_size)
6961 pg_data_t *pgdat = NODE_DATA(nid);
6962 unsigned long start_pfn = 0;
6963 unsigned long end_pfn = 0;
6965 /* pg_data_t should be reset to zero when it's allocated */
6966 WARN_ON(pgdat->nr_zones || pgdat->kswapd_classzone_idx);
6968 pgdat->node_id = nid;
6969 pgdat->node_start_pfn = node_start_pfn;
6970 pgdat->per_cpu_nodestats = NULL;
6971 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6972 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
6973 pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
6974 (u64)start_pfn << PAGE_SHIFT,
6975 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
6976 #else
6977 start_pfn = node_start_pfn;
6978 #endif
6979 calculate_node_totalpages(pgdat, start_pfn, end_pfn,
6980 zones_size, zholes_size);
6982 alloc_node_mem_map(pgdat);
6983 pgdat_set_deferred_range(pgdat);
6985 free_area_init_core(pgdat);
6988 #if !defined(CONFIG_FLAT_NODE_MEM_MAP)
6990 * Initialize all valid struct pages in the range [spfn, epfn) and mark them
6991 * PageReserved(). Return the number of struct pages that were initialized.
6993 static u64 __init init_unavailable_range(unsigned long spfn, unsigned long epfn)
6995 unsigned long pfn;
6996 u64 pgcnt = 0;
6998 for (pfn = spfn; pfn < epfn; pfn++) {
6999 if (!pfn_valid(ALIGN_DOWN(pfn, pageblock_nr_pages))) {
7000 pfn = ALIGN_DOWN(pfn, pageblock_nr_pages)
7001 + pageblock_nr_pages - 1;
7002 continue;
7005 * Use a fake node/zone (0) for now. Some of these pages
7006 * (in memblock.reserved but not in memblock.memory) will
7007 * get re-initialized via reserve_bootmem_region() later.
7009 __init_single_page(pfn_to_page(pfn), pfn, 0, 0);
7010 __SetPageReserved(pfn_to_page(pfn));
7011 pgcnt++;
7014 return pgcnt;
7018 * Only struct pages that are backed by physical memory are zeroed and
7019 * initialized by going through __init_single_page(). But, there are some
7020 * struct pages which are reserved in memblock allocator and their fields
7021 * may be accessed (for example page_to_pfn() on some configuration accesses
7022 * flags). We must explicitly initialize those struct pages.
7024 * This function also addresses a similar issue where struct pages are left
7025 * uninitialized because the physical address range is not covered by
7026 * memblock.memory or memblock.reserved. That could happen when memblock
7027 * layout is manually configured via memmap=, or when the highest physical
7028 * address (max_pfn) does not end on a section boundary.
7030 static void __init init_unavailable_mem(void)
7032 phys_addr_t start, end;
7033 u64 i, pgcnt;
7034 phys_addr_t next = 0;
7037 * Loop through unavailable ranges not covered by memblock.memory.
7039 pgcnt = 0;
7040 for_each_mem_range(i, &memblock.memory, NULL,
7041 NUMA_NO_NODE, MEMBLOCK_NONE, &start, &end, NULL) {
7042 if (next < start)
7043 pgcnt += init_unavailable_range(PFN_DOWN(next),
7044 PFN_UP(start));
7045 next = end;
7049 * Early sections always have a fully populated memmap for the whole
7050 * section - see pfn_valid(). If the last section has holes at the
7051 * end and that section is marked "online", the memmap will be
7052 * considered initialized. Make sure that memmap has a well defined
7053 * state.
7055 pgcnt += init_unavailable_range(PFN_DOWN(next),
7056 round_up(max_pfn, PAGES_PER_SECTION));
7059 * Struct pages that do not have backing memory. This could be because
7060 * firmware is using some of this memory, or for some other reasons.
7062 if (pgcnt)
7063 pr_info("Zeroed struct page in unavailable ranges: %lld pages", pgcnt);
7065 #else
7066 static inline void __init init_unavailable_mem(void)
7069 #endif /* !CONFIG_FLAT_NODE_MEM_MAP */
7071 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
7073 #if MAX_NUMNODES > 1
7075 * Figure out the number of possible node ids.
7077 void __init setup_nr_node_ids(void)
7079 unsigned int highest;
7081 highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
7082 nr_node_ids = highest + 1;
7084 #endif
7087 * node_map_pfn_alignment - determine the maximum internode alignment
7089 * This function should be called after node map is populated and sorted.
7090 * It calculates the maximum power of two alignment which can distinguish
7091 * all the nodes.
7093 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
7094 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
7095 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
7096 * shifted, 1GiB is enough and this function will indicate so.
7098 * This is used to test whether pfn -> nid mapping of the chosen memory
7099 * model has fine enough granularity to avoid incorrect mapping for the
7100 * populated node map.
7102 * Return: the determined alignment in pfn's. 0 if there is no alignment
7103 * requirement (single node).
7105 unsigned long __init node_map_pfn_alignment(void)
7107 unsigned long accl_mask = 0, last_end = 0;
7108 unsigned long start, end, mask;
7109 int last_nid = NUMA_NO_NODE;
7110 int i, nid;
7112 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
7113 if (!start || last_nid < 0 || last_nid == nid) {
7114 last_nid = nid;
7115 last_end = end;
7116 continue;
7120 * Start with a mask granular enough to pin-point to the
7121 * start pfn and tick off bits one-by-one until it becomes
7122 * too coarse to separate the current node from the last.
7124 mask = ~((1 << __ffs(start)) - 1);
7125 while (mask && last_end <= (start & (mask << 1)))
7126 mask <<= 1;
7128 /* accumulate all internode masks */
7129 accl_mask |= mask;
7132 /* convert mask to number of pages */
7133 return ~accl_mask + 1;
7136 /* Find the lowest pfn for a node */
7137 static unsigned long __init find_min_pfn_for_node(int nid)
7139 unsigned long min_pfn = ULONG_MAX;
7140 unsigned long start_pfn;
7141 int i;
7143 for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
7144 min_pfn = min(min_pfn, start_pfn);
7146 if (min_pfn == ULONG_MAX) {
7147 pr_warn("Could not find start_pfn for node %d\n", nid);
7148 return 0;
7151 return min_pfn;
7155 * find_min_pfn_with_active_regions - Find the minimum PFN registered
7157 * Return: the minimum PFN based on information provided via
7158 * memblock_set_node().
7160 unsigned long __init find_min_pfn_with_active_regions(void)
7162 return find_min_pfn_for_node(MAX_NUMNODES);
7166 * early_calculate_totalpages()
7167 * Sum pages in active regions for movable zone.
7168 * Populate N_MEMORY for calculating usable_nodes.
7170 static unsigned long __init early_calculate_totalpages(void)
7172 unsigned long totalpages = 0;
7173 unsigned long start_pfn, end_pfn;
7174 int i, nid;
7176 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7177 unsigned long pages = end_pfn - start_pfn;
7179 totalpages += pages;
7180 if (pages)
7181 node_set_state(nid, N_MEMORY);
7183 return totalpages;
7187 * Find the PFN the Movable zone begins in each node. Kernel memory
7188 * is spread evenly between nodes as long as the nodes have enough
7189 * memory. When they don't, some nodes will have more kernelcore than
7190 * others
7192 static void __init find_zone_movable_pfns_for_nodes(void)
7194 int i, nid;
7195 unsigned long usable_startpfn;
7196 unsigned long kernelcore_node, kernelcore_remaining;
7197 /* save the state before borrow the nodemask */
7198 nodemask_t saved_node_state = node_states[N_MEMORY];
7199 unsigned long totalpages = early_calculate_totalpages();
7200 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
7201 struct memblock_region *r;
7203 /* Need to find movable_zone earlier when movable_node is specified. */
7204 find_usable_zone_for_movable();
7207 * If movable_node is specified, ignore kernelcore and movablecore
7208 * options.
7210 if (movable_node_is_enabled()) {
7211 for_each_memblock(memory, r) {
7212 if (!memblock_is_hotpluggable(r))
7213 continue;
7215 nid = r->nid;
7217 usable_startpfn = PFN_DOWN(r->base);
7218 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7219 min(usable_startpfn, zone_movable_pfn[nid]) :
7220 usable_startpfn;
7223 goto out2;
7227 * If kernelcore=mirror is specified, ignore movablecore option
7229 if (mirrored_kernelcore) {
7230 bool mem_below_4gb_not_mirrored = false;
7232 for_each_memblock(memory, r) {
7233 if (memblock_is_mirror(r))
7234 continue;
7236 nid = r->nid;
7238 usable_startpfn = memblock_region_memory_base_pfn(r);
7240 if (usable_startpfn < 0x100000) {
7241 mem_below_4gb_not_mirrored = true;
7242 continue;
7245 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7246 min(usable_startpfn, zone_movable_pfn[nid]) :
7247 usable_startpfn;
7250 if (mem_below_4gb_not_mirrored)
7251 pr_warn("This configuration results in unmirrored kernel memory.");
7253 goto out2;
7257 * If kernelcore=nn% or movablecore=nn% was specified, calculate the
7258 * amount of necessary memory.
7260 if (required_kernelcore_percent)
7261 required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
7262 10000UL;
7263 if (required_movablecore_percent)
7264 required_movablecore = (totalpages * 100 * required_movablecore_percent) /
7265 10000UL;
7268 * If movablecore= was specified, calculate what size of
7269 * kernelcore that corresponds so that memory usable for
7270 * any allocation type is evenly spread. If both kernelcore
7271 * and movablecore are specified, then the value of kernelcore
7272 * will be used for required_kernelcore if it's greater than
7273 * what movablecore would have allowed.
7275 if (required_movablecore) {
7276 unsigned long corepages;
7279 * Round-up so that ZONE_MOVABLE is at least as large as what
7280 * was requested by the user
7282 required_movablecore =
7283 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
7284 required_movablecore = min(totalpages, required_movablecore);
7285 corepages = totalpages - required_movablecore;
7287 required_kernelcore = max(required_kernelcore, corepages);
7291 * If kernelcore was not specified or kernelcore size is larger
7292 * than totalpages, there is no ZONE_MOVABLE.
7294 if (!required_kernelcore || required_kernelcore >= totalpages)
7295 goto out;
7297 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
7298 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
7300 restart:
7301 /* Spread kernelcore memory as evenly as possible throughout nodes */
7302 kernelcore_node = required_kernelcore / usable_nodes;
7303 for_each_node_state(nid, N_MEMORY) {
7304 unsigned long start_pfn, end_pfn;
7307 * Recalculate kernelcore_node if the division per node
7308 * now exceeds what is necessary to satisfy the requested
7309 * amount of memory for the kernel
7311 if (required_kernelcore < kernelcore_node)
7312 kernelcore_node = required_kernelcore / usable_nodes;
7315 * As the map is walked, we track how much memory is usable
7316 * by the kernel using kernelcore_remaining. When it is
7317 * 0, the rest of the node is usable by ZONE_MOVABLE
7319 kernelcore_remaining = kernelcore_node;
7321 /* Go through each range of PFNs within this node */
7322 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
7323 unsigned long size_pages;
7325 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
7326 if (start_pfn >= end_pfn)
7327 continue;
7329 /* Account for what is only usable for kernelcore */
7330 if (start_pfn < usable_startpfn) {
7331 unsigned long kernel_pages;
7332 kernel_pages = min(end_pfn, usable_startpfn)
7333 - start_pfn;
7335 kernelcore_remaining -= min(kernel_pages,
7336 kernelcore_remaining);
7337 required_kernelcore -= min(kernel_pages,
7338 required_kernelcore);
7340 /* Continue if range is now fully accounted */
7341 if (end_pfn <= usable_startpfn) {
7344 * Push zone_movable_pfn to the end so
7345 * that if we have to rebalance
7346 * kernelcore across nodes, we will
7347 * not double account here
7349 zone_movable_pfn[nid] = end_pfn;
7350 continue;
7352 start_pfn = usable_startpfn;
7356 * The usable PFN range for ZONE_MOVABLE is from
7357 * start_pfn->end_pfn. Calculate size_pages as the
7358 * number of pages used as kernelcore
7360 size_pages = end_pfn - start_pfn;
7361 if (size_pages > kernelcore_remaining)
7362 size_pages = kernelcore_remaining;
7363 zone_movable_pfn[nid] = start_pfn + size_pages;
7366 * Some kernelcore has been met, update counts and
7367 * break if the kernelcore for this node has been
7368 * satisfied
7370 required_kernelcore -= min(required_kernelcore,
7371 size_pages);
7372 kernelcore_remaining -= size_pages;
7373 if (!kernelcore_remaining)
7374 break;
7379 * If there is still required_kernelcore, we do another pass with one
7380 * less node in the count. This will push zone_movable_pfn[nid] further
7381 * along on the nodes that still have memory until kernelcore is
7382 * satisfied
7384 usable_nodes--;
7385 if (usable_nodes && required_kernelcore > usable_nodes)
7386 goto restart;
7388 out2:
7389 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
7390 for (nid = 0; nid < MAX_NUMNODES; nid++)
7391 zone_movable_pfn[nid] =
7392 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
7394 out:
7395 /* restore the node_state */
7396 node_states[N_MEMORY] = saved_node_state;
7399 /* Any regular or high memory on that node ? */
7400 static void check_for_memory(pg_data_t *pgdat, int nid)
7402 enum zone_type zone_type;
7404 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
7405 struct zone *zone = &pgdat->node_zones[zone_type];
7406 if (populated_zone(zone)) {
7407 if (IS_ENABLED(CONFIG_HIGHMEM))
7408 node_set_state(nid, N_HIGH_MEMORY);
7409 if (zone_type <= ZONE_NORMAL)
7410 node_set_state(nid, N_NORMAL_MEMORY);
7411 break;
7417 * free_area_init_nodes - Initialise all pg_data_t and zone data
7418 * @max_zone_pfn: an array of max PFNs for each zone
7420 * This will call free_area_init_node() for each active node in the system.
7421 * Using the page ranges provided by memblock_set_node(), the size of each
7422 * zone in each node and their holes is calculated. If the maximum PFN
7423 * between two adjacent zones match, it is assumed that the zone is empty.
7424 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
7425 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
7426 * starts where the previous one ended. For example, ZONE_DMA32 starts
7427 * at arch_max_dma_pfn.
7429 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
7431 unsigned long start_pfn, end_pfn;
7432 int i, nid;
7434 /* Record where the zone boundaries are */
7435 memset(arch_zone_lowest_possible_pfn, 0,
7436 sizeof(arch_zone_lowest_possible_pfn));
7437 memset(arch_zone_highest_possible_pfn, 0,
7438 sizeof(arch_zone_highest_possible_pfn));
7440 start_pfn = find_min_pfn_with_active_regions();
7442 for (i = 0; i < MAX_NR_ZONES; i++) {
7443 if (i == ZONE_MOVABLE)
7444 continue;
7446 end_pfn = max(max_zone_pfn[i], start_pfn);
7447 arch_zone_lowest_possible_pfn[i] = start_pfn;
7448 arch_zone_highest_possible_pfn[i] = end_pfn;
7450 start_pfn = end_pfn;
7453 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
7454 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
7455 find_zone_movable_pfns_for_nodes();
7457 /* Print out the zone ranges */
7458 pr_info("Zone ranges:\n");
7459 for (i = 0; i < MAX_NR_ZONES; i++) {
7460 if (i == ZONE_MOVABLE)
7461 continue;
7462 pr_info(" %-8s ", zone_names[i]);
7463 if (arch_zone_lowest_possible_pfn[i] ==
7464 arch_zone_highest_possible_pfn[i])
7465 pr_cont("empty\n");
7466 else
7467 pr_cont("[mem %#018Lx-%#018Lx]\n",
7468 (u64)arch_zone_lowest_possible_pfn[i]
7469 << PAGE_SHIFT,
7470 ((u64)arch_zone_highest_possible_pfn[i]
7471 << PAGE_SHIFT) - 1);
7474 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
7475 pr_info("Movable zone start for each node\n");
7476 for (i = 0; i < MAX_NUMNODES; i++) {
7477 if (zone_movable_pfn[i])
7478 pr_info(" Node %d: %#018Lx\n", i,
7479 (u64)zone_movable_pfn[i] << PAGE_SHIFT);
7483 * Print out the early node map, and initialize the
7484 * subsection-map relative to active online memory ranges to
7485 * enable future "sub-section" extensions of the memory map.
7487 pr_info("Early memory node ranges\n");
7488 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7489 pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid,
7490 (u64)start_pfn << PAGE_SHIFT,
7491 ((u64)end_pfn << PAGE_SHIFT) - 1);
7492 subsection_map_init(start_pfn, end_pfn - start_pfn);
7495 /* Initialise every node */
7496 mminit_verify_pageflags_layout();
7497 setup_nr_node_ids();
7498 init_unavailable_mem();
7499 for_each_online_node(nid) {
7500 pg_data_t *pgdat = NODE_DATA(nid);
7501 free_area_init_node(nid, NULL,
7502 find_min_pfn_for_node(nid), NULL);
7504 /* Any memory on that node */
7505 if (pgdat->node_present_pages)
7506 node_set_state(nid, N_MEMORY);
7507 check_for_memory(pgdat, nid);
7511 static int __init cmdline_parse_core(char *p, unsigned long *core,
7512 unsigned long *percent)
7514 unsigned long long coremem;
7515 char *endptr;
7517 if (!p)
7518 return -EINVAL;
7520 /* Value may be a percentage of total memory, otherwise bytes */
7521 coremem = simple_strtoull(p, &endptr, 0);
7522 if (*endptr == '%') {
7523 /* Paranoid check for percent values greater than 100 */
7524 WARN_ON(coremem > 100);
7526 *percent = coremem;
7527 } else {
7528 coremem = memparse(p, &p);
7529 /* Paranoid check that UL is enough for the coremem value */
7530 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
7532 *core = coremem >> PAGE_SHIFT;
7533 *percent = 0UL;
7535 return 0;
7539 * kernelcore=size sets the amount of memory for use for allocations that
7540 * cannot be reclaimed or migrated.
7542 static int __init cmdline_parse_kernelcore(char *p)
7544 /* parse kernelcore=mirror */
7545 if (parse_option_str(p, "mirror")) {
7546 mirrored_kernelcore = true;
7547 return 0;
7550 return cmdline_parse_core(p, &required_kernelcore,
7551 &required_kernelcore_percent);
7555 * movablecore=size sets the amount of memory for use for allocations that
7556 * can be reclaimed or migrated.
7558 static int __init cmdline_parse_movablecore(char *p)
7560 return cmdline_parse_core(p, &required_movablecore,
7561 &required_movablecore_percent);
7564 early_param("kernelcore", cmdline_parse_kernelcore);
7565 early_param("movablecore", cmdline_parse_movablecore);
7567 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
7569 void adjust_managed_page_count(struct page *page, long count)
7571 atomic_long_add(count, &page_zone(page)->managed_pages);
7572 totalram_pages_add(count);
7573 #ifdef CONFIG_HIGHMEM
7574 if (PageHighMem(page))
7575 totalhigh_pages_add(count);
7576 #endif
7578 EXPORT_SYMBOL(adjust_managed_page_count);
7580 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
7582 void *pos;
7583 unsigned long pages = 0;
7585 start = (void *)PAGE_ALIGN((unsigned long)start);
7586 end = (void *)((unsigned long)end & PAGE_MASK);
7587 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
7588 struct page *page = virt_to_page(pos);
7589 void *direct_map_addr;
7592 * 'direct_map_addr' might be different from 'pos'
7593 * because some architectures' virt_to_page()
7594 * work with aliases. Getting the direct map
7595 * address ensures that we get a _writeable_
7596 * alias for the memset().
7598 direct_map_addr = page_address(page);
7599 if ((unsigned int)poison <= 0xFF)
7600 memset(direct_map_addr, poison, PAGE_SIZE);
7602 free_reserved_page(page);
7605 if (pages && s)
7606 pr_info("Freeing %s memory: %ldK\n",
7607 s, pages << (PAGE_SHIFT - 10));
7609 return pages;
7612 #ifdef CONFIG_HIGHMEM
7613 void free_highmem_page(struct page *page)
7615 __free_reserved_page(page);
7616 totalram_pages_inc();
7617 atomic_long_inc(&page_zone(page)->managed_pages);
7618 totalhigh_pages_inc();
7620 #endif
7623 void __init mem_init_print_info(const char *str)
7625 unsigned long physpages, codesize, datasize, rosize, bss_size;
7626 unsigned long init_code_size, init_data_size;
7628 physpages = get_num_physpages();
7629 codesize = _etext - _stext;
7630 datasize = _edata - _sdata;
7631 rosize = __end_rodata - __start_rodata;
7632 bss_size = __bss_stop - __bss_start;
7633 init_data_size = __init_end - __init_begin;
7634 init_code_size = _einittext - _sinittext;
7637 * Detect special cases and adjust section sizes accordingly:
7638 * 1) .init.* may be embedded into .data sections
7639 * 2) .init.text.* may be out of [__init_begin, __init_end],
7640 * please refer to arch/tile/kernel/vmlinux.lds.S.
7641 * 3) .rodata.* may be embedded into .text or .data sections.
7643 #define adj_init_size(start, end, size, pos, adj) \
7644 do { \
7645 if (start <= pos && pos < end && size > adj) \
7646 size -= adj; \
7647 } while (0)
7649 adj_init_size(__init_begin, __init_end, init_data_size,
7650 _sinittext, init_code_size);
7651 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
7652 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
7653 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
7654 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
7656 #undef adj_init_size
7658 pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
7659 #ifdef CONFIG_HIGHMEM
7660 ", %luK highmem"
7661 #endif
7662 "%s%s)\n",
7663 nr_free_pages() << (PAGE_SHIFT - 10),
7664 physpages << (PAGE_SHIFT - 10),
7665 codesize >> 10, datasize >> 10, rosize >> 10,
7666 (init_data_size + init_code_size) >> 10, bss_size >> 10,
7667 (physpages - totalram_pages() - totalcma_pages) << (PAGE_SHIFT - 10),
7668 totalcma_pages << (PAGE_SHIFT - 10),
7669 #ifdef CONFIG_HIGHMEM
7670 totalhigh_pages() << (PAGE_SHIFT - 10),
7671 #endif
7672 str ? ", " : "", str ? str : "");
7676 * set_dma_reserve - set the specified number of pages reserved in the first zone
7677 * @new_dma_reserve: The number of pages to mark reserved
7679 * The per-cpu batchsize and zone watermarks are determined by managed_pages.
7680 * In the DMA zone, a significant percentage may be consumed by kernel image
7681 * and other unfreeable allocations which can skew the watermarks badly. This
7682 * function may optionally be used to account for unfreeable pages in the
7683 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
7684 * smaller per-cpu batchsize.
7686 void __init set_dma_reserve(unsigned long new_dma_reserve)
7688 dma_reserve = new_dma_reserve;
7691 void __init free_area_init(unsigned long *zones_size)
7693 init_unavailable_mem();
7694 free_area_init_node(0, zones_size,
7695 __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
7698 static int page_alloc_cpu_dead(unsigned int cpu)
7701 lru_add_drain_cpu(cpu);
7702 drain_pages(cpu);
7705 * Spill the event counters of the dead processor
7706 * into the current processors event counters.
7707 * This artificially elevates the count of the current
7708 * processor.
7710 vm_events_fold_cpu(cpu);
7713 * Zero the differential counters of the dead processor
7714 * so that the vm statistics are consistent.
7716 * This is only okay since the processor is dead and cannot
7717 * race with what we are doing.
7719 cpu_vm_stats_fold(cpu);
7720 return 0;
7723 #ifdef CONFIG_NUMA
7724 int hashdist = HASHDIST_DEFAULT;
7726 static int __init set_hashdist(char *str)
7728 if (!str)
7729 return 0;
7730 hashdist = simple_strtoul(str, &str, 0);
7731 return 1;
7733 __setup("hashdist=", set_hashdist);
7734 #endif
7736 void __init page_alloc_init(void)
7738 int ret;
7740 #ifdef CONFIG_NUMA
7741 if (num_node_state(N_MEMORY) == 1)
7742 hashdist = 0;
7743 #endif
7745 ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC_DEAD,
7746 "mm/page_alloc:dead", NULL,
7747 page_alloc_cpu_dead);
7748 WARN_ON(ret < 0);
7752 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
7753 * or min_free_kbytes changes.
7755 static void calculate_totalreserve_pages(void)
7757 struct pglist_data *pgdat;
7758 unsigned long reserve_pages = 0;
7759 enum zone_type i, j;
7761 for_each_online_pgdat(pgdat) {
7763 pgdat->totalreserve_pages = 0;
7765 for (i = 0; i < MAX_NR_ZONES; i++) {
7766 struct zone *zone = pgdat->node_zones + i;
7767 long max = 0;
7768 unsigned long managed_pages = zone_managed_pages(zone);
7770 /* Find valid and maximum lowmem_reserve in the zone */
7771 for (j = i; j < MAX_NR_ZONES; j++) {
7772 if (zone->lowmem_reserve[j] > max)
7773 max = zone->lowmem_reserve[j];
7776 /* we treat the high watermark as reserved pages. */
7777 max += high_wmark_pages(zone);
7779 if (max > managed_pages)
7780 max = managed_pages;
7782 pgdat->totalreserve_pages += max;
7784 reserve_pages += max;
7787 totalreserve_pages = reserve_pages;
7791 * setup_per_zone_lowmem_reserve - called whenever
7792 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
7793 * has a correct pages reserved value, so an adequate number of
7794 * pages are left in the zone after a successful __alloc_pages().
7796 static void setup_per_zone_lowmem_reserve(void)
7798 struct pglist_data *pgdat;
7799 enum zone_type j, idx;
7801 for_each_online_pgdat(pgdat) {
7802 for (j = 0; j < MAX_NR_ZONES; j++) {
7803 struct zone *zone = pgdat->node_zones + j;
7804 unsigned long managed_pages = zone_managed_pages(zone);
7806 zone->lowmem_reserve[j] = 0;
7808 idx = j;
7809 while (idx) {
7810 struct zone *lower_zone;
7812 idx--;
7813 lower_zone = pgdat->node_zones + idx;
7815 if (sysctl_lowmem_reserve_ratio[idx] < 1) {
7816 sysctl_lowmem_reserve_ratio[idx] = 0;
7817 lower_zone->lowmem_reserve[j] = 0;
7818 } else {
7819 lower_zone->lowmem_reserve[j] =
7820 managed_pages / sysctl_lowmem_reserve_ratio[idx];
7822 managed_pages += zone_managed_pages(lower_zone);
7827 /* update totalreserve_pages */
7828 calculate_totalreserve_pages();
7831 static void __setup_per_zone_wmarks(void)
7833 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
7834 unsigned long lowmem_pages = 0;
7835 struct zone *zone;
7836 unsigned long flags;
7838 /* Calculate total number of !ZONE_HIGHMEM pages */
7839 for_each_zone(zone) {
7840 if (!is_highmem(zone))
7841 lowmem_pages += zone_managed_pages(zone);
7844 for_each_zone(zone) {
7845 u64 tmp;
7847 spin_lock_irqsave(&zone->lock, flags);
7848 tmp = (u64)pages_min * zone_managed_pages(zone);
7849 do_div(tmp, lowmem_pages);
7850 if (is_highmem(zone)) {
7852 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
7853 * need highmem pages, so cap pages_min to a small
7854 * value here.
7856 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
7857 * deltas control async page reclaim, and so should
7858 * not be capped for highmem.
7860 unsigned long min_pages;
7862 min_pages = zone_managed_pages(zone) / 1024;
7863 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
7864 zone->_watermark[WMARK_MIN] = min_pages;
7865 } else {
7867 * If it's a lowmem zone, reserve a number of pages
7868 * proportionate to the zone's size.
7870 zone->_watermark[WMARK_MIN] = tmp;
7874 * Set the kswapd watermarks distance according to the
7875 * scale factor in proportion to available memory, but
7876 * ensure a minimum size on small systems.
7878 tmp = max_t(u64, tmp >> 2,
7879 mult_frac(zone_managed_pages(zone),
7880 watermark_scale_factor, 10000));
7882 zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp;
7883 zone->_watermark[WMARK_HIGH] = min_wmark_pages(zone) + tmp * 2;
7884 zone->watermark_boost = 0;
7886 spin_unlock_irqrestore(&zone->lock, flags);
7889 /* update totalreserve_pages */
7890 calculate_totalreserve_pages();
7894 * setup_per_zone_wmarks - called when min_free_kbytes changes
7895 * or when memory is hot-{added|removed}
7897 * Ensures that the watermark[min,low,high] values for each zone are set
7898 * correctly with respect to min_free_kbytes.
7900 void setup_per_zone_wmarks(void)
7902 static DEFINE_SPINLOCK(lock);
7904 spin_lock(&lock);
7905 __setup_per_zone_wmarks();
7906 spin_unlock(&lock);
7910 * Initialise min_free_kbytes.
7912 * For small machines we want it small (128k min). For large machines
7913 * we want it large (64MB max). But it is not linear, because network
7914 * bandwidth does not increase linearly with machine size. We use
7916 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
7917 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
7919 * which yields
7921 * 16MB: 512k
7922 * 32MB: 724k
7923 * 64MB: 1024k
7924 * 128MB: 1448k
7925 * 256MB: 2048k
7926 * 512MB: 2896k
7927 * 1024MB: 4096k
7928 * 2048MB: 5792k
7929 * 4096MB: 8192k
7930 * 8192MB: 11584k
7931 * 16384MB: 16384k
7933 int __meminit init_per_zone_wmark_min(void)
7935 unsigned long lowmem_kbytes;
7936 int new_min_free_kbytes;
7938 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
7939 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
7941 if (new_min_free_kbytes > user_min_free_kbytes) {
7942 min_free_kbytes = new_min_free_kbytes;
7943 if (min_free_kbytes < 128)
7944 min_free_kbytes = 128;
7945 if (min_free_kbytes > 262144)
7946 min_free_kbytes = 262144;
7947 } else {
7948 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
7949 new_min_free_kbytes, user_min_free_kbytes);
7951 setup_per_zone_wmarks();
7952 refresh_zone_stat_thresholds();
7953 setup_per_zone_lowmem_reserve();
7955 #ifdef CONFIG_NUMA
7956 setup_min_unmapped_ratio();
7957 setup_min_slab_ratio();
7958 #endif
7960 return 0;
7962 core_initcall(init_per_zone_wmark_min)
7965 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
7966 * that we can call two helper functions whenever min_free_kbytes
7967 * changes.
7969 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
7970 void __user *buffer, size_t *length, loff_t *ppos)
7972 int rc;
7974 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7975 if (rc)
7976 return rc;
7978 if (write) {
7979 user_min_free_kbytes = min_free_kbytes;
7980 setup_per_zone_wmarks();
7982 return 0;
7985 int watermark_boost_factor_sysctl_handler(struct ctl_table *table, int write,
7986 void __user *buffer, size_t *length, loff_t *ppos)
7988 int rc;
7990 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7991 if (rc)
7992 return rc;
7994 return 0;
7997 int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write,
7998 void __user *buffer, size_t *length, loff_t *ppos)
8000 int rc;
8002 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8003 if (rc)
8004 return rc;
8006 if (write)
8007 setup_per_zone_wmarks();
8009 return 0;
8012 #ifdef CONFIG_NUMA
8013 static void setup_min_unmapped_ratio(void)
8015 pg_data_t *pgdat;
8016 struct zone *zone;
8018 for_each_online_pgdat(pgdat)
8019 pgdat->min_unmapped_pages = 0;
8021 for_each_zone(zone)
8022 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
8023 sysctl_min_unmapped_ratio) / 100;
8027 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
8028 void __user *buffer, size_t *length, loff_t *ppos)
8030 int rc;
8032 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8033 if (rc)
8034 return rc;
8036 setup_min_unmapped_ratio();
8038 return 0;
8041 static void setup_min_slab_ratio(void)
8043 pg_data_t *pgdat;
8044 struct zone *zone;
8046 for_each_online_pgdat(pgdat)
8047 pgdat->min_slab_pages = 0;
8049 for_each_zone(zone)
8050 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
8051 sysctl_min_slab_ratio) / 100;
8054 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
8055 void __user *buffer, size_t *length, loff_t *ppos)
8057 int rc;
8059 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8060 if (rc)
8061 return rc;
8063 setup_min_slab_ratio();
8065 return 0;
8067 #endif
8070 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
8071 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
8072 * whenever sysctl_lowmem_reserve_ratio changes.
8074 * The reserve ratio obviously has absolutely no relation with the
8075 * minimum watermarks. The lowmem reserve ratio can only make sense
8076 * if in function of the boot time zone sizes.
8078 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
8079 void __user *buffer, size_t *length, loff_t *ppos)
8081 proc_dointvec_minmax(table, write, buffer, length, ppos);
8082 setup_per_zone_lowmem_reserve();
8083 return 0;
8086 static void __zone_pcp_update(struct zone *zone)
8088 unsigned int cpu;
8090 for_each_possible_cpu(cpu)
8091 pageset_set_high_and_batch(zone,
8092 per_cpu_ptr(zone->pageset, cpu));
8096 * percpu_pagelist_fraction - changes the pcp->high for each zone on each
8097 * cpu. It is the fraction of total pages in each zone that a hot per cpu
8098 * pagelist can have before it gets flushed back to buddy allocator.
8100 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
8101 void __user *buffer, size_t *length, loff_t *ppos)
8103 struct zone *zone;
8104 int old_percpu_pagelist_fraction;
8105 int ret;
8107 mutex_lock(&pcp_batch_high_lock);
8108 old_percpu_pagelist_fraction = percpu_pagelist_fraction;
8110 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
8111 if (!write || ret < 0)
8112 goto out;
8114 /* Sanity checking to avoid pcp imbalance */
8115 if (percpu_pagelist_fraction &&
8116 percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
8117 percpu_pagelist_fraction = old_percpu_pagelist_fraction;
8118 ret = -EINVAL;
8119 goto out;
8122 /* No change? */
8123 if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
8124 goto out;
8126 for_each_populated_zone(zone)
8127 __zone_pcp_update(zone);
8128 out:
8129 mutex_unlock(&pcp_batch_high_lock);
8130 return ret;
8133 #ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES
8135 * Returns the number of pages that arch has reserved but
8136 * is not known to alloc_large_system_hash().
8138 static unsigned long __init arch_reserved_kernel_pages(void)
8140 return 0;
8142 #endif
8145 * Adaptive scale is meant to reduce sizes of hash tables on large memory
8146 * machines. As memory size is increased the scale is also increased but at
8147 * slower pace. Starting from ADAPT_SCALE_BASE (64G), every time memory
8148 * quadruples the scale is increased by one, which means the size of hash table
8149 * only doubles, instead of quadrupling as well.
8150 * Because 32-bit systems cannot have large physical memory, where this scaling
8151 * makes sense, it is disabled on such platforms.
8153 #if __BITS_PER_LONG > 32
8154 #define ADAPT_SCALE_BASE (64ul << 30)
8155 #define ADAPT_SCALE_SHIFT 2
8156 #define ADAPT_SCALE_NPAGES (ADAPT_SCALE_BASE >> PAGE_SHIFT)
8157 #endif
8160 * allocate a large system hash table from bootmem
8161 * - it is assumed that the hash table must contain an exact power-of-2
8162 * quantity of entries
8163 * - limit is the number of hash buckets, not the total allocation size
8165 void *__init alloc_large_system_hash(const char *tablename,
8166 unsigned long bucketsize,
8167 unsigned long numentries,
8168 int scale,
8169 int flags,
8170 unsigned int *_hash_shift,
8171 unsigned int *_hash_mask,
8172 unsigned long low_limit,
8173 unsigned long high_limit)
8175 unsigned long long max = high_limit;
8176 unsigned long log2qty, size;
8177 void *table = NULL;
8178 gfp_t gfp_flags;
8179 bool virt;
8181 /* allow the kernel cmdline to have a say */
8182 if (!numentries) {
8183 /* round applicable memory size up to nearest megabyte */
8184 numentries = nr_kernel_pages;
8185 numentries -= arch_reserved_kernel_pages();
8187 /* It isn't necessary when PAGE_SIZE >= 1MB */
8188 if (PAGE_SHIFT < 20)
8189 numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
8191 #if __BITS_PER_LONG > 32
8192 if (!high_limit) {
8193 unsigned long adapt;
8195 for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
8196 adapt <<= ADAPT_SCALE_SHIFT)
8197 scale++;
8199 #endif
8201 /* limit to 1 bucket per 2^scale bytes of low memory */
8202 if (scale > PAGE_SHIFT)
8203 numentries >>= (scale - PAGE_SHIFT);
8204 else
8205 numentries <<= (PAGE_SHIFT - scale);
8207 /* Make sure we've got at least a 0-order allocation.. */
8208 if (unlikely(flags & HASH_SMALL)) {
8209 /* Makes no sense without HASH_EARLY */
8210 WARN_ON(!(flags & HASH_EARLY));
8211 if (!(numentries >> *_hash_shift)) {
8212 numentries = 1UL << *_hash_shift;
8213 BUG_ON(!numentries);
8215 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
8216 numentries = PAGE_SIZE / bucketsize;
8218 numentries = roundup_pow_of_two(numentries);
8220 /* limit allocation size to 1/16 total memory by default */
8221 if (max == 0) {
8222 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
8223 do_div(max, bucketsize);
8225 max = min(max, 0x80000000ULL);
8227 if (numentries < low_limit)
8228 numentries = low_limit;
8229 if (numentries > max)
8230 numentries = max;
8232 log2qty = ilog2(numentries);
8234 gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
8235 do {
8236 virt = false;
8237 size = bucketsize << log2qty;
8238 if (flags & HASH_EARLY) {
8239 if (flags & HASH_ZERO)
8240 table = memblock_alloc(size, SMP_CACHE_BYTES);
8241 else
8242 table = memblock_alloc_raw(size,
8243 SMP_CACHE_BYTES);
8244 } else if (get_order(size) >= MAX_ORDER || hashdist) {
8245 table = __vmalloc(size, gfp_flags, PAGE_KERNEL);
8246 virt = true;
8247 } else {
8249 * If bucketsize is not a power-of-two, we may free
8250 * some pages at the end of hash table which
8251 * alloc_pages_exact() automatically does
8253 table = alloc_pages_exact(size, gfp_flags);
8254 kmemleak_alloc(table, size, 1, gfp_flags);
8256 } while (!table && size > PAGE_SIZE && --log2qty);
8258 if (!table)
8259 panic("Failed to allocate %s hash table\n", tablename);
8261 pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n",
8262 tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size,
8263 virt ? "vmalloc" : "linear");
8265 if (_hash_shift)
8266 *_hash_shift = log2qty;
8267 if (_hash_mask)
8268 *_hash_mask = (1 << log2qty) - 1;
8270 return table;
8274 * This function checks whether pageblock includes unmovable pages or not.
8276 * PageLRU check without isolation or lru_lock could race so that
8277 * MIGRATE_MOVABLE block might include unmovable pages. And __PageMovable
8278 * check without lock_page also may miss some movable non-lru pages at
8279 * race condition. So you can't expect this function should be exact.
8281 * Returns a page without holding a reference. If the caller wants to
8282 * dereference that page (e.g., dumping), it has to make sure that that it
8283 * cannot get removed (e.g., via memory unplug) concurrently.
8286 struct page *has_unmovable_pages(struct zone *zone, struct page *page,
8287 int migratetype, int flags)
8289 unsigned long iter = 0;
8290 unsigned long pfn = page_to_pfn(page);
8293 * TODO we could make this much more efficient by not checking every
8294 * page in the range if we know all of them are in MOVABLE_ZONE and
8295 * that the movable zone guarantees that pages are migratable but
8296 * the later is not the case right now unfortunatelly. E.g. movablecore
8297 * can still lead to having bootmem allocations in zone_movable.
8300 if (is_migrate_cma_page(page)) {
8302 * CMA allocations (alloc_contig_range) really need to mark
8303 * isolate CMA pageblocks even when they are not movable in fact
8304 * so consider them movable here.
8306 if (is_migrate_cma(migratetype))
8307 return NULL;
8309 return page;
8312 for (; iter < pageblock_nr_pages; iter++) {
8313 if (!pfn_valid_within(pfn + iter))
8314 continue;
8316 page = pfn_to_page(pfn + iter);
8318 if (PageReserved(page))
8319 return page;
8322 * If the zone is movable and we have ruled out all reserved
8323 * pages then it should be reasonably safe to assume the rest
8324 * is movable.
8326 if (zone_idx(zone) == ZONE_MOVABLE)
8327 continue;
8330 * Hugepages are not in LRU lists, but they're movable.
8331 * THPs are on the LRU, but need to be counted as #small pages.
8332 * We need not scan over tail pages because we don't
8333 * handle each tail page individually in migration.
8335 if (PageHuge(page) || PageTransCompound(page)) {
8336 struct page *head = compound_head(page);
8337 unsigned int skip_pages;
8339 if (PageHuge(page)) {
8340 if (!hugepage_migration_supported(page_hstate(head)))
8341 return page;
8342 } else if (!PageLRU(head) && !__PageMovable(head)) {
8343 return page;
8346 skip_pages = compound_nr(head) - (page - head);
8347 iter += skip_pages - 1;
8348 continue;
8352 * We can't use page_count without pin a page
8353 * because another CPU can free compound page.
8354 * This check already skips compound tails of THP
8355 * because their page->_refcount is zero at all time.
8357 if (!page_ref_count(page)) {
8358 if (PageBuddy(page))
8359 iter += (1 << page_order(page)) - 1;
8360 continue;
8364 * The HWPoisoned page may be not in buddy system, and
8365 * page_count() is not 0.
8367 if ((flags & MEMORY_OFFLINE) && PageHWPoison(page))
8368 continue;
8370 if (__PageMovable(page) || PageLRU(page))
8371 continue;
8374 * If there are RECLAIMABLE pages, we need to check
8375 * it. But now, memory offline itself doesn't call
8376 * shrink_node_slabs() and it still to be fixed.
8379 * If the page is not RAM, page_count()should be 0.
8380 * we don't need more check. This is an _used_ not-movable page.
8382 * The problematic thing here is PG_reserved pages. PG_reserved
8383 * is set to both of a memory hole page and a _used_ kernel
8384 * page at boot.
8386 return page;
8388 return NULL;
8391 #ifdef CONFIG_CONTIG_ALLOC
8392 static unsigned long pfn_max_align_down(unsigned long pfn)
8394 return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
8395 pageblock_nr_pages) - 1);
8398 static unsigned long pfn_max_align_up(unsigned long pfn)
8400 return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
8401 pageblock_nr_pages));
8404 /* [start, end) must belong to a single zone. */
8405 static int __alloc_contig_migrate_range(struct compact_control *cc,
8406 unsigned long start, unsigned long end)
8408 /* This function is based on compact_zone() from compaction.c. */
8409 unsigned long nr_reclaimed;
8410 unsigned long pfn = start;
8411 unsigned int tries = 0;
8412 int ret = 0;
8414 migrate_prep();
8416 while (pfn < end || !list_empty(&cc->migratepages)) {
8417 if (fatal_signal_pending(current)) {
8418 ret = -EINTR;
8419 break;
8422 if (list_empty(&cc->migratepages)) {
8423 cc->nr_migratepages = 0;
8424 pfn = isolate_migratepages_range(cc, pfn, end);
8425 if (!pfn) {
8426 ret = -EINTR;
8427 break;
8429 tries = 0;
8430 } else if (++tries == 5) {
8431 ret = ret < 0 ? ret : -EBUSY;
8432 break;
8435 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
8436 &cc->migratepages);
8437 cc->nr_migratepages -= nr_reclaimed;
8439 ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
8440 NULL, 0, cc->mode, MR_CONTIG_RANGE);
8442 if (ret < 0) {
8443 putback_movable_pages(&cc->migratepages);
8444 return ret;
8446 return 0;
8450 * alloc_contig_range() -- tries to allocate given range of pages
8451 * @start: start PFN to allocate
8452 * @end: one-past-the-last PFN to allocate
8453 * @migratetype: migratetype of the underlaying pageblocks (either
8454 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
8455 * in range must have the same migratetype and it must
8456 * be either of the two.
8457 * @gfp_mask: GFP mask to use during compaction
8459 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
8460 * aligned. The PFN range must belong to a single zone.
8462 * The first thing this routine does is attempt to MIGRATE_ISOLATE all
8463 * pageblocks in the range. Once isolated, the pageblocks should not
8464 * be modified by others.
8466 * Return: zero on success or negative error code. On success all
8467 * pages which PFN is in [start, end) are allocated for the caller and
8468 * need to be freed with free_contig_range().
8470 int alloc_contig_range(unsigned long start, unsigned long end,
8471 unsigned migratetype, gfp_t gfp_mask)
8473 unsigned long outer_start, outer_end;
8474 unsigned int order;
8475 int ret = 0;
8477 struct compact_control cc = {
8478 .nr_migratepages = 0,
8479 .order = -1,
8480 .zone = page_zone(pfn_to_page(start)),
8481 .mode = MIGRATE_SYNC,
8482 .ignore_skip_hint = true,
8483 .no_set_skip_hint = true,
8484 .gfp_mask = current_gfp_context(gfp_mask),
8485 .alloc_contig = true,
8487 INIT_LIST_HEAD(&cc.migratepages);
8490 * What we do here is we mark all pageblocks in range as
8491 * MIGRATE_ISOLATE. Because pageblock and max order pages may
8492 * have different sizes, and due to the way page allocator
8493 * work, we align the range to biggest of the two pages so
8494 * that page allocator won't try to merge buddies from
8495 * different pageblocks and change MIGRATE_ISOLATE to some
8496 * other migration type.
8498 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
8499 * migrate the pages from an unaligned range (ie. pages that
8500 * we are interested in). This will put all the pages in
8501 * range back to page allocator as MIGRATE_ISOLATE.
8503 * When this is done, we take the pages in range from page
8504 * allocator removing them from the buddy system. This way
8505 * page allocator will never consider using them.
8507 * This lets us mark the pageblocks back as
8508 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
8509 * aligned range but not in the unaligned, original range are
8510 * put back to page allocator so that buddy can use them.
8513 ret = start_isolate_page_range(pfn_max_align_down(start),
8514 pfn_max_align_up(end), migratetype, 0);
8515 if (ret < 0)
8516 return ret;
8519 * In case of -EBUSY, we'd like to know which page causes problem.
8520 * So, just fall through. test_pages_isolated() has a tracepoint
8521 * which will report the busy page.
8523 * It is possible that busy pages could become available before
8524 * the call to test_pages_isolated, and the range will actually be
8525 * allocated. So, if we fall through be sure to clear ret so that
8526 * -EBUSY is not accidentally used or returned to caller.
8528 ret = __alloc_contig_migrate_range(&cc, start, end);
8529 if (ret && ret != -EBUSY)
8530 goto done;
8531 ret =0;
8534 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
8535 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
8536 * more, all pages in [start, end) are free in page allocator.
8537 * What we are going to do is to allocate all pages from
8538 * [start, end) (that is remove them from page allocator).
8540 * The only problem is that pages at the beginning and at the
8541 * end of interesting range may be not aligned with pages that
8542 * page allocator holds, ie. they can be part of higher order
8543 * pages. Because of this, we reserve the bigger range and
8544 * once this is done free the pages we are not interested in.
8546 * We don't have to hold zone->lock here because the pages are
8547 * isolated thus they won't get removed from buddy.
8550 lru_add_drain_all();
8552 order = 0;
8553 outer_start = start;
8554 while (!PageBuddy(pfn_to_page(outer_start))) {
8555 if (++order >= MAX_ORDER) {
8556 outer_start = start;
8557 break;
8559 outer_start &= ~0UL << order;
8562 if (outer_start != start) {
8563 order = page_order(pfn_to_page(outer_start));
8566 * outer_start page could be small order buddy page and
8567 * it doesn't include start page. Adjust outer_start
8568 * in this case to report failed page properly
8569 * on tracepoint in test_pages_isolated()
8571 if (outer_start + (1UL << order) <= start)
8572 outer_start = start;
8575 /* Make sure the range is really isolated. */
8576 if (test_pages_isolated(outer_start, end, 0)) {
8577 pr_info_ratelimited("%s: [%lx, %lx) PFNs busy\n",
8578 __func__, outer_start, end);
8579 ret = -EBUSY;
8580 goto done;
8583 /* Grab isolated pages from freelists. */
8584 outer_end = isolate_freepages_range(&cc, outer_start, end);
8585 if (!outer_end) {
8586 ret = -EBUSY;
8587 goto done;
8590 /* Free head and tail (if any) */
8591 if (start != outer_start)
8592 free_contig_range(outer_start, start - outer_start);
8593 if (end != outer_end)
8594 free_contig_range(end, outer_end - end);
8596 done:
8597 undo_isolate_page_range(pfn_max_align_down(start),
8598 pfn_max_align_up(end), migratetype);
8599 return ret;
8602 static int __alloc_contig_pages(unsigned long start_pfn,
8603 unsigned long nr_pages, gfp_t gfp_mask)
8605 unsigned long end_pfn = start_pfn + nr_pages;
8607 return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE,
8608 gfp_mask);
8611 static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn,
8612 unsigned long nr_pages)
8614 unsigned long i, end_pfn = start_pfn + nr_pages;
8615 struct page *page;
8617 for (i = start_pfn; i < end_pfn; i++) {
8618 page = pfn_to_online_page(i);
8619 if (!page)
8620 return false;
8622 if (page_zone(page) != z)
8623 return false;
8625 if (PageReserved(page))
8626 return false;
8628 if (page_count(page) > 0)
8629 return false;
8631 if (PageHuge(page))
8632 return false;
8634 return true;
8637 static bool zone_spans_last_pfn(const struct zone *zone,
8638 unsigned long start_pfn, unsigned long nr_pages)
8640 unsigned long last_pfn = start_pfn + nr_pages - 1;
8642 return zone_spans_pfn(zone, last_pfn);
8646 * alloc_contig_pages() -- tries to find and allocate contiguous range of pages
8647 * @nr_pages: Number of contiguous pages to allocate
8648 * @gfp_mask: GFP mask to limit search and used during compaction
8649 * @nid: Target node
8650 * @nodemask: Mask for other possible nodes
8652 * This routine is a wrapper around alloc_contig_range(). It scans over zones
8653 * on an applicable zonelist to find a contiguous pfn range which can then be
8654 * tried for allocation with alloc_contig_range(). This routine is intended
8655 * for allocation requests which can not be fulfilled with the buddy allocator.
8657 * The allocated memory is always aligned to a page boundary. If nr_pages is a
8658 * power of two then the alignment is guaranteed to be to the given nr_pages
8659 * (e.g. 1GB request would be aligned to 1GB).
8661 * Allocated pages can be freed with free_contig_range() or by manually calling
8662 * __free_page() on each allocated page.
8664 * Return: pointer to contiguous pages on success, or NULL if not successful.
8666 struct page *alloc_contig_pages(unsigned long nr_pages, gfp_t gfp_mask,
8667 int nid, nodemask_t *nodemask)
8669 unsigned long ret, pfn, flags;
8670 struct zonelist *zonelist;
8671 struct zone *zone;
8672 struct zoneref *z;
8674 zonelist = node_zonelist(nid, gfp_mask);
8675 for_each_zone_zonelist_nodemask(zone, z, zonelist,
8676 gfp_zone(gfp_mask), nodemask) {
8677 spin_lock_irqsave(&zone->lock, flags);
8679 pfn = ALIGN(zone->zone_start_pfn, nr_pages);
8680 while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
8681 if (pfn_range_valid_contig(zone, pfn, nr_pages)) {
8683 * We release the zone lock here because
8684 * alloc_contig_range() will also lock the zone
8685 * at some point. If there's an allocation
8686 * spinning on this lock, it may win the race
8687 * and cause alloc_contig_range() to fail...
8689 spin_unlock_irqrestore(&zone->lock, flags);
8690 ret = __alloc_contig_pages(pfn, nr_pages,
8691 gfp_mask);
8692 if (!ret)
8693 return pfn_to_page(pfn);
8694 spin_lock_irqsave(&zone->lock, flags);
8696 pfn += nr_pages;
8698 spin_unlock_irqrestore(&zone->lock, flags);
8700 return NULL;
8702 #endif /* CONFIG_CONTIG_ALLOC */
8704 void free_contig_range(unsigned long pfn, unsigned int nr_pages)
8706 unsigned int count = 0;
8708 for (; nr_pages--; pfn++) {
8709 struct page *page = pfn_to_page(pfn);
8711 count += page_count(page) != 1;
8712 __free_page(page);
8714 WARN(count != 0, "%d pages are still in use!\n", count);
8718 * The zone indicated has a new number of managed_pages; batch sizes and percpu
8719 * page high values need to be recalulated.
8721 void __meminit zone_pcp_update(struct zone *zone)
8723 mutex_lock(&pcp_batch_high_lock);
8724 __zone_pcp_update(zone);
8725 mutex_unlock(&pcp_batch_high_lock);
8728 void zone_pcp_reset(struct zone *zone)
8730 unsigned long flags;
8731 int cpu;
8732 struct per_cpu_pageset *pset;
8734 /* avoid races with drain_pages() */
8735 local_irq_save(flags);
8736 if (zone->pageset != &boot_pageset) {
8737 for_each_online_cpu(cpu) {
8738 pset = per_cpu_ptr(zone->pageset, cpu);
8739 drain_zonestat(zone, pset);
8741 free_percpu(zone->pageset);
8742 zone->pageset = &boot_pageset;
8744 local_irq_restore(flags);
8747 #ifdef CONFIG_MEMORY_HOTREMOVE
8749 * All pages in the range must be in a single zone and isolated
8750 * before calling this.
8752 unsigned long
8753 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
8755 struct page *page;
8756 struct zone *zone;
8757 unsigned int order;
8758 unsigned long pfn;
8759 unsigned long flags;
8760 unsigned long offlined_pages = 0;
8762 /* find the first valid pfn */
8763 for (pfn = start_pfn; pfn < end_pfn; pfn++)
8764 if (pfn_valid(pfn))
8765 break;
8766 if (pfn == end_pfn)
8767 return offlined_pages;
8769 offline_mem_sections(pfn, end_pfn);
8770 zone = page_zone(pfn_to_page(pfn));
8771 spin_lock_irqsave(&zone->lock, flags);
8772 pfn = start_pfn;
8773 while (pfn < end_pfn) {
8774 if (!pfn_valid(pfn)) {
8775 pfn++;
8776 continue;
8778 page = pfn_to_page(pfn);
8780 * The HWPoisoned page may be not in buddy system, and
8781 * page_count() is not 0.
8783 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
8784 pfn++;
8785 offlined_pages++;
8786 continue;
8789 BUG_ON(page_count(page));
8790 BUG_ON(!PageBuddy(page));
8791 order = page_order(page);
8792 offlined_pages += 1 << order;
8793 del_page_from_free_list(page, zone, order);
8794 pfn += (1 << order);
8796 spin_unlock_irqrestore(&zone->lock, flags);
8798 return offlined_pages;
8800 #endif
8802 bool is_free_buddy_page(struct page *page)
8804 struct zone *zone = page_zone(page);
8805 unsigned long pfn = page_to_pfn(page);
8806 unsigned long flags;
8807 unsigned int order;
8809 spin_lock_irqsave(&zone->lock, flags);
8810 for (order = 0; order < MAX_ORDER; order++) {
8811 struct page *page_head = page - (pfn & ((1 << order) - 1));
8813 if (PageBuddy(page_head) && page_order(page_head) >= order)
8814 break;
8816 spin_unlock_irqrestore(&zone->lock, flags);
8818 return order < MAX_ORDER;
8821 #ifdef CONFIG_MEMORY_FAILURE
8823 * Set PG_hwpoison flag if a given page is confirmed to be a free page. This
8824 * test is performed under the zone lock to prevent a race against page
8825 * allocation.
8827 bool set_hwpoison_free_buddy_page(struct page *page)
8829 struct zone *zone = page_zone(page);
8830 unsigned long pfn = page_to_pfn(page);
8831 unsigned long flags;
8832 unsigned int order;
8833 bool hwpoisoned = false;
8835 spin_lock_irqsave(&zone->lock, flags);
8836 for (order = 0; order < MAX_ORDER; order++) {
8837 struct page *page_head = page - (pfn & ((1 << order) - 1));
8839 if (PageBuddy(page_head) && page_order(page_head) >= order) {
8840 if (!TestSetPageHWPoison(page))
8841 hwpoisoned = true;
8842 break;
8845 spin_unlock_irqrestore(&zone->lock, flags);
8847 return hwpoisoned;
8849 #endif