]> git.ipfire.org Git - thirdparty/linux.git/blame - mm/page_alloc.c
mm: make alloc_contig_range work at pageblock granularity
[thirdparty/linux.git] / mm / page_alloc.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4
LT
2/*
3 * linux/mm/page_alloc.c
4 *
5 * Manages the free list, the system allocates free pages here.
6 * Note that kmalloc() lives in slab.c
7 *
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)
16 */
17
1da177e4
LT
18#include <linux/stddef.h>
19#include <linux/mm.h>
ca79b0c2 20#include <linux/highmem.h>
1da177e4 21#include <linux/swap.h>
bf181c58 22#include <linux/swapops.h>
1da177e4
LT
23#include <linux/interrupt.h>
24#include <linux/pagemap.h>
10ed273f 25#include <linux/jiffies.h>
edbe7d23 26#include <linux/memblock.h>
1da177e4 27#include <linux/compiler.h>
9f158333 28#include <linux/kernel.h>
b8c73fc2 29#include <linux/kasan.h>
1da177e4
LT
30#include <linux/module.h>
31#include <linux/suspend.h>
32#include <linux/pagevec.h>
33#include <linux/blkdev.h>
34#include <linux/slab.h>
a238ab5b 35#include <linux/ratelimit.h>
5a3135c2 36#include <linux/oom.h>
1da177e4
LT
37#include <linux/topology.h>
38#include <linux/sysctl.h>
39#include <linux/cpu.h>
40#include <linux/cpuset.h>
bdc8cb98 41#include <linux/memory_hotplug.h>
1da177e4
LT
42#include <linux/nodemask.h>
43#include <linux/vmalloc.h>
a6cccdc3 44#include <linux/vmstat.h>
4be38e35 45#include <linux/mempolicy.h>
4b94ffdc 46#include <linux/memremap.h>
6811378e 47#include <linux/stop_machine.h>
97500a4a 48#include <linux/random.h>
c713216d
MG
49#include <linux/sort.h>
50#include <linux/pfn.h>
3fcfab16 51#include <linux/backing-dev.h>
933e312e 52#include <linux/fault-inject.h>
a5d76b54 53#include <linux/page-isolation.h>
3ac7fe5a 54#include <linux/debugobjects.h>
dbb1f81c 55#include <linux/kmemleak.h>
56de7263 56#include <linux/compaction.h>
0d3d062a 57#include <trace/events/kmem.h>
d379f01d 58#include <trace/events/oom.h>
268bb0ce 59#include <linux/prefetch.h>
6e543d57 60#include <linux/mm_inline.h>
f920e413 61#include <linux/mmu_notifier.h>
041d3a8c 62#include <linux/migrate.h>
949f7ec5 63#include <linux/hugetlb.h>
8bd75c77 64#include <linux/sched/rt.h>
5b3cc15a 65#include <linux/sched/mm.h>
48c96a36 66#include <linux/page_owner.h>
df4e817b 67#include <linux/page_table_check.h>
0e1cc95b 68#include <linux/kthread.h>
4949148a 69#include <linux/memcontrol.h>
42c269c8 70#include <linux/ftrace.h>
d92a8cfc 71#include <linux/lockdep.h>
556b969a 72#include <linux/nmi.h>
eb414681 73#include <linux/psi.h>
e4443149 74#include <linux/padata.h>
4aab2be0 75#include <linux/khugepaged.h>
ba8f3587 76#include <linux/buffer_head.h>
5bf18281 77#include <linux/delayacct.h>
7ee3d4e8 78#include <asm/sections.h>
1da177e4 79#include <asm/tlbflush.h>
ac924c60 80#include <asm/div64.h>
1da177e4 81#include "internal.h"
e900a918 82#include "shuffle.h"
36e66c55 83#include "page_reporting.h"
014bb1de 84#include "swap.h"
1da177e4 85
f04a5d5d
DH
86/* Free Page Internal flags: for internal, non-pcp variants of free_pages(). */
87typedef int __bitwise fpi_t;
88
89/* No special request */
90#define FPI_NONE ((__force fpi_t)0)
91
92/*
93 * Skip free page reporting notification for the (possibly merged) page.
94 * This does not hinder free page reporting from grabbing the page,
95 * reporting it and marking it "reported" - it only skips notifying
96 * the free page reporting infrastructure about a newly freed page. For
97 * example, used when temporarily pulling a page from a freelist and
98 * putting it back unmodified.
99 */
100#define FPI_SKIP_REPORT_NOTIFY ((__force fpi_t)BIT(0))
101
47b6a24a
DH
102/*
103 * Place the (possibly merged) page to the tail of the freelist. Will ignore
104 * page shuffling (relevant code - e.g., memory onlining - is expected to
105 * shuffle the whole zone).
106 *
107 * Note: No code should rely on this flag for correctness - it's purely
108 * to allow for optimizations when handing back either fresh pages
109 * (memory onlining) or untouched pages (page isolation, free page
110 * reporting).
111 */
112#define FPI_TO_TAIL ((__force fpi_t)BIT(1))
113
2c335680
AK
114/*
115 * Don't poison memory with KASAN (only for the tag-based modes).
116 * During boot, all non-reserved memblock memory is exposed to page_alloc.
117 * Poisoning all that memory lengthens boot time, especially on systems with
118 * large amount of RAM. This flag is used to skip that poisoning.
119 * This is only done for the tag-based KASAN modes, as those are able to
120 * detect memory corruptions with the memory tags assigned by default.
121 * All memory allocated normally after boot gets poisoned as usual.
122 */
123#define FPI_SKIP_KASAN_POISON ((__force fpi_t)BIT(2))
124
c8e251fa
CS
125/* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
126static DEFINE_MUTEX(pcp_batch_high_lock);
74f44822 127#define MIN_PERCPU_PAGELIST_HIGH_FRACTION (8)
c8e251fa 128
dbbee9d5
MG
129struct pagesets {
130 local_lock_t lock;
dbbee9d5 131};
273ba85b 132static DEFINE_PER_CPU(struct pagesets, pagesets) = {
dbbee9d5
MG
133 .lock = INIT_LOCAL_LOCK(lock),
134};
c8e251fa 135
72812019
LS
136#ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
137DEFINE_PER_CPU(int, numa_node);
138EXPORT_PER_CPU_SYMBOL(numa_node);
139#endif
140
4518085e
KW
141DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
142
7aac7898
LS
143#ifdef CONFIG_HAVE_MEMORYLESS_NODES
144/*
145 * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
146 * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
147 * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
148 * defined in <linux/topology.h>.
149 */
150DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */
151EXPORT_PER_CPU_SYMBOL(_numa_mem_);
152#endif
153
bd233f53 154/* work_structs for global per-cpu drains */
d9367bd0
WY
155struct pcpu_drain {
156 struct zone *zone;
157 struct work_struct work;
158};
8b885f53
JY
159static DEFINE_MUTEX(pcpu_drain_mutex);
160static DEFINE_PER_CPU(struct pcpu_drain, pcpu_drain);
bd233f53 161
38addce8 162#ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
58bea414 163volatile unsigned long latent_entropy __latent_entropy;
38addce8
ER
164EXPORT_SYMBOL(latent_entropy);
165#endif
166
1da177e4 167/*
13808910 168 * Array of node states.
1da177e4 169 */
13808910
CL
170nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
171 [N_POSSIBLE] = NODE_MASK_ALL,
172 [N_ONLINE] = { { [0] = 1UL } },
173#ifndef CONFIG_NUMA
174 [N_NORMAL_MEMORY] = { { [0] = 1UL } },
175#ifdef CONFIG_HIGHMEM
176 [N_HIGH_MEMORY] = { { [0] = 1UL } },
20b2f52b 177#endif
20b2f52b 178 [N_MEMORY] = { { [0] = 1UL } },
13808910
CL
179 [N_CPU] = { { [0] = 1UL } },
180#endif /* NUMA */
181};
182EXPORT_SYMBOL(node_states);
183
ca79b0c2
AK
184atomic_long_t _totalram_pages __read_mostly;
185EXPORT_SYMBOL(_totalram_pages);
cb45b0e9 186unsigned long totalreserve_pages __read_mostly;
e48322ab 187unsigned long totalcma_pages __read_mostly;
ab8fabd4 188
74f44822 189int percpu_pagelist_high_fraction;
dcce284a 190gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
51cba1eb 191DEFINE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_ALLOC_DEFAULT_ON, init_on_alloc);
6471384a
AP
192EXPORT_SYMBOL(init_on_alloc);
193
51cba1eb 194DEFINE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_FREE_DEFAULT_ON, init_on_free);
6471384a
AP
195EXPORT_SYMBOL(init_on_free);
196
04013513
VB
197static bool _init_on_alloc_enabled_early __read_mostly
198 = IS_ENABLED(CONFIG_INIT_ON_ALLOC_DEFAULT_ON);
6471384a
AP
199static int __init early_init_on_alloc(char *buf)
200{
6471384a 201
04013513 202 return kstrtobool(buf, &_init_on_alloc_enabled_early);
6471384a
AP
203}
204early_param("init_on_alloc", early_init_on_alloc);
205
04013513
VB
206static bool _init_on_free_enabled_early __read_mostly
207 = IS_ENABLED(CONFIG_INIT_ON_FREE_DEFAULT_ON);
6471384a
AP
208static int __init early_init_on_free(char *buf)
209{
04013513 210 return kstrtobool(buf, &_init_on_free_enabled_early);
6471384a
AP
211}
212early_param("init_on_free", early_init_on_free);
1da177e4 213
bb14c2c7
VB
214/*
215 * A cached value of the page's pageblock's migratetype, used when the page is
216 * put on a pcplist. Used to avoid the pageblock migratetype lookup when
217 * freeing from pcplists in most cases, at the cost of possibly becoming stale.
218 * Also the migratetype set in the page does not necessarily match the pcplist
219 * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
220 * other index - this ensures that it will be put on the correct CMA freelist.
221 */
222static inline int get_pcppage_migratetype(struct page *page)
223{
224 return page->index;
225}
226
227static inline void set_pcppage_migratetype(struct page *page, int migratetype)
228{
229 page->index = migratetype;
230}
231
452aa699
RW
232#ifdef CONFIG_PM_SLEEP
233/*
234 * The following functions are used by the suspend/hibernate code to temporarily
235 * change gfp_allowed_mask in order to avoid using I/O during memory allocations
236 * while devices are suspended. To avoid races with the suspend/hibernate code,
55f2503c
PL
237 * they should always be called with system_transition_mutex held
238 * (gfp_allowed_mask also should only be modified with system_transition_mutex
239 * held, unless the suspend/hibernate code is guaranteed not to run in parallel
240 * with that modification).
452aa699 241 */
c9e664f1
RW
242
243static gfp_t saved_gfp_mask;
244
245void pm_restore_gfp_mask(void)
452aa699 246{
55f2503c 247 WARN_ON(!mutex_is_locked(&system_transition_mutex));
c9e664f1
RW
248 if (saved_gfp_mask) {
249 gfp_allowed_mask = saved_gfp_mask;
250 saved_gfp_mask = 0;
251 }
452aa699
RW
252}
253
c9e664f1 254void pm_restrict_gfp_mask(void)
452aa699 255{
55f2503c 256 WARN_ON(!mutex_is_locked(&system_transition_mutex));
c9e664f1
RW
257 WARN_ON(saved_gfp_mask);
258 saved_gfp_mask = gfp_allowed_mask;
d0164adc 259 gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
452aa699 260}
f90ac398
MG
261
262bool pm_suspended_storage(void)
263{
d0164adc 264 if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
f90ac398
MG
265 return false;
266 return true;
267}
452aa699
RW
268#endif /* CONFIG_PM_SLEEP */
269
d9c23400 270#ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
d00181b9 271unsigned int pageblock_order __read_mostly;
d9c23400
MG
272#endif
273
7fef431b
DH
274static void __free_pages_ok(struct page *page, unsigned int order,
275 fpi_t fpi_flags);
a226f6c8 276
1da177e4
LT
277/*
278 * results with 256, 32 in the lowmem_reserve sysctl:
279 * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
280 * 1G machine -> (16M dma, 784M normal, 224M high)
281 * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
282 * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
84109e15 283 * HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
a2f1b424
AK
284 *
285 * TBD: should special case ZONE_DMA32 machines here - in those we normally
286 * don't need any ZONE_NORMAL reservation
1da177e4 287 */
d3cda233 288int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
4b51d669 289#ifdef CONFIG_ZONE_DMA
d3cda233 290 [ZONE_DMA] = 256,
4b51d669 291#endif
fb0e7942 292#ifdef CONFIG_ZONE_DMA32
d3cda233 293 [ZONE_DMA32] = 256,
fb0e7942 294#endif
d3cda233 295 [ZONE_NORMAL] = 32,
e53ef38d 296#ifdef CONFIG_HIGHMEM
d3cda233 297 [ZONE_HIGHMEM] = 0,
e53ef38d 298#endif
d3cda233 299 [ZONE_MOVABLE] = 0,
2f1b6248 300};
1da177e4 301
15ad7cdc 302static char * const zone_names[MAX_NR_ZONES] = {
4b51d669 303#ifdef CONFIG_ZONE_DMA
2f1b6248 304 "DMA",
4b51d669 305#endif
fb0e7942 306#ifdef CONFIG_ZONE_DMA32
2f1b6248 307 "DMA32",
fb0e7942 308#endif
2f1b6248 309 "Normal",
e53ef38d 310#ifdef CONFIG_HIGHMEM
2a1e274a 311 "HighMem",
e53ef38d 312#endif
2a1e274a 313 "Movable",
033fbae9
DW
314#ifdef CONFIG_ZONE_DEVICE
315 "Device",
316#endif
2f1b6248
CL
317};
318
c999fbd3 319const char * const migratetype_names[MIGRATE_TYPES] = {
60f30350
VB
320 "Unmovable",
321 "Movable",
322 "Reclaimable",
323 "HighAtomic",
324#ifdef CONFIG_CMA
325 "CMA",
326#endif
327#ifdef CONFIG_MEMORY_ISOLATION
328 "Isolate",
329#endif
330};
331
ae70eddd
AK
332compound_page_dtor * const compound_page_dtors[NR_COMPOUND_DTORS] = {
333 [NULL_COMPOUND_DTOR] = NULL,
334 [COMPOUND_PAGE_DTOR] = free_compound_page,
f1e61557 335#ifdef CONFIG_HUGETLB_PAGE
ae70eddd 336 [HUGETLB_PAGE_DTOR] = free_huge_page,
f1e61557 337#endif
9a982250 338#ifdef CONFIG_TRANSPARENT_HUGEPAGE
ae70eddd 339 [TRANSHUGE_PAGE_DTOR] = free_transhuge_page,
9a982250 340#endif
f1e61557
KS
341};
342
1da177e4 343int min_free_kbytes = 1024;
42aa83cb 344int user_min_free_kbytes = -1;
1c30844d 345int watermark_boost_factor __read_mostly = 15000;
795ae7a0 346int watermark_scale_factor = 10;
1da177e4 347
bbe5d993
OS
348static unsigned long nr_kernel_pages __initdata;
349static unsigned long nr_all_pages __initdata;
350static unsigned long dma_reserve __initdata;
1da177e4 351
bbe5d993
OS
352static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata;
353static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata;
7f16f91f 354static unsigned long required_kernelcore __initdata;
a5c6d650 355static unsigned long required_kernelcore_percent __initdata;
7f16f91f 356static unsigned long required_movablecore __initdata;
a5c6d650 357static unsigned long required_movablecore_percent __initdata;
bbe5d993 358static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata;
7f16f91f 359static bool mirrored_kernelcore __meminitdata;
0ee332c1
TH
360
361/* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
362int movable_zone;
363EXPORT_SYMBOL(movable_zone);
c713216d 364
418508c1 365#if MAX_NUMNODES > 1
b9726c26 366unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
ce0725f7 367unsigned int nr_online_nodes __read_mostly = 1;
418508c1 368EXPORT_SYMBOL(nr_node_ids);
62bc62a8 369EXPORT_SYMBOL(nr_online_nodes);
418508c1
MS
370#endif
371
9ef9acb0
MG
372int page_group_by_mobility_disabled __read_mostly;
373
3a80a7fa 374#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3c0c12cc
WL
375/*
376 * During boot we initialize deferred pages on-demand, as needed, but once
377 * page_alloc_init_late() has finished, the deferred pages are all initialized,
378 * and we can permanently disable that path.
379 */
380static DEFINE_STATIC_KEY_TRUE(deferred_pages);
381
94ae8b83 382static inline bool deferred_pages_enabled(void)
3c0c12cc 383{
94ae8b83 384 return static_branch_unlikely(&deferred_pages);
3c0c12cc
WL
385}
386
3a80a7fa 387/* Returns true if the struct page for the pfn is uninitialised */
0e1cc95b 388static inline bool __meminit early_page_uninitialised(unsigned long pfn)
3a80a7fa 389{
ef70b6f4
MG
390 int nid = early_pfn_to_nid(pfn);
391
392 if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
3a80a7fa
MG
393 return true;
394
395 return false;
396}
397
398/*
d3035be4 399 * Returns true when the remaining initialisation should be deferred until
3a80a7fa
MG
400 * later in the boot cycle when it can be parallelised.
401 */
d3035be4
PT
402static bool __meminit
403defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
3a80a7fa 404{
d3035be4
PT
405 static unsigned long prev_end_pfn, nr_initialised;
406
407 /*
408 * prev_end_pfn static that contains the end of previous zone
409 * No need to protect because called very early in boot before smp_init.
410 */
411 if (prev_end_pfn != end_pfn) {
412 prev_end_pfn = end_pfn;
413 nr_initialised = 0;
414 }
415
3c2c6488 416 /* Always populate low zones for address-constrained allocations */
d3035be4 417 if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
3a80a7fa 418 return false;
23b68cfa 419
dc2da7b4
BH
420 if (NODE_DATA(nid)->first_deferred_pfn != ULONG_MAX)
421 return true;
23b68cfa
WY
422 /*
423 * We start only with one section of pages, more pages are added as
424 * needed until the rest of deferred pages are initialized.
425 */
d3035be4 426 nr_initialised++;
23b68cfa 427 if ((nr_initialised > PAGES_PER_SECTION) &&
d3035be4
PT
428 (pfn & (PAGES_PER_SECTION - 1)) == 0) {
429 NODE_DATA(nid)->first_deferred_pfn = pfn;
430 return true;
3a80a7fa 431 }
d3035be4 432 return false;
3a80a7fa
MG
433}
434#else
94ae8b83 435static inline bool deferred_pages_enabled(void)
2c335680 436{
94ae8b83 437 return false;
2c335680 438}
3c0c12cc 439
3a80a7fa
MG
440static inline bool early_page_uninitialised(unsigned long pfn)
441{
442 return false;
443}
444
d3035be4 445static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
3a80a7fa 446{
d3035be4 447 return false;
3a80a7fa
MG
448}
449#endif
450
0b423ca2 451/* Return a pointer to the bitmap storing bits affecting a block of pages */
ca891f41 452static inline unsigned long *get_pageblock_bitmap(const struct page *page,
0b423ca2
MG
453 unsigned long pfn)
454{
455#ifdef CONFIG_SPARSEMEM
f1eca35a 456 return section_to_usemap(__pfn_to_section(pfn));
0b423ca2
MG
457#else
458 return page_zone(page)->pageblock_flags;
459#endif /* CONFIG_SPARSEMEM */
460}
461
ca891f41 462static inline int pfn_to_bitidx(const struct page *page, unsigned long pfn)
0b423ca2
MG
463{
464#ifdef CONFIG_SPARSEMEM
465 pfn &= (PAGES_PER_SECTION-1);
0b423ca2
MG
466#else
467 pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
0b423ca2 468#endif /* CONFIG_SPARSEMEM */
399b795b 469 return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
0b423ca2
MG
470}
471
535b81e2 472static __always_inline
ca891f41 473unsigned long __get_pfnblock_flags_mask(const struct page *page,
0b423ca2 474 unsigned long pfn,
0b423ca2
MG
475 unsigned long mask)
476{
477 unsigned long *bitmap;
478 unsigned long bitidx, word_bitidx;
479 unsigned long word;
480
481 bitmap = get_pageblock_bitmap(page, pfn);
482 bitidx = pfn_to_bitidx(page, pfn);
483 word_bitidx = bitidx / BITS_PER_LONG;
484 bitidx &= (BITS_PER_LONG-1);
485
486 word = bitmap[word_bitidx];
d93d5ab9 487 return (word >> bitidx) & mask;
0b423ca2
MG
488}
489
a00cda3f
MCC
490/**
491 * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
492 * @page: The page within the block of interest
493 * @pfn: The target page frame number
494 * @mask: mask of bits that the caller is interested in
495 *
496 * Return: pageblock_bits flags
497 */
ca891f41
MWO
498unsigned long get_pfnblock_flags_mask(const struct page *page,
499 unsigned long pfn, unsigned long mask)
0b423ca2 500{
535b81e2 501 return __get_pfnblock_flags_mask(page, pfn, mask);
0b423ca2
MG
502}
503
ca891f41
MWO
504static __always_inline int get_pfnblock_migratetype(const struct page *page,
505 unsigned long pfn)
0b423ca2 506{
535b81e2 507 return __get_pfnblock_flags_mask(page, pfn, MIGRATETYPE_MASK);
0b423ca2
MG
508}
509
510/**
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
0b423ca2
MG
515 * @mask: mask of bits that the caller is interested in
516 */
517void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
518 unsigned long pfn,
0b423ca2
MG
519 unsigned long mask)
520{
521 unsigned long *bitmap;
522 unsigned long bitidx, word_bitidx;
523 unsigned long old_word, word;
524
525 BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
125b860b 526 BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits));
0b423ca2
MG
527
528 bitmap = get_pageblock_bitmap(page, pfn);
529 bitidx = pfn_to_bitidx(page, pfn);
530 word_bitidx = bitidx / BITS_PER_LONG;
531 bitidx &= (BITS_PER_LONG-1);
532
533 VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
534
d93d5ab9
WY
535 mask <<= bitidx;
536 flags <<= bitidx;
0b423ca2
MG
537
538 word = READ_ONCE(bitmap[word_bitidx]);
539 for (;;) {
540 old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
541 if (word == old_word)
542 break;
543 word = old_word;
544 }
545}
3a80a7fa 546
ee6f509c 547void set_pageblock_migratetype(struct page *page, int migratetype)
b2a0ac88 548{
5d0f3f72
KM
549 if (unlikely(page_group_by_mobility_disabled &&
550 migratetype < MIGRATE_PCPTYPES))
49255c61
MG
551 migratetype = MIGRATE_UNMOVABLE;
552
d93d5ab9 553 set_pfnblock_flags_mask(page, (unsigned long)migratetype,
535b81e2 554 page_to_pfn(page), MIGRATETYPE_MASK);
b2a0ac88
MG
555}
556
13e7444b 557#ifdef CONFIG_DEBUG_VM
c6a57e19 558static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
1da177e4 559{
bdc8cb98
DH
560 int ret = 0;
561 unsigned seq;
562 unsigned long pfn = page_to_pfn(page);
b5e6a5a2 563 unsigned long sp, start_pfn;
c6a57e19 564
bdc8cb98
DH
565 do {
566 seq = zone_span_seqbegin(zone);
b5e6a5a2
CS
567 start_pfn = zone->zone_start_pfn;
568 sp = zone->spanned_pages;
108bcc96 569 if (!zone_spans_pfn(zone, pfn))
bdc8cb98
DH
570 ret = 1;
571 } while (zone_span_seqretry(zone, seq));
572
b5e6a5a2 573 if (ret)
613813e8
DH
574 pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
575 pfn, zone_to_nid(zone), zone->name,
576 start_pfn, start_pfn + sp);
b5e6a5a2 577
bdc8cb98 578 return ret;
c6a57e19
DH
579}
580
581static int page_is_consistent(struct zone *zone, struct page *page)
582{
1da177e4 583 if (zone != page_zone(page))
c6a57e19
DH
584 return 0;
585
586 return 1;
587}
588/*
589 * Temporary debugging check for pages not lying within a given zone.
590 */
d73d3c9f 591static int __maybe_unused bad_range(struct zone *zone, struct page *page)
c6a57e19
DH
592{
593 if (page_outside_zone_boundaries(zone, page))
1da177e4 594 return 1;
c6a57e19
DH
595 if (!page_is_consistent(zone, page))
596 return 1;
597
1da177e4
LT
598 return 0;
599}
13e7444b 600#else
d73d3c9f 601static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
13e7444b
NP
602{
603 return 0;
604}
605#endif
606
82a3241a 607static void bad_page(struct page *page, const char *reason)
1da177e4 608{
d936cf9b
HD
609 static unsigned long resume;
610 static unsigned long nr_shown;
611 static unsigned long nr_unshown;
612
613 /*
614 * Allow a burst of 60 reports, then keep quiet for that minute;
615 * or allow a steady drip of one report per second.
616 */
617 if (nr_shown == 60) {
618 if (time_before(jiffies, resume)) {
619 nr_unshown++;
620 goto out;
621 }
622 if (nr_unshown) {
ff8e8116 623 pr_alert(
1e9e6365 624 "BUG: Bad page state: %lu messages suppressed\n",
d936cf9b
HD
625 nr_unshown);
626 nr_unshown = 0;
627 }
628 nr_shown = 0;
629 }
630 if (nr_shown++ == 0)
631 resume = jiffies + 60 * HZ;
632
ff8e8116 633 pr_alert("BUG: Bad page state in process %s pfn:%05lx\n",
3dc14741 634 current->comm, page_to_pfn(page));
d2f07ec0 635 dump_page(page, reason);
3dc14741 636
4f31888c 637 print_modules();
1da177e4 638 dump_stack();
d936cf9b 639out:
8cc3b392 640 /* Leave bad fields for debug, except PageBuddy could make trouble */
22b751c3 641 page_mapcount_reset(page); /* remove PageBuddy */
373d4d09 642 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1da177e4
LT
643}
644
44042b44
MG
645static inline unsigned int order_to_pindex(int migratetype, int order)
646{
647 int base = order;
648
649#ifdef CONFIG_TRANSPARENT_HUGEPAGE
650 if (order > PAGE_ALLOC_COSTLY_ORDER) {
651 VM_BUG_ON(order != pageblock_order);
652 base = PAGE_ALLOC_COSTLY_ORDER + 1;
653 }
654#else
655 VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER);
656#endif
657
658 return (MIGRATE_PCPTYPES * base) + migratetype;
659}
660
661static inline int pindex_to_order(unsigned int pindex)
662{
663 int order = pindex / MIGRATE_PCPTYPES;
664
665#ifdef CONFIG_TRANSPARENT_HUGEPAGE
ea808b4e 666 if (order > PAGE_ALLOC_COSTLY_ORDER)
44042b44 667 order = pageblock_order;
44042b44
MG
668#else
669 VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER);
670#endif
671
672 return order;
673}
674
675static inline bool pcp_allowed_order(unsigned int order)
676{
677 if (order <= PAGE_ALLOC_COSTLY_ORDER)
678 return true;
679#ifdef CONFIG_TRANSPARENT_HUGEPAGE
680 if (order == pageblock_order)
681 return true;
682#endif
683 return false;
684}
685
21d02f8f
MG
686static inline void free_the_page(struct page *page, unsigned int order)
687{
44042b44
MG
688 if (pcp_allowed_order(order)) /* Via pcp? */
689 free_unref_page(page, order);
21d02f8f
MG
690 else
691 __free_pages_ok(page, order, FPI_NONE);
692}
693
1da177e4
LT
694/*
695 * Higher-order pages are called "compound pages". They are structured thusly:
696 *
1d798ca3 697 * The first PAGE_SIZE page is called the "head page" and have PG_head set.
1da177e4 698 *
1d798ca3
KS
699 * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
700 * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
1da177e4 701 *
1d798ca3
KS
702 * The first tail page's ->compound_dtor holds the offset in array of compound
703 * page destructors. See compound_page_dtors.
1da177e4 704 *
1d798ca3 705 * The first tail page's ->compound_order holds the order of allocation.
41d78ba5 706 * This usage means that zero-order pages may not be compound.
1da177e4 707 */
d98c7a09 708
9a982250 709void free_compound_page(struct page *page)
d98c7a09 710{
bbc6b703 711 mem_cgroup_uncharge(page_folio(page));
44042b44 712 free_the_page(page, compound_order(page));
d98c7a09
HD
713}
714
5b24eeef
JM
715static void prep_compound_head(struct page *page, unsigned int order)
716{
717 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
718 set_compound_order(page, order);
719 atomic_set(compound_mapcount_ptr(page), -1);
5232c63f 720 atomic_set(compound_pincount_ptr(page), 0);
5b24eeef
JM
721}
722
723static void prep_compound_tail(struct page *head, int tail_idx)
724{
725 struct page *p = head + tail_idx;
726
727 p->mapping = TAIL_MAPPING;
728 set_compound_head(p, head);
729}
730
d00181b9 731void prep_compound_page(struct page *page, unsigned int order)
18229df5
AW
732{
733 int i;
734 int nr_pages = 1 << order;
735
18229df5 736 __SetPageHead(page);
5b24eeef
JM
737 for (i = 1; i < nr_pages; i++)
738 prep_compound_tail(page, i);
1378a5ee 739
5b24eeef 740 prep_compound_head(page, order);
18229df5
AW
741}
742
c0a32fc5
SG
743#ifdef CONFIG_DEBUG_PAGEALLOC
744unsigned int _debug_guardpage_minorder;
96a2b03f 745
8e57f8ac
VB
746bool _debug_pagealloc_enabled_early __read_mostly
747 = IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
748EXPORT_SYMBOL(_debug_pagealloc_enabled_early);
96a2b03f 749DEFINE_STATIC_KEY_FALSE(_debug_pagealloc_enabled);
505f6d22 750EXPORT_SYMBOL(_debug_pagealloc_enabled);
96a2b03f
VB
751
752DEFINE_STATIC_KEY_FALSE(_debug_guardpage_enabled);
e30825f1 753
031bc574
JK
754static int __init early_debug_pagealloc(char *buf)
755{
8e57f8ac 756 return kstrtobool(buf, &_debug_pagealloc_enabled_early);
031bc574
JK
757}
758early_param("debug_pagealloc", early_debug_pagealloc);
759
c0a32fc5
SG
760static int __init debug_guardpage_minorder_setup(char *buf)
761{
762 unsigned long res;
763
764 if (kstrtoul(buf, 10, &res) < 0 || res > MAX_ORDER / 2) {
1170532b 765 pr_err("Bad debug_guardpage_minorder value\n");
c0a32fc5
SG
766 return 0;
767 }
768 _debug_guardpage_minorder = res;
1170532b 769 pr_info("Setting debug_guardpage_minorder to %lu\n", res);
c0a32fc5
SG
770 return 0;
771}
f1c1e9f7 772early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
c0a32fc5 773
acbc15a4 774static inline bool set_page_guard(struct zone *zone, struct page *page,
2847cf95 775 unsigned int order, int migratetype)
c0a32fc5 776{
e30825f1 777 if (!debug_guardpage_enabled())
acbc15a4
JK
778 return false;
779
780 if (order >= debug_guardpage_minorder())
781 return false;
e30825f1 782
3972f6bb 783 __SetPageGuard(page);
2847cf95
JK
784 INIT_LIST_HEAD(&page->lru);
785 set_page_private(page, order);
786 /* Guard pages are not available for any usage */
787 __mod_zone_freepage_state(zone, -(1 << order), migratetype);
acbc15a4
JK
788
789 return true;
c0a32fc5
SG
790}
791
2847cf95
JK
792static inline void clear_page_guard(struct zone *zone, struct page *page,
793 unsigned int order, int migratetype)
c0a32fc5 794{
e30825f1
JK
795 if (!debug_guardpage_enabled())
796 return;
797
3972f6bb 798 __ClearPageGuard(page);
e30825f1 799
2847cf95
JK
800 set_page_private(page, 0);
801 if (!is_migrate_isolate(migratetype))
802 __mod_zone_freepage_state(zone, (1 << order), migratetype);
c0a32fc5
SG
803}
804#else
acbc15a4
JK
805static inline bool set_page_guard(struct zone *zone, struct page *page,
806 unsigned int order, int migratetype) { return false; }
2847cf95
JK
807static inline void clear_page_guard(struct zone *zone, struct page *page,
808 unsigned int order, int migratetype) {}
c0a32fc5
SG
809#endif
810
04013513
VB
811/*
812 * Enable static keys related to various memory debugging and hardening options.
813 * Some override others, and depend on early params that are evaluated in the
814 * order of appearance. So we need to first gather the full picture of what was
815 * enabled, and then make decisions.
816 */
817void init_mem_debugging_and_hardening(void)
818{
9df65f52
ST
819 bool page_poisoning_requested = false;
820
821#ifdef CONFIG_PAGE_POISONING
822 /*
823 * Page poisoning is debug page alloc for some arches. If
824 * either of those options are enabled, enable poisoning.
825 */
826 if (page_poisoning_enabled() ||
827 (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_DEBUG_PAGEALLOC) &&
828 debug_pagealloc_enabled())) {
829 static_branch_enable(&_page_poisoning_enabled);
830 page_poisoning_requested = true;
831 }
832#endif
833
69e5d322
ST
834 if ((_init_on_alloc_enabled_early || _init_on_free_enabled_early) &&
835 page_poisoning_requested) {
836 pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, "
837 "will take precedence over init_on_alloc and init_on_free\n");
838 _init_on_alloc_enabled_early = false;
839 _init_on_free_enabled_early = false;
04013513
VB
840 }
841
69e5d322
ST
842 if (_init_on_alloc_enabled_early)
843 static_branch_enable(&init_on_alloc);
844 else
845 static_branch_disable(&init_on_alloc);
846
847 if (_init_on_free_enabled_early)
848 static_branch_enable(&init_on_free);
849 else
850 static_branch_disable(&init_on_free);
851
04013513
VB
852#ifdef CONFIG_DEBUG_PAGEALLOC
853 if (!debug_pagealloc_enabled())
854 return;
855
856 static_branch_enable(&_debug_pagealloc_enabled);
857
858 if (!debug_guardpage_minorder())
859 return;
860
861 static_branch_enable(&_debug_guardpage_enabled);
862#endif
863}
864
ab130f91 865static inline void set_buddy_order(struct page *page, unsigned int order)
6aa3001b 866{
4c21e2f2 867 set_page_private(page, order);
676165a8 868 __SetPageBuddy(page);
1da177e4
LT
869}
870
5e1f0f09
MG
871#ifdef CONFIG_COMPACTION
872static inline struct capture_control *task_capc(struct zone *zone)
873{
874 struct capture_control *capc = current->capture_control;
875
deba0487 876 return unlikely(capc) &&
5e1f0f09
MG
877 !(current->flags & PF_KTHREAD) &&
878 !capc->page &&
deba0487 879 capc->cc->zone == zone ? capc : NULL;
5e1f0f09
MG
880}
881
882static inline bool
883compaction_capture(struct capture_control *capc, struct page *page,
884 int order, int migratetype)
885{
886 if (!capc || order != capc->cc->order)
887 return false;
888
889 /* Do not accidentally pollute CMA or isolated regions*/
890 if (is_migrate_cma(migratetype) ||
891 is_migrate_isolate(migratetype))
892 return false;
893
894 /*
f0953a1b 895 * Do not let lower order allocations pollute a movable pageblock.
5e1f0f09
MG
896 * This might let an unmovable request use a reclaimable pageblock
897 * and vice-versa but no more than normal fallback logic which can
898 * have trouble finding a high-order free page.
899 */
900 if (order < pageblock_order && migratetype == MIGRATE_MOVABLE)
901 return false;
902
903 capc->page = page;
904 return true;
905}
906
907#else
908static inline struct capture_control *task_capc(struct zone *zone)
909{
910 return NULL;
911}
912
913static inline bool
914compaction_capture(struct capture_control *capc, struct page *page,
915 int order, int migratetype)
916{
917 return false;
918}
919#endif /* CONFIG_COMPACTION */
920
6ab01363
AD
921/* Used for pages not on another list */
922static inline void add_to_free_list(struct page *page, struct zone *zone,
923 unsigned int order, int migratetype)
924{
925 struct free_area *area = &zone->free_area[order];
926
927 list_add(&page->lru, &area->free_list[migratetype]);
928 area->nr_free++;
929}
930
931/* Used for pages not on another list */
932static inline void add_to_free_list_tail(struct page *page, struct zone *zone,
933 unsigned int order, int migratetype)
934{
935 struct free_area *area = &zone->free_area[order];
936
937 list_add_tail(&page->lru, &area->free_list[migratetype]);
938 area->nr_free++;
939}
940
293ffa5e
DH
941/*
942 * Used for pages which are on another list. Move the pages to the tail
943 * of the list - so the moved pages won't immediately be considered for
944 * allocation again (e.g., optimization for memory onlining).
945 */
6ab01363
AD
946static inline void move_to_free_list(struct page *page, struct zone *zone,
947 unsigned int order, int migratetype)
948{
949 struct free_area *area = &zone->free_area[order];
950
293ffa5e 951 list_move_tail(&page->lru, &area->free_list[migratetype]);
6ab01363
AD
952}
953
954static inline void del_page_from_free_list(struct page *page, struct zone *zone,
955 unsigned int order)
956{
36e66c55
AD
957 /* clear reported state and update reported page count */
958 if (page_reported(page))
959 __ClearPageReported(page);
960
6ab01363
AD
961 list_del(&page->lru);
962 __ClearPageBuddy(page);
963 set_page_private(page, 0);
964 zone->free_area[order].nr_free--;
965}
966
a2129f24
AD
967/*
968 * If this is not the largest possible page, check if the buddy
969 * of the next-highest order is free. If it is, it's possible
970 * that pages are being freed that will coalesce soon. In case,
971 * that is happening, add the free page to the tail of the list
972 * so it's less likely to be used soon and more likely to be merged
973 * as a higher order page
974 */
975static inline bool
976buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
977 struct page *page, unsigned int order)
978{
8170ac47
ZY
979 unsigned long higher_page_pfn;
980 struct page *higher_page;
a2129f24
AD
981
982 if (order >= MAX_ORDER - 2)
983 return false;
984
8170ac47
ZY
985 higher_page_pfn = buddy_pfn & pfn;
986 higher_page = page + (higher_page_pfn - pfn);
a2129f24 987
8170ac47
ZY
988 return find_buddy_page_pfn(higher_page, higher_page_pfn, order + 1,
989 NULL) != NULL;
a2129f24
AD
990}
991
1da177e4
LT
992/*
993 * Freeing function for a buddy system allocator.
994 *
995 * The concept of a buddy system is to maintain direct-mapped table
996 * (containing bit values) for memory blocks of various "orders".
997 * The bottom level table contains the map for the smallest allocatable
998 * units of memory (here, pages), and each level above it describes
999 * pairs of units from the levels below, hence, "buddies".
1000 * At a high level, all that happens here is marking the table entry
1001 * at the bottom level available, and propagating the changes upward
1002 * as necessary, plus some accounting needed to play nicely with other
1003 * parts of the VM system.
1004 * At each level, we keep a list of pages, which are heads of continuous
6e292b9b
MW
1005 * free pages of length of (1 << order) and marked with PageBuddy.
1006 * Page's order is recorded in page_private(page) field.
1da177e4 1007 * So when we are allocating or freeing one, we can derive the state of the
5f63b720
MN
1008 * other. That is, if we allocate a small block, and both were
1009 * free, the remainder of the region must be split into blocks.
1da177e4 1010 * If a block is freed, and its buddy is also free, then this
5f63b720 1011 * triggers coalescing into a block of larger size.
1da177e4 1012 *
6d49e352 1013 * -- nyc
1da177e4
LT
1014 */
1015
48db57f8 1016static inline void __free_one_page(struct page *page,
dc4b0caf 1017 unsigned long pfn,
ed0ae21d 1018 struct zone *zone, unsigned int order,
f04a5d5d 1019 int migratetype, fpi_t fpi_flags)
1da177e4 1020{
a2129f24 1021 struct capture_control *capc = task_capc(zone);
3f649ab7 1022 unsigned long buddy_pfn;
a2129f24 1023 unsigned long combined_pfn;
a2129f24
AD
1024 struct page *buddy;
1025 bool to_tail;
d9dddbf5 1026
d29bb978 1027 VM_BUG_ON(!zone_is_initialized(zone));
6e9f0d58 1028 VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
1da177e4 1029
ed0ae21d 1030 VM_BUG_ON(migratetype == -1);
d9dddbf5 1031 if (likely(!is_migrate_isolate(migratetype)))
8f82b55d 1032 __mod_zone_freepage_state(zone, 1 << order, migratetype);
ed0ae21d 1033
76741e77 1034 VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
309381fe 1035 VM_BUG_ON_PAGE(bad_range(zone, page), page);
1da177e4 1036
bb0e28eb 1037 while (order < MAX_ORDER - 1) {
5e1f0f09
MG
1038 if (compaction_capture(capc, page, order, migratetype)) {
1039 __mod_zone_freepage_state(zone, -(1 << order),
1040 migratetype);
1041 return;
1042 }
13ad59df 1043
8170ac47
ZY
1044 buddy = find_buddy_page_pfn(page, pfn, order, &buddy_pfn);
1045 if (!buddy)
d9dddbf5 1046 goto done_merging;
bb0e28eb
ZY
1047
1048 if (unlikely(order >= pageblock_order)) {
1049 /*
1050 * We want to prevent merge between freepages on pageblock
1051 * without fallbacks and normal pageblock. Without this,
1052 * pageblock isolation could cause incorrect freepage or CMA
1053 * accounting or HIGHATOMIC accounting.
1054 */
1055 int buddy_mt = get_pageblock_migratetype(buddy);
1056
1057 if (migratetype != buddy_mt
1058 && (!migratetype_is_mergeable(migratetype) ||
1059 !migratetype_is_mergeable(buddy_mt)))
1060 goto done_merging;
1061 }
1062
c0a32fc5
SG
1063 /*
1064 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
1065 * merge with it and move up one order.
1066 */
b03641af 1067 if (page_is_guard(buddy))
2847cf95 1068 clear_page_guard(zone, buddy, order, migratetype);
b03641af 1069 else
6ab01363 1070 del_page_from_free_list(buddy, zone, order);
76741e77
VB
1071 combined_pfn = buddy_pfn & pfn;
1072 page = page + (combined_pfn - pfn);
1073 pfn = combined_pfn;
1da177e4
LT
1074 order++;
1075 }
d9dddbf5
VB
1076
1077done_merging:
ab130f91 1078 set_buddy_order(page, order);
6dda9d55 1079
47b6a24a
DH
1080 if (fpi_flags & FPI_TO_TAIL)
1081 to_tail = true;
1082 else if (is_shuffle_order(order))
a2129f24 1083 to_tail = shuffle_pick_tail();
97500a4a 1084 else
a2129f24 1085 to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
97500a4a 1086
a2129f24 1087 if (to_tail)
6ab01363 1088 add_to_free_list_tail(page, zone, order, migratetype);
a2129f24 1089 else
6ab01363 1090 add_to_free_list(page, zone, order, migratetype);
36e66c55
AD
1091
1092 /* Notify page reporting subsystem of freed page */
f04a5d5d 1093 if (!(fpi_flags & FPI_SKIP_REPORT_NOTIFY))
36e66c55 1094 page_reporting_notify_free(order);
1da177e4
LT
1095}
1096
b2c9e2fb
ZY
1097/**
1098 * split_free_page() -- split a free page at split_pfn_offset
1099 * @free_page: the original free page
1100 * @order: the order of the page
1101 * @split_pfn_offset: split offset within the page
1102 *
1103 * It is used when the free page crosses two pageblocks with different migratetypes
1104 * at split_pfn_offset within the page. The split free page will be put into
1105 * separate migratetype lists afterwards. Otherwise, the function achieves
1106 * nothing.
1107 */
1108void split_free_page(struct page *free_page,
1109 int order, unsigned long split_pfn_offset)
1110{
1111 struct zone *zone = page_zone(free_page);
1112 unsigned long free_page_pfn = page_to_pfn(free_page);
1113 unsigned long pfn;
1114 unsigned long flags;
1115 int free_page_order;
1116
1117 spin_lock_irqsave(&zone->lock, flags);
1118 del_page_from_free_list(free_page, zone, order);
1119 for (pfn = free_page_pfn;
1120 pfn < free_page_pfn + (1UL << order);) {
1121 int mt = get_pfnblock_migratetype(pfn_to_page(pfn), pfn);
1122
1123 free_page_order = ffs(split_pfn_offset) - 1;
1124 __free_one_page(pfn_to_page(pfn), pfn, zone, free_page_order,
1125 mt, FPI_NONE);
1126 pfn += 1UL << free_page_order;
1127 split_pfn_offset -= (1UL << free_page_order);
1128 /* we have done the first part, now switch to second part */
1129 if (split_pfn_offset == 0)
1130 split_pfn_offset = (1UL << order) - (pfn - free_page_pfn);
1131 }
1132 spin_unlock_irqrestore(&zone->lock, flags);
1133}
7bfec6f4
MG
1134/*
1135 * A bad page could be due to a number of fields. Instead of multiple branches,
1136 * try and check multiple fields with one check. The caller must do a detailed
1137 * check if necessary.
1138 */
1139static inline bool page_expected_state(struct page *page,
1140 unsigned long check_flags)
1141{
1142 if (unlikely(atomic_read(&page->_mapcount) != -1))
1143 return false;
1144
1145 if (unlikely((unsigned long)page->mapping |
1146 page_ref_count(page) |
1147#ifdef CONFIG_MEMCG
48060834 1148 page->memcg_data |
7bfec6f4
MG
1149#endif
1150 (page->flags & check_flags)))
1151 return false;
1152
1153 return true;
1154}
1155
58b7f119 1156static const char *page_bad_reason(struct page *page, unsigned long flags)
1da177e4 1157{
82a3241a 1158 const char *bad_reason = NULL;
f0b791a3 1159
53f9263b 1160 if (unlikely(atomic_read(&page->_mapcount) != -1))
f0b791a3
DH
1161 bad_reason = "nonzero mapcount";
1162 if (unlikely(page->mapping != NULL))
1163 bad_reason = "non-NULL mapping";
fe896d18 1164 if (unlikely(page_ref_count(page) != 0))
0139aa7b 1165 bad_reason = "nonzero _refcount";
58b7f119
WY
1166 if (unlikely(page->flags & flags)) {
1167 if (flags == PAGE_FLAGS_CHECK_AT_PREP)
1168 bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag(s) set";
1169 else
1170 bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
f0b791a3 1171 }
9edad6ea 1172#ifdef CONFIG_MEMCG
48060834 1173 if (unlikely(page->memcg_data))
9edad6ea
JW
1174 bad_reason = "page still charged to cgroup";
1175#endif
58b7f119
WY
1176 return bad_reason;
1177}
1178
1179static void check_free_page_bad(struct page *page)
1180{
1181 bad_page(page,
1182 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_FREE));
bb552ac6
MG
1183}
1184
534fe5e3 1185static inline int check_free_page(struct page *page)
bb552ac6 1186{
da838d4f 1187 if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
bb552ac6 1188 return 0;
bb552ac6
MG
1189
1190 /* Something has gone sideways, find it */
0d0c48a2 1191 check_free_page_bad(page);
7bfec6f4 1192 return 1;
1da177e4
LT
1193}
1194
4db7548c
MG
1195static int free_tail_pages_check(struct page *head_page, struct page *page)
1196{
1197 int ret = 1;
1198
1199 /*
1200 * We rely page->lru.next never has bit 0 set, unless the page
1201 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
1202 */
1203 BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
1204
1205 if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
1206 ret = 0;
1207 goto out;
1208 }
1209 switch (page - head_page) {
1210 case 1:
4da1984e 1211 /* the first tail page: ->mapping may be compound_mapcount() */
4db7548c 1212 if (unlikely(compound_mapcount(page))) {
82a3241a 1213 bad_page(page, "nonzero compound_mapcount");
4db7548c
MG
1214 goto out;
1215 }
1216 break;
1217 case 2:
1218 /*
1219 * the second tail page: ->mapping is
fa3015b7 1220 * deferred_list.next -- ignore value.
4db7548c
MG
1221 */
1222 break;
1223 default:
1224 if (page->mapping != TAIL_MAPPING) {
82a3241a 1225 bad_page(page, "corrupted mapping in tail page");
4db7548c
MG
1226 goto out;
1227 }
1228 break;
1229 }
1230 if (unlikely(!PageTail(page))) {
82a3241a 1231 bad_page(page, "PageTail not set");
4db7548c
MG
1232 goto out;
1233 }
1234 if (unlikely(compound_head(page) != head_page)) {
82a3241a 1235 bad_page(page, "compound_head not consistent");
4db7548c
MG
1236 goto out;
1237 }
1238 ret = 0;
1239out:
1240 page->mapping = NULL;
1241 clear_compound_head(page);
1242 return ret;
1243}
1244
94ae8b83
AK
1245/*
1246 * Skip KASAN memory poisoning when either:
1247 *
1248 * 1. Deferred memory initialization has not yet completed,
1249 * see the explanation below.
1250 * 2. Skipping poisoning is requested via FPI_SKIP_KASAN_POISON,
1251 * see the comment next to it.
1252 * 3. Skipping poisoning is requested via __GFP_SKIP_KASAN_POISON,
1253 * see the comment next to it.
1254 *
1255 * Poisoning pages during deferred memory init will greatly lengthen the
1256 * process and cause problem in large memory systems as the deferred pages
1257 * initialization is done with interrupt disabled.
1258 *
1259 * Assuming that there will be no reference to those newly initialized
1260 * pages before they are ever allocated, this should have no effect on
1261 * KASAN memory tracking as the poison will be properly inserted at page
1262 * allocation time. The only corner case is when pages are allocated by
1263 * on-demand allocation and then freed again before the deferred pages
1264 * initialization is done, but this is not likely to happen.
1265 */
1266static inline bool should_skip_kasan_poison(struct page *page, fpi_t fpi_flags)
1267{
1268 return deferred_pages_enabled() ||
1269 (!IS_ENABLED(CONFIG_KASAN_GENERIC) &&
1270 (fpi_flags & FPI_SKIP_KASAN_POISON)) ||
1271 PageSkipKASanPoison(page);
1272}
1273
5b2c0713 1274static void kernel_init_free_pages(struct page *page, int numpages)
6471384a
AP
1275{
1276 int i;
1277
9e15afa5
QC
1278 /* s390's use of memset() could override KASAN redzones. */
1279 kasan_disable_current();
aa1ef4d7 1280 for (i = 0; i < numpages; i++) {
acb35b17 1281 u8 tag = page_kasan_tag(page + i);
aa1ef4d7 1282 page_kasan_tag_reset(page + i);
6471384a 1283 clear_highpage(page + i);
acb35b17 1284 page_kasan_tag_set(page + i, tag);
aa1ef4d7 1285 }
9e15afa5 1286 kasan_enable_current();
6471384a
AP
1287}
1288
e2769dbd 1289static __always_inline bool free_pages_prepare(struct page *page,
2c335680 1290 unsigned int order, bool check_free, fpi_t fpi_flags)
4db7548c 1291{
e2769dbd 1292 int bad = 0;
c3525330 1293 bool init = want_init_on_free();
4db7548c 1294
4db7548c
MG
1295 VM_BUG_ON_PAGE(PageTail(page), page);
1296
e2769dbd 1297 trace_mm_page_free(page, order);
e2769dbd 1298
79f5f8fa
OS
1299 if (unlikely(PageHWPoison(page)) && !order) {
1300 /*
1301 * Do not let hwpoison pages hit pcplists/buddy
1302 * Untie memcg state and reset page's owner
1303 */
18b2db3b 1304 if (memcg_kmem_enabled() && PageMemcgKmem(page))
79f5f8fa
OS
1305 __memcg_kmem_uncharge_page(page, order);
1306 reset_page_owner(page, order);
df4e817b 1307 page_table_check_free(page, order);
79f5f8fa
OS
1308 return false;
1309 }
1310
e2769dbd
MG
1311 /*
1312 * Check tail pages before head page information is cleared to
1313 * avoid checking PageCompound for order-0 pages.
1314 */
1315 if (unlikely(order)) {
1316 bool compound = PageCompound(page);
1317 int i;
1318
1319 VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
4db7548c 1320
eac96c3e 1321 if (compound) {
9a73f61b 1322 ClearPageDoubleMap(page);
eac96c3e
YS
1323 ClearPageHasHWPoisoned(page);
1324 }
e2769dbd
MG
1325 for (i = 1; i < (1 << order); i++) {
1326 if (compound)
1327 bad += free_tail_pages_check(page, page + i);
534fe5e3 1328 if (unlikely(check_free_page(page + i))) {
e2769dbd
MG
1329 bad++;
1330 continue;
1331 }
1332 (page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1333 }
1334 }
bda807d4 1335 if (PageMappingFlags(page))
4db7548c 1336 page->mapping = NULL;
18b2db3b 1337 if (memcg_kmem_enabled() && PageMemcgKmem(page))
f4b00eab 1338 __memcg_kmem_uncharge_page(page, order);
e2769dbd 1339 if (check_free)
534fe5e3 1340 bad += check_free_page(page);
e2769dbd
MG
1341 if (bad)
1342 return false;
4db7548c 1343
e2769dbd
MG
1344 page_cpupid_reset_last(page);
1345 page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1346 reset_page_owner(page, order);
df4e817b 1347 page_table_check_free(page, order);
4db7548c
MG
1348
1349 if (!PageHighMem(page)) {
1350 debug_check_no_locks_freed(page_address(page),
e2769dbd 1351 PAGE_SIZE << order);
4db7548c 1352 debug_check_no_obj_freed(page_address(page),
e2769dbd 1353 PAGE_SIZE << order);
4db7548c 1354 }
6471384a 1355
8db26a3d
VB
1356 kernel_poison_pages(page, 1 << order);
1357
f9d79e8d 1358 /*
1bb5eab3 1359 * As memory initialization might be integrated into KASAN,
7c13c163 1360 * KASAN poisoning and memory initialization code must be
1bb5eab3
AK
1361 * kept together to avoid discrepancies in behavior.
1362 *
f9d79e8d
AK
1363 * With hardware tag-based KASAN, memory tags must be set before the
1364 * page becomes unavailable via debug_pagealloc or arch_free_page.
1365 */
487a32ec 1366 if (!should_skip_kasan_poison(page, fpi_flags)) {
c3525330 1367 kasan_poison_pages(page, order, init);
f9d79e8d 1368
db8a0477
AK
1369 /* Memory is already initialized if KASAN did it internally. */
1370 if (kasan_has_integrated_init())
1371 init = false;
1372 }
1373 if (init)
1374 kernel_init_free_pages(page, 1 << order);
1375
234fdce8
QC
1376 /*
1377 * arch_free_page() can make the page's contents inaccessible. s390
1378 * does this. So nothing which can access the page's contents should
1379 * happen after this.
1380 */
1381 arch_free_page(page, order);
1382
77bc7fd6 1383 debug_pagealloc_unmap_pages(page, 1 << order);
d6332692 1384
4db7548c
MG
1385 return true;
1386}
1387
e2769dbd 1388#ifdef CONFIG_DEBUG_VM
4462b32c
VB
1389/*
1390 * With DEBUG_VM enabled, order-0 pages are checked immediately when being freed
1391 * to pcp lists. With debug_pagealloc also enabled, they are also rechecked when
1392 * moved from pcp lists to free lists.
1393 */
44042b44 1394static bool free_pcp_prepare(struct page *page, unsigned int order)
e2769dbd 1395{
44042b44 1396 return free_pages_prepare(page, order, true, FPI_NONE);
e2769dbd
MG
1397}
1398
4462b32c 1399static bool bulkfree_pcp_prepare(struct page *page)
e2769dbd 1400{
8e57f8ac 1401 if (debug_pagealloc_enabled_static())
534fe5e3 1402 return check_free_page(page);
4462b32c
VB
1403 else
1404 return false;
e2769dbd
MG
1405}
1406#else
4462b32c
VB
1407/*
1408 * With DEBUG_VM disabled, order-0 pages being freed are checked only when
1409 * moving from pcp lists to free list in order to reduce overhead. With
1410 * debug_pagealloc enabled, they are checked also immediately when being freed
1411 * to the pcp lists.
1412 */
44042b44 1413static bool free_pcp_prepare(struct page *page, unsigned int order)
e2769dbd 1414{
8e57f8ac 1415 if (debug_pagealloc_enabled_static())
44042b44 1416 return free_pages_prepare(page, order, true, FPI_NONE);
4462b32c 1417 else
44042b44 1418 return free_pages_prepare(page, order, false, FPI_NONE);
e2769dbd
MG
1419}
1420
4db7548c
MG
1421static bool bulkfree_pcp_prepare(struct page *page)
1422{
534fe5e3 1423 return check_free_page(page);
4db7548c
MG
1424}
1425#endif /* CONFIG_DEBUG_VM */
1426
1da177e4 1427/*
5f8dcc21 1428 * Frees a number of pages from the PCP lists
7cba630b 1429 * Assumes all pages on list are in same zone.
207f36ee 1430 * count is the number of pages to free.
1da177e4 1431 */
5f8dcc21 1432static void free_pcppages_bulk(struct zone *zone, int count,
fd56eef2
MG
1433 struct per_cpu_pages *pcp,
1434 int pindex)
1da177e4 1435{
35b6d770
MG
1436 int min_pindex = 0;
1437 int max_pindex = NR_PCP_LISTS - 1;
44042b44 1438 unsigned int order;
3777999d 1439 bool isolated_pageblocks;
8b10b465 1440 struct page *page;
f2260e6b 1441
88e8ac11
CTR
1442 /*
1443 * Ensure proper count is passed which otherwise would stuck in the
1444 * below while (list_empty(list)) loop.
1445 */
1446 count = min(pcp->count, count);
d61372bc
MG
1447
1448 /* Ensure requested pindex is drained first. */
1449 pindex = pindex - 1;
1450
8b10b465
MG
1451 /*
1452 * local_lock_irq held so equivalent to spin_lock_irqsave for
1453 * both PREEMPT_RT and non-PREEMPT_RT configurations.
1454 */
1455 spin_lock(&zone->lock);
1456 isolated_pageblocks = has_isolate_pageblock(zone);
1457
44042b44 1458 while (count > 0) {
5f8dcc21 1459 struct list_head *list;
fd56eef2 1460 int nr_pages;
5f8dcc21 1461
fd56eef2 1462 /* Remove pages from lists in a round-robin fashion. */
5f8dcc21 1463 do {
35b6d770
MG
1464 if (++pindex > max_pindex)
1465 pindex = min_pindex;
44042b44 1466 list = &pcp->lists[pindex];
35b6d770
MG
1467 if (!list_empty(list))
1468 break;
1469
1470 if (pindex == max_pindex)
1471 max_pindex--;
1472 if (pindex == min_pindex)
1473 min_pindex++;
1474 } while (1);
48db57f8 1475
44042b44 1476 order = pindex_to_order(pindex);
fd56eef2 1477 nr_pages = 1 << order;
44042b44 1478 BUILD_BUG_ON(MAX_ORDER >= (1<<NR_PCP_ORDER_WIDTH));
a6f9edd6 1479 do {
8b10b465
MG
1480 int mt;
1481
a16601c5 1482 page = list_last_entry(list, struct page, lru);
8b10b465
MG
1483 mt = get_pcppage_migratetype(page);
1484
0a5f4e5b 1485 /* must delete to avoid corrupting pcp list */
a6f9edd6 1486 list_del(&page->lru);
fd56eef2
MG
1487 count -= nr_pages;
1488 pcp->count -= nr_pages;
aa016d14 1489
4db7548c
MG
1490 if (bulkfree_pcp_prepare(page))
1491 continue;
1492
8b10b465
MG
1493 /* MIGRATE_ISOLATE page should not go to pcplists */
1494 VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1495 /* Pageblock could have been isolated meanwhile */
1496 if (unlikely(isolated_pageblocks))
1497 mt = get_pageblock_migratetype(page);
0a5f4e5b 1498
8b10b465
MG
1499 __free_one_page(page, page_to_pfn(page), zone, order, mt, FPI_NONE);
1500 trace_mm_page_pcpu_drain(page, order, mt);
1501 } while (count > 0 && !list_empty(list));
0a5f4e5b 1502 }
8b10b465 1503
d34b0733 1504 spin_unlock(&zone->lock);
1da177e4
LT
1505}
1506
dc4b0caf
MG
1507static void free_one_page(struct zone *zone,
1508 struct page *page, unsigned long pfn,
7aeb09f9 1509 unsigned int order,
7fef431b 1510 int migratetype, fpi_t fpi_flags)
1da177e4 1511{
df1acc85
MG
1512 unsigned long flags;
1513
1514 spin_lock_irqsave(&zone->lock, flags);
ad53f92e
JK
1515 if (unlikely(has_isolate_pageblock(zone) ||
1516 is_migrate_isolate(migratetype))) {
1517 migratetype = get_pfnblock_migratetype(page, pfn);
ad53f92e 1518 }
7fef431b 1519 __free_one_page(page, pfn, zone, order, migratetype, fpi_flags);
df1acc85 1520 spin_unlock_irqrestore(&zone->lock, flags);
48db57f8
NP
1521}
1522
1e8ce83c 1523static void __meminit __init_single_page(struct page *page, unsigned long pfn,
d0dc12e8 1524 unsigned long zone, int nid)
1e8ce83c 1525{
d0dc12e8 1526 mm_zero_struct_page(page);
1e8ce83c 1527 set_page_links(page, zone, nid, pfn);
1e8ce83c
RH
1528 init_page_count(page);
1529 page_mapcount_reset(page);
1530 page_cpupid_reset_last(page);
2813b9c0 1531 page_kasan_tag_reset(page);
1e8ce83c 1532
1e8ce83c
RH
1533 INIT_LIST_HEAD(&page->lru);
1534#ifdef WANT_PAGE_VIRTUAL
1535 /* The shift won't overflow because ZONE_NORMAL is below 4G. */
1536 if (!is_highmem_idx(zone))
1537 set_page_address(page, __va(pfn << PAGE_SHIFT));
1538#endif
1539}
1540
7e18adb4 1541#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
57148a64 1542static void __meminit init_reserved_page(unsigned long pfn)
7e18adb4
MG
1543{
1544 pg_data_t *pgdat;
1545 int nid, zid;
1546
1547 if (!early_page_uninitialised(pfn))
1548 return;
1549
1550 nid = early_pfn_to_nid(pfn);
1551 pgdat = NODE_DATA(nid);
1552
1553 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1554 struct zone *zone = &pgdat->node_zones[zid];
1555
86fb05b9 1556 if (zone_spans_pfn(zone, pfn))
7e18adb4
MG
1557 break;
1558 }
d0dc12e8 1559 __init_single_page(pfn_to_page(pfn), pfn, zid, nid);
7e18adb4
MG
1560}
1561#else
1562static inline void init_reserved_page(unsigned long pfn)
1563{
1564}
1565#endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1566
92923ca3
NZ
1567/*
1568 * Initialised pages do not have PageReserved set. This function is
1569 * called for each range allocated by the bootmem allocator and
1570 * marks the pages PageReserved. The remaining valid pages are later
1571 * sent to the buddy page allocator.
1572 */
4b50bcc7 1573void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
92923ca3
NZ
1574{
1575 unsigned long start_pfn = PFN_DOWN(start);
1576 unsigned long end_pfn = PFN_UP(end);
1577
7e18adb4
MG
1578 for (; start_pfn < end_pfn; start_pfn++) {
1579 if (pfn_valid(start_pfn)) {
1580 struct page *page = pfn_to_page(start_pfn);
1581
1582 init_reserved_page(start_pfn);
1d798ca3
KS
1583
1584 /* Avoid false-positive PageTail() */
1585 INIT_LIST_HEAD(&page->lru);
1586
d483da5b
AD
1587 /*
1588 * no need for atomic set_bit because the struct
1589 * page is not visible yet so nobody should
1590 * access it yet.
1591 */
1592 __SetPageReserved(page);
7e18adb4
MG
1593 }
1594 }
92923ca3
NZ
1595}
1596
7fef431b
DH
1597static void __free_pages_ok(struct page *page, unsigned int order,
1598 fpi_t fpi_flags)
ec95f53a 1599{
d34b0733 1600 unsigned long flags;
95e34412 1601 int migratetype;
dc4b0caf 1602 unsigned long pfn = page_to_pfn(page);
56f0e661 1603 struct zone *zone = page_zone(page);
ec95f53a 1604
2c335680 1605 if (!free_pages_prepare(page, order, true, fpi_flags))
ec95f53a
KM
1606 return;
1607
cfc47a28 1608 migratetype = get_pfnblock_migratetype(page, pfn);
dbbee9d5 1609
56f0e661 1610 spin_lock_irqsave(&zone->lock, flags);
56f0e661
MG
1611 if (unlikely(has_isolate_pageblock(zone) ||
1612 is_migrate_isolate(migratetype))) {
1613 migratetype = get_pfnblock_migratetype(page, pfn);
1614 }
1615 __free_one_page(page, pfn, zone, order, migratetype, fpi_flags);
1616 spin_unlock_irqrestore(&zone->lock, flags);
90249993 1617
d34b0733 1618 __count_vm_events(PGFREE, 1 << order);
1da177e4
LT
1619}
1620
a9cd410a 1621void __free_pages_core(struct page *page, unsigned int order)
a226f6c8 1622{
c3993076 1623 unsigned int nr_pages = 1 << order;
e2d0bd2b 1624 struct page *p = page;
c3993076 1625 unsigned int loop;
a226f6c8 1626
7fef431b
DH
1627 /*
1628 * When initializing the memmap, __init_single_page() sets the refcount
1629 * of all pages to 1 ("allocated"/"not free"). We have to set the
1630 * refcount of all involved pages to 0.
1631 */
e2d0bd2b
YL
1632 prefetchw(p);
1633 for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1634 prefetchw(p + 1);
c3993076
JW
1635 __ClearPageReserved(p);
1636 set_page_count(p, 0);
a226f6c8 1637 }
e2d0bd2b
YL
1638 __ClearPageReserved(p);
1639 set_page_count(p, 0);
c3993076 1640
9705bea5 1641 atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
7fef431b
DH
1642
1643 /*
1644 * Bypass PCP and place fresh pages right to the tail, primarily
1645 * relevant for memory onlining.
1646 */
2c335680 1647 __free_pages_ok(page, order, FPI_TO_TAIL | FPI_SKIP_KASAN_POISON);
a226f6c8
DH
1648}
1649
a9ee6cf5 1650#ifdef CONFIG_NUMA
7ace9917 1651
03e92a5e
MR
1652/*
1653 * During memory init memblocks map pfns to nids. The search is expensive and
1654 * this caches recent lookups. The implementation of __early_pfn_to_nid
1655 * treats start/end as pfns.
1656 */
1657struct mminit_pfnnid_cache {
1658 unsigned long last_start;
1659 unsigned long last_end;
1660 int last_nid;
1661};
75a592a4 1662
03e92a5e 1663static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
6f24fbd3
MR
1664
1665/*
1666 * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
1667 */
03e92a5e 1668static int __meminit __early_pfn_to_nid(unsigned long pfn,
6f24fbd3 1669 struct mminit_pfnnid_cache *state)
75a592a4 1670{
6f24fbd3 1671 unsigned long start_pfn, end_pfn;
75a592a4
MG
1672 int nid;
1673
6f24fbd3
MR
1674 if (state->last_start <= pfn && pfn < state->last_end)
1675 return state->last_nid;
1676
1677 nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
1678 if (nid != NUMA_NO_NODE) {
1679 state->last_start = start_pfn;
1680 state->last_end = end_pfn;
1681 state->last_nid = nid;
1682 }
7ace9917
MG
1683
1684 return nid;
75a592a4 1685}
75a592a4 1686
75a592a4 1687int __meminit early_pfn_to_nid(unsigned long pfn)
75a592a4 1688{
7ace9917 1689 static DEFINE_SPINLOCK(early_pfn_lock);
75a592a4
MG
1690 int nid;
1691
7ace9917 1692 spin_lock(&early_pfn_lock);
56ec43d8 1693 nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
7ace9917 1694 if (nid < 0)
e4568d38 1695 nid = first_online_node;
7ace9917 1696 spin_unlock(&early_pfn_lock);
75a592a4 1697
7ace9917 1698 return nid;
75a592a4 1699}
a9ee6cf5 1700#endif /* CONFIG_NUMA */
75a592a4 1701
7c2ee349 1702void __init memblock_free_pages(struct page *page, unsigned long pfn,
3a80a7fa
MG
1703 unsigned int order)
1704{
1705 if (early_page_uninitialised(pfn))
1706 return;
a9cd410a 1707 __free_pages_core(page, order);
3a80a7fa
MG
1708}
1709
7cf91a98
JK
1710/*
1711 * Check that the whole (or subset of) a pageblock given by the interval of
1712 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
859a85dd 1713 * with the migration of free compaction scanner.
7cf91a98
JK
1714 *
1715 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1716 *
1717 * It's possible on some configurations to have a setup like node0 node1 node0
1718 * i.e. it's possible that all pages within a zones range of pages do not
1719 * belong to a single zone. We assume that a border between node0 and node1
1720 * can occur within a single pageblock, but not a node0 node1 node0
1721 * interleaving within a single pageblock. It is therefore sufficient to check
1722 * the first and last page of a pageblock and avoid checking each individual
1723 * page in a pageblock.
1724 */
1725struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1726 unsigned long end_pfn, struct zone *zone)
1727{
1728 struct page *start_page;
1729 struct page *end_page;
1730
1731 /* end_pfn is one past the range we are checking */
1732 end_pfn--;
1733
1734 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1735 return NULL;
1736
2d070eab
MH
1737 start_page = pfn_to_online_page(start_pfn);
1738 if (!start_page)
1739 return NULL;
7cf91a98
JK
1740
1741 if (page_zone(start_page) != zone)
1742 return NULL;
1743
1744 end_page = pfn_to_page(end_pfn);
1745
1746 /* This gives a shorter code than deriving page_zone(end_page) */
1747 if (page_zone_id(start_page) != page_zone_id(end_page))
1748 return NULL;
1749
1750 return start_page;
1751}
1752
1753void set_zone_contiguous(struct zone *zone)
1754{
1755 unsigned long block_start_pfn = zone->zone_start_pfn;
1756 unsigned long block_end_pfn;
1757
1758 block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1759 for (; block_start_pfn < zone_end_pfn(zone);
1760 block_start_pfn = block_end_pfn,
1761 block_end_pfn += pageblock_nr_pages) {
1762
1763 block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1764
1765 if (!__pageblock_pfn_to_page(block_start_pfn,
1766 block_end_pfn, zone))
1767 return;
e84fe99b 1768 cond_resched();
7cf91a98
JK
1769 }
1770
1771 /* We confirm that there is no hole */
1772 zone->contiguous = true;
1773}
1774
1775void clear_zone_contiguous(struct zone *zone)
1776{
1777 zone->contiguous = false;
1778}
1779
7e18adb4 1780#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
2f47a91f
PT
1781static void __init deferred_free_range(unsigned long pfn,
1782 unsigned long nr_pages)
a4de83dd 1783{
2f47a91f
PT
1784 struct page *page;
1785 unsigned long i;
a4de83dd 1786
2f47a91f 1787 if (!nr_pages)
a4de83dd
MG
1788 return;
1789
2f47a91f
PT
1790 page = pfn_to_page(pfn);
1791
a4de83dd 1792 /* Free a large naturally-aligned chunk if possible */
e780149b
XQ
1793 if (nr_pages == pageblock_nr_pages &&
1794 (pfn & (pageblock_nr_pages - 1)) == 0) {
ac5d2539 1795 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
a9cd410a 1796 __free_pages_core(page, pageblock_order);
a4de83dd
MG
1797 return;
1798 }
1799
e780149b
XQ
1800 for (i = 0; i < nr_pages; i++, page++, pfn++) {
1801 if ((pfn & (pageblock_nr_pages - 1)) == 0)
1802 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
a9cd410a 1803 __free_pages_core(page, 0);
e780149b 1804 }
a4de83dd
MG
1805}
1806
d3cd131d
NS
1807/* Completion tracking for deferred_init_memmap() threads */
1808static atomic_t pgdat_init_n_undone __initdata;
1809static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1810
1811static inline void __init pgdat_init_report_one_done(void)
1812{
1813 if (atomic_dec_and_test(&pgdat_init_n_undone))
1814 complete(&pgdat_init_all_done_comp);
1815}
0e1cc95b 1816
2f47a91f 1817/*
80b1f41c
PT
1818 * Returns true if page needs to be initialized or freed to buddy allocator.
1819 *
1820 * First we check if pfn is valid on architectures where it is possible to have
1821 * holes within pageblock_nr_pages. On systems where it is not possible, this
1822 * function is optimized out.
1823 *
1824 * Then, we check if a current large page is valid by only checking the validity
1825 * of the head pfn.
2f47a91f 1826 */
56ec43d8 1827static inline bool __init deferred_pfn_valid(unsigned long pfn)
2f47a91f 1828{
80b1f41c
PT
1829 if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1830 return false;
80b1f41c
PT
1831 return true;
1832}
2f47a91f 1833
80b1f41c
PT
1834/*
1835 * Free pages to buddy allocator. Try to free aligned pages in
1836 * pageblock_nr_pages sizes.
1837 */
56ec43d8 1838static void __init deferred_free_pages(unsigned long pfn,
80b1f41c
PT
1839 unsigned long end_pfn)
1840{
80b1f41c
PT
1841 unsigned long nr_pgmask = pageblock_nr_pages - 1;
1842 unsigned long nr_free = 0;
2f47a91f 1843
80b1f41c 1844 for (; pfn < end_pfn; pfn++) {
56ec43d8 1845 if (!deferred_pfn_valid(pfn)) {
80b1f41c
PT
1846 deferred_free_range(pfn - nr_free, nr_free);
1847 nr_free = 0;
1848 } else if (!(pfn & nr_pgmask)) {
1849 deferred_free_range(pfn - nr_free, nr_free);
1850 nr_free = 1;
80b1f41c
PT
1851 } else {
1852 nr_free++;
1853 }
1854 }
1855 /* Free the last block of pages to allocator */
1856 deferred_free_range(pfn - nr_free, nr_free);
2f47a91f
PT
1857}
1858
80b1f41c
PT
1859/*
1860 * Initialize struct pages. We minimize pfn page lookups and scheduler checks
1861 * by performing it only once every pageblock_nr_pages.
1862 * Return number of pages initialized.
1863 */
56ec43d8 1864static unsigned long __init deferred_init_pages(struct zone *zone,
80b1f41c
PT
1865 unsigned long pfn,
1866 unsigned long end_pfn)
2f47a91f 1867{
2f47a91f 1868 unsigned long nr_pgmask = pageblock_nr_pages - 1;
56ec43d8 1869 int nid = zone_to_nid(zone);
2f47a91f 1870 unsigned long nr_pages = 0;
56ec43d8 1871 int zid = zone_idx(zone);
2f47a91f 1872 struct page *page = NULL;
2f47a91f 1873
80b1f41c 1874 for (; pfn < end_pfn; pfn++) {
56ec43d8 1875 if (!deferred_pfn_valid(pfn)) {
80b1f41c 1876 page = NULL;
2f47a91f 1877 continue;
80b1f41c 1878 } else if (!page || !(pfn & nr_pgmask)) {
2f47a91f 1879 page = pfn_to_page(pfn);
80b1f41c
PT
1880 } else {
1881 page++;
2f47a91f 1882 }
d0dc12e8 1883 __init_single_page(page, pfn, zid, nid);
80b1f41c 1884 nr_pages++;
2f47a91f 1885 }
80b1f41c 1886 return (nr_pages);
2f47a91f
PT
1887}
1888
0e56acae
AD
1889/*
1890 * This function is meant to pre-load the iterator for the zone init.
1891 * Specifically it walks through the ranges until we are caught up to the
1892 * first_init_pfn value and exits there. If we never encounter the value we
1893 * return false indicating there are no valid ranges left.
1894 */
1895static bool __init
1896deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone,
1897 unsigned long *spfn, unsigned long *epfn,
1898 unsigned long first_init_pfn)
1899{
1900 u64 j;
1901
1902 /*
1903 * Start out by walking through the ranges in this zone that have
1904 * already been initialized. We don't need to do anything with them
1905 * so we just need to flush them out of the system.
1906 */
1907 for_each_free_mem_pfn_range_in_zone(j, zone, spfn, epfn) {
1908 if (*epfn <= first_init_pfn)
1909 continue;
1910 if (*spfn < first_init_pfn)
1911 *spfn = first_init_pfn;
1912 *i = j;
1913 return true;
1914 }
1915
1916 return false;
1917}
1918
1919/*
1920 * Initialize and free pages. We do it in two loops: first we initialize
1921 * struct page, then free to buddy allocator, because while we are
1922 * freeing pages we can access pages that are ahead (computing buddy
1923 * page in __free_one_page()).
1924 *
1925 * In order to try and keep some memory in the cache we have the loop
1926 * broken along max page order boundaries. This way we will not cause
1927 * any issues with the buddy page computation.
1928 */
1929static unsigned long __init
1930deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn,
1931 unsigned long *end_pfn)
1932{
1933 unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES);
1934 unsigned long spfn = *start_pfn, epfn = *end_pfn;
1935 unsigned long nr_pages = 0;
1936 u64 j = *i;
1937
1938 /* First we loop through and initialize the page values */
1939 for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) {
1940 unsigned long t;
1941
1942 if (mo_pfn <= *start_pfn)
1943 break;
1944
1945 t = min(mo_pfn, *end_pfn);
1946 nr_pages += deferred_init_pages(zone, *start_pfn, t);
1947
1948 if (mo_pfn < *end_pfn) {
1949 *start_pfn = mo_pfn;
1950 break;
1951 }
1952 }
1953
1954 /* Reset values and now loop through freeing pages as needed */
1955 swap(j, *i);
1956
1957 for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) {
1958 unsigned long t;
1959
1960 if (mo_pfn <= spfn)
1961 break;
1962
1963 t = min(mo_pfn, epfn);
1964 deferred_free_pages(spfn, t);
1965
1966 if (mo_pfn <= epfn)
1967 break;
1968 }
1969
1970 return nr_pages;
1971}
1972
e4443149
DJ
1973static void __init
1974deferred_init_memmap_chunk(unsigned long start_pfn, unsigned long end_pfn,
1975 void *arg)
1976{
1977 unsigned long spfn, epfn;
1978 struct zone *zone = arg;
1979 u64 i;
1980
1981 deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, start_pfn);
1982
1983 /*
1984 * Initialize and free pages in MAX_ORDER sized increments so that we
1985 * can avoid introducing any issues with the buddy allocator.
1986 */
1987 while (spfn < end_pfn) {
1988 deferred_init_maxorder(&i, zone, &spfn, &epfn);
1989 cond_resched();
1990 }
1991}
1992
ecd09650
DJ
1993/* An arch may override for more concurrency. */
1994__weak int __init
1995deferred_page_init_max_threads(const struct cpumask *node_cpumask)
1996{
1997 return 1;
1998}
1999
7e18adb4 2000/* Initialise remaining memory on a node */
0e1cc95b 2001static int __init deferred_init_memmap(void *data)
7e18adb4 2002{
0e1cc95b 2003 pg_data_t *pgdat = data;
0e56acae 2004 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
89c7c402 2005 unsigned long spfn = 0, epfn = 0;
0e56acae 2006 unsigned long first_init_pfn, flags;
7e18adb4 2007 unsigned long start = jiffies;
7e18adb4 2008 struct zone *zone;
e4443149 2009 int zid, max_threads;
2f47a91f 2010 u64 i;
7e18adb4 2011
3a2d7fa8
PT
2012 /* Bind memory initialisation thread to a local node if possible */
2013 if (!cpumask_empty(cpumask))
2014 set_cpus_allowed_ptr(current, cpumask);
2015
2016 pgdat_resize_lock(pgdat, &flags);
2017 first_init_pfn = pgdat->first_deferred_pfn;
0e1cc95b 2018 if (first_init_pfn == ULONG_MAX) {
3a2d7fa8 2019 pgdat_resize_unlock(pgdat, &flags);
d3cd131d 2020 pgdat_init_report_one_done();
0e1cc95b
MG
2021 return 0;
2022 }
2023
7e18adb4
MG
2024 /* Sanity check boundaries */
2025 BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
2026 BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
2027 pgdat->first_deferred_pfn = ULONG_MAX;
2028
3d060856
PT
2029 /*
2030 * Once we unlock here, the zone cannot be grown anymore, thus if an
2031 * interrupt thread must allocate this early in boot, zone must be
2032 * pre-grown prior to start of deferred page initialization.
2033 */
2034 pgdat_resize_unlock(pgdat, &flags);
2035
7e18adb4
MG
2036 /* Only the highest zone is deferred so find it */
2037 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2038 zone = pgdat->node_zones + zid;
2039 if (first_init_pfn < zone_end_pfn(zone))
2040 break;
2041 }
0e56acae
AD
2042
2043 /* If the zone is empty somebody else may have cleared out the zone */
2044 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
2045 first_init_pfn))
2046 goto zone_empty;
7e18adb4 2047
ecd09650 2048 max_threads = deferred_page_init_max_threads(cpumask);
7e18adb4 2049
117003c3 2050 while (spfn < epfn) {
e4443149
DJ
2051 unsigned long epfn_align = ALIGN(epfn, PAGES_PER_SECTION);
2052 struct padata_mt_job job = {
2053 .thread_fn = deferred_init_memmap_chunk,
2054 .fn_arg = zone,
2055 .start = spfn,
2056 .size = epfn_align - spfn,
2057 .align = PAGES_PER_SECTION,
2058 .min_chunk = PAGES_PER_SECTION,
2059 .max_threads = max_threads,
2060 };
2061
2062 padata_do_multithreaded(&job);
2063 deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
2064 epfn_align);
117003c3 2065 }
0e56acae 2066zone_empty:
7e18adb4
MG
2067 /* Sanity check that the next zone really is unpopulated */
2068 WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
2069
89c7c402
DJ
2070 pr_info("node %d deferred pages initialised in %ums\n",
2071 pgdat->node_id, jiffies_to_msecs(jiffies - start));
d3cd131d
NS
2072
2073 pgdat_init_report_one_done();
0e1cc95b
MG
2074 return 0;
2075}
c9e97a19 2076
c9e97a19
PT
2077/*
2078 * If this zone has deferred pages, try to grow it by initializing enough
2079 * deferred pages to satisfy the allocation specified by order, rounded up to
2080 * the nearest PAGES_PER_SECTION boundary. So we're adding memory in increments
2081 * of SECTION_SIZE bytes by initializing struct pages in increments of
2082 * PAGES_PER_SECTION * sizeof(struct page) bytes.
2083 *
2084 * Return true when zone was grown, otherwise return false. We return true even
2085 * when we grow less than requested, to let the caller decide if there are
2086 * enough pages to satisfy the allocation.
2087 *
2088 * Note: We use noinline because this function is needed only during boot, and
2089 * it is called from a __ref function _deferred_grow_zone. This way we are
2090 * making sure that it is not inlined into permanent text section.
2091 */
2092static noinline bool __init
2093deferred_grow_zone(struct zone *zone, unsigned int order)
2094{
c9e97a19 2095 unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
837566e7 2096 pg_data_t *pgdat = zone->zone_pgdat;
c9e97a19 2097 unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
0e56acae
AD
2098 unsigned long spfn, epfn, flags;
2099 unsigned long nr_pages = 0;
c9e97a19
PT
2100 u64 i;
2101
2102 /* Only the last zone may have deferred pages */
2103 if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
2104 return false;
2105
2106 pgdat_resize_lock(pgdat, &flags);
2107
c9e97a19
PT
2108 /*
2109 * If someone grew this zone while we were waiting for spinlock, return
2110 * true, as there might be enough pages already.
2111 */
2112 if (first_deferred_pfn != pgdat->first_deferred_pfn) {
2113 pgdat_resize_unlock(pgdat, &flags);
2114 return true;
2115 }
2116
0e56acae
AD
2117 /* If the zone is empty somebody else may have cleared out the zone */
2118 if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
2119 first_deferred_pfn)) {
2120 pgdat->first_deferred_pfn = ULONG_MAX;
c9e97a19 2121 pgdat_resize_unlock(pgdat, &flags);
b9705d87
JG
2122 /* Retry only once. */
2123 return first_deferred_pfn != ULONG_MAX;
c9e97a19
PT
2124 }
2125
0e56acae
AD
2126 /*
2127 * Initialize and free pages in MAX_ORDER sized increments so
2128 * that we can avoid introducing any issues with the buddy
2129 * allocator.
2130 */
2131 while (spfn < epfn) {
2132 /* update our first deferred PFN for this section */
2133 first_deferred_pfn = spfn;
2134
2135 nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
117003c3 2136 touch_nmi_watchdog();
c9e97a19 2137
0e56acae
AD
2138 /* We should only stop along section boundaries */
2139 if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION)
2140 continue;
c9e97a19 2141
0e56acae 2142 /* If our quota has been met we can stop here */
c9e97a19
PT
2143 if (nr_pages >= nr_pages_needed)
2144 break;
2145 }
2146
0e56acae 2147 pgdat->first_deferred_pfn = spfn;
c9e97a19
PT
2148 pgdat_resize_unlock(pgdat, &flags);
2149
2150 return nr_pages > 0;
2151}
2152
2153/*
2154 * deferred_grow_zone() is __init, but it is called from
2155 * get_page_from_freelist() during early boot until deferred_pages permanently
2156 * disables this call. This is why we have refdata wrapper to avoid warning,
2157 * and to ensure that the function body gets unloaded.
2158 */
2159static bool __ref
2160_deferred_grow_zone(struct zone *zone, unsigned int order)
2161{
2162 return deferred_grow_zone(zone, order);
2163}
2164
7cf91a98 2165#endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
0e1cc95b
MG
2166
2167void __init page_alloc_init_late(void)
2168{
7cf91a98 2169 struct zone *zone;
e900a918 2170 int nid;
7cf91a98
JK
2171
2172#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
0e1cc95b 2173
d3cd131d
NS
2174 /* There will be num_node_state(N_MEMORY) threads */
2175 atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
0e1cc95b 2176 for_each_node_state(nid, N_MEMORY) {
0e1cc95b
MG
2177 kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
2178 }
2179
2180 /* Block until all are initialised */
d3cd131d 2181 wait_for_completion(&pgdat_init_all_done_comp);
4248b0da 2182
c9e97a19
PT
2183 /*
2184 * We initialized the rest of the deferred pages. Permanently disable
2185 * on-demand struct page initialization.
2186 */
2187 static_branch_disable(&deferred_pages);
2188
4248b0da
MG
2189 /* Reinit limits that are based on free pages after the kernel is up */
2190 files_maxfiles_init();
7cf91a98 2191#endif
350e88ba 2192
ba8f3587
LF
2193 buffer_init();
2194
3010f876
PT
2195 /* Discard memblock private memory */
2196 memblock_discard();
7cf91a98 2197
e900a918
DW
2198 for_each_node_state(nid, N_MEMORY)
2199 shuffle_free_memory(NODE_DATA(nid));
2200
7cf91a98
JK
2201 for_each_populated_zone(zone)
2202 set_zone_contiguous(zone);
7e18adb4 2203}
7e18adb4 2204
47118af0 2205#ifdef CONFIG_CMA
9cf510a5 2206/* Free whole pageblock and set its migration type to MIGRATE_CMA. */
47118af0
MN
2207void __init init_cma_reserved_pageblock(struct page *page)
2208{
2209 unsigned i = pageblock_nr_pages;
2210 struct page *p = page;
2211
2212 do {
2213 __ClearPageReserved(p);
2214 set_page_count(p, 0);
d883c6cf 2215 } while (++p, --i);
47118af0 2216
47118af0 2217 set_pageblock_migratetype(page, MIGRATE_CMA);
b3d40a2b
DH
2218 set_page_refcounted(page);
2219 __free_pages(page, pageblock_order);
dc78327c 2220
3dcc0571 2221 adjust_managed_page_count(page, pageblock_nr_pages);
3c381db1 2222 page_zone(page)->cma_pages += pageblock_nr_pages;
47118af0
MN
2223}
2224#endif
1da177e4
LT
2225
2226/*
2227 * The order of subdivision here is critical for the IO subsystem.
2228 * Please do not alter this order without good reasons and regression
2229 * testing. Specifically, as large blocks of memory are subdivided,
2230 * the order in which smaller blocks are delivered depends on the order
2231 * they're subdivided in this function. This is the primary factor
2232 * influencing the order in which pages are delivered to the IO
2233 * subsystem according to empirical testing, and this is also justified
2234 * by considering the behavior of a buddy system containing a single
2235 * large block of memory acted on by a series of small allocations.
2236 * This behavior is a critical factor in sglist merging's success.
2237 *
6d49e352 2238 * -- nyc
1da177e4 2239 */
085cc7d5 2240static inline void expand(struct zone *zone, struct page *page,
6ab01363 2241 int low, int high, int migratetype)
1da177e4
LT
2242{
2243 unsigned long size = 1 << high;
2244
2245 while (high > low) {
1da177e4
LT
2246 high--;
2247 size >>= 1;
309381fe 2248 VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
c0a32fc5 2249
acbc15a4
JK
2250 /*
2251 * Mark as guard pages (or page), that will allow to
2252 * merge back to allocator when buddy will be freed.
2253 * Corresponding page table entries will not be touched,
2254 * pages will stay not present in virtual address space
2255 */
2256 if (set_page_guard(zone, &page[size], high, migratetype))
c0a32fc5 2257 continue;
acbc15a4 2258
6ab01363 2259 add_to_free_list(&page[size], zone, high, migratetype);
ab130f91 2260 set_buddy_order(&page[size], high);
1da177e4 2261 }
1da177e4
LT
2262}
2263
4e611801 2264static void check_new_page_bad(struct page *page)
1da177e4 2265{
f4c18e6f 2266 if (unlikely(page->flags & __PG_HWPOISON)) {
e570f56c
NH
2267 /* Don't complain about hwpoisoned pages */
2268 page_mapcount_reset(page); /* remove PageBuddy */
2269 return;
f4c18e6f 2270 }
58b7f119
WY
2271
2272 bad_page(page,
2273 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_PREP));
4e611801
VB
2274}
2275
2276/*
2277 * This page is about to be returned from the page allocator
2278 */
2279static inline int check_new_page(struct page *page)
2280{
2281 if (likely(page_expected_state(page,
2282 PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
2283 return 0;
2284
2285 check_new_page_bad(page);
2286 return 1;
2a7684a2
WF
2287}
2288
77fe7f13
MG
2289static bool check_new_pages(struct page *page, unsigned int order)
2290{
2291 int i;
2292 for (i = 0; i < (1 << order); i++) {
2293 struct page *p = page + i;
2294
2295 if (unlikely(check_new_page(p)))
2296 return true;
2297 }
2298
2299 return false;
2300}
2301
479f854a 2302#ifdef CONFIG_DEBUG_VM
4462b32c
VB
2303/*
2304 * With DEBUG_VM enabled, order-0 pages are checked for expected state when
2305 * being allocated from pcp lists. With debug_pagealloc also enabled, they are
2306 * also checked when pcp lists are refilled from the free lists.
2307 */
77fe7f13 2308static inline bool check_pcp_refill(struct page *page, unsigned int order)
479f854a 2309{
8e57f8ac 2310 if (debug_pagealloc_enabled_static())
77fe7f13 2311 return check_new_pages(page, order);
4462b32c
VB
2312 else
2313 return false;
479f854a
MG
2314}
2315
77fe7f13 2316static inline bool check_new_pcp(struct page *page, unsigned int order)
479f854a 2317{
77fe7f13 2318 return check_new_pages(page, order);
479f854a
MG
2319}
2320#else
4462b32c
VB
2321/*
2322 * With DEBUG_VM disabled, free order-0 pages are checked for expected state
2323 * when pcp lists are being refilled from the free lists. With debug_pagealloc
2324 * enabled, they are also checked when being allocated from the pcp lists.
2325 */
77fe7f13 2326static inline bool check_pcp_refill(struct page *page, unsigned int order)
479f854a 2327{
77fe7f13 2328 return check_new_pages(page, order);
479f854a 2329}
77fe7f13 2330static inline bool check_new_pcp(struct page *page, unsigned int order)
479f854a 2331{
8e57f8ac 2332 if (debug_pagealloc_enabled_static())
77fe7f13 2333 return check_new_pages(page, order);
4462b32c
VB
2334 else
2335 return false;
479f854a
MG
2336}
2337#endif /* CONFIG_DEBUG_VM */
2338
53ae233c
AK
2339static inline bool should_skip_kasan_unpoison(gfp_t flags, bool init_tags)
2340{
2341 /* Don't skip if a software KASAN mode is enabled. */
2342 if (IS_ENABLED(CONFIG_KASAN_GENERIC) ||
2343 IS_ENABLED(CONFIG_KASAN_SW_TAGS))
2344 return false;
2345
2346 /* Skip, if hardware tag-based KASAN is not enabled. */
2347 if (!kasan_hw_tags_enabled())
2348 return true;
2349
2350 /*
2351 * With hardware tag-based KASAN enabled, skip if either:
2352 *
2353 * 1. Memory tags have already been cleared via tag_clear_highpage().
2354 * 2. Skipping has been requested via __GFP_SKIP_KASAN_UNPOISON.
2355 */
2356 return init_tags || (flags & __GFP_SKIP_KASAN_UNPOISON);
2357}
2358
9353ffa6
AK
2359static inline bool should_skip_init(gfp_t flags)
2360{
2361 /* Don't skip, if hardware tag-based KASAN is not enabled. */
2362 if (!kasan_hw_tags_enabled())
2363 return false;
2364
2365 /* For hardware tag-based KASAN, skip if requested. */
2366 return (flags & __GFP_SKIP_ZERO);
2367}
2368
46f24fd8
JK
2369inline void post_alloc_hook(struct page *page, unsigned int order,
2370 gfp_t gfp_flags)
2371{
9353ffa6
AK
2372 bool init = !want_init_on_free() && want_init_on_alloc(gfp_flags) &&
2373 !should_skip_init(gfp_flags);
b42090ae
AK
2374 bool init_tags = init && (gfp_flags & __GFP_ZEROTAGS);
2375
46f24fd8
JK
2376 set_page_private(page, 0);
2377 set_page_refcounted(page);
2378
2379 arch_alloc_page(page, order);
77bc7fd6 2380 debug_pagealloc_map_pages(page, 1 << order);
1bb5eab3
AK
2381
2382 /*
2383 * Page unpoisoning must happen before memory initialization.
2384 * Otherwise, the poison pattern will be overwritten for __GFP_ZERO
2385 * allocations and the page unpoisoning code will complain.
2386 */
8db26a3d 2387 kernel_unpoison_pages(page, 1 << order);
862b6dee 2388
1bb5eab3
AK
2389 /*
2390 * As memory initialization might be integrated into KASAN,
b42090ae 2391 * KASAN unpoisoning and memory initializion code must be
1bb5eab3
AK
2392 * kept together to avoid discrepancies in behavior.
2393 */
9294b128
AK
2394
2395 /*
2396 * If memory tags should be zeroed (which happens only when memory
2397 * should be initialized as well).
2398 */
2399 if (init_tags) {
2400 int i;
2401
2402 /* Initialize both memory and tags. */
2403 for (i = 0; i != 1 << order; ++i)
2404 tag_clear_highpage(page + i);
2405
2406 /* Note that memory is already initialized by the loop above. */
2407 init = false;
2408 }
53ae233c
AK
2409 if (!should_skip_kasan_unpoison(gfp_flags, init_tags)) {
2410 /* Unpoison shadow memory or set memory tags. */
e9d0ca92 2411 kasan_unpoison_pages(page, order, init);
7e3cbba6 2412
e9d0ca92
AK
2413 /* Note that memory is already initialized by KASAN. */
2414 if (kasan_has_integrated_init())
7e3cbba6 2415 init = false;
7a3b8353 2416 }
7e3cbba6
AK
2417 /* If memory is still not initialized, do it now. */
2418 if (init)
2419 kernel_init_free_pages(page, 1 << order);
89b27116
AK
2420 /* Propagate __GFP_SKIP_KASAN_POISON to page flags. */
2421 if (kasan_hw_tags_enabled() && (gfp_flags & __GFP_SKIP_KASAN_POISON))
2422 SetPageSkipKASanPoison(page);
1bb5eab3
AK
2423
2424 set_page_owner(page, order, gfp_flags);
df4e817b 2425 page_table_check_alloc(page, order);
46f24fd8
JK
2426}
2427
479f854a 2428static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
c603844b 2429 unsigned int alloc_flags)
2a7684a2 2430{
46f24fd8 2431 post_alloc_hook(page, order, gfp_flags);
17cf4406 2432
17cf4406
NP
2433 if (order && (gfp_flags & __GFP_COMP))
2434 prep_compound_page(page, order);
2435
75379191 2436 /*
2f064f34 2437 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
75379191
VB
2438 * allocate the page. The expectation is that the caller is taking
2439 * steps that will free more memory. The caller should avoid the page
2440 * being used for !PFMEMALLOC purposes.
2441 */
2f064f34
MH
2442 if (alloc_flags & ALLOC_NO_WATERMARKS)
2443 set_page_pfmemalloc(page);
2444 else
2445 clear_page_pfmemalloc(page);
1da177e4
LT
2446}
2447
56fd56b8
MG
2448/*
2449 * Go through the free lists for the given migratetype and remove
2450 * the smallest available page from the freelists
2451 */
85ccc8fa 2452static __always_inline
728ec980 2453struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
56fd56b8
MG
2454 int migratetype)
2455{
2456 unsigned int current_order;
b8af2941 2457 struct free_area *area;
56fd56b8
MG
2458 struct page *page;
2459
2460 /* Find a page of the appropriate size in the preferred list */
2461 for (current_order = order; current_order < MAX_ORDER; ++current_order) {
2462 area = &(zone->free_area[current_order]);
b03641af 2463 page = get_page_from_free_area(area, migratetype);
a16601c5
GT
2464 if (!page)
2465 continue;
6ab01363
AD
2466 del_page_from_free_list(page, zone, current_order);
2467 expand(zone, page, order, current_order, migratetype);
bb14c2c7 2468 set_pcppage_migratetype(page, migratetype);
56fd56b8
MG
2469 return page;
2470 }
2471
2472 return NULL;
2473}
2474
2475
b2a0ac88
MG
2476/*
2477 * This array describes the order lists are fallen back to when
2478 * the free lists for the desirable migrate type are depleted
1dd214b8
ZY
2479 *
2480 * The other migratetypes do not have fallbacks.
b2a0ac88 2481 */
da415663 2482static int fallbacks[MIGRATE_TYPES][3] = {
974a786e 2483 [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
974a786e 2484 [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
7ead3342 2485 [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_TYPES },
b2a0ac88
MG
2486};
2487
dc67647b 2488#ifdef CONFIG_CMA
85ccc8fa 2489static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
dc67647b
JK
2490 unsigned int order)
2491{
2492 return __rmqueue_smallest(zone, order, MIGRATE_CMA);
2493}
2494#else
2495static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2496 unsigned int order) { return NULL; }
2497#endif
2498
c361be55 2499/*
293ffa5e 2500 * Move the free pages in a range to the freelist tail of the requested type.
d9c23400 2501 * Note that start_page and end_pages are not aligned on a pageblock
c361be55
MG
2502 * boundary. If alignment is required, use move_freepages_block()
2503 */
02aa0cdd 2504static int move_freepages(struct zone *zone,
39ddb991 2505 unsigned long start_pfn, unsigned long end_pfn,
02aa0cdd 2506 int migratetype, int *num_movable)
c361be55
MG
2507{
2508 struct page *page;
39ddb991 2509 unsigned long pfn;
d00181b9 2510 unsigned int order;
d100313f 2511 int pages_moved = 0;
c361be55 2512
39ddb991 2513 for (pfn = start_pfn; pfn <= end_pfn;) {
39ddb991 2514 page = pfn_to_page(pfn);
c361be55 2515 if (!PageBuddy(page)) {
02aa0cdd
VB
2516 /*
2517 * We assume that pages that could be isolated for
2518 * migration are movable. But we don't actually try
2519 * isolating, as that would be expensive.
2520 */
2521 if (num_movable &&
2522 (PageLRU(page) || __PageMovable(page)))
2523 (*num_movable)++;
39ddb991 2524 pfn++;
c361be55
MG
2525 continue;
2526 }
2527
cd961038
DR
2528 /* Make sure we are not inadvertently changing nodes */
2529 VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2530 VM_BUG_ON_PAGE(page_zone(page) != zone, page);
2531
ab130f91 2532 order = buddy_order(page);
6ab01363 2533 move_to_free_list(page, zone, order, migratetype);
39ddb991 2534 pfn += 1 << order;
d100313f 2535 pages_moved += 1 << order;
c361be55
MG
2536 }
2537
d100313f 2538 return pages_moved;
c361be55
MG
2539}
2540
ee6f509c 2541int move_freepages_block(struct zone *zone, struct page *page,
02aa0cdd 2542 int migratetype, int *num_movable)
c361be55 2543{
39ddb991 2544 unsigned long start_pfn, end_pfn, pfn;
c361be55 2545
4a222127
DR
2546 if (num_movable)
2547 *num_movable = 0;
2548
39ddb991
KW
2549 pfn = page_to_pfn(page);
2550 start_pfn = pfn & ~(pageblock_nr_pages - 1);
d9c23400 2551 end_pfn = start_pfn + pageblock_nr_pages - 1;
c361be55
MG
2552
2553 /* Do not cross zone boundaries */
108bcc96 2554 if (!zone_spans_pfn(zone, start_pfn))
39ddb991 2555 start_pfn = pfn;
108bcc96 2556 if (!zone_spans_pfn(zone, end_pfn))
c361be55
MG
2557 return 0;
2558
39ddb991 2559 return move_freepages(zone, start_pfn, end_pfn, migratetype,
02aa0cdd 2560 num_movable);
c361be55
MG
2561}
2562
2f66a68f
MG
2563static void change_pageblock_range(struct page *pageblock_page,
2564 int start_order, int migratetype)
2565{
2566 int nr_pageblocks = 1 << (start_order - pageblock_order);
2567
2568 while (nr_pageblocks--) {
2569 set_pageblock_migratetype(pageblock_page, migratetype);
2570 pageblock_page += pageblock_nr_pages;
2571 }
2572}
2573
fef903ef 2574/*
9c0415eb
VB
2575 * When we are falling back to another migratetype during allocation, try to
2576 * steal extra free pages from the same pageblocks to satisfy further
2577 * allocations, instead of polluting multiple pageblocks.
2578 *
2579 * If we are stealing a relatively large buddy page, it is likely there will
2580 * be more free pages in the pageblock, so try to steal them all. For
2581 * reclaimable and unmovable allocations, we steal regardless of page size,
2582 * as fragmentation caused by those allocations polluting movable pageblocks
2583 * is worse than movable allocations stealing from unmovable and reclaimable
2584 * pageblocks.
fef903ef 2585 */
4eb7dce6
JK
2586static bool can_steal_fallback(unsigned int order, int start_mt)
2587{
2588 /*
2589 * Leaving this order check is intended, although there is
2590 * relaxed order check in next check. The reason is that
2591 * we can actually steal whole pageblock if this condition met,
2592 * but, below check doesn't guarantee it and that is just heuristic
2593 * so could be changed anytime.
2594 */
2595 if (order >= pageblock_order)
2596 return true;
2597
2598 if (order >= pageblock_order / 2 ||
2599 start_mt == MIGRATE_RECLAIMABLE ||
2600 start_mt == MIGRATE_UNMOVABLE ||
2601 page_group_by_mobility_disabled)
2602 return true;
2603
2604 return false;
2605}
2606
597c8920 2607static inline bool boost_watermark(struct zone *zone)
1c30844d
MG
2608{
2609 unsigned long max_boost;
2610
2611 if (!watermark_boost_factor)
597c8920 2612 return false;
14f69140
HW
2613 /*
2614 * Don't bother in zones that are unlikely to produce results.
2615 * On small machines, including kdump capture kernels running
2616 * in a small area, boosting the watermark can cause an out of
2617 * memory situation immediately.
2618 */
2619 if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
597c8920 2620 return false;
1c30844d
MG
2621
2622 max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
2623 watermark_boost_factor, 10000);
94b3334c
MG
2624
2625 /*
2626 * high watermark may be uninitialised if fragmentation occurs
2627 * very early in boot so do not boost. We do not fall
2628 * through and boost by pageblock_nr_pages as failing
2629 * allocations that early means that reclaim is not going
2630 * to help and it may even be impossible to reclaim the
2631 * boosted watermark resulting in a hang.
2632 */
2633 if (!max_boost)
597c8920 2634 return false;
94b3334c 2635
1c30844d
MG
2636 max_boost = max(pageblock_nr_pages, max_boost);
2637
2638 zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
2639 max_boost);
597c8920
JW
2640
2641 return true;
1c30844d
MG
2642}
2643
4eb7dce6
JK
2644/*
2645 * This function implements actual steal behaviour. If order is large enough,
2646 * we can steal whole pageblock. If not, we first move freepages in this
02aa0cdd
VB
2647 * pageblock to our migratetype and determine how many already-allocated pages
2648 * are there in the pageblock with a compatible migratetype. If at least half
2649 * of pages are free or compatible, we can change migratetype of the pageblock
2650 * itself, so pages freed in the future will be put on the correct free list.
4eb7dce6
JK
2651 */
2652static void steal_suitable_fallback(struct zone *zone, struct page *page,
1c30844d 2653 unsigned int alloc_flags, int start_type, bool whole_block)
fef903ef 2654{
ab130f91 2655 unsigned int current_order = buddy_order(page);
02aa0cdd
VB
2656 int free_pages, movable_pages, alike_pages;
2657 int old_block_type;
2658
2659 old_block_type = get_pageblock_migratetype(page);
fef903ef 2660
3bc48f96
VB
2661 /*
2662 * This can happen due to races and we want to prevent broken
2663 * highatomic accounting.
2664 */
02aa0cdd 2665 if (is_migrate_highatomic(old_block_type))
3bc48f96
VB
2666 goto single_page;
2667
fef903ef
SB
2668 /* Take ownership for orders >= pageblock_order */
2669 if (current_order >= pageblock_order) {
2670 change_pageblock_range(page, current_order, start_type);
3bc48f96 2671 goto single_page;
fef903ef
SB
2672 }
2673
1c30844d
MG
2674 /*
2675 * Boost watermarks to increase reclaim pressure to reduce the
2676 * likelihood of future fallbacks. Wake kswapd now as the node
2677 * may be balanced overall and kswapd will not wake naturally.
2678 */
597c8920 2679 if (boost_watermark(zone) && (alloc_flags & ALLOC_KSWAPD))
73444bc4 2680 set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
1c30844d 2681
3bc48f96
VB
2682 /* We are not allowed to try stealing from the whole block */
2683 if (!whole_block)
2684 goto single_page;
2685
02aa0cdd
VB
2686 free_pages = move_freepages_block(zone, page, start_type,
2687 &movable_pages);
2688 /*
2689 * Determine how many pages are compatible with our allocation.
2690 * For movable allocation, it's the number of movable pages which
2691 * we just obtained. For other types it's a bit more tricky.
2692 */
2693 if (start_type == MIGRATE_MOVABLE) {
2694 alike_pages = movable_pages;
2695 } else {
2696 /*
2697 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2698 * to MOVABLE pageblock, consider all non-movable pages as
2699 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2700 * vice versa, be conservative since we can't distinguish the
2701 * exact migratetype of non-movable pages.
2702 */
2703 if (old_block_type == MIGRATE_MOVABLE)
2704 alike_pages = pageblock_nr_pages
2705 - (free_pages + movable_pages);
2706 else
2707 alike_pages = 0;
2708 }
2709
3bc48f96 2710 /* moving whole block can fail due to zone boundary conditions */
02aa0cdd 2711 if (!free_pages)
3bc48f96 2712 goto single_page;
fef903ef 2713
02aa0cdd
VB
2714 /*
2715 * If a sufficient number of pages in the block are either free or of
2716 * comparable migratability as our allocation, claim the whole block.
2717 */
2718 if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
4eb7dce6
JK
2719 page_group_by_mobility_disabled)
2720 set_pageblock_migratetype(page, start_type);
3bc48f96
VB
2721
2722 return;
2723
2724single_page:
6ab01363 2725 move_to_free_list(page, zone, current_order, start_type);
4eb7dce6
JK
2726}
2727
2149cdae
JK
2728/*
2729 * Check whether there is a suitable fallback freepage with requested order.
2730 * If only_stealable is true, this function returns fallback_mt only if
2731 * we can steal other freepages all together. This would help to reduce
2732 * fragmentation due to mixed migratetype pages in one pageblock.
2733 */
2734int find_suitable_fallback(struct free_area *area, unsigned int order,
2735 int migratetype, bool only_stealable, bool *can_steal)
4eb7dce6
JK
2736{
2737 int i;
2738 int fallback_mt;
2739
2740 if (area->nr_free == 0)
2741 return -1;
2742
2743 *can_steal = false;
2744 for (i = 0;; i++) {
2745 fallback_mt = fallbacks[migratetype][i];
974a786e 2746 if (fallback_mt == MIGRATE_TYPES)
4eb7dce6
JK
2747 break;
2748
b03641af 2749 if (free_area_empty(area, fallback_mt))
4eb7dce6 2750 continue;
fef903ef 2751
4eb7dce6
JK
2752 if (can_steal_fallback(order, migratetype))
2753 *can_steal = true;
2754
2149cdae
JK
2755 if (!only_stealable)
2756 return fallback_mt;
2757
2758 if (*can_steal)
2759 return fallback_mt;
fef903ef 2760 }
4eb7dce6
JK
2761
2762 return -1;
fef903ef
SB
2763}
2764
0aaa29a5
MG
2765/*
2766 * Reserve a pageblock for exclusive use of high-order atomic allocations if
2767 * there are no empty page blocks that contain a page with a suitable order
2768 */
2769static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2770 unsigned int alloc_order)
2771{
2772 int mt;
2773 unsigned long max_managed, flags;
2774
2775 /*
2776 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2777 * Check is race-prone but harmless.
2778 */
9705bea5 2779 max_managed = (zone_managed_pages(zone) / 100) + pageblock_nr_pages;
0aaa29a5
MG
2780 if (zone->nr_reserved_highatomic >= max_managed)
2781 return;
2782
2783 spin_lock_irqsave(&zone->lock, flags);
2784
2785 /* Recheck the nr_reserved_highatomic limit under the lock */
2786 if (zone->nr_reserved_highatomic >= max_managed)
2787 goto out_unlock;
2788
2789 /* Yoink! */
2790 mt = get_pageblock_migratetype(page);
1dd214b8
ZY
2791 /* Only reserve normal pageblocks (i.e., they can merge with others) */
2792 if (migratetype_is_mergeable(mt)) {
0aaa29a5
MG
2793 zone->nr_reserved_highatomic += pageblock_nr_pages;
2794 set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
02aa0cdd 2795 move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
0aaa29a5
MG
2796 }
2797
2798out_unlock:
2799 spin_unlock_irqrestore(&zone->lock, flags);
2800}
2801
2802/*
2803 * Used when an allocation is about to fail under memory pressure. This
2804 * potentially hurts the reliability of high-order allocations when under
2805 * intense memory pressure but failed atomic allocations should be easier
2806 * to recover from than an OOM.
29fac03b
MK
2807 *
2808 * If @force is true, try to unreserve a pageblock even though highatomic
2809 * pageblock is exhausted.
0aaa29a5 2810 */
29fac03b
MK
2811static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2812 bool force)
0aaa29a5
MG
2813{
2814 struct zonelist *zonelist = ac->zonelist;
2815 unsigned long flags;
2816 struct zoneref *z;
2817 struct zone *zone;
2818 struct page *page;
2819 int order;
04c8716f 2820 bool ret;
0aaa29a5 2821
97a225e6 2822 for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->highest_zoneidx,
0aaa29a5 2823 ac->nodemask) {
29fac03b
MK
2824 /*
2825 * Preserve at least one pageblock unless memory pressure
2826 * is really high.
2827 */
2828 if (!force && zone->nr_reserved_highatomic <=
2829 pageblock_nr_pages)
0aaa29a5
MG
2830 continue;
2831
2832 spin_lock_irqsave(&zone->lock, flags);
2833 for (order = 0; order < MAX_ORDER; order++) {
2834 struct free_area *area = &(zone->free_area[order]);
2835
b03641af 2836 page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
a16601c5 2837 if (!page)
0aaa29a5
MG
2838 continue;
2839
0aaa29a5 2840 /*
4855e4a7
MK
2841 * In page freeing path, migratetype change is racy so
2842 * we can counter several free pages in a pageblock
f0953a1b 2843 * in this loop although we changed the pageblock type
4855e4a7
MK
2844 * from highatomic to ac->migratetype. So we should
2845 * adjust the count once.
0aaa29a5 2846 */
a6ffdc07 2847 if (is_migrate_highatomic_page(page)) {
4855e4a7
MK
2848 /*
2849 * It should never happen but changes to
2850 * locking could inadvertently allow a per-cpu
2851 * drain to add pages to MIGRATE_HIGHATOMIC
2852 * while unreserving so be safe and watch for
2853 * underflows.
2854 */
2855 zone->nr_reserved_highatomic -= min(
2856 pageblock_nr_pages,
2857 zone->nr_reserved_highatomic);
2858 }
0aaa29a5
MG
2859
2860 /*
2861 * Convert to ac->migratetype and avoid the normal
2862 * pageblock stealing heuristics. Minimally, the caller
2863 * is doing the work and needs the pages. More
2864 * importantly, if the block was always converted to
2865 * MIGRATE_UNMOVABLE or another type then the number
2866 * of pageblocks that cannot be completely freed
2867 * may increase.
2868 */
2869 set_pageblock_migratetype(page, ac->migratetype);
02aa0cdd
VB
2870 ret = move_freepages_block(zone, page, ac->migratetype,
2871 NULL);
29fac03b
MK
2872 if (ret) {
2873 spin_unlock_irqrestore(&zone->lock, flags);
2874 return ret;
2875 }
0aaa29a5
MG
2876 }
2877 spin_unlock_irqrestore(&zone->lock, flags);
2878 }
04c8716f
MK
2879
2880 return false;
0aaa29a5
MG
2881}
2882
3bc48f96
VB
2883/*
2884 * Try finding a free buddy page on the fallback list and put it on the free
2885 * list of requested migratetype, possibly along with other pages from the same
2886 * block, depending on fragmentation avoidance heuristics. Returns true if
2887 * fallback was found so that __rmqueue_smallest() can grab it.
b002529d
RV
2888 *
2889 * The use of signed ints for order and current_order is a deliberate
2890 * deviation from the rest of this file, to make the for loop
2891 * condition simpler.
3bc48f96 2892 */
85ccc8fa 2893static __always_inline bool
6bb15450
MG
2894__rmqueue_fallback(struct zone *zone, int order, int start_migratetype,
2895 unsigned int alloc_flags)
b2a0ac88 2896{
b8af2941 2897 struct free_area *area;
b002529d 2898 int current_order;
6bb15450 2899 int min_order = order;
b2a0ac88 2900 struct page *page;
4eb7dce6
JK
2901 int fallback_mt;
2902 bool can_steal;
b2a0ac88 2903
6bb15450
MG
2904 /*
2905 * Do not steal pages from freelists belonging to other pageblocks
2906 * i.e. orders < pageblock_order. If there are no local zones free,
2907 * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2908 */
2909 if (alloc_flags & ALLOC_NOFRAGMENT)
2910 min_order = pageblock_order;
2911
7a8f58f3
VB
2912 /*
2913 * Find the largest available free page in the other list. This roughly
2914 * approximates finding the pageblock with the most free pages, which
2915 * would be too costly to do exactly.
2916 */
6bb15450 2917 for (current_order = MAX_ORDER - 1; current_order >= min_order;
7aeb09f9 2918 --current_order) {
4eb7dce6
JK
2919 area = &(zone->free_area[current_order]);
2920 fallback_mt = find_suitable_fallback(area, current_order,
2149cdae 2921 start_migratetype, false, &can_steal);
4eb7dce6
JK
2922 if (fallback_mt == -1)
2923 continue;
b2a0ac88 2924
7a8f58f3
VB
2925 /*
2926 * We cannot steal all free pages from the pageblock and the
2927 * requested migratetype is movable. In that case it's better to
2928 * steal and split the smallest available page instead of the
2929 * largest available page, because even if the next movable
2930 * allocation falls back into a different pageblock than this
2931 * one, it won't cause permanent fragmentation.
2932 */
2933 if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2934 && current_order > order)
2935 goto find_smallest;
b2a0ac88 2936
7a8f58f3
VB
2937 goto do_steal;
2938 }
e0fff1bd 2939
7a8f58f3 2940 return false;
e0fff1bd 2941
7a8f58f3
VB
2942find_smallest:
2943 for (current_order = order; current_order < MAX_ORDER;
2944 current_order++) {
2945 area = &(zone->free_area[current_order]);
2946 fallback_mt = find_suitable_fallback(area, current_order,
2947 start_migratetype, false, &can_steal);
2948 if (fallback_mt != -1)
2949 break;
b2a0ac88
MG
2950 }
2951
7a8f58f3
VB
2952 /*
2953 * This should not happen - we already found a suitable fallback
2954 * when looking for the largest page.
2955 */
2956 VM_BUG_ON(current_order == MAX_ORDER);
2957
2958do_steal:
b03641af 2959 page = get_page_from_free_area(area, fallback_mt);
7a8f58f3 2960
1c30844d
MG
2961 steal_suitable_fallback(zone, page, alloc_flags, start_migratetype,
2962 can_steal);
7a8f58f3
VB
2963
2964 trace_mm_page_alloc_extfrag(page, order, current_order,
2965 start_migratetype, fallback_mt);
2966
2967 return true;
2968
b2a0ac88
MG
2969}
2970
56fd56b8 2971/*
1da177e4
LT
2972 * Do the hard work of removing an element from the buddy allocator.
2973 * Call me with the zone->lock already held.
2974 */
85ccc8fa 2975static __always_inline struct page *
6bb15450
MG
2976__rmqueue(struct zone *zone, unsigned int order, int migratetype,
2977 unsigned int alloc_flags)
1da177e4 2978{
1da177e4
LT
2979 struct page *page;
2980
ce8f86ee
H
2981 if (IS_ENABLED(CONFIG_CMA)) {
2982 /*
2983 * Balance movable allocations between regular and CMA areas by
2984 * allocating from CMA when over half of the zone's free memory
2985 * is in the CMA area.
2986 */
2987 if (alloc_flags & ALLOC_CMA &&
2988 zone_page_state(zone, NR_FREE_CMA_PAGES) >
2989 zone_page_state(zone, NR_FREE_PAGES) / 2) {
2990 page = __rmqueue_cma_fallback(zone, order);
2991 if (page)
2992 goto out;
2993 }
16867664 2994 }
3bc48f96 2995retry:
56fd56b8 2996 page = __rmqueue_smallest(zone, order, migratetype);
974a786e 2997 if (unlikely(!page)) {
8510e69c 2998 if (alloc_flags & ALLOC_CMA)
dc67647b
JK
2999 page = __rmqueue_cma_fallback(zone, order);
3000
6bb15450
MG
3001 if (!page && __rmqueue_fallback(zone, order, migratetype,
3002 alloc_flags))
3bc48f96 3003 goto retry;
728ec980 3004 }
ce8f86ee
H
3005out:
3006 if (page)
3007 trace_mm_page_alloc_zone_locked(page, order, migratetype);
b2a0ac88 3008 return page;
1da177e4
LT
3009}
3010
5f63b720 3011/*
1da177e4
LT
3012 * Obtain a specified number of elements from the buddy allocator, all under
3013 * a single hold of the lock, for efficiency. Add them to the supplied list.
3014 * Returns the number of new pages which were placed at *list.
3015 */
5f63b720 3016static int rmqueue_bulk(struct zone *zone, unsigned int order,
b2a0ac88 3017 unsigned long count, struct list_head *list,
6bb15450 3018 int migratetype, unsigned int alloc_flags)
1da177e4 3019{
cb66bede 3020 int i, allocated = 0;
5f63b720 3021
dbbee9d5
MG
3022 /*
3023 * local_lock_irq held so equivalent to spin_lock_irqsave for
3024 * both PREEMPT_RT and non-PREEMPT_RT configurations.
3025 */
d34b0733 3026 spin_lock(&zone->lock);
1da177e4 3027 for (i = 0; i < count; ++i) {
6bb15450
MG
3028 struct page *page = __rmqueue(zone, order, migratetype,
3029 alloc_flags);
085cc7d5 3030 if (unlikely(page == NULL))
1da177e4 3031 break;
81eabcbe 3032
77fe7f13 3033 if (unlikely(check_pcp_refill(page, order)))
479f854a
MG
3034 continue;
3035
81eabcbe 3036 /*
0fac3ba5
VB
3037 * Split buddy pages returned by expand() are received here in
3038 * physical page order. The page is added to the tail of
3039 * caller's list. From the callers perspective, the linked list
3040 * is ordered by page number under some conditions. This is
3041 * useful for IO devices that can forward direction from the
3042 * head, thus also in the physical page order. This is useful
3043 * for IO devices that can merge IO requests if the physical
3044 * pages are ordered properly.
81eabcbe 3045 */
0fac3ba5 3046 list_add_tail(&page->lru, list);
cb66bede 3047 allocated++;
bb14c2c7 3048 if (is_migrate_cma(get_pcppage_migratetype(page)))
d1ce749a
BZ
3049 __mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
3050 -(1 << order));
1da177e4 3051 }
a6de734b
MG
3052
3053 /*
3054 * i pages were removed from the buddy list even if some leak due
3055 * to check_pcp_refill failing so adjust NR_FREE_PAGES based
cb66bede 3056 * on i. Do not confuse with 'allocated' which is the number of
a6de734b
MG
3057 * pages added to the pcp list.
3058 */
f2260e6b 3059 __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
d34b0733 3060 spin_unlock(&zone->lock);
cb66bede 3061 return allocated;
1da177e4
LT
3062}
3063
4ae7c039 3064#ifdef CONFIG_NUMA
8fce4d8e 3065/*
4037d452
CL
3066 * Called from the vmstat counter updater to drain pagesets of this
3067 * currently executing processor on remote nodes after they have
3068 * expired.
3069 *
879336c3
CL
3070 * Note that this function must be called with the thread pinned to
3071 * a single processor.
8fce4d8e 3072 */
4037d452 3073void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
4ae7c039 3074{
4ae7c039 3075 unsigned long flags;
7be12fc9 3076 int to_drain, batch;
4ae7c039 3077
dbbee9d5 3078 local_lock_irqsave(&pagesets.lock, flags);
4db0c3c2 3079 batch = READ_ONCE(pcp->batch);
7be12fc9 3080 to_drain = min(pcp->count, batch);
77ba9062 3081 if (to_drain > 0)
fd56eef2 3082 free_pcppages_bulk(zone, to_drain, pcp, 0);
dbbee9d5 3083 local_unlock_irqrestore(&pagesets.lock, flags);
4ae7c039
CL
3084}
3085#endif
3086
9f8f2172 3087/*
93481ff0 3088 * Drain pcplists of the indicated processor and zone.
9f8f2172
CL
3089 *
3090 * The processor must either be the current processor and the
3091 * thread pinned to the current processor or a processor that
3092 * is not online.
3093 */
93481ff0 3094static void drain_pages_zone(unsigned int cpu, struct zone *zone)
1da177e4 3095{
c54ad30c 3096 unsigned long flags;
93481ff0 3097 struct per_cpu_pages *pcp;
1da177e4 3098
dbbee9d5 3099 local_lock_irqsave(&pagesets.lock, flags);
1da177e4 3100
28f836b6 3101 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
77ba9062 3102 if (pcp->count)
fd56eef2 3103 free_pcppages_bulk(zone, pcp->count, pcp, 0);
28f836b6 3104
dbbee9d5 3105 local_unlock_irqrestore(&pagesets.lock, flags);
93481ff0 3106}
3dfa5721 3107
93481ff0
VB
3108/*
3109 * Drain pcplists of all zones on the indicated processor.
3110 *
3111 * The processor must either be the current processor and the
3112 * thread pinned to the current processor or a processor that
3113 * is not online.
3114 */
3115static void drain_pages(unsigned int cpu)
3116{
3117 struct zone *zone;
3118
3119 for_each_populated_zone(zone) {
3120 drain_pages_zone(cpu, zone);
1da177e4
LT
3121 }
3122}
1da177e4 3123
9f8f2172
CL
3124/*
3125 * Spill all of this CPU's per-cpu pages back into the buddy allocator.
93481ff0
VB
3126 *
3127 * The CPU has to be pinned. When zone parameter is non-NULL, spill just
3128 * the single zone's pages.
9f8f2172 3129 */
93481ff0 3130void drain_local_pages(struct zone *zone)
9f8f2172 3131{
93481ff0
VB
3132 int cpu = smp_processor_id();
3133
3134 if (zone)
3135 drain_pages_zone(cpu, zone);
3136 else
3137 drain_pages(cpu);
9f8f2172
CL
3138}
3139
0ccce3b9
MG
3140static void drain_local_pages_wq(struct work_struct *work)
3141{
d9367bd0
WY
3142 struct pcpu_drain *drain;
3143
3144 drain = container_of(work, struct pcpu_drain, work);
3145
a459eeb7
MH
3146 /*
3147 * drain_all_pages doesn't use proper cpu hotplug protection so
3148 * we can race with cpu offline when the WQ can move this from
3149 * a cpu pinned worker to an unbound one. We can operate on a different
f0953a1b 3150 * cpu which is alright but we also have to make sure to not move to
a459eeb7
MH
3151 * a different one.
3152 */
9c25cbfc 3153 migrate_disable();
d9367bd0 3154 drain_local_pages(drain->zone);
9c25cbfc 3155 migrate_enable();
0ccce3b9
MG
3156}
3157
9f8f2172 3158/*
ec6e8c7e
VB
3159 * The implementation of drain_all_pages(), exposing an extra parameter to
3160 * drain on all cpus.
93481ff0 3161 *
ec6e8c7e
VB
3162 * drain_all_pages() is optimized to only execute on cpus where pcplists are
3163 * not empty. The check for non-emptiness can however race with a free to
3164 * pcplist that has not yet increased the pcp->count from 0 to 1. Callers
3165 * that need the guarantee that every CPU has drained can disable the
3166 * optimizing racy check.
9f8f2172 3167 */
3b1f3658 3168static void __drain_all_pages(struct zone *zone, bool force_all_cpus)
9f8f2172 3169{
74046494 3170 int cpu;
74046494
GBY
3171
3172 /*
041711ce 3173 * Allocate in the BSS so we won't require allocation in
74046494
GBY
3174 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
3175 */
3176 static cpumask_t cpus_with_pcps;
3177
ce612879
MH
3178 /*
3179 * Make sure nobody triggers this path before mm_percpu_wq is fully
3180 * initialized.
3181 */
3182 if (WARN_ON_ONCE(!mm_percpu_wq))
3183 return;
3184
bd233f53
MG
3185 /*
3186 * Do not drain if one is already in progress unless it's specific to
3187 * a zone. Such callers are primarily CMA and memory hotplug and need
3188 * the drain to be complete when the call returns.
3189 */
3190 if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
3191 if (!zone)
3192 return;
3193 mutex_lock(&pcpu_drain_mutex);
3194 }
0ccce3b9 3195
74046494
GBY
3196 /*
3197 * We don't care about racing with CPU hotplug event
3198 * as offline notification will cause the notified
3199 * cpu to drain that CPU pcps and on_each_cpu_mask
3200 * disables preemption as part of its processing
3201 */
3202 for_each_online_cpu(cpu) {
28f836b6 3203 struct per_cpu_pages *pcp;
93481ff0 3204 struct zone *z;
74046494 3205 bool has_pcps = false;
93481ff0 3206
ec6e8c7e
VB
3207 if (force_all_cpus) {
3208 /*
3209 * The pcp.count check is racy, some callers need a
3210 * guarantee that no cpu is missed.
3211 */
3212 has_pcps = true;
3213 } else if (zone) {
28f836b6
MG
3214 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
3215 if (pcp->count)
74046494 3216 has_pcps = true;
93481ff0
VB
3217 } else {
3218 for_each_populated_zone(z) {
28f836b6
MG
3219 pcp = per_cpu_ptr(z->per_cpu_pageset, cpu);
3220 if (pcp->count) {
93481ff0
VB
3221 has_pcps = true;
3222 break;
3223 }
74046494
GBY
3224 }
3225 }
93481ff0 3226
74046494
GBY
3227 if (has_pcps)
3228 cpumask_set_cpu(cpu, &cpus_with_pcps);
3229 else
3230 cpumask_clear_cpu(cpu, &cpus_with_pcps);
3231 }
0ccce3b9 3232
bd233f53 3233 for_each_cpu(cpu, &cpus_with_pcps) {
d9367bd0
WY
3234 struct pcpu_drain *drain = per_cpu_ptr(&pcpu_drain, cpu);
3235
3236 drain->zone = zone;
3237 INIT_WORK(&drain->work, drain_local_pages_wq);
3238 queue_work_on(cpu, mm_percpu_wq, &drain->work);
0ccce3b9 3239 }
bd233f53 3240 for_each_cpu(cpu, &cpus_with_pcps)
d9367bd0 3241 flush_work(&per_cpu_ptr(&pcpu_drain, cpu)->work);
bd233f53
MG
3242
3243 mutex_unlock(&pcpu_drain_mutex);
9f8f2172
CL
3244}
3245
ec6e8c7e
VB
3246/*
3247 * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
3248 *
3249 * When zone parameter is non-NULL, spill just the single zone's pages.
3250 *
3251 * Note that this can be extremely slow as the draining happens in a workqueue.
3252 */
3253void drain_all_pages(struct zone *zone)
3254{
3255 __drain_all_pages(zone, false);
3256}
3257
296699de 3258#ifdef CONFIG_HIBERNATION
1da177e4 3259
556b969a
CY
3260/*
3261 * Touch the watchdog for every WD_PAGE_COUNT pages.
3262 */
3263#define WD_PAGE_COUNT (128*1024)
3264
1da177e4
LT
3265void mark_free_pages(struct zone *zone)
3266{
556b969a 3267 unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
f623f0db 3268 unsigned long flags;
7aeb09f9 3269 unsigned int order, t;
86760a2c 3270 struct page *page;
1da177e4 3271
8080fc03 3272 if (zone_is_empty(zone))
1da177e4
LT
3273 return;
3274
3275 spin_lock_irqsave(&zone->lock, flags);
f623f0db 3276
108bcc96 3277 max_zone_pfn = zone_end_pfn(zone);
f623f0db
RW
3278 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
3279 if (pfn_valid(pfn)) {
86760a2c 3280 page = pfn_to_page(pfn);
ba6b0979 3281
556b969a
CY
3282 if (!--page_count) {
3283 touch_nmi_watchdog();
3284 page_count = WD_PAGE_COUNT;
3285 }
3286
ba6b0979
JK
3287 if (page_zone(page) != zone)
3288 continue;
3289
7be98234
RW
3290 if (!swsusp_page_is_forbidden(page))
3291 swsusp_unset_page_free(page);
f623f0db 3292 }
1da177e4 3293
b2a0ac88 3294 for_each_migratetype_order(order, t) {
86760a2c
GT
3295 list_for_each_entry(page,
3296 &zone->free_area[order].free_list[t], lru) {
f623f0db 3297 unsigned long i;
1da177e4 3298
86760a2c 3299 pfn = page_to_pfn(page);
556b969a
CY
3300 for (i = 0; i < (1UL << order); i++) {
3301 if (!--page_count) {
3302 touch_nmi_watchdog();
3303 page_count = WD_PAGE_COUNT;
3304 }
7be98234 3305 swsusp_set_page_free(pfn_to_page(pfn + i));
556b969a 3306 }
f623f0db 3307 }
b2a0ac88 3308 }
1da177e4
LT
3309 spin_unlock_irqrestore(&zone->lock, flags);
3310}
e2c55dc8 3311#endif /* CONFIG_PM */
1da177e4 3312
44042b44
MG
3313static bool free_unref_page_prepare(struct page *page, unsigned long pfn,
3314 unsigned int order)
1da177e4 3315{
5f8dcc21 3316 int migratetype;
1da177e4 3317
44042b44 3318 if (!free_pcp_prepare(page, order))
9cca35d4 3319 return false;
689bcebf 3320
dc4b0caf 3321 migratetype = get_pfnblock_migratetype(page, pfn);
bb14c2c7 3322 set_pcppage_migratetype(page, migratetype);
9cca35d4
MG
3323 return true;
3324}
3325
f26b3fa0
MG
3326static int nr_pcp_free(struct per_cpu_pages *pcp, int high, int batch,
3327 bool free_high)
3b12e7e9
MG
3328{
3329 int min_nr_free, max_nr_free;
3330
f26b3fa0
MG
3331 /* Free everything if batch freeing high-order pages. */
3332 if (unlikely(free_high))
3333 return pcp->count;
3334
3b12e7e9
MG
3335 /* Check for PCP disabled or boot pageset */
3336 if (unlikely(high < batch))
3337 return 1;
3338
3339 /* Leave at least pcp->batch pages on the list */
3340 min_nr_free = batch;
3341 max_nr_free = high - batch;
3342
3343 /*
3344 * Double the number of pages freed each time there is subsequent
3345 * freeing of pages without any allocation.
3346 */
3347 batch <<= pcp->free_factor;
3348 if (batch < max_nr_free)
3349 pcp->free_factor++;
3350 batch = clamp(batch, min_nr_free, max_nr_free);
3351
3352 return batch;
3353}
3354
f26b3fa0
MG
3355static int nr_pcp_high(struct per_cpu_pages *pcp, struct zone *zone,
3356 bool free_high)
c49c2c47
MG
3357{
3358 int high = READ_ONCE(pcp->high);
3359
f26b3fa0 3360 if (unlikely(!high || free_high))
c49c2c47
MG
3361 return 0;
3362
3363 if (!test_bit(ZONE_RECLAIM_ACTIVE, &zone->flags))
3364 return high;
3365
3366 /*
3367 * If reclaim is active, limit the number of pages that can be
3368 * stored on pcp lists
3369 */
3370 return min(READ_ONCE(pcp->batch) << 2, high);
3371}
3372
56651377
NSJ
3373static void free_unref_page_commit(struct page *page, int migratetype,
3374 unsigned int order)
9cca35d4
MG
3375{
3376 struct zone *zone = page_zone(page);
3377 struct per_cpu_pages *pcp;
3b12e7e9 3378 int high;
44042b44 3379 int pindex;
f26b3fa0 3380 bool free_high;
9cca35d4 3381
d34b0733 3382 __count_vm_event(PGFREE);
28f836b6 3383 pcp = this_cpu_ptr(zone->per_cpu_pageset);
44042b44
MG
3384 pindex = order_to_pindex(migratetype, order);
3385 list_add(&page->lru, &pcp->lists[pindex]);
3386 pcp->count += 1 << order;
f26b3fa0
MG
3387
3388 /*
3389 * As high-order pages other than THP's stored on PCP can contribute
3390 * to fragmentation, limit the number stored when PCP is heavily
3391 * freeing without allocation. The remainder after bulk freeing
3392 * stops will be drained from vmstat refresh context.
3393 */
3394 free_high = (pcp->free_factor && order && order <= PAGE_ALLOC_COSTLY_ORDER);
3395
3396 high = nr_pcp_high(pcp, zone, free_high);
3b12e7e9
MG
3397 if (pcp->count >= high) {
3398 int batch = READ_ONCE(pcp->batch);
3399
f26b3fa0 3400 free_pcppages_bulk(zone, nr_pcp_free(pcp, high, batch, free_high), pcp, pindex);
3b12e7e9 3401 }
9cca35d4 3402}
5f8dcc21 3403
9cca35d4 3404/*
44042b44 3405 * Free a pcp page
9cca35d4 3406 */
44042b44 3407void free_unref_page(struct page *page, unsigned int order)
9cca35d4
MG
3408{
3409 unsigned long flags;
3410 unsigned long pfn = page_to_pfn(page);
df1acc85 3411 int migratetype;
9cca35d4 3412
44042b44 3413 if (!free_unref_page_prepare(page, pfn, order))
9cca35d4 3414 return;
da456f14 3415
5f8dcc21
MG
3416 /*
3417 * We only track unmovable, reclaimable and movable on pcp lists.
df1acc85 3418 * Place ISOLATE pages on the isolated list because they are being
a6ffdc07 3419 * offlined but treat HIGHATOMIC as movable pages so we can get those
5f8dcc21
MG
3420 * areas back if necessary. Otherwise, we may have to free
3421 * excessively into the page allocator
3422 */
df1acc85
MG
3423 migratetype = get_pcppage_migratetype(page);
3424 if (unlikely(migratetype >= MIGRATE_PCPTYPES)) {
194159fb 3425 if (unlikely(is_migrate_isolate(migratetype))) {
44042b44 3426 free_one_page(page_zone(page), page, pfn, order, migratetype, FPI_NONE);
9cca35d4 3427 return;
5f8dcc21
MG
3428 }
3429 migratetype = MIGRATE_MOVABLE;
3430 }
3431
dbbee9d5 3432 local_lock_irqsave(&pagesets.lock, flags);
56651377 3433 free_unref_page_commit(page, migratetype, order);
dbbee9d5 3434 local_unlock_irqrestore(&pagesets.lock, flags);
1da177e4
LT
3435}
3436
cc59850e
KK
3437/*
3438 * Free a list of 0-order pages
3439 */
2d4894b5 3440void free_unref_page_list(struct list_head *list)
cc59850e
KK
3441{
3442 struct page *page, *next;
56651377 3443 unsigned long flags;
c24ad77d 3444 int batch_count = 0;
df1acc85 3445 int migratetype;
9cca35d4
MG
3446
3447 /* Prepare pages for freeing */
3448 list_for_each_entry_safe(page, next, list, lru) {
56651377 3449 unsigned long pfn = page_to_pfn(page);
053cfda1 3450 if (!free_unref_page_prepare(page, pfn, 0)) {
9cca35d4 3451 list_del(&page->lru);
053cfda1
ML
3452 continue;
3453 }
df1acc85
MG
3454
3455 /*
3456 * Free isolated pages directly to the allocator, see
3457 * comment in free_unref_page.
3458 */
3459 migratetype = get_pcppage_migratetype(page);
47aef601
DB
3460 if (unlikely(is_migrate_isolate(migratetype))) {
3461 list_del(&page->lru);
3462 free_one_page(page_zone(page), page, pfn, 0, migratetype, FPI_NONE);
3463 continue;
df1acc85 3464 }
9cca35d4 3465 }
cc59850e 3466
dbbee9d5 3467 local_lock_irqsave(&pagesets.lock, flags);
cc59850e 3468 list_for_each_entry_safe(page, next, list, lru) {
47aef601
DB
3469 /*
3470 * Non-isolated types over MIGRATE_PCPTYPES get added
3471 * to the MIGRATE_MOVABLE pcp list.
3472 */
df1acc85 3473 migratetype = get_pcppage_migratetype(page);
47aef601
DB
3474 if (unlikely(migratetype >= MIGRATE_PCPTYPES))
3475 migratetype = MIGRATE_MOVABLE;
3476
2d4894b5 3477 trace_mm_page_free_batched(page);
56651377 3478 free_unref_page_commit(page, migratetype, 0);
c24ad77d
LS
3479
3480 /*
3481 * Guard against excessive IRQ disabled times when we get
3482 * a large list of pages to free.
3483 */
3484 if (++batch_count == SWAP_CLUSTER_MAX) {
dbbee9d5 3485 local_unlock_irqrestore(&pagesets.lock, flags);
c24ad77d 3486 batch_count = 0;
dbbee9d5 3487 local_lock_irqsave(&pagesets.lock, flags);
c24ad77d 3488 }
cc59850e 3489 }
dbbee9d5 3490 local_unlock_irqrestore(&pagesets.lock, flags);
cc59850e
KK
3491}
3492
8dfcc9ba
NP
3493/*
3494 * split_page takes a non-compound higher-order page, and splits it into
3495 * n (1<<order) sub-pages: page[0..n]
3496 * Each sub-page must be freed individually.
3497 *
3498 * Note: this is probably too low level an operation for use in drivers.
3499 * Please consult with lkml before using this in your driver.
3500 */
3501void split_page(struct page *page, unsigned int order)
3502{
3503 int i;
3504
309381fe
SL
3505 VM_BUG_ON_PAGE(PageCompound(page), page);
3506 VM_BUG_ON_PAGE(!page_count(page), page);
b1eeab67 3507
a9627bc5 3508 for (i = 1; i < (1 << order); i++)
7835e98b 3509 set_page_refcounted(page + i);
8fb156c9 3510 split_page_owner(page, 1 << order);
e1baddf8 3511 split_page_memcg(page, 1 << order);
8dfcc9ba 3512}
5853ff23 3513EXPORT_SYMBOL_GPL(split_page);
8dfcc9ba 3514
3c605096 3515int __isolate_free_page(struct page *page, unsigned int order)
748446bb 3516{
748446bb
MG
3517 unsigned long watermark;
3518 struct zone *zone;
2139cbe6 3519 int mt;
748446bb
MG
3520
3521 BUG_ON(!PageBuddy(page));
3522
3523 zone = page_zone(page);
2e30abd1 3524 mt = get_pageblock_migratetype(page);
748446bb 3525
194159fb 3526 if (!is_migrate_isolate(mt)) {
8348faf9
VB
3527 /*
3528 * Obey watermarks as if the page was being allocated. We can
3529 * emulate a high-order watermark check with a raised order-0
3530 * watermark, because we already know our high-order page
3531 * exists.
3532 */
fd1444b2 3533 watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
d883c6cf 3534 if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
2e30abd1
MS
3535 return 0;
3536
8fb74b9f 3537 __mod_zone_freepage_state(zone, -(1UL << order), mt);
2e30abd1 3538 }
748446bb
MG
3539
3540 /* Remove page from free list */
b03641af 3541
6ab01363 3542 del_page_from_free_list(page, zone, order);
2139cbe6 3543
400bc7fd 3544 /*
3545 * Set the pageblock if the isolated page is at least half of a
3546 * pageblock
3547 */
748446bb
MG
3548 if (order >= pageblock_order - 1) {
3549 struct page *endpage = page + (1 << order) - 1;
47118af0
MN
3550 for (; page < endpage; page += pageblock_nr_pages) {
3551 int mt = get_pageblock_migratetype(page);
1dd214b8
ZY
3552 /*
3553 * Only change normal pageblocks (i.e., they can merge
3554 * with others)
3555 */
3556 if (migratetype_is_mergeable(mt))
47118af0
MN
3557 set_pageblock_migratetype(page,
3558 MIGRATE_MOVABLE);
3559 }
748446bb
MG
3560 }
3561
f3a14ced 3562
8fb74b9f 3563 return 1UL << order;
1fb3f8ca
MG
3564}
3565
624f58d8
AD
3566/**
3567 * __putback_isolated_page - Return a now-isolated page back where we got it
3568 * @page: Page that was isolated
3569 * @order: Order of the isolated page
e6a0a7ad 3570 * @mt: The page's pageblock's migratetype
624f58d8
AD
3571 *
3572 * This function is meant to return a page pulled from the free lists via
3573 * __isolate_free_page back to the free lists they were pulled from.
3574 */
3575void __putback_isolated_page(struct page *page, unsigned int order, int mt)
3576{
3577 struct zone *zone = page_zone(page);
3578
3579 /* zone lock should be held when this function is called */
3580 lockdep_assert_held(&zone->lock);
3581
3582 /* Return isolated page to tail of freelist. */
f04a5d5d 3583 __free_one_page(page, page_to_pfn(page), zone, order, mt,
47b6a24a 3584 FPI_SKIP_REPORT_NOTIFY | FPI_TO_TAIL);
624f58d8
AD
3585}
3586
060e7417
MG
3587/*
3588 * Update NUMA hit/miss statistics
3589 *
3590 * Must be called with interrupts disabled.
060e7417 3591 */
3e23060b
MG
3592static inline void zone_statistics(struct zone *preferred_zone, struct zone *z,
3593 long nr_account)
060e7417
MG
3594{
3595#ifdef CONFIG_NUMA
3a321d2a 3596 enum numa_stat_item local_stat = NUMA_LOCAL;
060e7417 3597
4518085e
KW
3598 /* skip numa counters update if numa stats is disabled */
3599 if (!static_branch_likely(&vm_numa_stat_key))
3600 return;
3601
c1093b74 3602 if (zone_to_nid(z) != numa_node_id())
060e7417 3603 local_stat = NUMA_OTHER;
060e7417 3604
c1093b74 3605 if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3e23060b 3606 __count_numa_events(z, NUMA_HIT, nr_account);
2df26639 3607 else {
3e23060b
MG
3608 __count_numa_events(z, NUMA_MISS, nr_account);
3609 __count_numa_events(preferred_zone, NUMA_FOREIGN, nr_account);
060e7417 3610 }
3e23060b 3611 __count_numa_events(z, local_stat, nr_account);
060e7417
MG
3612#endif
3613}
3614
066b2393 3615/* Remove page from the per-cpu list, caller must protect the list */
3b822017 3616static inline
44042b44
MG
3617struct page *__rmqueue_pcplist(struct zone *zone, unsigned int order,
3618 int migratetype,
6bb15450 3619 unsigned int alloc_flags,
453f85d4 3620 struct per_cpu_pages *pcp,
066b2393
MG
3621 struct list_head *list)
3622{
3623 struct page *page;
3624
3625 do {
3626 if (list_empty(list)) {
44042b44
MG
3627 int batch = READ_ONCE(pcp->batch);
3628 int alloced;
3629
3630 /*
3631 * Scale batch relative to order if batch implies
3632 * free pages can be stored on the PCP. Batch can
3633 * be 1 for small zones or for boot pagesets which
3634 * should never store free pages as the pages may
3635 * belong to arbitrary zones.
3636 */
3637 if (batch > 1)
3638 batch = max(batch >> order, 2);
3639 alloced = rmqueue_bulk(zone, order,
3640 batch, list,
6bb15450 3641 migratetype, alloc_flags);
44042b44
MG
3642
3643 pcp->count += alloced << order;
066b2393
MG
3644 if (unlikely(list_empty(list)))
3645 return NULL;
3646 }
3647
453f85d4 3648 page = list_first_entry(list, struct page, lru);
066b2393 3649 list_del(&page->lru);
44042b44 3650 pcp->count -= 1 << order;
77fe7f13 3651 } while (check_new_pcp(page, order));
066b2393
MG
3652
3653 return page;
3654}
3655
3656/* Lock and remove page from the per-cpu list */
3657static struct page *rmqueue_pcplist(struct zone *preferred_zone,
44042b44
MG
3658 struct zone *zone, unsigned int order,
3659 gfp_t gfp_flags, int migratetype,
3660 unsigned int alloc_flags)
066b2393
MG
3661{
3662 struct per_cpu_pages *pcp;
3663 struct list_head *list;
066b2393 3664 struct page *page;
d34b0733 3665 unsigned long flags;
066b2393 3666
dbbee9d5 3667 local_lock_irqsave(&pagesets.lock, flags);
3b12e7e9
MG
3668
3669 /*
3670 * On allocation, reduce the number of pages that are batch freed.
3671 * See nr_pcp_free() where free_factor is increased for subsequent
3672 * frees.
3673 */
28f836b6 3674 pcp = this_cpu_ptr(zone->per_cpu_pageset);
3b12e7e9 3675 pcp->free_factor >>= 1;
44042b44
MG
3676 list = &pcp->lists[order_to_pindex(migratetype, order)];
3677 page = __rmqueue_pcplist(zone, order, migratetype, alloc_flags, pcp, list);
43c95bcc 3678 local_unlock_irqrestore(&pagesets.lock, flags);
066b2393 3679 if (page) {
1c52e6d0 3680 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1);
3e23060b 3681 zone_statistics(preferred_zone, zone, 1);
066b2393 3682 }
066b2393
MG
3683 return page;
3684}
3685
1da177e4 3686/*
75379191 3687 * Allocate a page from the given zone. Use pcplists for order-0 allocations.
1da177e4 3688 */
0a15c3e9 3689static inline
066b2393 3690struct page *rmqueue(struct zone *preferred_zone,
7aeb09f9 3691 struct zone *zone, unsigned int order,
c603844b
MG
3692 gfp_t gfp_flags, unsigned int alloc_flags,
3693 int migratetype)
1da177e4
LT
3694{
3695 unsigned long flags;
689bcebf 3696 struct page *page;
1da177e4 3697
44042b44 3698 if (likely(pcp_allowed_order(order))) {
1d91df85
JK
3699 /*
3700 * MIGRATE_MOVABLE pcplist could have the pages on CMA area and
3701 * we need to skip it when CMA area isn't allowed.
3702 */
3703 if (!IS_ENABLED(CONFIG_CMA) || alloc_flags & ALLOC_CMA ||
3704 migratetype != MIGRATE_MOVABLE) {
44042b44
MG
3705 page = rmqueue_pcplist(preferred_zone, zone, order,
3706 gfp_flags, migratetype, alloc_flags);
1d91df85
JK
3707 goto out;
3708 }
066b2393 3709 }
83b9355b 3710
066b2393
MG
3711 /*
3712 * We most definitely don't want callers attempting to
3713 * allocate greater than order-1 page units with __GFP_NOFAIL.
3714 */
3715 WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
0aaa29a5 3716
066b2393
MG
3717 do {
3718 page = NULL;
3313204c 3719 spin_lock_irqsave(&zone->lock, flags);
1d91df85
JK
3720 /*
3721 * order-0 request can reach here when the pcplist is skipped
3722 * due to non-CMA allocation context. HIGHATOMIC area is
3723 * reserved for high-order atomic allocation, so order-0
3724 * request should skip it.
3725 */
3726 if (order > 0 && alloc_flags & ALLOC_HARDER) {
066b2393
MG
3727 page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3728 if (page)
3729 trace_mm_page_alloc_zone_locked(page, order, migratetype);
3730 }
3313204c 3731 if (!page) {
6bb15450 3732 page = __rmqueue(zone, order, migratetype, alloc_flags);
3313204c
ED
3733 if (!page)
3734 goto failed;
3735 }
3736 __mod_zone_freepage_state(zone, -(1 << order),
3737 get_pcppage_migratetype(page));
3738 spin_unlock_irqrestore(&zone->lock, flags);
3739 } while (check_new_pages(page, order));
1da177e4 3740
16709d1d 3741 __count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3e23060b 3742 zone_statistics(preferred_zone, zone, 1);
1da177e4 3743
066b2393 3744out:
73444bc4
MG
3745 /* Separate test+clear to avoid unnecessary atomics */
3746 if (test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags)) {
3747 clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3748 wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3749 }
3750
066b2393 3751 VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
1da177e4 3752 return page;
a74609fa
NP
3753
3754failed:
43c95bcc 3755 spin_unlock_irqrestore(&zone->lock, flags);
a74609fa 3756 return NULL;
1da177e4
LT
3757}
3758
933e312e
AM
3759#ifdef CONFIG_FAIL_PAGE_ALLOC
3760
b2588c4b 3761static struct {
933e312e
AM
3762 struct fault_attr attr;
3763
621a5f7a 3764 bool ignore_gfp_highmem;
71baba4b 3765 bool ignore_gfp_reclaim;
54114994 3766 u32 min_order;
933e312e
AM
3767} fail_page_alloc = {
3768 .attr = FAULT_ATTR_INITIALIZER,
71baba4b 3769 .ignore_gfp_reclaim = true,
621a5f7a 3770 .ignore_gfp_highmem = true,
54114994 3771 .min_order = 1,
933e312e
AM
3772};
3773
3774static int __init setup_fail_page_alloc(char *str)
3775{
3776 return setup_fault_attr(&fail_page_alloc.attr, str);
3777}
3778__setup("fail_page_alloc=", setup_fail_page_alloc);
3779
af3b8544 3780static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
933e312e 3781{
54114994 3782 if (order < fail_page_alloc.min_order)
deaf386e 3783 return false;
933e312e 3784 if (gfp_mask & __GFP_NOFAIL)
deaf386e 3785 return false;
933e312e 3786 if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
deaf386e 3787 return false;
71baba4b
MG
3788 if (fail_page_alloc.ignore_gfp_reclaim &&
3789 (gfp_mask & __GFP_DIRECT_RECLAIM))
deaf386e 3790 return false;
933e312e
AM
3791
3792 return should_fail(&fail_page_alloc.attr, 1 << order);
3793}
3794
3795#ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3796
3797static int __init fail_page_alloc_debugfs(void)
3798{
0825a6f9 3799 umode_t mode = S_IFREG | 0600;
933e312e 3800 struct dentry *dir;
933e312e 3801
dd48c085
AM
3802 dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3803 &fail_page_alloc.attr);
b2588c4b 3804
d9f7979c
GKH
3805 debugfs_create_bool("ignore-gfp-wait", mode, dir,
3806 &fail_page_alloc.ignore_gfp_reclaim);
3807 debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3808 &fail_page_alloc.ignore_gfp_highmem);
3809 debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order);
933e312e 3810
d9f7979c 3811 return 0;
933e312e
AM
3812}
3813
3814late_initcall(fail_page_alloc_debugfs);
3815
3816#endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3817
3818#else /* CONFIG_FAIL_PAGE_ALLOC */
3819
af3b8544 3820static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
933e312e 3821{
deaf386e 3822 return false;
933e312e
AM
3823}
3824
3825#endif /* CONFIG_FAIL_PAGE_ALLOC */
3826
54aa3866 3827noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
af3b8544
BP
3828{
3829 return __should_fail_alloc_page(gfp_mask, order);
3830}
3831ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE);
3832
f27ce0e1
JK
3833static inline long __zone_watermark_unusable_free(struct zone *z,
3834 unsigned int order, unsigned int alloc_flags)
3835{
3836 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3837 long unusable_free = (1 << order) - 1;
3838
3839 /*
3840 * If the caller does not have rights to ALLOC_HARDER then subtract
3841 * the high-atomic reserves. This will over-estimate the size of the
3842 * atomic reserve but it avoids a search.
3843 */
3844 if (likely(!alloc_harder))
3845 unusable_free += z->nr_reserved_highatomic;
3846
3847#ifdef CONFIG_CMA
3848 /* If allocation can't use CMA areas don't use free CMA pages */
3849 if (!(alloc_flags & ALLOC_CMA))
3850 unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES);
3851#endif
3852
3853 return unusable_free;
3854}
3855
1da177e4 3856/*
97a16fc8
MG
3857 * Return true if free base pages are above 'mark'. For high-order checks it
3858 * will return true of the order-0 watermark is reached and there is at least
3859 * one free page of a suitable size. Checking now avoids taking the zone lock
3860 * to check in the allocation paths if no pages are free.
1da177e4 3861 */
86a294a8 3862bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
97a225e6 3863 int highest_zoneidx, unsigned int alloc_flags,
86a294a8 3864 long free_pages)
1da177e4 3865{
d23ad423 3866 long min = mark;
1da177e4 3867 int o;
cd04ae1e 3868 const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
1da177e4 3869
0aaa29a5 3870 /* free_pages may go negative - that's OK */
f27ce0e1 3871 free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags);
0aaa29a5 3872
7fb1d9fc 3873 if (alloc_flags & ALLOC_HIGH)
1da177e4 3874 min -= min / 2;
0aaa29a5 3875
f27ce0e1 3876 if (unlikely(alloc_harder)) {
cd04ae1e
MH
3877 /*
3878 * OOM victims can try even harder than normal ALLOC_HARDER
3879 * users on the grounds that it's definitely going to be in
3880 * the exit path shortly and free memory. Any allocation it
3881 * makes during the free path will be small and short-lived.
3882 */
3883 if (alloc_flags & ALLOC_OOM)
3884 min -= min / 2;
3885 else
3886 min -= min / 4;
3887 }
3888
97a16fc8
MG
3889 /*
3890 * Check watermarks for an order-0 allocation request. If these
3891 * are not met, then a high-order request also cannot go ahead
3892 * even if a suitable page happened to be free.
3893 */
97a225e6 3894 if (free_pages <= min + z->lowmem_reserve[highest_zoneidx])
88f5acf8 3895 return false;
1da177e4 3896
97a16fc8
MG
3897 /* If this is an order-0 request then the watermark is fine */
3898 if (!order)
3899 return true;
3900
3901 /* For a high-order request, check at least one suitable page is free */
3902 for (o = order; o < MAX_ORDER; o++) {
3903 struct free_area *area = &z->free_area[o];
3904 int mt;
3905
3906 if (!area->nr_free)
3907 continue;
3908
97a16fc8 3909 for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
b03641af 3910 if (!free_area_empty(area, mt))
97a16fc8
MG
3911 return true;
3912 }
3913
3914#ifdef CONFIG_CMA
d883c6cf 3915 if ((alloc_flags & ALLOC_CMA) &&
b03641af 3916 !free_area_empty(area, MIGRATE_CMA)) {
97a16fc8 3917 return true;
d883c6cf 3918 }
97a16fc8 3919#endif
76089d00 3920 if (alloc_harder && !free_area_empty(area, MIGRATE_HIGHATOMIC))
b050e376 3921 return true;
1da177e4 3922 }
97a16fc8 3923 return false;
88f5acf8
MG
3924}
3925
7aeb09f9 3926bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
97a225e6 3927 int highest_zoneidx, unsigned int alloc_flags)
88f5acf8 3928{
97a225e6 3929 return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
88f5acf8
MG
3930 zone_page_state(z, NR_FREE_PAGES));
3931}
3932
48ee5f36 3933static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
97a225e6 3934 unsigned long mark, int highest_zoneidx,
f80b08fc 3935 unsigned int alloc_flags, gfp_t gfp_mask)
48ee5f36 3936{
f27ce0e1 3937 long free_pages;
d883c6cf 3938
f27ce0e1 3939 free_pages = zone_page_state(z, NR_FREE_PAGES);
48ee5f36
MG
3940
3941 /*
3942 * Fast check for order-0 only. If this fails then the reserves
f27ce0e1 3943 * need to be calculated.
48ee5f36 3944 */
f27ce0e1
JK
3945 if (!order) {
3946 long fast_free;
3947
3948 fast_free = free_pages;
3949 fast_free -= __zone_watermark_unusable_free(z, 0, alloc_flags);
3950 if (fast_free > mark + z->lowmem_reserve[highest_zoneidx])
3951 return true;
3952 }
48ee5f36 3953
f80b08fc
CTR
3954 if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3955 free_pages))
3956 return true;
3957 /*
3958 * Ignore watermark boosting for GFP_ATOMIC order-0 allocations
3959 * when checking the min watermark. The min watermark is the
3960 * point where boosting is ignored so that kswapd is woken up
3961 * when below the low watermark.
3962 */
3963 if (unlikely(!order && (gfp_mask & __GFP_ATOMIC) && z->watermark_boost
3964 && ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) {
3965 mark = z->_watermark[WMARK_MIN];
3966 return __zone_watermark_ok(z, order, mark, highest_zoneidx,
3967 alloc_flags, free_pages);
3968 }
3969
3970 return false;
48ee5f36
MG
3971}
3972
7aeb09f9 3973bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
97a225e6 3974 unsigned long mark, int highest_zoneidx)
88f5acf8
MG
3975{
3976 long free_pages = zone_page_state(z, NR_FREE_PAGES);
3977
3978 if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3979 free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3980
97a225e6 3981 return __zone_watermark_ok(z, order, mark, highest_zoneidx, 0,
88f5acf8 3982 free_pages);
1da177e4
LT
3983}
3984
9276b1bc 3985#ifdef CONFIG_NUMA
61bb6cd2
GU
3986int __read_mostly node_reclaim_distance = RECLAIM_DISTANCE;
3987
957f822a
DR
3988static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3989{
e02dc017 3990 return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
a55c7454 3991 node_reclaim_distance;
957f822a 3992}
9276b1bc 3993#else /* CONFIG_NUMA */
957f822a
DR
3994static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3995{
3996 return true;
3997}
9276b1bc
PJ
3998#endif /* CONFIG_NUMA */
3999
6bb15450
MG
4000/*
4001 * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
4002 * fragmentation is subtle. If the preferred zone was HIGHMEM then
4003 * premature use of a lower zone may cause lowmem pressure problems that
4004 * are worse than fragmentation. If the next zone is ZONE_DMA then it is
4005 * probably too small. It only makes sense to spread allocations to avoid
4006 * fragmentation between the Normal and DMA32 zones.
4007 */
4008static inline unsigned int
0a79cdad 4009alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
6bb15450 4010{
736838e9 4011 unsigned int alloc_flags;
0a79cdad 4012
736838e9
MN
4013 /*
4014 * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
4015 * to save a branch.
4016 */
4017 alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
0a79cdad
MG
4018
4019#ifdef CONFIG_ZONE_DMA32
8139ad04
AR
4020 if (!zone)
4021 return alloc_flags;
4022
6bb15450 4023 if (zone_idx(zone) != ZONE_NORMAL)
8118b82e 4024 return alloc_flags;
6bb15450
MG
4025
4026 /*
4027 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
4028 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
4029 * on UMA that if Normal is populated then so is DMA32.
4030 */
4031 BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
4032 if (nr_online_nodes > 1 && !populated_zone(--zone))
8118b82e 4033 return alloc_flags;
6bb15450 4034
8118b82e 4035 alloc_flags |= ALLOC_NOFRAGMENT;
0a79cdad
MG
4036#endif /* CONFIG_ZONE_DMA32 */
4037 return alloc_flags;
6bb15450 4038}
6bb15450 4039
8e3560d9
PT
4040/* Must be called after current_gfp_context() which can change gfp_mask */
4041static inline unsigned int gfp_to_alloc_flags_cma(gfp_t gfp_mask,
4042 unsigned int alloc_flags)
8510e69c
JK
4043{
4044#ifdef CONFIG_CMA
8e3560d9 4045 if (gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE)
8510e69c 4046 alloc_flags |= ALLOC_CMA;
8510e69c
JK
4047#endif
4048 return alloc_flags;
4049}
4050
7fb1d9fc 4051/*
0798e519 4052 * get_page_from_freelist goes through the zonelist trying to allocate
7fb1d9fc
RS
4053 * a page.
4054 */
4055static struct page *
a9263751
VB
4056get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
4057 const struct alloc_context *ac)
753ee728 4058{
6bb15450 4059 struct zoneref *z;
5117f45d 4060 struct zone *zone;
8a87d695
WY
4061 struct pglist_data *last_pgdat = NULL;
4062 bool last_pgdat_dirty_ok = false;
6bb15450 4063 bool no_fallback;
3b8c0be4 4064
6bb15450 4065retry:
7fb1d9fc 4066 /*
9276b1bc 4067 * Scan zonelist, looking for a zone with enough free.
344736f2 4068 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
7fb1d9fc 4069 */
6bb15450
MG
4070 no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
4071 z = ac->preferred_zoneref;
30d8ec73
MN
4072 for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx,
4073 ac->nodemask) {
be06af00 4074 struct page *page;
e085dbc5
JW
4075 unsigned long mark;
4076
664eedde
MG
4077 if (cpusets_enabled() &&
4078 (alloc_flags & ALLOC_CPUSET) &&
002f2906 4079 !__cpuset_zone_allowed(zone, gfp_mask))
cd38b115 4080 continue;
a756cf59
JW
4081 /*
4082 * When allocating a page cache page for writing, we
281e3726
MG
4083 * want to get it from a node that is within its dirty
4084 * limit, such that no single node holds more than its
a756cf59 4085 * proportional share of globally allowed dirty pages.
281e3726 4086 * The dirty limits take into account the node's
a756cf59
JW
4087 * lowmem reserves and high watermark so that kswapd
4088 * should be able to balance it without having to
4089 * write pages from its LRU list.
4090 *
a756cf59 4091 * XXX: For now, allow allocations to potentially
281e3726 4092 * exceed the per-node dirty limit in the slowpath
c9ab0c4f 4093 * (spread_dirty_pages unset) before going into reclaim,
a756cf59 4094 * which is important when on a NUMA setup the allowed
281e3726 4095 * nodes are together not big enough to reach the
a756cf59 4096 * global limit. The proper fix for these situations
281e3726 4097 * will require awareness of nodes in the
a756cf59
JW
4098 * dirty-throttling and the flusher threads.
4099 */
3b8c0be4 4100 if (ac->spread_dirty_pages) {
8a87d695
WY
4101 if (last_pgdat != zone->zone_pgdat) {
4102 last_pgdat = zone->zone_pgdat;
4103 last_pgdat_dirty_ok = node_dirty_ok(zone->zone_pgdat);
4104 }
3b8c0be4 4105
8a87d695 4106 if (!last_pgdat_dirty_ok)
3b8c0be4 4107 continue;
3b8c0be4 4108 }
7fb1d9fc 4109
6bb15450
MG
4110 if (no_fallback && nr_online_nodes > 1 &&
4111 zone != ac->preferred_zoneref->zone) {
4112 int local_nid;
4113
4114 /*
4115 * If moving to a remote node, retry but allow
4116 * fragmenting fallbacks. Locality is more important
4117 * than fragmentation avoidance.
4118 */
4119 local_nid = zone_to_nid(ac->preferred_zoneref->zone);
4120 if (zone_to_nid(zone) != local_nid) {
4121 alloc_flags &= ~ALLOC_NOFRAGMENT;
4122 goto retry;
4123 }
4124 }
4125
a9214443 4126 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
48ee5f36 4127 if (!zone_watermark_fast(zone, order, mark,
f80b08fc
CTR
4128 ac->highest_zoneidx, alloc_flags,
4129 gfp_mask)) {
fa5e084e
MG
4130 int ret;
4131
c9e97a19
PT
4132#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
4133 /*
4134 * Watermark failed for this zone, but see if we can
4135 * grow this zone if it contains deferred pages.
4136 */
4137 if (static_branch_unlikely(&deferred_pages)) {
4138 if (_deferred_grow_zone(zone, order))
4139 goto try_this_zone;
4140 }
4141#endif
5dab2911
MG
4142 /* Checked here to keep the fast path fast */
4143 BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
4144 if (alloc_flags & ALLOC_NO_WATERMARKS)
4145 goto try_this_zone;
4146
202e35db 4147 if (!node_reclaim_enabled() ||
c33d6c06 4148 !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
cd38b115
MG
4149 continue;
4150
a5f5f91d 4151 ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
fa5e084e 4152 switch (ret) {
a5f5f91d 4153 case NODE_RECLAIM_NOSCAN:
fa5e084e 4154 /* did not scan */
cd38b115 4155 continue;
a5f5f91d 4156 case NODE_RECLAIM_FULL:
fa5e084e 4157 /* scanned but unreclaimable */
cd38b115 4158 continue;
fa5e084e
MG
4159 default:
4160 /* did we reclaim enough */
fed2719e 4161 if (zone_watermark_ok(zone, order, mark,
97a225e6 4162 ac->highest_zoneidx, alloc_flags))
fed2719e
MG
4163 goto try_this_zone;
4164
fed2719e 4165 continue;
0798e519 4166 }
7fb1d9fc
RS
4167 }
4168
fa5e084e 4169try_this_zone:
066b2393 4170 page = rmqueue(ac->preferred_zoneref->zone, zone, order,
0aaa29a5 4171 gfp_mask, alloc_flags, ac->migratetype);
75379191 4172 if (page) {
479f854a 4173 prep_new_page(page, order, gfp_mask, alloc_flags);
0aaa29a5
MG
4174
4175 /*
4176 * If this is a high-order atomic allocation then check
4177 * if the pageblock should be reserved for the future
4178 */
4179 if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
4180 reserve_highatomic_pageblock(page, zone, order);
4181
75379191 4182 return page;
c9e97a19
PT
4183 } else {
4184#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
4185 /* Try again if zone has deferred pages */
4186 if (static_branch_unlikely(&deferred_pages)) {
4187 if (_deferred_grow_zone(zone, order))
4188 goto try_this_zone;
4189 }
4190#endif
75379191 4191 }
54a6eb5c 4192 }
9276b1bc 4193
6bb15450
MG
4194 /*
4195 * It's possible on a UMA machine to get through all zones that are
4196 * fragmented. If avoiding fragmentation, reset and try again.
4197 */
4198 if (no_fallback) {
4199 alloc_flags &= ~ALLOC_NOFRAGMENT;
4200 goto retry;
4201 }
4202
4ffeaf35 4203 return NULL;
753ee728
MH
4204}
4205
9af744d7 4206static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
a238ab5b 4207{
a238ab5b 4208 unsigned int filter = SHOW_MEM_FILTER_NODES;
a238ab5b
DH
4209
4210 /*
4211 * This documents exceptions given to allocations in certain
4212 * contexts that are allowed to allocate outside current's set
4213 * of allowed nodes.
4214 */
4215 if (!(gfp_mask & __GFP_NOMEMALLOC))
cd04ae1e 4216 if (tsk_is_oom_victim(current) ||
a238ab5b
DH
4217 (current->flags & (PF_MEMALLOC | PF_EXITING)))
4218 filter &= ~SHOW_MEM_FILTER_NODES;
88dc6f20 4219 if (!in_task() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
a238ab5b
DH
4220 filter &= ~SHOW_MEM_FILTER_NODES;
4221
9af744d7 4222 show_mem(filter, nodemask);
aa187507
MH
4223}
4224
a8e99259 4225void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
aa187507
MH
4226{
4227 struct va_format vaf;
4228 va_list args;
1be334e5 4229 static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
aa187507 4230
c4dc63f0
BH
4231 if ((gfp_mask & __GFP_NOWARN) ||
4232 !__ratelimit(&nopage_rs) ||
4233 ((gfp_mask & __GFP_DMA) && !has_managed_dma()))
aa187507
MH
4234 return;
4235
7877cdcc
MH
4236 va_start(args, fmt);
4237 vaf.fmt = fmt;
4238 vaf.va = &args;
ef8444ea 4239 pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
0205f755
MH
4240 current->comm, &vaf, gfp_mask, &gfp_mask,
4241 nodemask_pr_args(nodemask));
7877cdcc 4242 va_end(args);
3ee9a4f0 4243
a8e99259 4244 cpuset_print_current_mems_allowed();
ef8444ea 4245 pr_cont("\n");
a238ab5b 4246 dump_stack();
685dbf6f 4247 warn_alloc_show_mem(gfp_mask, nodemask);
a238ab5b
DH
4248}
4249
6c18ba7a
MH
4250static inline struct page *
4251__alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
4252 unsigned int alloc_flags,
4253 const struct alloc_context *ac)
4254{
4255 struct page *page;
4256
4257 page = get_page_from_freelist(gfp_mask, order,
4258 alloc_flags|ALLOC_CPUSET, ac);
4259 /*
4260 * fallback to ignore cpuset restriction if our nodes
4261 * are depleted
4262 */
4263 if (!page)
4264 page = get_page_from_freelist(gfp_mask, order,
4265 alloc_flags, ac);
4266
4267 return page;
4268}
4269
11e33f6a
MG
4270static inline struct page *
4271__alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
a9263751 4272 const struct alloc_context *ac, unsigned long *did_some_progress)
11e33f6a 4273{
6e0fc46d
DR
4274 struct oom_control oc = {
4275 .zonelist = ac->zonelist,
4276 .nodemask = ac->nodemask,
2a966b77 4277 .memcg = NULL,
6e0fc46d
DR
4278 .gfp_mask = gfp_mask,
4279 .order = order,
6e0fc46d 4280 };
11e33f6a
MG
4281 struct page *page;
4282
9879de73
JW
4283 *did_some_progress = 0;
4284
9879de73 4285 /*
dc56401f
JW
4286 * Acquire the oom lock. If that fails, somebody else is
4287 * making progress for us.
9879de73 4288 */
dc56401f 4289 if (!mutex_trylock(&oom_lock)) {
9879de73 4290 *did_some_progress = 1;
11e33f6a 4291 schedule_timeout_uninterruptible(1);
1da177e4
LT
4292 return NULL;
4293 }
6b1de916 4294
11e33f6a
MG
4295 /*
4296 * Go through the zonelist yet one more time, keep very high watermark
4297 * here, this is only to catch a parallel oom killing, we must fail if
e746bf73
TH
4298 * we're still under heavy pressure. But make sure that this reclaim
4299 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
4300 * allocation which will never fail due to oom_lock already held.
11e33f6a 4301 */
e746bf73
TH
4302 page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
4303 ~__GFP_DIRECT_RECLAIM, order,
4304 ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
7fb1d9fc 4305 if (page)
11e33f6a
MG
4306 goto out;
4307
06ad276a
MH
4308 /* Coredumps can quickly deplete all memory reserves */
4309 if (current->flags & PF_DUMPCORE)
4310 goto out;
4311 /* The OOM killer will not help higher order allocs */
4312 if (order > PAGE_ALLOC_COSTLY_ORDER)
4313 goto out;
dcda9b04
MH
4314 /*
4315 * We have already exhausted all our reclaim opportunities without any
4316 * success so it is time to admit defeat. We will skip the OOM killer
4317 * because it is very likely that the caller has a more reasonable
4318 * fallback than shooting a random task.
cfb4a541
MN
4319 *
4320 * The OOM killer may not free memory on a specific node.
dcda9b04 4321 */
cfb4a541 4322 if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE))
dcda9b04 4323 goto out;
06ad276a 4324 /* The OOM killer does not needlessly kill tasks for lowmem */
97a225e6 4325 if (ac->highest_zoneidx < ZONE_NORMAL)
06ad276a
MH
4326 goto out;
4327 if (pm_suspended_storage())
4328 goto out;
4329 /*
4330 * XXX: GFP_NOFS allocations should rather fail than rely on
4331 * other request to make a forward progress.
4332 * We are in an unfortunate situation where out_of_memory cannot
4333 * do much for this context but let's try it to at least get
4334 * access to memory reserved if the current task is killed (see
4335 * out_of_memory). Once filesystems are ready to handle allocation
4336 * failures more gracefully we should just bail out here.
4337 */
4338
3c2c6488 4339 /* Exhausted what can be done so it's blame time */
5020e285 4340 if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
c32b3cbe 4341 *did_some_progress = 1;
5020e285 4342
6c18ba7a
MH
4343 /*
4344 * Help non-failing allocations by giving them access to memory
4345 * reserves
4346 */
4347 if (gfp_mask & __GFP_NOFAIL)
4348 page = __alloc_pages_cpuset_fallback(gfp_mask, order,
5020e285 4349 ALLOC_NO_WATERMARKS, ac);
5020e285 4350 }
11e33f6a 4351out:
dc56401f 4352 mutex_unlock(&oom_lock);
11e33f6a
MG
4353 return page;
4354}
4355
33c2d214 4356/*
baf2f90b 4357 * Maximum number of compaction retries with a progress before OOM
33c2d214
MH
4358 * killer is consider as the only way to move forward.
4359 */
4360#define MAX_COMPACT_RETRIES 16
4361
56de7263
MG
4362#ifdef CONFIG_COMPACTION
4363/* Try memory compaction for high-order allocations before reclaim */
4364static struct page *
4365__alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
c603844b 4366 unsigned int alloc_flags, const struct alloc_context *ac,
a5508cd8 4367 enum compact_priority prio, enum compact_result *compact_result)
56de7263 4368{
5e1f0f09 4369 struct page *page = NULL;
eb414681 4370 unsigned long pflags;
499118e9 4371 unsigned int noreclaim_flag;
53853e2d
VB
4372
4373 if (!order)
66199712 4374 return NULL;
66199712 4375
eb414681 4376 psi_memstall_enter(&pflags);
5bf18281 4377 delayacct_compact_start();
499118e9 4378 noreclaim_flag = memalloc_noreclaim_save();
eb414681 4379
c5d01d0d 4380 *compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
5e1f0f09 4381 prio, &page);
eb414681 4382
499118e9 4383 memalloc_noreclaim_restore(noreclaim_flag);
eb414681 4384 psi_memstall_leave(&pflags);
5bf18281 4385 delayacct_compact_end();
56de7263 4386
06dac2f4
CTR
4387 if (*compact_result == COMPACT_SKIPPED)
4388 return NULL;
98dd3b48
VB
4389 /*
4390 * At least in one zone compaction wasn't deferred or skipped, so let's
4391 * count a compaction stall
4392 */
4393 count_vm_event(COMPACTSTALL);
8fb74b9f 4394
5e1f0f09
MG
4395 /* Prep a captured page if available */
4396 if (page)
4397 prep_new_page(page, order, gfp_mask, alloc_flags);
4398
4399 /* Try get a page from the freelist if available */
4400 if (!page)
4401 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
53853e2d 4402
98dd3b48
VB
4403 if (page) {
4404 struct zone *zone = page_zone(page);
53853e2d 4405
98dd3b48
VB
4406 zone->compact_blockskip_flush = false;
4407 compaction_defer_reset(zone, order, true);
4408 count_vm_event(COMPACTSUCCESS);
4409 return page;
4410 }
56de7263 4411
98dd3b48
VB
4412 /*
4413 * It's bad if compaction run occurs and fails. The most likely reason
4414 * is that pages exist, but not enough to satisfy watermarks.
4415 */
4416 count_vm_event(COMPACTFAIL);
66199712 4417
98dd3b48 4418 cond_resched();
56de7263
MG
4419
4420 return NULL;
4421}
33c2d214 4422
3250845d
VB
4423static inline bool
4424should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
4425 enum compact_result compact_result,
4426 enum compact_priority *compact_priority,
d9436498 4427 int *compaction_retries)
3250845d
VB
4428{
4429 int max_retries = MAX_COMPACT_RETRIES;
c2033b00 4430 int min_priority;
65190cff
MH
4431 bool ret = false;
4432 int retries = *compaction_retries;
4433 enum compact_priority priority = *compact_priority;
3250845d
VB
4434
4435 if (!order)
4436 return false;
4437
691d9497
AT
4438 if (fatal_signal_pending(current))
4439 return false;
4440
d9436498
VB
4441 if (compaction_made_progress(compact_result))
4442 (*compaction_retries)++;
4443
3250845d
VB
4444 /*
4445 * compaction considers all the zone as desperately out of memory
4446 * so it doesn't really make much sense to retry except when the
4447 * failure could be caused by insufficient priority
4448 */
d9436498
VB
4449 if (compaction_failed(compact_result))
4450 goto check_priority;
3250845d 4451
49433085
VB
4452 /*
4453 * compaction was skipped because there are not enough order-0 pages
4454 * to work with, so we retry only if it looks like reclaim can help.
4455 */
4456 if (compaction_needs_reclaim(compact_result)) {
4457 ret = compaction_zonelist_suitable(ac, order, alloc_flags);
4458 goto out;
4459 }
4460
3250845d
VB
4461 /*
4462 * make sure the compaction wasn't deferred or didn't bail out early
4463 * due to locks contention before we declare that we should give up.
49433085
VB
4464 * But the next retry should use a higher priority if allowed, so
4465 * we don't just keep bailing out endlessly.
3250845d 4466 */
65190cff 4467 if (compaction_withdrawn(compact_result)) {
49433085 4468 goto check_priority;
65190cff 4469 }
3250845d
VB
4470
4471 /*
dcda9b04 4472 * !costly requests are much more important than __GFP_RETRY_MAYFAIL
3250845d
VB
4473 * costly ones because they are de facto nofail and invoke OOM
4474 * killer to move on while costly can fail and users are ready
4475 * to cope with that. 1/4 retries is rather arbitrary but we
4476 * would need much more detailed feedback from compaction to
4477 * make a better decision.
4478 */
4479 if (order > PAGE_ALLOC_COSTLY_ORDER)
4480 max_retries /= 4;
65190cff
MH
4481 if (*compaction_retries <= max_retries) {
4482 ret = true;
4483 goto out;
4484 }
3250845d 4485
d9436498
VB
4486 /*
4487 * Make sure there are attempts at the highest priority if we exhausted
4488 * all retries or failed at the lower priorities.
4489 */
4490check_priority:
c2033b00
VB
4491 min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
4492 MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
65190cff 4493
c2033b00 4494 if (*compact_priority > min_priority) {
d9436498
VB
4495 (*compact_priority)--;
4496 *compaction_retries = 0;
65190cff 4497 ret = true;
d9436498 4498 }
65190cff
MH
4499out:
4500 trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
4501 return ret;
3250845d 4502}
56de7263
MG
4503#else
4504static inline struct page *
4505__alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
c603844b 4506 unsigned int alloc_flags, const struct alloc_context *ac,
a5508cd8 4507 enum compact_priority prio, enum compact_result *compact_result)
56de7263 4508{
33c2d214 4509 *compact_result = COMPACT_SKIPPED;
56de7263
MG
4510 return NULL;
4511}
33c2d214
MH
4512
4513static inline bool
86a294a8
MH
4514should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
4515 enum compact_result compact_result,
a5508cd8 4516 enum compact_priority *compact_priority,
d9436498 4517 int *compaction_retries)
33c2d214 4518{
31e49bfd
MH
4519 struct zone *zone;
4520 struct zoneref *z;
4521
4522 if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
4523 return false;
4524
4525 /*
4526 * There are setups with compaction disabled which would prefer to loop
4527 * inside the allocator rather than hit the oom killer prematurely.
4528 * Let's give them a good hope and keep retrying while the order-0
4529 * watermarks are OK.
4530 */
97a225e6
JK
4531 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4532 ac->highest_zoneidx, ac->nodemask) {
31e49bfd 4533 if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
97a225e6 4534 ac->highest_zoneidx, alloc_flags))
31e49bfd
MH
4535 return true;
4536 }
33c2d214
MH
4537 return false;
4538}
3250845d 4539#endif /* CONFIG_COMPACTION */
56de7263 4540
d92a8cfc 4541#ifdef CONFIG_LOCKDEP
93781325 4542static struct lockdep_map __fs_reclaim_map =
d92a8cfc
PZ
4543 STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
4544
f920e413 4545static bool __need_reclaim(gfp_t gfp_mask)
d92a8cfc 4546{
d92a8cfc
PZ
4547 /* no reclaim without waiting on it */
4548 if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
4549 return false;
4550
4551 /* this guy won't enter reclaim */
2e517d68 4552 if (current->flags & PF_MEMALLOC)
d92a8cfc
PZ
4553 return false;
4554
d92a8cfc
PZ
4555 if (gfp_mask & __GFP_NOLOCKDEP)
4556 return false;
4557
4558 return true;
4559}
4560
4f3eaf45 4561void __fs_reclaim_acquire(unsigned long ip)
93781325 4562{
4f3eaf45 4563 lock_acquire_exclusive(&__fs_reclaim_map, 0, 0, NULL, ip);
93781325
OS
4564}
4565
4f3eaf45 4566void __fs_reclaim_release(unsigned long ip)
93781325 4567{
4f3eaf45 4568 lock_release(&__fs_reclaim_map, ip);
93781325
OS
4569}
4570
d92a8cfc
PZ
4571void fs_reclaim_acquire(gfp_t gfp_mask)
4572{
f920e413
SV
4573 gfp_mask = current_gfp_context(gfp_mask);
4574
4575 if (__need_reclaim(gfp_mask)) {
4576 if (gfp_mask & __GFP_FS)
4f3eaf45 4577 __fs_reclaim_acquire(_RET_IP_);
f920e413
SV
4578
4579#ifdef CONFIG_MMU_NOTIFIER
4580 lock_map_acquire(&__mmu_notifier_invalidate_range_start_map);
4581 lock_map_release(&__mmu_notifier_invalidate_range_start_map);
4582#endif
4583
4584 }
d92a8cfc
PZ
4585}
4586EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
4587
4588void fs_reclaim_release(gfp_t gfp_mask)
4589{
f920e413
SV
4590 gfp_mask = current_gfp_context(gfp_mask);
4591
4592 if (__need_reclaim(gfp_mask)) {
4593 if (gfp_mask & __GFP_FS)
4f3eaf45 4594 __fs_reclaim_release(_RET_IP_);
f920e413 4595 }
d92a8cfc
PZ
4596}
4597EXPORT_SYMBOL_GPL(fs_reclaim_release);
4598#endif
4599
bba90710 4600/* Perform direct synchronous page reclaim */
2187e17b 4601static unsigned long
a9263751
VB
4602__perform_reclaim(gfp_t gfp_mask, unsigned int order,
4603 const struct alloc_context *ac)
11e33f6a 4604{
499118e9 4605 unsigned int noreclaim_flag;
fa7fc75f 4606 unsigned long progress;
11e33f6a
MG
4607
4608 cond_resched();
4609
4610 /* We now go into synchronous reclaim */
4611 cpuset_memory_pressure_bump();
d92a8cfc 4612 fs_reclaim_acquire(gfp_mask);
93781325 4613 noreclaim_flag = memalloc_noreclaim_save();
11e33f6a 4614
a9263751
VB
4615 progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
4616 ac->nodemask);
11e33f6a 4617
499118e9 4618 memalloc_noreclaim_restore(noreclaim_flag);
93781325 4619 fs_reclaim_release(gfp_mask);
11e33f6a
MG
4620
4621 cond_resched();
4622
bba90710
MS
4623 return progress;
4624}
4625
4626/* The really slow allocator path where we enter direct reclaim */
4627static inline struct page *
4628__alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
c603844b 4629 unsigned int alloc_flags, const struct alloc_context *ac,
a9263751 4630 unsigned long *did_some_progress)
bba90710
MS
4631{
4632 struct page *page = NULL;
fa7fc75f 4633 unsigned long pflags;
bba90710
MS
4634 bool drained = false;
4635
fa7fc75f 4636 psi_memstall_enter(&pflags);
a9263751 4637 *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
9ee493ce 4638 if (unlikely(!(*did_some_progress)))
fa7fc75f 4639 goto out;
11e33f6a 4640
9ee493ce 4641retry:
31a6c190 4642 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
9ee493ce
MG
4643
4644 /*
4645 * If an allocation failed after direct reclaim, it could be because
0aaa29a5 4646 * pages are pinned on the per-cpu lists or in high alloc reserves.
047b9967 4647 * Shrink them and try again
9ee493ce
MG
4648 */
4649 if (!page && !drained) {
29fac03b 4650 unreserve_highatomic_pageblock(ac, false);
93481ff0 4651 drain_all_pages(NULL);
9ee493ce
MG
4652 drained = true;
4653 goto retry;
4654 }
fa7fc75f
SB
4655out:
4656 psi_memstall_leave(&pflags);
9ee493ce 4657
11e33f6a
MG
4658 return page;
4659}
4660
5ecd9d40
DR
4661static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
4662 const struct alloc_context *ac)
3a025760
JW
4663{
4664 struct zoneref *z;
4665 struct zone *zone;
e1a55637 4666 pg_data_t *last_pgdat = NULL;
97a225e6 4667 enum zone_type highest_zoneidx = ac->highest_zoneidx;
3a025760 4668
97a225e6 4669 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx,
5ecd9d40 4670 ac->nodemask) {
bc53008e
WY
4671 if (!managed_zone(zone))
4672 continue;
d137a7cb 4673 if (last_pgdat != zone->zone_pgdat) {
97a225e6 4674 wakeup_kswapd(zone, gfp_mask, order, highest_zoneidx);
d137a7cb
CW
4675 last_pgdat = zone->zone_pgdat;
4676 }
e1a55637 4677 }
3a025760
JW
4678}
4679
c603844b 4680static inline unsigned int
341ce06f
PZ
4681gfp_to_alloc_flags(gfp_t gfp_mask)
4682{
c603844b 4683 unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
1da177e4 4684
736838e9
MN
4685 /*
4686 * __GFP_HIGH is assumed to be the same as ALLOC_HIGH
4687 * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
4688 * to save two branches.
4689 */
e6223a3b 4690 BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
736838e9 4691 BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD);
933e312e 4692
341ce06f
PZ
4693 /*
4694 * The caller may dip into page reserves a bit more if the caller
4695 * cannot run direct reclaim, or if the caller has realtime scheduling
4696 * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will
d0164adc 4697 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
341ce06f 4698 */
736838e9
MN
4699 alloc_flags |= (__force int)
4700 (gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM));
1da177e4 4701
d0164adc 4702 if (gfp_mask & __GFP_ATOMIC) {
5c3240d9 4703 /*
b104a35d
DR
4704 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4705 * if it can't schedule.
5c3240d9 4706 */
b104a35d 4707 if (!(gfp_mask & __GFP_NOMEMALLOC))
5c3240d9 4708 alloc_flags |= ALLOC_HARDER;
523b9458 4709 /*
b104a35d 4710 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
344736f2 4711 * comment for __cpuset_node_allowed().
523b9458 4712 */
341ce06f 4713 alloc_flags &= ~ALLOC_CPUSET;
88dc6f20 4714 } else if (unlikely(rt_task(current)) && in_task())
341ce06f
PZ
4715 alloc_flags |= ALLOC_HARDER;
4716
8e3560d9 4717 alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, alloc_flags);
8510e69c 4718
341ce06f
PZ
4719 return alloc_flags;
4720}
4721
cd04ae1e 4722static bool oom_reserves_allowed(struct task_struct *tsk)
072bb0aa 4723{
cd04ae1e
MH
4724 if (!tsk_is_oom_victim(tsk))
4725 return false;
4726
4727 /*
4728 * !MMU doesn't have oom reaper so give access to memory reserves
4729 * only to the thread with TIF_MEMDIE set
4730 */
4731 if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
31a6c190
VB
4732 return false;
4733
cd04ae1e
MH
4734 return true;
4735}
4736
4737/*
4738 * Distinguish requests which really need access to full memory
4739 * reserves from oom victims which can live with a portion of it
4740 */
4741static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4742{
4743 if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4744 return 0;
31a6c190 4745 if (gfp_mask & __GFP_MEMALLOC)
cd04ae1e 4746 return ALLOC_NO_WATERMARKS;
31a6c190 4747 if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
cd04ae1e
MH
4748 return ALLOC_NO_WATERMARKS;
4749 if (!in_interrupt()) {
4750 if (current->flags & PF_MEMALLOC)
4751 return ALLOC_NO_WATERMARKS;
4752 else if (oom_reserves_allowed(current))
4753 return ALLOC_OOM;
4754 }
31a6c190 4755
cd04ae1e
MH
4756 return 0;
4757}
4758
4759bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4760{
4761 return !!__gfp_pfmemalloc_flags(gfp_mask);
072bb0aa
MG
4762}
4763
0a0337e0
MH
4764/*
4765 * Checks whether it makes sense to retry the reclaim to make a forward progress
4766 * for the given allocation request.
491d79ae
JW
4767 *
4768 * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4769 * without success, or when we couldn't even meet the watermark if we
4770 * reclaimed all remaining pages on the LRU lists.
0a0337e0
MH
4771 *
4772 * Returns true if a retry is viable or false to enter the oom path.
4773 */
4774static inline bool
4775should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4776 struct alloc_context *ac, int alloc_flags,
423b452e 4777 bool did_some_progress, int *no_progress_loops)
0a0337e0
MH
4778{
4779 struct zone *zone;
4780 struct zoneref *z;
15f570bf 4781 bool ret = false;
0a0337e0 4782
423b452e
VB
4783 /*
4784 * Costly allocations might have made a progress but this doesn't mean
4785 * their order will become available due to high fragmentation so
4786 * always increment the no progress counter for them
4787 */
4788 if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4789 *no_progress_loops = 0;
4790 else
4791 (*no_progress_loops)++;
4792
0a0337e0
MH
4793 /*
4794 * Make sure we converge to OOM if we cannot make any progress
4795 * several times in the row.
4796 */
04c8716f
MK
4797 if (*no_progress_loops > MAX_RECLAIM_RETRIES) {
4798 /* Before OOM, exhaust highatomic_reserve */
29fac03b 4799 return unreserve_highatomic_pageblock(ac, true);
04c8716f 4800 }
0a0337e0 4801
bca67592
MG
4802 /*
4803 * Keep reclaiming pages while there is a chance this will lead
4804 * somewhere. If none of the target zones can satisfy our allocation
4805 * request even if all reclaimable pages are considered then we are
4806 * screwed and have to go OOM.
0a0337e0 4807 */
97a225e6
JK
4808 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4809 ac->highest_zoneidx, ac->nodemask) {
0a0337e0 4810 unsigned long available;
ede37713 4811 unsigned long reclaimable;
d379f01d
MH
4812 unsigned long min_wmark = min_wmark_pages(zone);
4813 bool wmark;
0a0337e0 4814
5a1c84b4 4815 available = reclaimable = zone_reclaimable_pages(zone);
5a1c84b4 4816 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
0a0337e0
MH
4817
4818 /*
491d79ae
JW
4819 * Would the allocation succeed if we reclaimed all
4820 * reclaimable pages?
0a0337e0 4821 */
d379f01d 4822 wmark = __zone_watermark_ok(zone, order, min_wmark,
97a225e6 4823 ac->highest_zoneidx, alloc_flags, available);
d379f01d
MH
4824 trace_reclaim_retry_zone(z, order, reclaimable,
4825 available, min_wmark, *no_progress_loops, wmark);
4826 if (wmark) {
15f570bf 4827 ret = true;
132b0d21 4828 break;
0a0337e0
MH
4829 }
4830 }
4831
15f570bf
MH
4832 /*
4833 * Memory allocation/reclaim might be called from a WQ context and the
4834 * current implementation of the WQ concurrency control doesn't
4835 * recognize that a particular WQ is congested if the worker thread is
4836 * looping without ever sleeping. Therefore we have to do a short sleep
4837 * here rather than calling cond_resched().
4838 */
4839 if (current->flags & PF_WQ_WORKER)
4840 schedule_timeout_uninterruptible(1);
4841 else
4842 cond_resched();
4843 return ret;
0a0337e0
MH
4844}
4845
902b6281
VB
4846static inline bool
4847check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4848{
4849 /*
4850 * It's possible that cpuset's mems_allowed and the nodemask from
4851 * mempolicy don't intersect. This should be normally dealt with by
4852 * policy_nodemask(), but it's possible to race with cpuset update in
4853 * such a way the check therein was true, and then it became false
4854 * before we got our cpuset_mems_cookie here.
4855 * This assumes that for all allocations, ac->nodemask can come only
4856 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4857 * when it does not intersect with the cpuset restrictions) or the
4858 * caller can deal with a violated nodemask.
4859 */
4860 if (cpusets_enabled() && ac->nodemask &&
4861 !cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4862 ac->nodemask = NULL;
4863 return true;
4864 }
4865
4866 /*
4867 * When updating a task's mems_allowed or mempolicy nodemask, it is
4868 * possible to race with parallel threads in such a way that our
4869 * allocation can fail while the mask is being updated. If we are about
4870 * to fail, check if the cpuset changed during allocation and if so,
4871 * retry.
4872 */
4873 if (read_mems_allowed_retry(cpuset_mems_cookie))
4874 return true;
4875
4876 return false;
4877}
4878
11e33f6a
MG
4879static inline struct page *
4880__alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
a9263751 4881 struct alloc_context *ac)
11e33f6a 4882{
d0164adc 4883 bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
282722b0 4884 const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
11e33f6a 4885 struct page *page = NULL;
c603844b 4886 unsigned int alloc_flags;
11e33f6a 4887 unsigned long did_some_progress;
5ce9bfef 4888 enum compact_priority compact_priority;
c5d01d0d 4889 enum compact_result compact_result;
5ce9bfef
VB
4890 int compaction_retries;
4891 int no_progress_loops;
5ce9bfef 4892 unsigned int cpuset_mems_cookie;
cd04ae1e 4893 int reserve_flags;
1da177e4 4894
d0164adc
MG
4895 /*
4896 * We also sanity check to catch abuse of atomic reserves being used by
4897 * callers that are not in atomic context.
4898 */
4899 if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
4900 (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
4901 gfp_mask &= ~__GFP_ATOMIC;
4902
5ce9bfef
VB
4903retry_cpuset:
4904 compaction_retries = 0;
4905 no_progress_loops = 0;
4906 compact_priority = DEF_COMPACT_PRIORITY;
4907 cpuset_mems_cookie = read_mems_allowed_begin();
9a67f648
MH
4908
4909 /*
4910 * The fast path uses conservative alloc_flags to succeed only until
4911 * kswapd needs to be woken up, and to avoid the cost of setting up
4912 * alloc_flags precisely. So we do that now.
4913 */
4914 alloc_flags = gfp_to_alloc_flags(gfp_mask);
4915
e47483bc
VB
4916 /*
4917 * We need to recalculate the starting point for the zonelist iterator
4918 * because we might have used different nodemask in the fast path, or
4919 * there was a cpuset modification and we are retrying - otherwise we
4920 * could end up iterating over non-eligible zones endlessly.
4921 */
4922 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
97a225e6 4923 ac->highest_zoneidx, ac->nodemask);
e47483bc
VB
4924 if (!ac->preferred_zoneref->zone)
4925 goto nopage;
4926
8ca1b5a4
FT
4927 /*
4928 * Check for insane configurations where the cpuset doesn't contain
4929 * any suitable zone to satisfy the request - e.g. non-movable
4930 * GFP_HIGHUSER allocations from MOVABLE nodes only.
4931 */
4932 if (cpusets_insane_config() && (gfp_mask & __GFP_HARDWALL)) {
4933 struct zoneref *z = first_zones_zonelist(ac->zonelist,
4934 ac->highest_zoneidx,
4935 &cpuset_current_mems_allowed);
4936 if (!z->zone)
4937 goto nopage;
4938 }
4939
0a79cdad 4940 if (alloc_flags & ALLOC_KSWAPD)
5ecd9d40 4941 wake_all_kswapds(order, gfp_mask, ac);
23771235
VB
4942
4943 /*
4944 * The adjusted alloc_flags might result in immediate success, so try
4945 * that first
4946 */
4947 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4948 if (page)
4949 goto got_pg;
4950
a8161d1e
VB
4951 /*
4952 * For costly allocations, try direct compaction first, as it's likely
282722b0
VB
4953 * that we have enough base pages and don't need to reclaim. For non-
4954 * movable high-order allocations, do that as well, as compaction will
4955 * try prevent permanent fragmentation by migrating from blocks of the
4956 * same migratetype.
4957 * Don't try this for allocations that are allowed to ignore
4958 * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
a8161d1e 4959 */
282722b0
VB
4960 if (can_direct_reclaim &&
4961 (costly_order ||
4962 (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
4963 && !gfp_pfmemalloc_allowed(gfp_mask)) {
a8161d1e
VB
4964 page = __alloc_pages_direct_compact(gfp_mask, order,
4965 alloc_flags, ac,
a5508cd8 4966 INIT_COMPACT_PRIORITY,
a8161d1e
VB
4967 &compact_result);
4968 if (page)
4969 goto got_pg;
4970
cc638f32
VB
4971 /*
4972 * Checks for costly allocations with __GFP_NORETRY, which
4973 * includes some THP page fault allocations
4974 */
4975 if (costly_order && (gfp_mask & __GFP_NORETRY)) {
b39d0ee2
DR
4976 /*
4977 * If allocating entire pageblock(s) and compaction
4978 * failed because all zones are below low watermarks
4979 * or is prohibited because it recently failed at this
3f36d866
DR
4980 * order, fail immediately unless the allocator has
4981 * requested compaction and reclaim retry.
b39d0ee2
DR
4982 *
4983 * Reclaim is
4984 * - potentially very expensive because zones are far
4985 * below their low watermarks or this is part of very
4986 * bursty high order allocations,
4987 * - not guaranteed to help because isolate_freepages()
4988 * may not iterate over freed pages as part of its
4989 * linear scan, and
4990 * - unlikely to make entire pageblocks free on its
4991 * own.
4992 */
4993 if (compact_result == COMPACT_SKIPPED ||
4994 compact_result == COMPACT_DEFERRED)
4995 goto nopage;
a8161d1e 4996
a8161d1e 4997 /*
3eb2771b
VB
4998 * Looks like reclaim/compaction is worth trying, but
4999 * sync compaction could be very expensive, so keep
25160354 5000 * using async compaction.
a8161d1e 5001 */
a5508cd8 5002 compact_priority = INIT_COMPACT_PRIORITY;
a8161d1e
VB
5003 }
5004 }
23771235 5005
31a6c190 5006retry:
23771235 5007 /* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
0a79cdad 5008 if (alloc_flags & ALLOC_KSWAPD)
5ecd9d40 5009 wake_all_kswapds(order, gfp_mask, ac);
31a6c190 5010
cd04ae1e
MH
5011 reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
5012 if (reserve_flags)
8e3560d9 5013 alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, reserve_flags);
23771235 5014
e46e7b77 5015 /*
d6a24df0
VB
5016 * Reset the nodemask and zonelist iterators if memory policies can be
5017 * ignored. These allocations are high priority and system rather than
5018 * user oriented.
e46e7b77 5019 */
cd04ae1e 5020 if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
d6a24df0 5021 ac->nodemask = NULL;
e46e7b77 5022 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
97a225e6 5023 ac->highest_zoneidx, ac->nodemask);
e46e7b77
MG
5024 }
5025
23771235 5026 /* Attempt with potentially adjusted zonelist and alloc_flags */
31a6c190 5027 page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
7fb1d9fc
RS
5028 if (page)
5029 goto got_pg;
1da177e4 5030
d0164adc 5031 /* Caller is not willing to reclaim, we can't balance anything */
9a67f648 5032 if (!can_direct_reclaim)
1da177e4
LT
5033 goto nopage;
5034
9a67f648
MH
5035 /* Avoid recursion of direct reclaim */
5036 if (current->flags & PF_MEMALLOC)
6583bb64
DR
5037 goto nopage;
5038
a8161d1e
VB
5039 /* Try direct reclaim and then allocating */
5040 page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
5041 &did_some_progress);
5042 if (page)
5043 goto got_pg;
5044
5045 /* Try direct compaction and then allocating */
a9263751 5046 page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
a5508cd8 5047 compact_priority, &compact_result);
56de7263
MG
5048 if (page)
5049 goto got_pg;
75f30861 5050
9083905a
JW
5051 /* Do not loop if specifically requested */
5052 if (gfp_mask & __GFP_NORETRY)
a8161d1e 5053 goto nopage;
9083905a 5054
0a0337e0
MH
5055 /*
5056 * Do not retry costly high order allocations unless they are
dcda9b04 5057 * __GFP_RETRY_MAYFAIL
0a0337e0 5058 */
dcda9b04 5059 if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL))
a8161d1e 5060 goto nopage;
0a0337e0 5061
0a0337e0 5062 if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
423b452e 5063 did_some_progress > 0, &no_progress_loops))
0a0337e0
MH
5064 goto retry;
5065
33c2d214
MH
5066 /*
5067 * It doesn't make any sense to retry for the compaction if the order-0
5068 * reclaim is not able to make any progress because the current
5069 * implementation of the compaction depends on the sufficient amount
5070 * of free memory (see __compaction_suitable)
5071 */
5072 if (did_some_progress > 0 &&
86a294a8 5073 should_compact_retry(ac, order, alloc_flags,
a5508cd8 5074 compact_result, &compact_priority,
d9436498 5075 &compaction_retries))
33c2d214
MH
5076 goto retry;
5077
902b6281
VB
5078
5079 /* Deal with possible cpuset update races before we start OOM killing */
5080 if (check_retry_cpuset(cpuset_mems_cookie, ac))
e47483bc
VB
5081 goto retry_cpuset;
5082
9083905a
JW
5083 /* Reclaim has failed us, start killing things */
5084 page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
5085 if (page)
5086 goto got_pg;
5087
9a67f648 5088 /* Avoid allocations with no watermarks from looping endlessly */
cd04ae1e 5089 if (tsk_is_oom_victim(current) &&
8510e69c 5090 (alloc_flags & ALLOC_OOM ||
c288983d 5091 (gfp_mask & __GFP_NOMEMALLOC)))
9a67f648
MH
5092 goto nopage;
5093
9083905a 5094 /* Retry as long as the OOM killer is making progress */
0a0337e0
MH
5095 if (did_some_progress) {
5096 no_progress_loops = 0;
9083905a 5097 goto retry;
0a0337e0 5098 }
9083905a 5099
1da177e4 5100nopage:
902b6281
VB
5101 /* Deal with possible cpuset update races before we fail */
5102 if (check_retry_cpuset(cpuset_mems_cookie, ac))
5ce9bfef
VB
5103 goto retry_cpuset;
5104
9a67f648
MH
5105 /*
5106 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
5107 * we always retry
5108 */
5109 if (gfp_mask & __GFP_NOFAIL) {
5110 /*
5111 * All existing users of the __GFP_NOFAIL are blockable, so warn
5112 * of any new users that actually require GFP_NOWAIT
5113 */
5114 if (WARN_ON_ONCE(!can_direct_reclaim))
5115 goto fail;
5116
5117 /*
5118 * PF_MEMALLOC request from this context is rather bizarre
5119 * because we cannot reclaim anything and only can loop waiting
5120 * for somebody to do a work for us
5121 */
5122 WARN_ON_ONCE(current->flags & PF_MEMALLOC);
5123
5124 /*
5125 * non failing costly orders are a hard requirement which we
5126 * are not prepared for much so let's warn about these users
5127 * so that we can identify them and convert them to something
5128 * else.
5129 */
5130 WARN_ON_ONCE(order > PAGE_ALLOC_COSTLY_ORDER);
5131
6c18ba7a
MH
5132 /*
5133 * Help non-failing allocations by giving them access to memory
5134 * reserves but do not use ALLOC_NO_WATERMARKS because this
5135 * could deplete whole memory reserves which would just make
5136 * the situation worse
5137 */
5138 page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac);
5139 if (page)
5140 goto got_pg;
5141
9a67f648
MH
5142 cond_resched();
5143 goto retry;
5144 }
5145fail:
a8e99259 5146 warn_alloc(gfp_mask, ac->nodemask,
7877cdcc 5147 "page allocation failure: order:%u", order);
1da177e4 5148got_pg:
072bb0aa 5149 return page;
1da177e4 5150}
11e33f6a 5151
9cd75558 5152static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
04ec6264 5153 int preferred_nid, nodemask_t *nodemask,
8e6a930b 5154 struct alloc_context *ac, gfp_t *alloc_gfp,
9cd75558 5155 unsigned int *alloc_flags)
11e33f6a 5156{
97a225e6 5157 ac->highest_zoneidx = gfp_zone(gfp_mask);
04ec6264 5158 ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
9cd75558 5159 ac->nodemask = nodemask;
01c0bfe0 5160 ac->migratetype = gfp_migratetype(gfp_mask);
11e33f6a 5161
682a3385 5162 if (cpusets_enabled()) {
8e6a930b 5163 *alloc_gfp |= __GFP_HARDWALL;
182f3d7a
MS
5164 /*
5165 * When we are in the interrupt context, it is irrelevant
5166 * to the current task context. It means that any node ok.
5167 */
88dc6f20 5168 if (in_task() && !ac->nodemask)
9cd75558 5169 ac->nodemask = &cpuset_current_mems_allowed;
51047820
VB
5170 else
5171 *alloc_flags |= ALLOC_CPUSET;
682a3385
MG
5172 }
5173
d92a8cfc
PZ
5174 fs_reclaim_acquire(gfp_mask);
5175 fs_reclaim_release(gfp_mask);
11e33f6a 5176
d0164adc 5177 might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
11e33f6a
MG
5178
5179 if (should_fail_alloc_page(gfp_mask, order))
9cd75558 5180 return false;
11e33f6a 5181
8e3560d9 5182 *alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, *alloc_flags);
d883c6cf 5183
c9ab0c4f 5184 /* Dirty zone balancing only done in the fast path */
9cd75558 5185 ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
c9ab0c4f 5186
e46e7b77
MG
5187 /*
5188 * The preferred zone is used for statistics but crucially it is
5189 * also used as the starting point for the zonelist iterator. It
5190 * may get reset for allocations that ignore memory policies.
5191 */
9cd75558 5192 ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
97a225e6 5193 ac->highest_zoneidx, ac->nodemask);
a0622d05
MN
5194
5195 return true;
9cd75558
MG
5196}
5197
387ba26f 5198/*
0f87d9d3 5199 * __alloc_pages_bulk - Allocate a number of order-0 pages to a list or array
387ba26f
MG
5200 * @gfp: GFP flags for the allocation
5201 * @preferred_nid: The preferred NUMA node ID to allocate from
5202 * @nodemask: Set of nodes to allocate from, may be NULL
0f87d9d3
MG
5203 * @nr_pages: The number of pages desired on the list or array
5204 * @page_list: Optional list to store the allocated pages
5205 * @page_array: Optional array to store the pages
387ba26f
MG
5206 *
5207 * This is a batched version of the page allocator that attempts to
0f87d9d3
MG
5208 * allocate nr_pages quickly. Pages are added to page_list if page_list
5209 * is not NULL, otherwise it is assumed that the page_array is valid.
387ba26f 5210 *
0f87d9d3
MG
5211 * For lists, nr_pages is the number of pages that should be allocated.
5212 *
5213 * For arrays, only NULL elements are populated with pages and nr_pages
5214 * is the maximum number of pages that will be stored in the array.
5215 *
5216 * Returns the number of pages on the list or array.
387ba26f
MG
5217 */
5218unsigned long __alloc_pages_bulk(gfp_t gfp, int preferred_nid,
5219 nodemask_t *nodemask, int nr_pages,
0f87d9d3
MG
5220 struct list_head *page_list,
5221 struct page **page_array)
387ba26f
MG
5222{
5223 struct page *page;
5224 unsigned long flags;
5225 struct zone *zone;
5226 struct zoneref *z;
5227 struct per_cpu_pages *pcp;
5228 struct list_head *pcp_list;
5229 struct alloc_context ac;
5230 gfp_t alloc_gfp;
5231 unsigned int alloc_flags = ALLOC_WMARK_LOW;
3e23060b 5232 int nr_populated = 0, nr_account = 0;
387ba26f 5233
0f87d9d3
MG
5234 /*
5235 * Skip populated array elements to determine if any pages need
5236 * to be allocated before disabling IRQs.
5237 */
b08e50dd 5238 while (page_array && nr_populated < nr_pages && page_array[nr_populated])
0f87d9d3
MG
5239 nr_populated++;
5240
06147843
CL
5241 /* No pages requested? */
5242 if (unlikely(nr_pages <= 0))
5243 goto out;
5244
b3b64ebd
MG
5245 /* Already populated array? */
5246 if (unlikely(page_array && nr_pages - nr_populated == 0))
06147843 5247 goto out;
b3b64ebd 5248
8dcb3060
SB
5249 /* Bulk allocator does not support memcg accounting. */
5250 if (memcg_kmem_enabled() && (gfp & __GFP_ACCOUNT))
5251 goto failed;
5252
387ba26f 5253 /* Use the single page allocator for one page. */
0f87d9d3 5254 if (nr_pages - nr_populated == 1)
387ba26f
MG
5255 goto failed;
5256
187ad460
MG
5257#ifdef CONFIG_PAGE_OWNER
5258 /*
5259 * PAGE_OWNER may recurse into the allocator to allocate space to
5260 * save the stack with pagesets.lock held. Releasing/reacquiring
5261 * removes much of the performance benefit of bulk allocation so
5262 * force the caller to allocate one page at a time as it'll have
5263 * similar performance to added complexity to the bulk allocator.
5264 */
5265 if (static_branch_unlikely(&page_owner_inited))
5266 goto failed;
5267#endif
5268
387ba26f
MG
5269 /* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */
5270 gfp &= gfp_allowed_mask;
5271 alloc_gfp = gfp;
5272 if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &alloc_gfp, &alloc_flags))
06147843 5273 goto out;
387ba26f
MG
5274 gfp = alloc_gfp;
5275
5276 /* Find an allowed local zone that meets the low watermark. */
5277 for_each_zone_zonelist_nodemask(zone, z, ac.zonelist, ac.highest_zoneidx, ac.nodemask) {
5278 unsigned long mark;
5279
5280 if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) &&
5281 !__cpuset_zone_allowed(zone, gfp)) {
5282 continue;
5283 }
5284
5285 if (nr_online_nodes > 1 && zone != ac.preferred_zoneref->zone &&
5286 zone_to_nid(zone) != zone_to_nid(ac.preferred_zoneref->zone)) {
5287 goto failed;
5288 }
5289
5290 mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages;
5291 if (zone_watermark_fast(zone, 0, mark,
5292 zonelist_zone_idx(ac.preferred_zoneref),
5293 alloc_flags, gfp)) {
5294 break;
5295 }
5296 }
5297
5298 /*
5299 * If there are no allowed local zones that meets the watermarks then
5300 * try to allocate a single page and reclaim if necessary.
5301 */
ce76f9a1 5302 if (unlikely(!zone))
387ba26f
MG
5303 goto failed;
5304
5305 /* Attempt the batch allocation */
dbbee9d5 5306 local_lock_irqsave(&pagesets.lock, flags);
28f836b6 5307 pcp = this_cpu_ptr(zone->per_cpu_pageset);
44042b44 5308 pcp_list = &pcp->lists[order_to_pindex(ac.migratetype, 0)];
387ba26f 5309
0f87d9d3
MG
5310 while (nr_populated < nr_pages) {
5311
5312 /* Skip existing pages */
5313 if (page_array && page_array[nr_populated]) {
5314 nr_populated++;
5315 continue;
5316 }
5317
44042b44 5318 page = __rmqueue_pcplist(zone, 0, ac.migratetype, alloc_flags,
387ba26f 5319 pcp, pcp_list);
ce76f9a1 5320 if (unlikely(!page)) {
387ba26f 5321 /* Try and get at least one page */
0f87d9d3 5322 if (!nr_populated)
387ba26f
MG
5323 goto failed_irq;
5324 break;
5325 }
3e23060b 5326 nr_account++;
387ba26f
MG
5327
5328 prep_new_page(page, 0, gfp, 0);
0f87d9d3
MG
5329 if (page_list)
5330 list_add(&page->lru, page_list);
5331 else
5332 page_array[nr_populated] = page;
5333 nr_populated++;
387ba26f
MG
5334 }
5335
43c95bcc
MG
5336 local_unlock_irqrestore(&pagesets.lock, flags);
5337
3e23060b
MG
5338 __count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account);
5339 zone_statistics(ac.preferred_zoneref->zone, zone, nr_account);
387ba26f 5340
06147843 5341out:
0f87d9d3 5342 return nr_populated;
387ba26f
MG
5343
5344failed_irq:
dbbee9d5 5345 local_unlock_irqrestore(&pagesets.lock, flags);
387ba26f
MG
5346
5347failed:
5348 page = __alloc_pages(gfp, 0, preferred_nid, nodemask);
5349 if (page) {
0f87d9d3
MG
5350 if (page_list)
5351 list_add(&page->lru, page_list);
5352 else
5353 page_array[nr_populated] = page;
5354 nr_populated++;
387ba26f
MG
5355 }
5356
06147843 5357 goto out;
387ba26f
MG
5358}
5359EXPORT_SYMBOL_GPL(__alloc_pages_bulk);
5360
9cd75558
MG
5361/*
5362 * This is the 'heart' of the zoned buddy allocator.
5363 */
84172f4b 5364struct page *__alloc_pages(gfp_t gfp, unsigned int order, int preferred_nid,
04ec6264 5365 nodemask_t *nodemask)
9cd75558
MG
5366{
5367 struct page *page;
5368 unsigned int alloc_flags = ALLOC_WMARK_LOW;
8e6a930b 5369 gfp_t alloc_gfp; /* The gfp_t that was actually used for allocation */
9cd75558
MG
5370 struct alloc_context ac = { };
5371
c63ae43b
MH
5372 /*
5373 * There are several places where we assume that the order value is sane
5374 * so bail out early if the request is out of bound.
5375 */
5376 if (unlikely(order >= MAX_ORDER)) {
6e5e0f28 5377 WARN_ON_ONCE(!(gfp & __GFP_NOWARN));
c63ae43b
MH
5378 return NULL;
5379 }
5380
6e5e0f28 5381 gfp &= gfp_allowed_mask;
da6df1b0
PT
5382 /*
5383 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
5384 * resp. GFP_NOIO which has to be inherited for all allocation requests
5385 * from a particular context which has been marked by
8e3560d9
PT
5386 * memalloc_no{fs,io}_{save,restore}. And PF_MEMALLOC_PIN which ensures
5387 * movable zones are not used during allocation.
da6df1b0
PT
5388 */
5389 gfp = current_gfp_context(gfp);
6e5e0f28
MWO
5390 alloc_gfp = gfp;
5391 if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac,
8e6a930b 5392 &alloc_gfp, &alloc_flags))
9cd75558
MG
5393 return NULL;
5394
6bb15450
MG
5395 /*
5396 * Forbid the first pass from falling back to types that fragment
5397 * memory until all local zones are considered.
5398 */
6e5e0f28 5399 alloc_flags |= alloc_flags_nofragment(ac.preferred_zoneref->zone, gfp);
6bb15450 5400
5117f45d 5401 /* First allocation attempt */
8e6a930b 5402 page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac);
4fcb0971
MG
5403 if (likely(page))
5404 goto out;
11e33f6a 5405
da6df1b0 5406 alloc_gfp = gfp;
4fcb0971 5407 ac.spread_dirty_pages = false;
23f086f9 5408
4741526b
MG
5409 /*
5410 * Restore the original nodemask if it was potentially replaced with
5411 * &cpuset_current_mems_allowed to optimize the fast-path attempt.
5412 */
97ce86f9 5413 ac.nodemask = nodemask;
16096c25 5414
8e6a930b 5415 page = __alloc_pages_slowpath(alloc_gfp, order, &ac);
cc9a6c87 5416
4fcb0971 5417out:
6e5e0f28
MWO
5418 if (memcg_kmem_enabled() && (gfp & __GFP_ACCOUNT) && page &&
5419 unlikely(__memcg_kmem_charge_page(page, gfp, order) != 0)) {
c4159a75
VD
5420 __free_pages(page, order);
5421 page = NULL;
4949148a
VD
5422 }
5423
8e6a930b 5424 trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype);
4fcb0971 5425
11e33f6a 5426 return page;
1da177e4 5427}
84172f4b 5428EXPORT_SYMBOL(__alloc_pages);
1da177e4 5429
cc09cb13
MWO
5430struct folio *__folio_alloc(gfp_t gfp, unsigned int order, int preferred_nid,
5431 nodemask_t *nodemask)
5432{
5433 struct page *page = __alloc_pages(gfp | __GFP_COMP, order,
5434 preferred_nid, nodemask);
5435
5436 if (page && order > 1)
5437 prep_transhuge_page(page);
5438 return (struct folio *)page;
5439}
5440EXPORT_SYMBOL(__folio_alloc);
5441
1da177e4 5442/*
9ea9a680
MH
5443 * Common helper functions. Never use with __GFP_HIGHMEM because the returned
5444 * address cannot represent highmem pages. Use alloc_pages and then kmap if
5445 * you need to access high mem.
1da177e4 5446 */
920c7a5d 5447unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
1da177e4 5448{
945a1113
AM
5449 struct page *page;
5450
9ea9a680 5451 page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order);
1da177e4
LT
5452 if (!page)
5453 return 0;
5454 return (unsigned long) page_address(page);
5455}
1da177e4
LT
5456EXPORT_SYMBOL(__get_free_pages);
5457
920c7a5d 5458unsigned long get_zeroed_page(gfp_t gfp_mask)
1da177e4 5459{
945a1113 5460 return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
1da177e4 5461}
1da177e4
LT
5462EXPORT_SYMBOL(get_zeroed_page);
5463
7f194fbb
MWO
5464/**
5465 * __free_pages - Free pages allocated with alloc_pages().
5466 * @page: The page pointer returned from alloc_pages().
5467 * @order: The order of the allocation.
5468 *
5469 * This function can free multi-page allocations that are not compound
5470 * pages. It does not check that the @order passed in matches that of
5471 * the allocation, so it is easy to leak memory. Freeing more memory
5472 * than was allocated will probably emit a warning.
5473 *
5474 * If the last reference to this page is speculative, it will be released
5475 * by put_page() which only frees the first page of a non-compound
5476 * allocation. To prevent the remaining pages from being leaked, we free
5477 * the subsequent pages here. If you want to use the page's reference
5478 * count to decide when to free the allocation, you should allocate a
5479 * compound page, and use put_page() instead of __free_pages().
5480 *
5481 * Context: May be called in interrupt context or while holding a normal
5482 * spinlock, but not in NMI context or while holding a raw spinlock.
5483 */
742aa7fb
AL
5484void __free_pages(struct page *page, unsigned int order)
5485{
5486 if (put_page_testzero(page))
5487 free_the_page(page, order);
e320d301
MWO
5488 else if (!PageHead(page))
5489 while (order-- > 0)
5490 free_the_page(page + (1 << order), order);
742aa7fb 5491}
1da177e4
LT
5492EXPORT_SYMBOL(__free_pages);
5493
920c7a5d 5494void free_pages(unsigned long addr, unsigned int order)
1da177e4
LT
5495{
5496 if (addr != 0) {
725d704e 5497 VM_BUG_ON(!virt_addr_valid((void *)addr));
1da177e4
LT
5498 __free_pages(virt_to_page((void *)addr), order);
5499 }
5500}
5501
5502EXPORT_SYMBOL(free_pages);
5503
b63ae8ca
AD
5504/*
5505 * Page Fragment:
5506 * An arbitrary-length arbitrary-offset area of memory which resides
5507 * within a 0 or higher order page. Multiple fragments within that page
5508 * are individually refcounted, in the page's reference counter.
5509 *
5510 * The page_frag functions below provide a simple allocation framework for
5511 * page fragments. This is used by the network stack and network device
5512 * drivers to provide a backing region of memory for use as either an
5513 * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
5514 */
2976db80
AD
5515static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
5516 gfp_t gfp_mask)
b63ae8ca
AD
5517{
5518 struct page *page = NULL;
5519 gfp_t gfp = gfp_mask;
5520
5521#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5522 gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
5523 __GFP_NOMEMALLOC;
5524 page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
5525 PAGE_FRAG_CACHE_MAX_ORDER);
5526 nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
5527#endif
5528 if (unlikely(!page))
5529 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
5530
5531 nc->va = page ? page_address(page) : NULL;
5532
5533 return page;
5534}
5535
2976db80 5536void __page_frag_cache_drain(struct page *page, unsigned int count)
44fdffd7
AD
5537{
5538 VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
5539
742aa7fb
AL
5540 if (page_ref_sub_and_test(page, count))
5541 free_the_page(page, compound_order(page));
44fdffd7 5542}
2976db80 5543EXPORT_SYMBOL(__page_frag_cache_drain);
44fdffd7 5544
b358e212
KH
5545void *page_frag_alloc_align(struct page_frag_cache *nc,
5546 unsigned int fragsz, gfp_t gfp_mask,
5547 unsigned int align_mask)
b63ae8ca
AD
5548{
5549 unsigned int size = PAGE_SIZE;
5550 struct page *page;
5551 int offset;
5552
5553 if (unlikely(!nc->va)) {
5554refill:
2976db80 5555 page = __page_frag_cache_refill(nc, gfp_mask);
b63ae8ca
AD
5556 if (!page)
5557 return NULL;
5558
5559#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5560 /* if size can vary use size else just use PAGE_SIZE */
5561 size = nc->size;
5562#endif
5563 /* Even if we own the page, we do not use atomic_set().
5564 * This would break get_page_unless_zero() users.
5565 */
86447726 5566 page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
b63ae8ca
AD
5567
5568 /* reset page count bias and offset to start of new frag */
2f064f34 5569 nc->pfmemalloc = page_is_pfmemalloc(page);
86447726 5570 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
b63ae8ca
AD
5571 nc->offset = size;
5572 }
5573
5574 offset = nc->offset - fragsz;
5575 if (unlikely(offset < 0)) {
5576 page = virt_to_page(nc->va);
5577
fe896d18 5578 if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
b63ae8ca
AD
5579 goto refill;
5580
d8c19014
DZ
5581 if (unlikely(nc->pfmemalloc)) {
5582 free_the_page(page, compound_order(page));
5583 goto refill;
5584 }
5585
b63ae8ca
AD
5586#if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
5587 /* if size can vary use size else just use PAGE_SIZE */
5588 size = nc->size;
5589#endif
5590 /* OK, page count is 0, we can safely set it */
86447726 5591 set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
b63ae8ca
AD
5592
5593 /* reset page count bias and offset to start of new frag */
86447726 5594 nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
b63ae8ca
AD
5595 offset = size - fragsz;
5596 }
5597
5598 nc->pagecnt_bias--;
b358e212 5599 offset &= align_mask;
b63ae8ca
AD
5600 nc->offset = offset;
5601
5602 return nc->va + offset;
5603}
b358e212 5604EXPORT_SYMBOL(page_frag_alloc_align);
b63ae8ca
AD
5605
5606/*
5607 * Frees a page fragment allocated out of either a compound or order 0 page.
5608 */
8c2dd3e4 5609void page_frag_free(void *addr)
b63ae8ca
AD
5610{
5611 struct page *page = virt_to_head_page(addr);
5612
742aa7fb
AL
5613 if (unlikely(put_page_testzero(page)))
5614 free_the_page(page, compound_order(page));
b63ae8ca 5615}
8c2dd3e4 5616EXPORT_SYMBOL(page_frag_free);
b63ae8ca 5617
d00181b9
KS
5618static void *make_alloc_exact(unsigned long addr, unsigned int order,
5619 size_t size)
ee85c2e1
AK
5620{
5621 if (addr) {
5622 unsigned long alloc_end = addr + (PAGE_SIZE << order);
5623 unsigned long used = addr + PAGE_ALIGN(size);
5624
5625 split_page(virt_to_page((void *)addr), order);
5626 while (used < alloc_end) {
5627 free_page(used);
5628 used += PAGE_SIZE;
5629 }
5630 }
5631 return (void *)addr;
5632}
5633
2be0ffe2
TT
5634/**
5635 * alloc_pages_exact - allocate an exact number physically-contiguous pages.
5636 * @size: the number of bytes to allocate
63931eb9 5637 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
2be0ffe2
TT
5638 *
5639 * This function is similar to alloc_pages(), except that it allocates the
5640 * minimum number of pages to satisfy the request. alloc_pages() can only
5641 * allocate memory in power-of-two pages.
5642 *
5643 * This function is also limited by MAX_ORDER.
5644 *
5645 * Memory allocated by this function must be released by free_pages_exact().
a862f68a
MR
5646 *
5647 * Return: pointer to the allocated area or %NULL in case of error.
2be0ffe2
TT
5648 */
5649void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
5650{
5651 unsigned int order = get_order(size);
5652 unsigned long addr;
5653
ba7f1b9e
ML
5654 if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
5655 gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
63931eb9 5656
2be0ffe2 5657 addr = __get_free_pages(gfp_mask, order);
ee85c2e1 5658 return make_alloc_exact(addr, order, size);
2be0ffe2
TT
5659}
5660EXPORT_SYMBOL(alloc_pages_exact);
5661
ee85c2e1
AK
5662/**
5663 * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
5664 * pages on a node.
b5e6ab58 5665 * @nid: the preferred node ID where memory should be allocated
ee85c2e1 5666 * @size: the number of bytes to allocate
63931eb9 5667 * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
ee85c2e1
AK
5668 *
5669 * Like alloc_pages_exact(), but try to allocate on node nid first before falling
5670 * back.
a862f68a
MR
5671 *
5672 * Return: pointer to the allocated area or %NULL in case of error.
ee85c2e1 5673 */
e1931811 5674void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
ee85c2e1 5675{
d00181b9 5676 unsigned int order = get_order(size);
63931eb9
VB
5677 struct page *p;
5678
ba7f1b9e
ML
5679 if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
5680 gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
63931eb9
VB
5681
5682 p = alloc_pages_node(nid, gfp_mask, order);
ee85c2e1
AK
5683 if (!p)
5684 return NULL;
5685 return make_alloc_exact((unsigned long)page_address(p), order, size);
5686}
ee85c2e1 5687
2be0ffe2
TT
5688/**
5689 * free_pages_exact - release memory allocated via alloc_pages_exact()
5690 * @virt: the value returned by alloc_pages_exact.
5691 * @size: size of allocation, same value as passed to alloc_pages_exact().
5692 *
5693 * Release the memory allocated by a previous call to alloc_pages_exact.
5694 */
5695void free_pages_exact(void *virt, size_t size)
5696{
5697 unsigned long addr = (unsigned long)virt;
5698 unsigned long end = addr + PAGE_ALIGN(size);
5699
5700 while (addr < end) {
5701 free_page(addr);
5702 addr += PAGE_SIZE;
5703 }
5704}
5705EXPORT_SYMBOL(free_pages_exact);
5706
e0fb5815
ZY
5707/**
5708 * nr_free_zone_pages - count number of pages beyond high watermark
5709 * @offset: The zone index of the highest zone
5710 *
a862f68a 5711 * nr_free_zone_pages() counts the number of pages which are beyond the
e0fb5815
ZY
5712 * high watermark within all zones at or below a given zone index. For each
5713 * zone, the number of pages is calculated as:
0e056eb5
MCC
5714 *
5715 * nr_free_zone_pages = managed_pages - high_pages
a862f68a
MR
5716 *
5717 * Return: number of pages beyond high watermark.
e0fb5815 5718 */
ebec3862 5719static unsigned long nr_free_zone_pages(int offset)
1da177e4 5720{
dd1a239f 5721 struct zoneref *z;
54a6eb5c
MG
5722 struct zone *zone;
5723
e310fd43 5724 /* Just pick one node, since fallback list is circular */
ebec3862 5725 unsigned long sum = 0;
1da177e4 5726
0e88460d 5727 struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
1da177e4 5728
54a6eb5c 5729 for_each_zone_zonelist(zone, z, zonelist, offset) {
9705bea5 5730 unsigned long size = zone_managed_pages(zone);
41858966 5731 unsigned long high = high_wmark_pages(zone);
e310fd43
MB
5732 if (size > high)
5733 sum += size - high;
1da177e4
LT
5734 }
5735
5736 return sum;
5737}
5738
e0fb5815
ZY
5739/**
5740 * nr_free_buffer_pages - count number of pages beyond high watermark
5741 *
5742 * nr_free_buffer_pages() counts the number of pages which are beyond the high
5743 * watermark within ZONE_DMA and ZONE_NORMAL.
a862f68a
MR
5744 *
5745 * Return: number of pages beyond high watermark within ZONE_DMA and
5746 * ZONE_NORMAL.
1da177e4 5747 */
ebec3862 5748unsigned long nr_free_buffer_pages(void)
1da177e4 5749{
af4ca457 5750 return nr_free_zone_pages(gfp_zone(GFP_USER));
1da177e4 5751}
c2f1a551 5752EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
1da177e4 5753
08e0f6a9 5754static inline void show_node(struct zone *zone)
1da177e4 5755{
e5adfffc 5756 if (IS_ENABLED(CONFIG_NUMA))
25ba77c1 5757 printk("Node %d ", zone_to_nid(zone));
1da177e4 5758}
1da177e4 5759
d02bd27b
IR
5760long si_mem_available(void)
5761{
5762 long available;
5763 unsigned long pagecache;
5764 unsigned long wmark_low = 0;
5765 unsigned long pages[NR_LRU_LISTS];
b29940c1 5766 unsigned long reclaimable;
d02bd27b
IR
5767 struct zone *zone;
5768 int lru;
5769
5770 for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
2f95ff90 5771 pages[lru] = global_node_page_state(NR_LRU_BASE + lru);
d02bd27b
IR
5772
5773 for_each_zone(zone)
a9214443 5774 wmark_low += low_wmark_pages(zone);
d02bd27b
IR
5775
5776 /*
5777 * Estimate the amount of memory available for userspace allocations,
5778 * without causing swapping.
5779 */
c41f012a 5780 available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages;
d02bd27b
IR
5781
5782 /*
5783 * Not all the page cache can be freed, otherwise the system will
5784 * start swapping. Assume at least half of the page cache, or the
5785 * low watermark worth of cache, needs to stay.
5786 */
5787 pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
5788 pagecache -= min(pagecache / 2, wmark_low);
5789 available += pagecache;
5790
5791 /*
b29940c1
VB
5792 * Part of the reclaimable slab and other kernel memory consists of
5793 * items that are in use, and cannot be freed. Cap this estimate at the
5794 * low watermark.
d02bd27b 5795 */
d42f3245
RG
5796 reclaimable = global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B) +
5797 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE);
b29940c1 5798 available += reclaimable - min(reclaimable / 2, wmark_low);
034ebf65 5799
d02bd27b
IR
5800 if (available < 0)
5801 available = 0;
5802 return available;
5803}
5804EXPORT_SYMBOL_GPL(si_mem_available);
5805
1da177e4
LT
5806void si_meminfo(struct sysinfo *val)
5807{
ca79b0c2 5808 val->totalram = totalram_pages();
11fb9989 5809 val->sharedram = global_node_page_state(NR_SHMEM);
c41f012a 5810 val->freeram = global_zone_page_state(NR_FREE_PAGES);
1da177e4 5811 val->bufferram = nr_blockdev_pages();
ca79b0c2 5812 val->totalhigh = totalhigh_pages();
1da177e4 5813 val->freehigh = nr_free_highpages();
1da177e4
LT
5814 val->mem_unit = PAGE_SIZE;
5815}
5816
5817EXPORT_SYMBOL(si_meminfo);
5818
5819#ifdef CONFIG_NUMA
5820void si_meminfo_node(struct sysinfo *val, int nid)
5821{
cdd91a77
JL
5822 int zone_type; /* needs to be signed */
5823 unsigned long managed_pages = 0;
fc2bd799
JK
5824 unsigned long managed_highpages = 0;
5825 unsigned long free_highpages = 0;
1da177e4
LT
5826 pg_data_t *pgdat = NODE_DATA(nid);
5827
cdd91a77 5828 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
9705bea5 5829 managed_pages += zone_managed_pages(&pgdat->node_zones[zone_type]);
cdd91a77 5830 val->totalram = managed_pages;
11fb9989 5831 val->sharedram = node_page_state(pgdat, NR_SHMEM);
75ef7184 5832 val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES);
98d2b0eb 5833#ifdef CONFIG_HIGHMEM
fc2bd799
JK
5834 for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
5835 struct zone *zone = &pgdat->node_zones[zone_type];
5836
5837 if (is_highmem(zone)) {
9705bea5 5838 managed_highpages += zone_managed_pages(zone);
fc2bd799
JK
5839 free_highpages += zone_page_state(zone, NR_FREE_PAGES);
5840 }
5841 }
5842 val->totalhigh = managed_highpages;
5843 val->freehigh = free_highpages;
98d2b0eb 5844#else
fc2bd799
JK
5845 val->totalhigh = managed_highpages;
5846 val->freehigh = free_highpages;
98d2b0eb 5847#endif
1da177e4
LT
5848 val->mem_unit = PAGE_SIZE;
5849}
5850#endif
5851
ddd588b5 5852/*
7bf02ea2
DR
5853 * Determine whether the node should be displayed or not, depending on whether
5854 * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
ddd588b5 5855 */
9af744d7 5856static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask)
ddd588b5 5857{
ddd588b5 5858 if (!(flags & SHOW_MEM_FILTER_NODES))
9af744d7 5859 return false;
ddd588b5 5860
9af744d7
MH
5861 /*
5862 * no node mask - aka implicit memory numa policy. Do not bother with
5863 * the synchronization - read_mems_allowed_begin - because we do not
5864 * have to be precise here.
5865 */
5866 if (!nodemask)
5867 nodemask = &cpuset_current_mems_allowed;
5868
5869 return !node_isset(nid, *nodemask);
ddd588b5
DR
5870}
5871
1da177e4
LT
5872#define K(x) ((x) << (PAGE_SHIFT-10))
5873
377e4f16
RV
5874static void show_migration_types(unsigned char type)
5875{
5876 static const char types[MIGRATE_TYPES] = {
5877 [MIGRATE_UNMOVABLE] = 'U',
377e4f16 5878 [MIGRATE_MOVABLE] = 'M',
475a2f90
VB
5879 [MIGRATE_RECLAIMABLE] = 'E',
5880 [MIGRATE_HIGHATOMIC] = 'H',
377e4f16
RV
5881#ifdef CONFIG_CMA
5882 [MIGRATE_CMA] = 'C',
5883#endif
194159fb 5884#ifdef CONFIG_MEMORY_ISOLATION
377e4f16 5885 [MIGRATE_ISOLATE] = 'I',
194159fb 5886#endif
377e4f16
RV
5887 };
5888 char tmp[MIGRATE_TYPES + 1];
5889 char *p = tmp;
5890 int i;
5891
5892 for (i = 0; i < MIGRATE_TYPES; i++) {
5893 if (type & (1 << i))
5894 *p++ = types[i];
5895 }
5896
5897 *p = '\0';
1f84a18f 5898 printk(KERN_CONT "(%s) ", tmp);
377e4f16
RV
5899}
5900
1da177e4
LT
5901/*
5902 * Show free area list (used inside shift_scroll-lock stuff)
5903 * We also calculate the percentage fragmentation. We do this by counting the
5904 * memory on each free list with the exception of the first item on the list.
d1bfcdb8
KK
5905 *
5906 * Bits in @filter:
5907 * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
5908 * cpuset.
1da177e4 5909 */
9af744d7 5910void show_free_areas(unsigned int filter, nodemask_t *nodemask)
1da177e4 5911{
d1bfcdb8 5912 unsigned long free_pcp = 0;
c7241913 5913 int cpu;
1da177e4 5914 struct zone *zone;
599d0c95 5915 pg_data_t *pgdat;
1da177e4 5916
ee99c71c 5917 for_each_populated_zone(zone) {
9af744d7 5918 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
ddd588b5 5919 continue;
d1bfcdb8 5920
761b0677 5921 for_each_online_cpu(cpu)
28f836b6 5922 free_pcp += per_cpu_ptr(zone->per_cpu_pageset, cpu)->count;
1da177e4
LT
5923 }
5924
a731286d
KM
5925 printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
5926 " active_file:%lu inactive_file:%lu isolated_file:%lu\n"
8d92890b 5927 " unevictable:%lu dirty:%lu writeback:%lu\n"
d1bfcdb8 5928 " slab_reclaimable:%lu slab_unreclaimable:%lu\n"
d1ce749a 5929 " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
eb2169ce 5930 " kernel_misc_reclaimable:%lu\n"
d1bfcdb8 5931 " free:%lu free_pcp:%lu free_cma:%lu\n",
599d0c95
MG
5932 global_node_page_state(NR_ACTIVE_ANON),
5933 global_node_page_state(NR_INACTIVE_ANON),
5934 global_node_page_state(NR_ISOLATED_ANON),
5935 global_node_page_state(NR_ACTIVE_FILE),
5936 global_node_page_state(NR_INACTIVE_FILE),
5937 global_node_page_state(NR_ISOLATED_FILE),
5938 global_node_page_state(NR_UNEVICTABLE),
11fb9989
MG
5939 global_node_page_state(NR_FILE_DIRTY),
5940 global_node_page_state(NR_WRITEBACK),
d42f3245
RG
5941 global_node_page_state_pages(NR_SLAB_RECLAIMABLE_B),
5942 global_node_page_state_pages(NR_SLAB_UNRECLAIMABLE_B),
50658e2e 5943 global_node_page_state(NR_FILE_MAPPED),
11fb9989 5944 global_node_page_state(NR_SHMEM),
f0c0c115 5945 global_node_page_state(NR_PAGETABLE),
c41f012a 5946 global_zone_page_state(NR_BOUNCE),
eb2169ce 5947 global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE),
c41f012a 5948 global_zone_page_state(NR_FREE_PAGES),
d1bfcdb8 5949 free_pcp,
c41f012a 5950 global_zone_page_state(NR_FREE_CMA_PAGES));
1da177e4 5951
599d0c95 5952 for_each_online_pgdat(pgdat) {
9af744d7 5953 if (show_mem_node_skip(filter, pgdat->node_id, nodemask))
c02e50bb
MH
5954 continue;
5955
599d0c95
MG
5956 printk("Node %d"
5957 " active_anon:%lukB"
5958 " inactive_anon:%lukB"
5959 " active_file:%lukB"
5960 " inactive_file:%lukB"
5961 " unevictable:%lukB"
5962 " isolated(anon):%lukB"
5963 " isolated(file):%lukB"
50658e2e 5964 " mapped:%lukB"
11fb9989
MG
5965 " dirty:%lukB"
5966 " writeback:%lukB"
5967 " shmem:%lukB"
5968#ifdef CONFIG_TRANSPARENT_HUGEPAGE
5969 " shmem_thp: %lukB"
5970 " shmem_pmdmapped: %lukB"
5971 " anon_thp: %lukB"
5972#endif
5973 " writeback_tmp:%lukB"
991e7673
SB
5974 " kernel_stack:%lukB"
5975#ifdef CONFIG_SHADOW_CALL_STACK
5976 " shadow_call_stack:%lukB"
5977#endif
f0c0c115 5978 " pagetables:%lukB"
599d0c95
MG
5979 " all_unreclaimable? %s"
5980 "\n",
5981 pgdat->node_id,
5982 K(node_page_state(pgdat, NR_ACTIVE_ANON)),
5983 K(node_page_state(pgdat, NR_INACTIVE_ANON)),
5984 K(node_page_state(pgdat, NR_ACTIVE_FILE)),
5985 K(node_page_state(pgdat, NR_INACTIVE_FILE)),
5986 K(node_page_state(pgdat, NR_UNEVICTABLE)),
5987 K(node_page_state(pgdat, NR_ISOLATED_ANON)),
5988 K(node_page_state(pgdat, NR_ISOLATED_FILE)),
50658e2e 5989 K(node_page_state(pgdat, NR_FILE_MAPPED)),
11fb9989
MG
5990 K(node_page_state(pgdat, NR_FILE_DIRTY)),
5991 K(node_page_state(pgdat, NR_WRITEBACK)),
1f06b81a 5992 K(node_page_state(pgdat, NR_SHMEM)),
11fb9989 5993#ifdef CONFIG_TRANSPARENT_HUGEPAGE
57b2847d 5994 K(node_page_state(pgdat, NR_SHMEM_THPS)),
a1528e21 5995 K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED)),
69473e5d 5996 K(node_page_state(pgdat, NR_ANON_THPS)),
11fb9989 5997#endif
11fb9989 5998 K(node_page_state(pgdat, NR_WRITEBACK_TEMP)),
991e7673
SB
5999 node_page_state(pgdat, NR_KERNEL_STACK_KB),
6000#ifdef CONFIG_SHADOW_CALL_STACK
6001 node_page_state(pgdat, NR_KERNEL_SCS_KB),
6002#endif
f0c0c115 6003 K(node_page_state(pgdat, NR_PAGETABLE)),
c73322d0
JW
6004 pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ?
6005 "yes" : "no");
599d0c95
MG
6006 }
6007
ee99c71c 6008 for_each_populated_zone(zone) {
1da177e4
LT
6009 int i;
6010
9af744d7 6011 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
ddd588b5 6012 continue;
d1bfcdb8
KK
6013
6014 free_pcp = 0;
6015 for_each_online_cpu(cpu)
28f836b6 6016 free_pcp += per_cpu_ptr(zone->per_cpu_pageset, cpu)->count;
d1bfcdb8 6017
1da177e4 6018 show_node(zone);
1f84a18f
JP
6019 printk(KERN_CONT
6020 "%s"
1da177e4 6021 " free:%lukB"
a6ea8b5b 6022 " boost:%lukB"
1da177e4
LT
6023 " min:%lukB"
6024 " low:%lukB"
6025 " high:%lukB"
e47b346a 6026 " reserved_highatomic:%luKB"
71c799f4
MK
6027 " active_anon:%lukB"
6028 " inactive_anon:%lukB"
6029 " active_file:%lukB"
6030 " inactive_file:%lukB"
6031 " unevictable:%lukB"
5a1c84b4 6032 " writepending:%lukB"
1da177e4 6033 " present:%lukB"
9feedc9d 6034 " managed:%lukB"
4a0aa73f 6035 " mlocked:%lukB"
4a0aa73f 6036 " bounce:%lukB"
d1bfcdb8
KK
6037 " free_pcp:%lukB"
6038 " local_pcp:%ukB"
d1ce749a 6039 " free_cma:%lukB"
1da177e4
LT
6040 "\n",
6041 zone->name,
88f5acf8 6042 K(zone_page_state(zone, NR_FREE_PAGES)),
a6ea8b5b 6043 K(zone->watermark_boost),
41858966
MG
6044 K(min_wmark_pages(zone)),
6045 K(low_wmark_pages(zone)),
6046 K(high_wmark_pages(zone)),
e47b346a 6047 K(zone->nr_reserved_highatomic),
71c799f4
MK
6048 K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)),
6049 K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)),
6050 K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)),
6051 K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)),
6052 K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)),
5a1c84b4 6053 K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)),
1da177e4 6054 K(zone->present_pages),
9705bea5 6055 K(zone_managed_pages(zone)),
4a0aa73f 6056 K(zone_page_state(zone, NR_MLOCK)),
4a0aa73f 6057 K(zone_page_state(zone, NR_BOUNCE)),
d1bfcdb8 6058 K(free_pcp),
28f836b6 6059 K(this_cpu_read(zone->per_cpu_pageset->count)),
33e077bd 6060 K(zone_page_state(zone, NR_FREE_CMA_PAGES)));
1da177e4
LT
6061 printk("lowmem_reserve[]:");
6062 for (i = 0; i < MAX_NR_ZONES; i++)
1f84a18f
JP
6063 printk(KERN_CONT " %ld", zone->lowmem_reserve[i]);
6064 printk(KERN_CONT "\n");
1da177e4
LT
6065 }
6066
ee99c71c 6067 for_each_populated_zone(zone) {
d00181b9
KS
6068 unsigned int order;
6069 unsigned long nr[MAX_ORDER], flags, total = 0;
377e4f16 6070 unsigned char types[MAX_ORDER];
1da177e4 6071
9af744d7 6072 if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
ddd588b5 6073 continue;
1da177e4 6074 show_node(zone);
1f84a18f 6075 printk(KERN_CONT "%s: ", zone->name);
1da177e4
LT
6076
6077 spin_lock_irqsave(&zone->lock, flags);
6078 for (order = 0; order < MAX_ORDER; order++) {
377e4f16
RV
6079 struct free_area *area = &zone->free_area[order];
6080 int type;
6081
6082 nr[order] = area->nr_free;
8f9de51a 6083 total += nr[order] << order;
377e4f16
RV
6084
6085 types[order] = 0;
6086 for (type = 0; type < MIGRATE_TYPES; type++) {
b03641af 6087 if (!free_area_empty(area, type))
377e4f16
RV
6088 types[order] |= 1 << type;
6089 }
1da177e4
LT
6090 }
6091 spin_unlock_irqrestore(&zone->lock, flags);
377e4f16 6092 for (order = 0; order < MAX_ORDER; order++) {
1f84a18f
JP
6093 printk(KERN_CONT "%lu*%lukB ",
6094 nr[order], K(1UL) << order);
377e4f16
RV
6095 if (nr[order])
6096 show_migration_types(types[order]);
6097 }
1f84a18f 6098 printk(KERN_CONT "= %lukB\n", K(total));
1da177e4
LT
6099 }
6100
949f7ec5
DR
6101 hugetlb_show_meminfo();
6102
11fb9989 6103 printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES));
e6f3602d 6104
1da177e4
LT
6105 show_swap_cache_info();
6106}
6107
19770b32
MG
6108static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
6109{
6110 zoneref->zone = zone;
6111 zoneref->zone_idx = zone_idx(zone);
6112}
6113
1da177e4
LT
6114/*
6115 * Builds allocation fallback zone lists.
1a93205b
CL
6116 *
6117 * Add all populated zones of a node to the zonelist.
1da177e4 6118 */
9d3be21b 6119static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
1da177e4 6120{
1a93205b 6121 struct zone *zone;
bc732f1d 6122 enum zone_type zone_type = MAX_NR_ZONES;
9d3be21b 6123 int nr_zones = 0;
02a68a5e
CL
6124
6125 do {
2f6726e5 6126 zone_type--;
070f8032 6127 zone = pgdat->node_zones + zone_type;
e553f62f 6128 if (populated_zone(zone)) {
9d3be21b 6129 zoneref_set_zone(zone, &zonerefs[nr_zones++]);
070f8032 6130 check_highest_zone(zone_type);
1da177e4 6131 }
2f6726e5 6132 } while (zone_type);
bc732f1d 6133
070f8032 6134 return nr_zones;
1da177e4
LT
6135}
6136
6137#ifdef CONFIG_NUMA
f0c0b2b8
KH
6138
6139static int __parse_numa_zonelist_order(char *s)
6140{
c9bff3ee 6141 /*
f0953a1b 6142 * We used to support different zonelists modes but they turned
c9bff3ee
MH
6143 * out to be just not useful. Let's keep the warning in place
6144 * if somebody still use the cmd line parameter so that we do
6145 * not fail it silently
6146 */
6147 if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
6148 pr_warn("Ignoring unsupported numa_zonelist_order value: %s\n", s);
f0c0b2b8
KH
6149 return -EINVAL;
6150 }
6151 return 0;
6152}
6153
c9bff3ee
MH
6154char numa_zonelist_order[] = "Node";
6155
f0c0b2b8
KH
6156/*
6157 * sysctl handler for numa_zonelist_order
6158 */
cccad5b9 6159int numa_zonelist_order_handler(struct ctl_table *table, int write,
32927393 6160 void *buffer, size_t *length, loff_t *ppos)
f0c0b2b8 6161{
32927393
CH
6162 if (write)
6163 return __parse_numa_zonelist_order(buffer);
6164 return proc_dostring(table, write, buffer, length, ppos);
f0c0b2b8
KH
6165}
6166
6167
f0c0b2b8
KH
6168static int node_load[MAX_NUMNODES];
6169
1da177e4 6170/**
4dc3b16b 6171 * find_next_best_node - find the next node that should appear in a given node's fallback list
1da177e4
LT
6172 * @node: node whose fallback list we're appending
6173 * @used_node_mask: nodemask_t of already used nodes
6174 *
6175 * We use a number of factors to determine which is the next node that should
6176 * appear on a given node's fallback list. The node should not have appeared
6177 * already in @node's fallback list, and it should be the next closest node
6178 * according to the distance array (which contains arbitrary distance values
6179 * from each node to each node in the system), and should also prefer nodes
6180 * with no CPUs, since presumably they'll have very little allocation pressure
6181 * on them otherwise.
a862f68a
MR
6182 *
6183 * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
1da177e4 6184 */
79c28a41 6185int find_next_best_node(int node, nodemask_t *used_node_mask)
1da177e4 6186{
4cf808eb 6187 int n, val;
1da177e4 6188 int min_val = INT_MAX;
00ef2d2f 6189 int best_node = NUMA_NO_NODE;
1da177e4 6190
4cf808eb
LT
6191 /* Use the local node if we haven't already */
6192 if (!node_isset(node, *used_node_mask)) {
6193 node_set(node, *used_node_mask);
6194 return node;
6195 }
1da177e4 6196
4b0ef1fe 6197 for_each_node_state(n, N_MEMORY) {
1da177e4
LT
6198
6199 /* Don't want a node to appear more than once */
6200 if (node_isset(n, *used_node_mask))
6201 continue;
6202
1da177e4
LT
6203 /* Use the distance array to find the distance */
6204 val = node_distance(node, n);
6205
4cf808eb
LT
6206 /* Penalize nodes under us ("prefer the next node") */
6207 val += (n < node);
6208
1da177e4 6209 /* Give preference to headless and unused nodes */
b630749f 6210 if (!cpumask_empty(cpumask_of_node(n)))
1da177e4
LT
6211 val += PENALTY_FOR_NODE_WITH_CPUS;
6212
6213 /* Slight preference for less loaded node */
37931324 6214 val *= MAX_NUMNODES;
1da177e4
LT
6215 val += node_load[n];
6216
6217 if (val < min_val) {
6218 min_val = val;
6219 best_node = n;
6220 }
6221 }
6222
6223 if (best_node >= 0)
6224 node_set(best_node, *used_node_mask);
6225
6226 return best_node;
6227}
6228
f0c0b2b8
KH
6229
6230/*
6231 * Build zonelists ordered by node and zones within node.
6232 * This results in maximum locality--normal zone overflows into local
6233 * DMA zone, if any--but risks exhausting DMA zone.
6234 */
9d3be21b
MH
6235static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
6236 unsigned nr_nodes)
1da177e4 6237{
9d3be21b
MH
6238 struct zoneref *zonerefs;
6239 int i;
6240
6241 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
6242
6243 for (i = 0; i < nr_nodes; i++) {
6244 int nr_zones;
6245
6246 pg_data_t *node = NODE_DATA(node_order[i]);
f0c0b2b8 6247
9d3be21b
MH
6248 nr_zones = build_zonerefs_node(node, zonerefs);
6249 zonerefs += nr_zones;
6250 }
6251 zonerefs->zone = NULL;
6252 zonerefs->zone_idx = 0;
f0c0b2b8
KH
6253}
6254
523b9458
CL
6255/*
6256 * Build gfp_thisnode zonelists
6257 */
6258static void build_thisnode_zonelists(pg_data_t *pgdat)
6259{
9d3be21b
MH
6260 struct zoneref *zonerefs;
6261 int nr_zones;
523b9458 6262
9d3be21b
MH
6263 zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
6264 nr_zones = build_zonerefs_node(pgdat, zonerefs);
6265 zonerefs += nr_zones;
6266 zonerefs->zone = NULL;
6267 zonerefs->zone_idx = 0;
523b9458
CL
6268}
6269
f0c0b2b8
KH
6270/*
6271 * Build zonelists ordered by zone and nodes within zones.
6272 * This results in conserving DMA zone[s] until all Normal memory is
6273 * exhausted, but results in overflowing to remote node while memory
6274 * may still exist in local DMA zone.
6275 */
f0c0b2b8 6276
f0c0b2b8
KH
6277static void build_zonelists(pg_data_t *pgdat)
6278{
9d3be21b 6279 static int node_order[MAX_NUMNODES];
37931324 6280 int node, nr_nodes = 0;
d0ddf49b 6281 nodemask_t used_mask = NODE_MASK_NONE;
f0c0b2b8 6282 int local_node, prev_node;
1da177e4
LT
6283
6284 /* NUMA-aware ordering of nodes */
6285 local_node = pgdat->node_id;
1da177e4 6286 prev_node = local_node;
f0c0b2b8 6287
f0c0b2b8 6288 memset(node_order, 0, sizeof(node_order));
1da177e4
LT
6289 while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
6290 /*
6291 * We don't want to pressure a particular node.
6292 * So adding penalty to the first node in same
6293 * distance group to make it round-robin.
6294 */
957f822a
DR
6295 if (node_distance(local_node, node) !=
6296 node_distance(local_node, prev_node))
37931324 6297 node_load[node] += 1;
f0c0b2b8 6298
9d3be21b 6299 node_order[nr_nodes++] = node;
1da177e4 6300 prev_node = node;
1da177e4 6301 }
523b9458 6302
9d3be21b 6303 build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
523b9458 6304 build_thisnode_zonelists(pgdat);
6cf25392
BR
6305 pr_info("Fallback order for Node %d: ", local_node);
6306 for (node = 0; node < nr_nodes; node++)
6307 pr_cont("%d ", node_order[node]);
6308 pr_cont("\n");
1da177e4
LT
6309}
6310
7aac7898
LS
6311#ifdef CONFIG_HAVE_MEMORYLESS_NODES
6312/*
6313 * Return node id of node used for "local" allocations.
6314 * I.e., first node id of first zone in arg node's generic zonelist.
6315 * Used for initializing percpu 'numa_mem', which is used primarily
6316 * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
6317 */
6318int local_memory_node(int node)
6319{
c33d6c06 6320 struct zoneref *z;
7aac7898 6321
c33d6c06 6322 z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
7aac7898 6323 gfp_zone(GFP_KERNEL),
c33d6c06 6324 NULL);
c1093b74 6325 return zone_to_nid(z->zone);
7aac7898
LS
6326}
6327#endif
f0c0b2b8 6328
6423aa81
JK
6329static void setup_min_unmapped_ratio(void);
6330static void setup_min_slab_ratio(void);
1da177e4
LT
6331#else /* CONFIG_NUMA */
6332
f0c0b2b8 6333static void build_zonelists(pg_data_t *pgdat)
1da177e4 6334{
19655d34 6335 int node, local_node;
9d3be21b
MH
6336 struct zoneref *zonerefs;
6337 int nr_zones;
1da177e4
LT
6338
6339 local_node = pgdat->node_id;
1da177e4 6340
9d3be21b
MH
6341 zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
6342 nr_zones = build_zonerefs_node(pgdat, zonerefs);
6343 zonerefs += nr_zones;
1da177e4 6344
54a6eb5c
MG
6345 /*
6346 * Now we build the zonelist so that it contains the zones
6347 * of all the other nodes.
6348 * We don't want to pressure a particular node, so when
6349 * building the zones for node N, we make sure that the
6350 * zones coming right after the local ones are those from
6351 * node N+1 (modulo N)
6352 */
6353 for (node = local_node + 1; node < MAX_NUMNODES; node++) {
6354 if (!node_online(node))
6355 continue;
9d3be21b
MH
6356 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
6357 zonerefs += nr_zones;
1da177e4 6358 }
54a6eb5c
MG
6359 for (node = 0; node < local_node; node++) {
6360 if (!node_online(node))
6361 continue;
9d3be21b
MH
6362 nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
6363 zonerefs += nr_zones;
54a6eb5c
MG
6364 }
6365
9d3be21b
MH
6366 zonerefs->zone = NULL;
6367 zonerefs->zone_idx = 0;
1da177e4
LT
6368}
6369
6370#endif /* CONFIG_NUMA */
6371
99dcc3e5
CL
6372/*
6373 * Boot pageset table. One per cpu which is going to be used for all
6374 * zones and all nodes. The parameters will be set in such a way
6375 * that an item put on a list will immediately be handed over to
6376 * the buddy list. This is safe since pageset manipulation is done
6377 * with interrupts disabled.
6378 *
6379 * The boot_pagesets must be kept even after bootup is complete for
6380 * unused processors and/or zones. They do play a role for bootstrapping
6381 * hotplugged processors.
6382 *
6383 * zoneinfo_show() and maybe other functions do
6384 * not check if the processor is online before following the pageset pointer.
6385 * Other parts of the kernel may not check if the zone is available.
6386 */
28f836b6 6387static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats);
952eaf81
VB
6388/* These effectively disable the pcplists in the boot pageset completely */
6389#define BOOT_PAGESET_HIGH 0
6390#define BOOT_PAGESET_BATCH 1
28f836b6
MG
6391static DEFINE_PER_CPU(struct per_cpu_pages, boot_pageset);
6392static DEFINE_PER_CPU(struct per_cpu_zonestat, boot_zonestats);
09f49dca 6393DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
99dcc3e5 6394
11cd8638 6395static void __build_all_zonelists(void *data)
1da177e4 6396{
6811378e 6397 int nid;
afb6ebb3 6398 int __maybe_unused cpu;
9adb62a5 6399 pg_data_t *self = data;
b93e0f32
MH
6400 static DEFINE_SPINLOCK(lock);
6401
6402 spin_lock(&lock);
9276b1bc 6403
7f9cfb31
BL
6404#ifdef CONFIG_NUMA
6405 memset(node_load, 0, sizeof(node_load));
6406#endif
9adb62a5 6407
c1152583
WY
6408 /*
6409 * This node is hotadded and no memory is yet present. So just
6410 * building zonelists is fine - no need to touch other nodes.
6411 */
9adb62a5
JL
6412 if (self && !node_online(self->node_id)) {
6413 build_zonelists(self);
c1152583 6414 } else {
09f49dca
MH
6415 /*
6416 * All possible nodes have pgdat preallocated
6417 * in free_area_init
6418 */
6419 for_each_node(nid) {
c1152583 6420 pg_data_t *pgdat = NODE_DATA(nid);
7ea1530a 6421
c1152583
WY
6422 build_zonelists(pgdat);
6423 }
99dcc3e5 6424
7aac7898
LS
6425#ifdef CONFIG_HAVE_MEMORYLESS_NODES
6426 /*
6427 * We now know the "local memory node" for each node--
6428 * i.e., the node of the first zone in the generic zonelist.
6429 * Set up numa_mem percpu variable for on-line cpus. During
6430 * boot, only the boot cpu should be on-line; we'll init the
6431 * secondary cpus' numa_mem as they come on-line. During
6432 * node/memory hotplug, we'll fixup all on-line cpus.
6433 */
d9c9a0b9 6434 for_each_online_cpu(cpu)
7aac7898 6435 set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
afb6ebb3 6436#endif
d9c9a0b9 6437 }
b93e0f32
MH
6438
6439 spin_unlock(&lock);
6811378e
YG
6440}
6441
061f67bc
RV
6442static noinline void __init
6443build_all_zonelists_init(void)
6444{
afb6ebb3
MH
6445 int cpu;
6446
061f67bc 6447 __build_all_zonelists(NULL);
afb6ebb3
MH
6448
6449 /*
6450 * Initialize the boot_pagesets that are going to be used
6451 * for bootstrapping processors. The real pagesets for
6452 * each zone will be allocated later when the per cpu
6453 * allocator is available.
6454 *
6455 * boot_pagesets are used also for bootstrapping offline
6456 * cpus if the system is already booted because the pagesets
6457 * are needed to initialize allocators on a specific cpu too.
6458 * F.e. the percpu allocator needs the page allocator which
6459 * needs the percpu allocator in order to allocate its pagesets
6460 * (a chicken-egg dilemma).
6461 */
6462 for_each_possible_cpu(cpu)
28f836b6 6463 per_cpu_pages_init(&per_cpu(boot_pageset, cpu), &per_cpu(boot_zonestats, cpu));
afb6ebb3 6464
061f67bc
RV
6465 mminit_verify_zonelist();
6466 cpuset_init_current_mems_allowed();
6467}
6468
4eaf3f64 6469/*
4eaf3f64 6470 * unless system_state == SYSTEM_BOOTING.
061f67bc 6471 *
72675e13 6472 * __ref due to call of __init annotated helper build_all_zonelists_init
061f67bc 6473 * [protected by SYSTEM_BOOTING].
4eaf3f64 6474 */
72675e13 6475void __ref build_all_zonelists(pg_data_t *pgdat)
6811378e 6476{
0a18e607
DH
6477 unsigned long vm_total_pages;
6478
6811378e 6479 if (system_state == SYSTEM_BOOTING) {
061f67bc 6480 build_all_zonelists_init();
6811378e 6481 } else {
11cd8638 6482 __build_all_zonelists(pgdat);
6811378e
YG
6483 /* cpuset refresh routine should be here */
6484 }
56b9413b
DH
6485 /* Get the number of free pages beyond high watermark in all zones. */
6486 vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
9ef9acb0
MG
6487 /*
6488 * Disable grouping by mobility if the number of pages in the
6489 * system is too low to allow the mechanism to work. It would be
6490 * more accurate, but expensive to check per-zone. This check is
6491 * made on memory-hotadd so a system can start with mobility
6492 * disabled and enable it later
6493 */
d9c23400 6494 if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
9ef9acb0
MG
6495 page_group_by_mobility_disabled = 1;
6496 else
6497 page_group_by_mobility_disabled = 0;
6498
ce0725f7 6499 pr_info("Built %u zonelists, mobility grouping %s. Total pages: %ld\n",
756a025f 6500 nr_online_nodes,
756a025f
JP
6501 page_group_by_mobility_disabled ? "off" : "on",
6502 vm_total_pages);
f0c0b2b8 6503#ifdef CONFIG_NUMA
f88dfff5 6504 pr_info("Policy zone: %s\n", zone_names[policy_zone]);
f0c0b2b8 6505#endif
1da177e4
LT
6506}
6507
a9a9e77f
PT
6508/* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
6509static bool __meminit
6510overlap_memmap_init(unsigned long zone, unsigned long *pfn)
6511{
a9a9e77f
PT
6512 static struct memblock_region *r;
6513
6514 if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
6515 if (!r || *pfn >= memblock_region_memory_end_pfn(r)) {
cc6de168 6516 for_each_mem_region(r) {
a9a9e77f
PT
6517 if (*pfn < memblock_region_memory_end_pfn(r))
6518 break;
6519 }
6520 }
6521 if (*pfn >= memblock_region_memory_base_pfn(r) &&
6522 memblock_is_mirror(r)) {
6523 *pfn = memblock_region_memory_end_pfn(r);
6524 return true;
6525 }
6526 }
a9a9e77f
PT
6527 return false;
6528}
6529
1da177e4
LT
6530/*
6531 * Initially all pages are reserved - free ones are freed
c6ffc5ca 6532 * up by memblock_free_all() once the early boot process is
1da177e4 6533 * done. Non-atomic initialization, single-pass.
d882c006
DH
6534 *
6535 * All aligned pageblocks are initialized to the specified migratetype
6536 * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
6537 * zone stats (e.g., nr_isolate_pageblock) are touched.
1da177e4 6538 */
ab28cb6e 6539void __meminit memmap_init_range(unsigned long size, int nid, unsigned long zone,
dc2da7b4 6540 unsigned long start_pfn, unsigned long zone_end_pfn,
d882c006
DH
6541 enum meminit_context context,
6542 struct vmem_altmap *altmap, int migratetype)
1da177e4 6543{
a9a9e77f 6544 unsigned long pfn, end_pfn = start_pfn + size;
d0dc12e8 6545 struct page *page;
1da177e4 6546
22b31eec
HD
6547 if (highest_memmap_pfn < end_pfn - 1)
6548 highest_memmap_pfn = end_pfn - 1;
6549
966cf44f 6550#ifdef CONFIG_ZONE_DEVICE
4b94ffdc
DW
6551 /*
6552 * Honor reservation requested by the driver for this ZONE_DEVICE
966cf44f
AD
6553 * memory. We limit the total number of pages to initialize to just
6554 * those that might contain the memory mapping. We will defer the
6555 * ZONE_DEVICE page initialization until after we have released
6556 * the hotplug lock.
4b94ffdc 6557 */
966cf44f
AD
6558 if (zone == ZONE_DEVICE) {
6559 if (!altmap)
6560 return;
6561
6562 if (start_pfn == altmap->base_pfn)
6563 start_pfn += altmap->reserve;
6564 end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
6565 }
6566#endif
4b94ffdc 6567
948c436e 6568 for (pfn = start_pfn; pfn < end_pfn; ) {
a2f3aa02 6569 /*
b72d0ffb
AM
6570 * There can be holes in boot-time mem_map[]s handed to this
6571 * function. They do not exist on hotplugged memory.
a2f3aa02 6572 */
c1d0da83 6573 if (context == MEMINIT_EARLY) {
a9a9e77f
PT
6574 if (overlap_memmap_init(zone, &pfn))
6575 continue;
dc2da7b4 6576 if (defer_init(nid, pfn, zone_end_pfn))
a9a9e77f 6577 break;
a2f3aa02 6578 }
ac5d2539 6579
d0dc12e8
PT
6580 page = pfn_to_page(pfn);
6581 __init_single_page(page, pfn, zone, nid);
c1d0da83 6582 if (context == MEMINIT_HOTPLUG)
d483da5b 6583 __SetPageReserved(page);
d0dc12e8 6584
ac5d2539 6585 /*
d882c006
DH
6586 * Usually, we want to mark the pageblock MIGRATE_MOVABLE,
6587 * such that unmovable allocations won't be scattered all
6588 * over the place during system boot.
ac5d2539 6589 */
4eb29bd9 6590 if (IS_ALIGNED(pfn, pageblock_nr_pages)) {
d882c006 6591 set_pageblock_migratetype(page, migratetype);
9b6e63cb 6592 cond_resched();
ac5d2539 6593 }
948c436e 6594 pfn++;
1da177e4
LT
6595 }
6596}
6597
966cf44f 6598#ifdef CONFIG_ZONE_DEVICE
46487e00
JM
6599static void __ref __init_zone_device_page(struct page *page, unsigned long pfn,
6600 unsigned long zone_idx, int nid,
6601 struct dev_pagemap *pgmap)
6602{
6603
6604 __init_single_page(page, pfn, zone_idx, nid);
6605
6606 /*
6607 * Mark page reserved as it will need to wait for onlining
6608 * phase for it to be fully associated with a zone.
6609 *
6610 * We can use the non-atomic __set_bit operation for setting
6611 * the flag as we are still initializing the pages.
6612 */
6613 __SetPageReserved(page);
6614
6615 /*
6616 * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer
6617 * and zone_device_data. It is a bug if a ZONE_DEVICE page is
6618 * ever freed or placed on a driver-private list.
6619 */
6620 page->pgmap = pgmap;
6621 page->zone_device_data = NULL;
6622
6623 /*
6624 * Mark the block movable so that blocks are reserved for
6625 * movable at startup. This will force kernel allocations
6626 * to reserve their blocks rather than leaking throughout
6627 * the address space during boot when many long-lived
6628 * kernel allocations are made.
6629 *
6630 * Please note that MEMINIT_HOTPLUG path doesn't clear memmap
6631 * because this is done early in section_activate()
6632 */
6633 if (IS_ALIGNED(pfn, pageblock_nr_pages)) {
6634 set_pageblock_migratetype(page, MIGRATE_MOVABLE);
6635 cond_resched();
6636 }
6637}
6638
6fd3620b
JM
6639/*
6640 * With compound page geometry and when struct pages are stored in ram most
6641 * tail pages are reused. Consequently, the amount of unique struct pages to
6642 * initialize is a lot smaller that the total amount of struct pages being
6643 * mapped. This is a paired / mild layering violation with explicit knowledge
6644 * of how the sparse_vmemmap internals handle compound pages in the lack
6645 * of an altmap. See vmemmap_populate_compound_pages().
6646 */
6647static inline unsigned long compound_nr_pages(struct vmem_altmap *altmap,
6648 unsigned long nr_pages)
6649{
6650 return is_power_of_2(sizeof(struct page)) &&
6651 !altmap ? 2 * (PAGE_SIZE / sizeof(struct page)) : nr_pages;
6652}
6653
c4386bd8
JM
6654static void __ref memmap_init_compound(struct page *head,
6655 unsigned long head_pfn,
6656 unsigned long zone_idx, int nid,
6657 struct dev_pagemap *pgmap,
6658 unsigned long nr_pages)
6659{
6660 unsigned long pfn, end_pfn = head_pfn + nr_pages;
6661 unsigned int order = pgmap->vmemmap_shift;
6662
6663 __SetPageHead(head);
6664 for (pfn = head_pfn + 1; pfn < end_pfn; pfn++) {
6665 struct page *page = pfn_to_page(pfn);
6666
6667 __init_zone_device_page(page, pfn, zone_idx, nid, pgmap);
6668 prep_compound_tail(head, pfn - head_pfn);
6669 set_page_count(page, 0);
6670
6671 /*
6672 * The first tail page stores compound_mapcount_ptr() and
6673 * compound_order() and the second tail page stores
6674 * compound_pincount_ptr(). Call prep_compound_head() after
6675 * the first and second tail pages have been initialized to
6676 * not have the data overwritten.
6677 */
6678 if (pfn == head_pfn + 2)
6679 prep_compound_head(head, order);
6680 }
6681}
6682
966cf44f
AD
6683void __ref memmap_init_zone_device(struct zone *zone,
6684 unsigned long start_pfn,
1f8d75c1 6685 unsigned long nr_pages,
966cf44f
AD
6686 struct dev_pagemap *pgmap)
6687{
1f8d75c1 6688 unsigned long pfn, end_pfn = start_pfn + nr_pages;
966cf44f 6689 struct pglist_data *pgdat = zone->zone_pgdat;
514caf23 6690 struct vmem_altmap *altmap = pgmap_altmap(pgmap);
c4386bd8 6691 unsigned int pfns_per_compound = pgmap_vmemmap_nr(pgmap);
966cf44f
AD
6692 unsigned long zone_idx = zone_idx(zone);
6693 unsigned long start = jiffies;
6694 int nid = pgdat->node_id;
6695
46d945ae 6696 if (WARN_ON_ONCE(!pgmap || zone_idx(zone) != ZONE_DEVICE))
966cf44f
AD
6697 return;
6698
6699 /*
122e093c 6700 * The call to memmap_init should have already taken care
966cf44f
AD
6701 * of the pages reserved for the memmap, so we can just jump to
6702 * the end of that region and start processing the device pages.
6703 */
514caf23 6704 if (altmap) {
966cf44f 6705 start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
1f8d75c1 6706 nr_pages = end_pfn - start_pfn;
966cf44f
AD
6707 }
6708
c4386bd8 6709 for (pfn = start_pfn; pfn < end_pfn; pfn += pfns_per_compound) {
966cf44f
AD
6710 struct page *page = pfn_to_page(pfn);
6711
46487e00 6712 __init_zone_device_page(page, pfn, zone_idx, nid, pgmap);
c4386bd8
JM
6713
6714 if (pfns_per_compound == 1)
6715 continue;
6716
6717 memmap_init_compound(page, pfn, zone_idx, nid, pgmap,
6fd3620b 6718 compound_nr_pages(altmap, pfns_per_compound));
966cf44f
AD
6719 }
6720
fdc029b1 6721 pr_info("%s initialised %lu pages in %ums\n", __func__,
1f8d75c1 6722 nr_pages, jiffies_to_msecs(jiffies - start));
966cf44f
AD
6723}
6724
6725#endif
1e548deb 6726static void __meminit zone_init_free_lists(struct zone *zone)
1da177e4 6727{
7aeb09f9 6728 unsigned int order, t;
b2a0ac88
MG
6729 for_each_migratetype_order(order, t) {
6730 INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
1da177e4
LT
6731 zone->free_area[order].nr_free = 0;
6732 }
6733}
6734
0740a50b
MR
6735/*
6736 * Only struct pages that correspond to ranges defined by memblock.memory
6737 * are zeroed and initialized by going through __init_single_page() during
122e093c 6738 * memmap_init_zone_range().
0740a50b
MR
6739 *
6740 * But, there could be struct pages that correspond to holes in
6741 * memblock.memory. This can happen because of the following reasons:
6742 * - physical memory bank size is not necessarily the exact multiple of the
6743 * arbitrary section size
6744 * - early reserved memory may not be listed in memblock.memory
6745 * - memory layouts defined with memmap= kernel parameter may not align
6746 * nicely with memmap sections
6747 *
6748 * Explicitly initialize those struct pages so that:
6749 * - PG_Reserved is set
6750 * - zone and node links point to zone and node that span the page if the
6751 * hole is in the middle of a zone
6752 * - zone and node links point to adjacent zone/node if the hole falls on
6753 * the zone boundary; the pages in such holes will be prepended to the
6754 * zone/node above the hole except for the trailing pages in the last
6755 * section that will be appended to the zone/node below.
6756 */
122e093c
MR
6757static void __init init_unavailable_range(unsigned long spfn,
6758 unsigned long epfn,
6759 int zone, int node)
0740a50b
MR
6760{
6761 unsigned long pfn;
6762 u64 pgcnt = 0;
6763
6764 for (pfn = spfn; pfn < epfn; pfn++) {
6765 if (!pfn_valid(ALIGN_DOWN(pfn, pageblock_nr_pages))) {
6766 pfn = ALIGN_DOWN(pfn, pageblock_nr_pages)
6767 + pageblock_nr_pages - 1;
6768 continue;
6769 }
6770 __init_single_page(pfn_to_page(pfn), pfn, zone, node);
6771 __SetPageReserved(pfn_to_page(pfn));
6772 pgcnt++;
6773 }
6774
122e093c
MR
6775 if (pgcnt)
6776 pr_info("On node %d, zone %s: %lld pages in unavailable ranges",
6777 node, zone_names[zone], pgcnt);
0740a50b 6778}
0740a50b 6779
122e093c
MR
6780static void __init memmap_init_zone_range(struct zone *zone,
6781 unsigned long start_pfn,
6782 unsigned long end_pfn,
6783 unsigned long *hole_pfn)
dfb3ccd0 6784{
3256ff83
BH
6785 unsigned long zone_start_pfn = zone->zone_start_pfn;
6786 unsigned long zone_end_pfn = zone_start_pfn + zone->spanned_pages;
122e093c
MR
6787 int nid = zone_to_nid(zone), zone_id = zone_idx(zone);
6788
6789 start_pfn = clamp(start_pfn, zone_start_pfn, zone_end_pfn);
6790 end_pfn = clamp(end_pfn, zone_start_pfn, zone_end_pfn);
6791
6792 if (start_pfn >= end_pfn)
6793 return;
6794
6795 memmap_init_range(end_pfn - start_pfn, nid, zone_id, start_pfn,
6796 zone_end_pfn, MEMINIT_EARLY, NULL, MIGRATE_MOVABLE);
6797
6798 if (*hole_pfn < start_pfn)
6799 init_unavailable_range(*hole_pfn, start_pfn, zone_id, nid);
6800
6801 *hole_pfn = end_pfn;
6802}
6803
6804static void __init memmap_init(void)
6805{
73a6e474 6806 unsigned long start_pfn, end_pfn;
122e093c 6807 unsigned long hole_pfn = 0;
b346075f 6808 int i, j, zone_id = 0, nid;
73a6e474 6809
122e093c
MR
6810 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
6811 struct pglist_data *node = NODE_DATA(nid);
73a6e474 6812
122e093c
MR
6813 for (j = 0; j < MAX_NR_ZONES; j++) {
6814 struct zone *zone = node->node_zones + j;
0740a50b 6815
122e093c
MR
6816 if (!populated_zone(zone))
6817 continue;
0740a50b 6818
122e093c
MR
6819 memmap_init_zone_range(zone, start_pfn, end_pfn,
6820 &hole_pfn);
6821 zone_id = j;
6822 }
73a6e474 6823 }
0740a50b
MR
6824
6825#ifdef CONFIG_SPARSEMEM
6826 /*
122e093c
MR
6827 * Initialize the memory map for hole in the range [memory_end,
6828 * section_end].
6829 * Append the pages in this hole to the highest zone in the last
6830 * node.
6831 * The call to init_unavailable_range() is outside the ifdef to
6832 * silence the compiler warining about zone_id set but not used;
6833 * for FLATMEM it is a nop anyway
0740a50b 6834 */
122e093c 6835 end_pfn = round_up(end_pfn, PAGES_PER_SECTION);
0740a50b 6836 if (hole_pfn < end_pfn)
0740a50b 6837#endif
122e093c 6838 init_unavailable_range(hole_pfn, end_pfn, zone_id, nid);
dfb3ccd0 6839}
1da177e4 6840
c803b3c8
MR
6841void __init *memmap_alloc(phys_addr_t size, phys_addr_t align,
6842 phys_addr_t min_addr, int nid, bool exact_nid)
6843{
6844 void *ptr;
6845
6846 if (exact_nid)
6847 ptr = memblock_alloc_exact_nid_raw(size, align, min_addr,
6848 MEMBLOCK_ALLOC_ACCESSIBLE,
6849 nid);
6850 else
6851 ptr = memblock_alloc_try_nid_raw(size, align, min_addr,
6852 MEMBLOCK_ALLOC_ACCESSIBLE,
6853 nid);
6854
6855 if (ptr && size > 0)
6856 page_init_poison(ptr, size);
6857
6858 return ptr;
6859}
6860
7cd2b0a3 6861static int zone_batchsize(struct zone *zone)
e7c8d5c9 6862{
3a6be87f 6863#ifdef CONFIG_MMU
e7c8d5c9
CL
6864 int batch;
6865
6866 /*
b92ca18e
MG
6867 * The number of pages to batch allocate is either ~0.1%
6868 * of the zone or 1MB, whichever is smaller. The batch
6869 * size is striking a balance between allocation latency
6870 * and zone lock contention.
e7c8d5c9 6871 */
b92ca18e 6872 batch = min(zone_managed_pages(zone) >> 10, (1024 * 1024) / PAGE_SIZE);
e7c8d5c9
CL
6873 batch /= 4; /* We effectively *= 4 below */
6874 if (batch < 1)
6875 batch = 1;
6876
6877 /*
0ceaacc9
NP
6878 * Clamp the batch to a 2^n - 1 value. Having a power
6879 * of 2 value was found to be more likely to have
6880 * suboptimal cache aliasing properties in some cases.
e7c8d5c9 6881 *
0ceaacc9
NP
6882 * For example if 2 tasks are alternately allocating
6883 * batches of pages, one task can end up with a lot
6884 * of pages of one half of the possible page colors
6885 * and the other with pages of the other colors.
e7c8d5c9 6886 */
9155203a 6887 batch = rounddown_pow_of_two(batch + batch/2) - 1;
ba56e91c 6888
e7c8d5c9 6889 return batch;
3a6be87f
DH
6890
6891#else
6892 /* The deferral and batching of frees should be suppressed under NOMMU
6893 * conditions.
6894 *
6895 * The problem is that NOMMU needs to be able to allocate large chunks
6896 * of contiguous memory as there's no hardware page translation to
6897 * assemble apparent contiguous memory from discontiguous pages.
6898 *
6899 * Queueing large contiguous runs of pages for batching, however,
6900 * causes the pages to actually be freed in smaller chunks. As there
6901 * can be a significant delay between the individual batches being
6902 * recycled, this leads to the once large chunks of space being
6903 * fragmented and becoming unavailable for high-order allocations.
6904 */
6905 return 0;
6906#endif
e7c8d5c9
CL
6907}
6908
04f8cfea 6909static int zone_highsize(struct zone *zone, int batch, int cpu_online)
b92ca18e
MG
6910{
6911#ifdef CONFIG_MMU
6912 int high;
203c06ee 6913 int nr_split_cpus;
74f44822
MG
6914 unsigned long total_pages;
6915
6916 if (!percpu_pagelist_high_fraction) {
6917 /*
6918 * By default, the high value of the pcp is based on the zone
6919 * low watermark so that if they are full then background
6920 * reclaim will not be started prematurely.
6921 */
6922 total_pages = low_wmark_pages(zone);
6923 } else {
6924 /*
6925 * If percpu_pagelist_high_fraction is configured, the high
6926 * value is based on a fraction of the managed pages in the
6927 * zone.
6928 */
6929 total_pages = zone_managed_pages(zone) / percpu_pagelist_high_fraction;
6930 }
b92ca18e
MG
6931
6932 /*
74f44822
MG
6933 * Split the high value across all online CPUs local to the zone. Note
6934 * that early in boot that CPUs may not be online yet and that during
6935 * CPU hotplug that the cpumask is not yet updated when a CPU is being
203c06ee
MG
6936 * onlined. For memory nodes that have no CPUs, split pcp->high across
6937 * all online CPUs to mitigate the risk that reclaim is triggered
6938 * prematurely due to pages stored on pcp lists.
b92ca18e 6939 */
203c06ee
MG
6940 nr_split_cpus = cpumask_weight(cpumask_of_node(zone_to_nid(zone))) + cpu_online;
6941 if (!nr_split_cpus)
6942 nr_split_cpus = num_online_cpus();
6943 high = total_pages / nr_split_cpus;
b92ca18e
MG
6944
6945 /*
6946 * Ensure high is at least batch*4. The multiple is based on the
6947 * historical relationship between high and batch.
6948 */
6949 high = max(high, batch << 2);
6950
6951 return high;
6952#else
6953 return 0;
6954#endif
6955}
6956
8d7a8fa9 6957/*
5c3ad2eb
VB
6958 * pcp->high and pcp->batch values are related and generally batch is lower
6959 * than high. They are also related to pcp->count such that count is lower
6960 * than high, and as soon as it reaches high, the pcplist is flushed.
8d7a8fa9 6961 *
5c3ad2eb
VB
6962 * However, guaranteeing these relations at all times would require e.g. write
6963 * barriers here but also careful usage of read barriers at the read side, and
6964 * thus be prone to error and bad for performance. Thus the update only prevents
6965 * store tearing. Any new users of pcp->batch and pcp->high should ensure they
6966 * can cope with those fields changing asynchronously, and fully trust only the
6967 * pcp->count field on the local CPU with interrupts disabled.
8d7a8fa9
CS
6968 *
6969 * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
6970 * outside of boot time (or some other assurance that no concurrent updaters
6971 * exist).
6972 */
6973static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
6974 unsigned long batch)
6975{
5c3ad2eb
VB
6976 WRITE_ONCE(pcp->batch, batch);
6977 WRITE_ONCE(pcp->high, high);
8d7a8fa9
CS
6978}
6979
28f836b6 6980static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats)
2caaad41 6981{
44042b44 6982 int pindex;
2caaad41 6983
28f836b6
MG
6984 memset(pcp, 0, sizeof(*pcp));
6985 memset(pzstats, 0, sizeof(*pzstats));
1c6fe946 6986
44042b44
MG
6987 for (pindex = 0; pindex < NR_PCP_LISTS; pindex++)
6988 INIT_LIST_HEAD(&pcp->lists[pindex]);
2caaad41 6989
69a8396a
VB
6990 /*
6991 * Set batch and high values safe for a boot pageset. A true percpu
6992 * pageset's initialization will update them subsequently. Here we don't
6993 * need to be as careful as pageset_update() as nobody can access the
6994 * pageset yet.
6995 */
952eaf81
VB
6996 pcp->high = BOOT_PAGESET_HIGH;
6997 pcp->batch = BOOT_PAGESET_BATCH;
3b12e7e9 6998 pcp->free_factor = 0;
88c90dbc
CS
6999}
7000
3b1f3658 7001static void __zone_set_pageset_high_and_batch(struct zone *zone, unsigned long high,
ec6e8c7e
VB
7002 unsigned long batch)
7003{
28f836b6 7004 struct per_cpu_pages *pcp;
ec6e8c7e
VB
7005 int cpu;
7006
7007 for_each_possible_cpu(cpu) {
28f836b6
MG
7008 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
7009 pageset_update(pcp, high, batch);
ec6e8c7e
VB
7010 }
7011}
7012
8ad4b1fb 7013/*
0a8b4f1d 7014 * Calculate and set new high and batch values for all per-cpu pagesets of a
bbbecb35 7015 * zone based on the zone's size.
8ad4b1fb 7016 */
04f8cfea 7017static void zone_set_pageset_high_and_batch(struct zone *zone, int cpu_online)
56cef2b8 7018{
b92ca18e 7019 int new_high, new_batch;
7115ac6e 7020
b92ca18e 7021 new_batch = max(1, zone_batchsize(zone));
04f8cfea 7022 new_high = zone_highsize(zone, new_batch, cpu_online);
169f6c19 7023
952eaf81
VB
7024 if (zone->pageset_high == new_high &&
7025 zone->pageset_batch == new_batch)
7026 return;
7027
7028 zone->pageset_high = new_high;
7029 zone->pageset_batch = new_batch;
7030
ec6e8c7e 7031 __zone_set_pageset_high_and_batch(zone, new_high, new_batch);
169f6c19
CS
7032}
7033
72675e13 7034void __meminit setup_zone_pageset(struct zone *zone)
319774e2
WF
7035{
7036 int cpu;
0a8b4f1d 7037
28f836b6
MG
7038 /* Size may be 0 on !SMP && !NUMA */
7039 if (sizeof(struct per_cpu_zonestat) > 0)
7040 zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat);
7041
7042 zone->per_cpu_pageset = alloc_percpu(struct per_cpu_pages);
0a8b4f1d 7043 for_each_possible_cpu(cpu) {
28f836b6
MG
7044 struct per_cpu_pages *pcp;
7045 struct per_cpu_zonestat *pzstats;
7046
7047 pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
7048 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
7049 per_cpu_pages_init(pcp, pzstats);
0a8b4f1d
VB
7050 }
7051
04f8cfea 7052 zone_set_pageset_high_and_batch(zone, 0);
319774e2
WF
7053}
7054
2caaad41 7055/*
99dcc3e5
CL
7056 * Allocate per cpu pagesets and initialize them.
7057 * Before this call only boot pagesets were available.
e7c8d5c9 7058 */
99dcc3e5 7059void __init setup_per_cpu_pageset(void)
e7c8d5c9 7060{
b4911ea2 7061 struct pglist_data *pgdat;
99dcc3e5 7062 struct zone *zone;
b418a0f9 7063 int __maybe_unused cpu;
e7c8d5c9 7064
319774e2
WF
7065 for_each_populated_zone(zone)
7066 setup_zone_pageset(zone);
b4911ea2 7067
b418a0f9
SD
7068#ifdef CONFIG_NUMA
7069 /*
7070 * Unpopulated zones continue using the boot pagesets.
7071 * The numa stats for these pagesets need to be reset.
7072 * Otherwise, they will end up skewing the stats of
7073 * the nodes these zones are associated with.
7074 */
7075 for_each_possible_cpu(cpu) {
28f836b6 7076 struct per_cpu_zonestat *pzstats = &per_cpu(boot_zonestats, cpu);
f19298b9
MG
7077 memset(pzstats->vm_numa_event, 0,
7078 sizeof(pzstats->vm_numa_event));
b418a0f9
SD
7079 }
7080#endif
7081
b4911ea2
MG
7082 for_each_online_pgdat(pgdat)
7083 pgdat->per_cpu_nodestats =
7084 alloc_percpu(struct per_cpu_nodestat);
e7c8d5c9
CL
7085}
7086
c09b4240 7087static __meminit void zone_pcp_init(struct zone *zone)
ed8ece2e 7088{
99dcc3e5
CL
7089 /*
7090 * per cpu subsystem is not up at this point. The following code
7091 * relies on the ability of the linker to provide the
7092 * offset of a (static) per cpu variable into the per cpu area.
7093 */
28f836b6
MG
7094 zone->per_cpu_pageset = &boot_pageset;
7095 zone->per_cpu_zonestats = &boot_zonestats;
952eaf81
VB
7096 zone->pageset_high = BOOT_PAGESET_HIGH;
7097 zone->pageset_batch = BOOT_PAGESET_BATCH;
ed8ece2e 7098
b38a8725 7099 if (populated_zone(zone))
9660ecaa
HK
7100 pr_debug(" %s zone: %lu pages, LIFO batch:%u\n", zone->name,
7101 zone->present_pages, zone_batchsize(zone));
ed8ece2e
DH
7102}
7103
dc0bbf3b 7104void __meminit init_currently_empty_zone(struct zone *zone,
718127cc 7105 unsigned long zone_start_pfn,
b171e409 7106 unsigned long size)
ed8ece2e
DH
7107{
7108 struct pglist_data *pgdat = zone->zone_pgdat;
8f416836 7109 int zone_idx = zone_idx(zone) + 1;
9dcb8b68 7110
8f416836
WY
7111 if (zone_idx > pgdat->nr_zones)
7112 pgdat->nr_zones = zone_idx;
ed8ece2e 7113
ed8ece2e
DH
7114 zone->zone_start_pfn = zone_start_pfn;
7115
708614e6
MG
7116 mminit_dprintk(MMINIT_TRACE, "memmap_init",
7117 "Initialising map node %d zone %lu pfns %lu -> %lu\n",
7118 pgdat->node_id,
7119 (unsigned long)zone_idx(zone),
7120 zone_start_pfn, (zone_start_pfn + size));
7121
1e548deb 7122 zone_init_free_lists(zone);
9dcb8b68 7123 zone->initialized = 1;
ed8ece2e
DH
7124}
7125
c713216d
MG
7126/**
7127 * get_pfn_range_for_nid - Return the start and end page frames for a node
88ca3b94
RD
7128 * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
7129 * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
7130 * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
c713216d
MG
7131 *
7132 * It returns the start and end page frame of a node based on information
7d018176 7133 * provided by memblock_set_node(). If called for a node
c713216d 7134 * with no available memory, a warning is printed and the start and end
88ca3b94 7135 * PFNs will be 0.
c713216d 7136 */
bbe5d993 7137void __init get_pfn_range_for_nid(unsigned int nid,
c713216d
MG
7138 unsigned long *start_pfn, unsigned long *end_pfn)
7139{
c13291a5 7140 unsigned long this_start_pfn, this_end_pfn;
c713216d 7141 int i;
c13291a5 7142
c713216d
MG
7143 *start_pfn = -1UL;
7144 *end_pfn = 0;
7145
c13291a5
TH
7146 for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
7147 *start_pfn = min(*start_pfn, this_start_pfn);
7148 *end_pfn = max(*end_pfn, this_end_pfn);
c713216d
MG
7149 }
7150
633c0666 7151 if (*start_pfn == -1UL)
c713216d 7152 *start_pfn = 0;
c713216d
MG
7153}
7154
2a1e274a
MG
7155/*
7156 * This finds a zone that can be used for ZONE_MOVABLE pages. The
7157 * assumption is made that zones within a node are ordered in monotonic
7158 * increasing memory addresses so that the "highest" populated zone is used
7159 */
b69a7288 7160static void __init find_usable_zone_for_movable(void)
2a1e274a
MG
7161{
7162 int zone_index;
7163 for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
7164 if (zone_index == ZONE_MOVABLE)
7165 continue;
7166
7167 if (arch_zone_highest_possible_pfn[zone_index] >
7168 arch_zone_lowest_possible_pfn[zone_index])
7169 break;
7170 }
7171
7172 VM_BUG_ON(zone_index == -1);
7173 movable_zone = zone_index;
7174}
7175
7176/*
7177 * The zone ranges provided by the architecture do not include ZONE_MOVABLE
25985edc 7178 * because it is sized independent of architecture. Unlike the other zones,
2a1e274a
MG
7179 * the starting point for ZONE_MOVABLE is not fixed. It may be different
7180 * in each node depending on the size of each node and how evenly kernelcore
7181 * is distributed. This helper function adjusts the zone ranges
7182 * provided by the architecture for a given node by using the end of the
7183 * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
7184 * zones within a node are in order of monotonic increases memory addresses
7185 */
bbe5d993 7186static void __init adjust_zone_range_for_zone_movable(int nid,
2a1e274a
MG
7187 unsigned long zone_type,
7188 unsigned long node_start_pfn,
7189 unsigned long node_end_pfn,
7190 unsigned long *zone_start_pfn,
7191 unsigned long *zone_end_pfn)
7192{
7193 /* Only adjust if ZONE_MOVABLE is on this node */
7194 if (zone_movable_pfn[nid]) {
7195 /* Size ZONE_MOVABLE */
7196 if (zone_type == ZONE_MOVABLE) {
7197 *zone_start_pfn = zone_movable_pfn[nid];
7198 *zone_end_pfn = min(node_end_pfn,
7199 arch_zone_highest_possible_pfn[movable_zone]);
7200
e506b996
XQ
7201 /* Adjust for ZONE_MOVABLE starting within this range */
7202 } else if (!mirrored_kernelcore &&
7203 *zone_start_pfn < zone_movable_pfn[nid] &&
7204 *zone_end_pfn > zone_movable_pfn[nid]) {
7205 *zone_end_pfn = zone_movable_pfn[nid];
7206
2a1e274a
MG
7207 /* Check if this whole range is within ZONE_MOVABLE */
7208 } else if (*zone_start_pfn >= zone_movable_pfn[nid])
7209 *zone_start_pfn = *zone_end_pfn;
7210 }
7211}
7212
c713216d
MG
7213/*
7214 * Return the number of pages a zone spans in a node, including holes
7215 * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
7216 */
bbe5d993 7217static unsigned long __init zone_spanned_pages_in_node(int nid,
c713216d 7218 unsigned long zone_type,
7960aedd
ZY
7219 unsigned long node_start_pfn,
7220 unsigned long node_end_pfn,
d91749c1 7221 unsigned long *zone_start_pfn,
854e8848 7222 unsigned long *zone_end_pfn)
c713216d 7223{
299c83dc
LF
7224 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
7225 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
b5685e92 7226 /* When hotadd a new node from cpu_up(), the node should be empty */
f9126ab9
XQ
7227 if (!node_start_pfn && !node_end_pfn)
7228 return 0;
7229
7960aedd 7230 /* Get the start and end of the zone */
299c83dc
LF
7231 *zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
7232 *zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
2a1e274a
MG
7233 adjust_zone_range_for_zone_movable(nid, zone_type,
7234 node_start_pfn, node_end_pfn,
d91749c1 7235 zone_start_pfn, zone_end_pfn);
c713216d
MG
7236
7237 /* Check that this node has pages within the zone's required range */
d91749c1 7238 if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
c713216d
MG
7239 return 0;
7240
7241 /* Move the zone boundaries inside the node if necessary */
d91749c1
TI
7242 *zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
7243 *zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
c713216d
MG
7244
7245 /* Return the spanned pages */
d91749c1 7246 return *zone_end_pfn - *zone_start_pfn;
c713216d
MG
7247}
7248
7249/*
7250 * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
88ca3b94 7251 * then all holes in the requested range will be accounted for.
c713216d 7252 */
bbe5d993 7253unsigned long __init __absent_pages_in_range(int nid,
c713216d
MG
7254 unsigned long range_start_pfn,
7255 unsigned long range_end_pfn)
7256{
96e907d1
TH
7257 unsigned long nr_absent = range_end_pfn - range_start_pfn;
7258 unsigned long start_pfn, end_pfn;
7259 int i;
c713216d 7260
96e907d1
TH
7261 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
7262 start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
7263 end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
7264 nr_absent -= end_pfn - start_pfn;
c713216d 7265 }
96e907d1 7266 return nr_absent;
c713216d
MG
7267}
7268
7269/**
7270 * absent_pages_in_range - Return number of page frames in holes within a range
7271 * @start_pfn: The start PFN to start searching for holes
7272 * @end_pfn: The end PFN to stop searching for holes
7273 *
a862f68a 7274 * Return: the number of pages frames in memory holes within a range.
c713216d
MG
7275 */
7276unsigned long __init absent_pages_in_range(unsigned long start_pfn,
7277 unsigned long end_pfn)
7278{
7279 return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
7280}
7281
7282/* Return the number of page frames in holes in a zone on a node */
bbe5d993 7283static unsigned long __init zone_absent_pages_in_node(int nid,
c713216d 7284 unsigned long zone_type,
7960aedd 7285 unsigned long node_start_pfn,
854e8848 7286 unsigned long node_end_pfn)
c713216d 7287{
96e907d1
TH
7288 unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
7289 unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
9c7cd687 7290 unsigned long zone_start_pfn, zone_end_pfn;
342332e6 7291 unsigned long nr_absent;
9c7cd687 7292
b5685e92 7293 /* When hotadd a new node from cpu_up(), the node should be empty */
f9126ab9
XQ
7294 if (!node_start_pfn && !node_end_pfn)
7295 return 0;
7296
96e907d1
TH
7297 zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
7298 zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
9c7cd687 7299
2a1e274a
MG
7300 adjust_zone_range_for_zone_movable(nid, zone_type,
7301 node_start_pfn, node_end_pfn,
7302 &zone_start_pfn, &zone_end_pfn);
342332e6
TI
7303 nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
7304
7305 /*
7306 * ZONE_MOVABLE handling.
7307 * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
7308 * and vice versa.
7309 */
e506b996
XQ
7310 if (mirrored_kernelcore && zone_movable_pfn[nid]) {
7311 unsigned long start_pfn, end_pfn;
7312 struct memblock_region *r;
7313
cc6de168 7314 for_each_mem_region(r) {
e506b996
XQ
7315 start_pfn = clamp(memblock_region_memory_base_pfn(r),
7316 zone_start_pfn, zone_end_pfn);
7317 end_pfn = clamp(memblock_region_memory_end_pfn(r),
7318 zone_start_pfn, zone_end_pfn);
7319
7320 if (zone_type == ZONE_MOVABLE &&
7321 memblock_is_mirror(r))
7322 nr_absent += end_pfn - start_pfn;
7323
7324 if (zone_type == ZONE_NORMAL &&
7325 !memblock_is_mirror(r))
7326 nr_absent += end_pfn - start_pfn;
342332e6
TI
7327 }
7328 }
7329
7330 return nr_absent;
c713216d 7331}
0e0b864e 7332
bbe5d993 7333static void __init calculate_node_totalpages(struct pglist_data *pgdat,
7960aedd 7334 unsigned long node_start_pfn,
854e8848 7335 unsigned long node_end_pfn)
c713216d 7336{
febd5949 7337 unsigned long realtotalpages = 0, totalpages = 0;
c713216d
MG
7338 enum zone_type i;
7339
febd5949
GZ
7340 for (i = 0; i < MAX_NR_ZONES; i++) {
7341 struct zone *zone = pgdat->node_zones + i;
d91749c1 7342 unsigned long zone_start_pfn, zone_end_pfn;
3f08a302 7343 unsigned long spanned, absent;
febd5949 7344 unsigned long size, real_size;
c713216d 7345
854e8848
MR
7346 spanned = zone_spanned_pages_in_node(pgdat->node_id, i,
7347 node_start_pfn,
7348 node_end_pfn,
7349 &zone_start_pfn,
7350 &zone_end_pfn);
7351 absent = zone_absent_pages_in_node(pgdat->node_id, i,
7352 node_start_pfn,
7353 node_end_pfn);
3f08a302
MR
7354
7355 size = spanned;
7356 real_size = size - absent;
7357
d91749c1
TI
7358 if (size)
7359 zone->zone_start_pfn = zone_start_pfn;
7360 else
7361 zone->zone_start_pfn = 0;
febd5949
GZ
7362 zone->spanned_pages = size;
7363 zone->present_pages = real_size;
4b097002
DH
7364#if defined(CONFIG_MEMORY_HOTPLUG)
7365 zone->present_early_pages = real_size;
7366#endif
febd5949
GZ
7367
7368 totalpages += size;
7369 realtotalpages += real_size;
7370 }
7371
7372 pgdat->node_spanned_pages = totalpages;
c713216d 7373 pgdat->node_present_pages = realtotalpages;
9660ecaa 7374 pr_debug("On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
c713216d
MG
7375}
7376
835c134e
MG
7377#ifndef CONFIG_SPARSEMEM
7378/*
7379 * Calculate the size of the zone->blockflags rounded to an unsigned long
d9c23400
MG
7380 * Start by making sure zonesize is a multiple of pageblock_order by rounding
7381 * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
835c134e
MG
7382 * round what is now in bits to nearest long in bits, then return it in
7383 * bytes.
7384 */
7c45512d 7385static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
835c134e
MG
7386{
7387 unsigned long usemapsize;
7388
7c45512d 7389 zonesize += zone_start_pfn & (pageblock_nr_pages-1);
d9c23400
MG
7390 usemapsize = roundup(zonesize, pageblock_nr_pages);
7391 usemapsize = usemapsize >> pageblock_order;
835c134e
MG
7392 usemapsize *= NR_PAGEBLOCK_BITS;
7393 usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
7394
7395 return usemapsize / 8;
7396}
7397
7010a6ec 7398static void __ref setup_usemap(struct zone *zone)
835c134e 7399{
7010a6ec
BH
7400 unsigned long usemapsize = usemap_size(zone->zone_start_pfn,
7401 zone->spanned_pages);
835c134e 7402 zone->pageblock_flags = NULL;
23a7052a 7403 if (usemapsize) {
6782832e 7404 zone->pageblock_flags =
26fb3dae 7405 memblock_alloc_node(usemapsize, SMP_CACHE_BYTES,
7010a6ec 7406 zone_to_nid(zone));
23a7052a
MR
7407 if (!zone->pageblock_flags)
7408 panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n",
7010a6ec 7409 usemapsize, zone->name, zone_to_nid(zone));
23a7052a 7410 }
835c134e
MG
7411}
7412#else
7010a6ec 7413static inline void setup_usemap(struct zone *zone) {}
835c134e
MG
7414#endif /* CONFIG_SPARSEMEM */
7415
d9c23400 7416#ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
ba72cb8c 7417
d9c23400 7418/* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
03e85f9d 7419void __init set_pageblock_order(void)
d9c23400 7420{
b3d40a2b 7421 unsigned int order = MAX_ORDER - 1;
955c1cd7 7422
d9c23400
MG
7423 /* Check that pageblock_nr_pages has not already been setup */
7424 if (pageblock_order)
7425 return;
7426
b3d40a2b
DH
7427 /* Don't let pageblocks exceed the maximum allocation granularity. */
7428 if (HPAGE_SHIFT > PAGE_SHIFT && HUGETLB_PAGE_ORDER < order)
955c1cd7 7429 order = HUGETLB_PAGE_ORDER;
955c1cd7 7430
d9c23400
MG
7431 /*
7432 * Assume the largest contiguous order of interest is a huge page.
955c1cd7
AM
7433 * This value may be variable depending on boot parameters on IA64 and
7434 * powerpc.
d9c23400
MG
7435 */
7436 pageblock_order = order;
7437}
7438#else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
7439
ba72cb8c
MG
7440/*
7441 * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
955c1cd7
AM
7442 * is unused as pageblock_order is set at compile-time. See
7443 * include/linux/pageblock-flags.h for the values of pageblock_order based on
7444 * the kernel config
ba72cb8c 7445 */
03e85f9d 7446void __init set_pageblock_order(void)
ba72cb8c 7447{
ba72cb8c 7448}
d9c23400
MG
7449
7450#endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
7451
03e85f9d 7452static unsigned long __init calc_memmap_size(unsigned long spanned_pages,
7cc2a959 7453 unsigned long present_pages)
01cefaef
JL
7454{
7455 unsigned long pages = spanned_pages;
7456
7457 /*
7458 * Provide a more accurate estimation if there are holes within
7459 * the zone and SPARSEMEM is in use. If there are holes within the
7460 * zone, each populated memory region may cost us one or two extra
7461 * memmap pages due to alignment because memmap pages for each
89d790ab 7462 * populated regions may not be naturally aligned on page boundary.
01cefaef
JL
7463 * So the (present_pages >> 4) heuristic is a tradeoff for that.
7464 */
7465 if (spanned_pages > present_pages + (present_pages >> 4) &&
7466 IS_ENABLED(CONFIG_SPARSEMEM))
7467 pages = present_pages;
7468
7469 return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
7470}
7471
ace1db39
OS
7472#ifdef CONFIG_TRANSPARENT_HUGEPAGE
7473static void pgdat_init_split_queue(struct pglist_data *pgdat)
7474{
364c1eeb
YS
7475 struct deferred_split *ds_queue = &pgdat->deferred_split_queue;
7476
7477 spin_lock_init(&ds_queue->split_queue_lock);
7478 INIT_LIST_HEAD(&ds_queue->split_queue);
7479 ds_queue->split_queue_len = 0;
ace1db39
OS
7480}
7481#else
7482static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
7483#endif
7484
7485#ifdef CONFIG_COMPACTION
7486static void pgdat_init_kcompactd(struct pglist_data *pgdat)
7487{
7488 init_waitqueue_head(&pgdat->kcompactd_wait);
7489}
7490#else
7491static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
7492#endif
7493
03e85f9d 7494static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
1da177e4 7495{
8cd7c588
MG
7496 int i;
7497
208d54e5 7498 pgdat_resize_init(pgdat);
ace1db39 7499
ace1db39
OS
7500 pgdat_init_split_queue(pgdat);
7501 pgdat_init_kcompactd(pgdat);
7502
1da177e4 7503 init_waitqueue_head(&pgdat->kswapd_wait);
5515061d 7504 init_waitqueue_head(&pgdat->pfmemalloc_wait);
ace1db39 7505
8cd7c588
MG
7506 for (i = 0; i < NR_VMSCAN_THROTTLE; i++)
7507 init_waitqueue_head(&pgdat->reclaim_wait[i]);
7508
eefa864b 7509 pgdat_page_ext_init(pgdat);
867e5e1d 7510 lruvec_init(&pgdat->__lruvec);
03e85f9d
OS
7511}
7512
7513static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
7514 unsigned long remaining_pages)
7515{
9705bea5 7516 atomic_long_set(&zone->managed_pages, remaining_pages);
03e85f9d
OS
7517 zone_set_nid(zone, nid);
7518 zone->name = zone_names[idx];
7519 zone->zone_pgdat = NODE_DATA(nid);
7520 spin_lock_init(&zone->lock);
7521 zone_seqlock_init(zone);
7522 zone_pcp_init(zone);
7523}
7524
7525/*
7526 * Set up the zone data structures
7527 * - init pgdat internals
7528 * - init all zones belonging to this node
7529 *
7530 * NOTE: this function is only called during memory hotplug
7531 */
7532#ifdef CONFIG_MEMORY_HOTPLUG
70b5b46a 7533void __ref free_area_init_core_hotplug(struct pglist_data *pgdat)
03e85f9d 7534{
70b5b46a 7535 int nid = pgdat->node_id;
03e85f9d 7536 enum zone_type z;
70b5b46a 7537 int cpu;
03e85f9d
OS
7538
7539 pgdat_init_internals(pgdat);
70b5b46a
MH
7540
7541 if (pgdat->per_cpu_nodestats == &boot_nodestats)
7542 pgdat->per_cpu_nodestats = alloc_percpu(struct per_cpu_nodestat);
7543
7544 /*
7545 * Reset the nr_zones, order and highest_zoneidx before reuse.
7546 * Note that kswapd will init kswapd_highest_zoneidx properly
7547 * when it starts in the near future.
7548 */
7549 pgdat->nr_zones = 0;
7550 pgdat->kswapd_order = 0;
7551 pgdat->kswapd_highest_zoneidx = 0;
7552 pgdat->node_start_pfn = 0;
7553 for_each_online_cpu(cpu) {
7554 struct per_cpu_nodestat *p;
7555
7556 p = per_cpu_ptr(pgdat->per_cpu_nodestats, cpu);
7557 memset(p, 0, sizeof(*p));
7558 }
7559
03e85f9d
OS
7560 for (z = 0; z < MAX_NR_ZONES; z++)
7561 zone_init_internals(&pgdat->node_zones[z], z, nid, 0);
7562}
7563#endif
7564
7565/*
7566 * Set up the zone data structures:
7567 * - mark all pages reserved
7568 * - mark all memory queues empty
7569 * - clear the memory bitmaps
7570 *
7571 * NOTE: pgdat should get zeroed by caller.
7572 * NOTE: this function is only called during early init.
7573 */
7574static void __init free_area_init_core(struct pglist_data *pgdat)
7575{
7576 enum zone_type j;
7577 int nid = pgdat->node_id;
5f63b720 7578
03e85f9d 7579 pgdat_init_internals(pgdat);
385386cf
JW
7580 pgdat->per_cpu_nodestats = &boot_nodestats;
7581
1da177e4
LT
7582 for (j = 0; j < MAX_NR_ZONES; j++) {
7583 struct zone *zone = pgdat->node_zones + j;
e6943859 7584 unsigned long size, freesize, memmap_pages;
1da177e4 7585
febd5949 7586 size = zone->spanned_pages;
e6943859 7587 freesize = zone->present_pages;
1da177e4 7588
0e0b864e 7589 /*
9feedc9d 7590 * Adjust freesize so that it accounts for how much memory
0e0b864e
MG
7591 * is used by this zone for memmap. This affects the watermark
7592 * and per-cpu initialisations
7593 */
e6943859 7594 memmap_pages = calc_memmap_size(size, freesize);
ba914f48
ZH
7595 if (!is_highmem_idx(j)) {
7596 if (freesize >= memmap_pages) {
7597 freesize -= memmap_pages;
7598 if (memmap_pages)
9660ecaa
HK
7599 pr_debug(" %s zone: %lu pages used for memmap\n",
7600 zone_names[j], memmap_pages);
ba914f48 7601 } else
e47aa905 7602 pr_warn(" %s zone: %lu memmap pages exceeds freesize %lu\n",
ba914f48
ZH
7603 zone_names[j], memmap_pages, freesize);
7604 }
0e0b864e 7605
6267276f 7606 /* Account for reserved pages */
9feedc9d
JL
7607 if (j == 0 && freesize > dma_reserve) {
7608 freesize -= dma_reserve;
9660ecaa 7609 pr_debug(" %s zone: %lu pages reserved\n", zone_names[0], dma_reserve);
0e0b864e
MG
7610 }
7611
98d2b0eb 7612 if (!is_highmem_idx(j))
9feedc9d 7613 nr_kernel_pages += freesize;
01cefaef
JL
7614 /* Charge for highmem memmap if there are enough kernel pages */
7615 else if (nr_kernel_pages > memmap_pages * 2)
7616 nr_kernel_pages -= memmap_pages;
9feedc9d 7617 nr_all_pages += freesize;
1da177e4 7618
9feedc9d
JL
7619 /*
7620 * Set an approximate value for lowmem here, it will be adjusted
7621 * when the bootmem allocator frees pages into the buddy system.
7622 * And all highmem pages will be managed by the buddy system.
7623 */
03e85f9d 7624 zone_init_internals(zone, j, nid, freesize);
81c0a2bb 7625
d883c6cf 7626 if (!size)
1da177e4
LT
7627 continue;
7628
955c1cd7 7629 set_pageblock_order();
7010a6ec 7630 setup_usemap(zone);
9699ee7b 7631 init_currently_empty_zone(zone, zone->zone_start_pfn, size);
1da177e4
LT
7632 }
7633}
7634
43b02ba9 7635#ifdef CONFIG_FLATMEM
3b446da6 7636static void __init alloc_node_mem_map(struct pglist_data *pgdat)
1da177e4 7637{
b0aeba74 7638 unsigned long __maybe_unused start = 0;
a1c34a3b
LA
7639 unsigned long __maybe_unused offset = 0;
7640
1da177e4
LT
7641 /* Skip empty nodes */
7642 if (!pgdat->node_spanned_pages)
7643 return;
7644
b0aeba74
TL
7645 start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
7646 offset = pgdat->node_start_pfn - start;
1da177e4
LT
7647 /* ia64 gets its own node_mem_map, before this, without bootmem */
7648 if (!pgdat->node_mem_map) {
b0aeba74 7649 unsigned long size, end;
d41dee36
AW
7650 struct page *map;
7651
e984bb43
BP
7652 /*
7653 * The zone's endpoints aren't required to be MAX_ORDER
7654 * aligned but the node_mem_map endpoints must be in order
7655 * for the buddy allocator to function correctly.
7656 */
108bcc96 7657 end = pgdat_end_pfn(pgdat);
e984bb43
BP
7658 end = ALIGN(end, MAX_ORDER_NR_PAGES);
7659 size = (end - start) * sizeof(struct page);
c803b3c8
MR
7660 map = memmap_alloc(size, SMP_CACHE_BYTES, MEMBLOCK_LOW_LIMIT,
7661 pgdat->node_id, false);
23a7052a
MR
7662 if (!map)
7663 panic("Failed to allocate %ld bytes for node %d memory map\n",
7664 size, pgdat->node_id);
a1c34a3b 7665 pgdat->node_mem_map = map + offset;
1da177e4 7666 }
0cd842f9
OS
7667 pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
7668 __func__, pgdat->node_id, (unsigned long)pgdat,
7669 (unsigned long)pgdat->node_mem_map);
a9ee6cf5 7670#ifndef CONFIG_NUMA
1da177e4
LT
7671 /*
7672 * With no DISCONTIG, the global mem_map is just set as node 0's
7673 */
c713216d 7674 if (pgdat == NODE_DATA(0)) {
1da177e4 7675 mem_map = NODE_DATA(0)->node_mem_map;
c713216d 7676 if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
a1c34a3b 7677 mem_map -= offset;
c713216d 7678 }
1da177e4
LT
7679#endif
7680}
0cd842f9 7681#else
3b446da6 7682static inline void alloc_node_mem_map(struct pglist_data *pgdat) { }
43b02ba9 7683#endif /* CONFIG_FLATMEM */
1da177e4 7684
0188dc98
OS
7685#ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
7686static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
7687{
0188dc98
OS
7688 pgdat->first_deferred_pfn = ULONG_MAX;
7689}
7690#else
7691static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
7692#endif
7693
854e8848 7694static void __init free_area_init_node(int nid)
1da177e4 7695{
9109fb7b 7696 pg_data_t *pgdat = NODE_DATA(nid);
7960aedd
ZY
7697 unsigned long start_pfn = 0;
7698 unsigned long end_pfn = 0;
9109fb7b 7699
88fdf75d 7700 /* pg_data_t should be reset to zero when it's allocated */
97a225e6 7701 WARN_ON(pgdat->nr_zones || pgdat->kswapd_highest_zoneidx);
88fdf75d 7702
854e8848 7703 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
88fdf75d 7704
1da177e4 7705 pgdat->node_id = nid;
854e8848 7706 pgdat->node_start_pfn = start_pfn;
75ef7184 7707 pgdat->per_cpu_nodestats = NULL;
854e8848 7708
7c30daac
MH
7709 if (start_pfn != end_pfn) {
7710 pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
7711 (u64)start_pfn << PAGE_SHIFT,
7712 end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
7713 } else {
7714 pr_info("Initmem setup node %d as memoryless\n", nid);
7715 }
7716
854e8848 7717 calculate_node_totalpages(pgdat, start_pfn, end_pfn);
1da177e4
LT
7718
7719 alloc_node_mem_map(pgdat);
0188dc98 7720 pgdat_set_deferred_range(pgdat);
1da177e4 7721
7f3eb55b 7722 free_area_init_core(pgdat);
1da177e4
LT
7723}
7724
1ca75fa7 7725static void __init free_area_init_memoryless_node(int nid)
3f08a302 7726{
854e8848 7727 free_area_init_node(nid);
3f08a302
MR
7728}
7729
418508c1
MS
7730#if MAX_NUMNODES > 1
7731/*
7732 * Figure out the number of possible node ids.
7733 */
f9872caf 7734void __init setup_nr_node_ids(void)
418508c1 7735{
904a9553 7736 unsigned int highest;
418508c1 7737
904a9553 7738 highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
418508c1
MS
7739 nr_node_ids = highest + 1;
7740}
418508c1
MS
7741#endif
7742
1e01979c
TH
7743/**
7744 * node_map_pfn_alignment - determine the maximum internode alignment
7745 *
7746 * This function should be called after node map is populated and sorted.
7747 * It calculates the maximum power of two alignment which can distinguish
7748 * all the nodes.
7749 *
7750 * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
7751 * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)). If the
7752 * nodes are shifted by 256MiB, 256MiB. Note that if only the last node is
7753 * shifted, 1GiB is enough and this function will indicate so.
7754 *
7755 * This is used to test whether pfn -> nid mapping of the chosen memory
7756 * model has fine enough granularity to avoid incorrect mapping for the
7757 * populated node map.
7758 *
a862f68a 7759 * Return: the determined alignment in pfn's. 0 if there is no alignment
1e01979c
TH
7760 * requirement (single node).
7761 */
7762unsigned long __init node_map_pfn_alignment(void)
7763{
7764 unsigned long accl_mask = 0, last_end = 0;
c13291a5 7765 unsigned long start, end, mask;
98fa15f3 7766 int last_nid = NUMA_NO_NODE;
c13291a5 7767 int i, nid;
1e01979c 7768
c13291a5 7769 for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
1e01979c
TH
7770 if (!start || last_nid < 0 || last_nid == nid) {
7771 last_nid = nid;
7772 last_end = end;
7773 continue;
7774 }
7775
7776 /*
7777 * Start with a mask granular enough to pin-point to the
7778 * start pfn and tick off bits one-by-one until it becomes
7779 * too coarse to separate the current node from the last.
7780 */
7781 mask = ~((1 << __ffs(start)) - 1);
7782 while (mask && last_end <= (start & (mask << 1)))
7783 mask <<= 1;
7784
7785 /* accumulate all internode masks */
7786 accl_mask |= mask;
7787 }
7788
7789 /* convert mask to number of pages */
7790 return ~accl_mask + 1;
7791}
7792
c713216d
MG
7793/**
7794 * find_min_pfn_with_active_regions - Find the minimum PFN registered
7795 *
a862f68a 7796 * Return: the minimum PFN based on information provided via
7d018176 7797 * memblock_set_node().
c713216d
MG
7798 */
7799unsigned long __init find_min_pfn_with_active_regions(void)
7800{
8a1b25fe 7801 return PHYS_PFN(memblock_start_of_DRAM());
c713216d
MG
7802}
7803
37b07e41
LS
7804/*
7805 * early_calculate_totalpages()
7806 * Sum pages in active regions for movable zone.
4b0ef1fe 7807 * Populate N_MEMORY for calculating usable_nodes.
37b07e41 7808 */
484f51f8 7809static unsigned long __init early_calculate_totalpages(void)
7e63efef 7810{
7e63efef 7811 unsigned long totalpages = 0;
c13291a5
TH
7812 unsigned long start_pfn, end_pfn;
7813 int i, nid;
7814
7815 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7816 unsigned long pages = end_pfn - start_pfn;
7e63efef 7817
37b07e41
LS
7818 totalpages += pages;
7819 if (pages)
4b0ef1fe 7820 node_set_state(nid, N_MEMORY);
37b07e41 7821 }
b8af2941 7822 return totalpages;
7e63efef
MG
7823}
7824
2a1e274a
MG
7825/*
7826 * Find the PFN the Movable zone begins in each node. Kernel memory
7827 * is spread evenly between nodes as long as the nodes have enough
7828 * memory. When they don't, some nodes will have more kernelcore than
7829 * others
7830 */
b224ef85 7831static void __init find_zone_movable_pfns_for_nodes(void)
2a1e274a
MG
7832{
7833 int i, nid;
7834 unsigned long usable_startpfn;
7835 unsigned long kernelcore_node, kernelcore_remaining;
66918dcd 7836 /* save the state before borrow the nodemask */
4b0ef1fe 7837 nodemask_t saved_node_state = node_states[N_MEMORY];
37b07e41 7838 unsigned long totalpages = early_calculate_totalpages();
4b0ef1fe 7839 int usable_nodes = nodes_weight(node_states[N_MEMORY]);
136199f0 7840 struct memblock_region *r;
b2f3eebe
TC
7841
7842 /* Need to find movable_zone earlier when movable_node is specified. */
7843 find_usable_zone_for_movable();
7844
7845 /*
7846 * If movable_node is specified, ignore kernelcore and movablecore
7847 * options.
7848 */
7849 if (movable_node_is_enabled()) {
cc6de168 7850 for_each_mem_region(r) {
136199f0 7851 if (!memblock_is_hotpluggable(r))
b2f3eebe
TC
7852 continue;
7853
d622abf7 7854 nid = memblock_get_region_node(r);
b2f3eebe 7855
136199f0 7856 usable_startpfn = PFN_DOWN(r->base);
b2f3eebe
TC
7857 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7858 min(usable_startpfn, zone_movable_pfn[nid]) :
7859 usable_startpfn;
7860 }
7861
7862 goto out2;
7863 }
2a1e274a 7864
342332e6
TI
7865 /*
7866 * If kernelcore=mirror is specified, ignore movablecore option
7867 */
7868 if (mirrored_kernelcore) {
7869 bool mem_below_4gb_not_mirrored = false;
7870
cc6de168 7871 for_each_mem_region(r) {
342332e6
TI
7872 if (memblock_is_mirror(r))
7873 continue;
7874
d622abf7 7875 nid = memblock_get_region_node(r);
342332e6
TI
7876
7877 usable_startpfn = memblock_region_memory_base_pfn(r);
7878
aa282a15 7879 if (usable_startpfn < PHYS_PFN(SZ_4G)) {
342332e6
TI
7880 mem_below_4gb_not_mirrored = true;
7881 continue;
7882 }
7883
7884 zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7885 min(usable_startpfn, zone_movable_pfn[nid]) :
7886 usable_startpfn;
7887 }
7888
7889 if (mem_below_4gb_not_mirrored)
633bf2fe 7890 pr_warn("This configuration results in unmirrored kernel memory.\n");
342332e6
TI
7891
7892 goto out2;
7893 }
7894
7e63efef 7895 /*
a5c6d650
DR
7896 * If kernelcore=nn% or movablecore=nn% was specified, calculate the
7897 * amount of necessary memory.
7898 */
7899 if (required_kernelcore_percent)
7900 required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
7901 10000UL;
7902 if (required_movablecore_percent)
7903 required_movablecore = (totalpages * 100 * required_movablecore_percent) /
7904 10000UL;
7905
7906 /*
7907 * If movablecore= was specified, calculate what size of
7e63efef
MG
7908 * kernelcore that corresponds so that memory usable for
7909 * any allocation type is evenly spread. If both kernelcore
7910 * and movablecore are specified, then the value of kernelcore
7911 * will be used for required_kernelcore if it's greater than
7912 * what movablecore would have allowed.
7913 */
7914 if (required_movablecore) {
7e63efef
MG
7915 unsigned long corepages;
7916
7917 /*
7918 * Round-up so that ZONE_MOVABLE is at least as large as what
7919 * was requested by the user
7920 */
7921 required_movablecore =
7922 roundup(required_movablecore, MAX_ORDER_NR_PAGES);
9fd745d4 7923 required_movablecore = min(totalpages, required_movablecore);
7e63efef
MG
7924 corepages = totalpages - required_movablecore;
7925
7926 required_kernelcore = max(required_kernelcore, corepages);
7927 }
7928
bde304bd
XQ
7929 /*
7930 * If kernelcore was not specified or kernelcore size is larger
7931 * than totalpages, there is no ZONE_MOVABLE.
7932 */
7933 if (!required_kernelcore || required_kernelcore >= totalpages)
66918dcd 7934 goto out;
2a1e274a
MG
7935
7936 /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
2a1e274a
MG
7937 usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
7938
7939restart:
7940 /* Spread kernelcore memory as evenly as possible throughout nodes */
7941 kernelcore_node = required_kernelcore / usable_nodes;
4b0ef1fe 7942 for_each_node_state(nid, N_MEMORY) {
c13291a5
TH
7943 unsigned long start_pfn, end_pfn;
7944
2a1e274a
MG
7945 /*
7946 * Recalculate kernelcore_node if the division per node
7947 * now exceeds what is necessary to satisfy the requested
7948 * amount of memory for the kernel
7949 */
7950 if (required_kernelcore < kernelcore_node)
7951 kernelcore_node = required_kernelcore / usable_nodes;
7952
7953 /*
7954 * As the map is walked, we track how much memory is usable
7955 * by the kernel using kernelcore_remaining. When it is
7956 * 0, the rest of the node is usable by ZONE_MOVABLE
7957 */
7958 kernelcore_remaining = kernelcore_node;
7959
7960 /* Go through each range of PFNs within this node */
c13291a5 7961 for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
2a1e274a
MG
7962 unsigned long size_pages;
7963
c13291a5 7964 start_pfn = max(start_pfn, zone_movable_pfn[nid]);
2a1e274a
MG
7965 if (start_pfn >= end_pfn)
7966 continue;
7967
7968 /* Account for what is only usable for kernelcore */
7969 if (start_pfn < usable_startpfn) {
7970 unsigned long kernel_pages;
7971 kernel_pages = min(end_pfn, usable_startpfn)
7972 - start_pfn;
7973
7974 kernelcore_remaining -= min(kernel_pages,
7975 kernelcore_remaining);
7976 required_kernelcore -= min(kernel_pages,
7977 required_kernelcore);
7978
7979 /* Continue if range is now fully accounted */
7980 if (end_pfn <= usable_startpfn) {
7981
7982 /*
7983 * Push zone_movable_pfn to the end so
7984 * that if we have to rebalance
7985 * kernelcore across nodes, we will
7986 * not double account here
7987 */
7988 zone_movable_pfn[nid] = end_pfn;
7989 continue;
7990 }
7991 start_pfn = usable_startpfn;
7992 }
7993
7994 /*
7995 * The usable PFN range for ZONE_MOVABLE is from
7996 * start_pfn->end_pfn. Calculate size_pages as the
7997 * number of pages used as kernelcore
7998 */
7999 size_pages = end_pfn - start_pfn;
8000 if (size_pages > kernelcore_remaining)
8001 size_pages = kernelcore_remaining;
8002 zone_movable_pfn[nid] = start_pfn + size_pages;
8003
8004 /*
8005 * Some kernelcore has been met, update counts and
8006 * break if the kernelcore for this node has been
b8af2941 8007 * satisfied
2a1e274a
MG
8008 */
8009 required_kernelcore -= min(required_kernelcore,
8010 size_pages);
8011 kernelcore_remaining -= size_pages;
8012 if (!kernelcore_remaining)
8013 break;
8014 }
8015 }
8016
8017 /*
8018 * If there is still required_kernelcore, we do another pass with one
8019 * less node in the count. This will push zone_movable_pfn[nid] further
8020 * along on the nodes that still have memory until kernelcore is
b8af2941 8021 * satisfied
2a1e274a
MG
8022 */
8023 usable_nodes--;
8024 if (usable_nodes && required_kernelcore > usable_nodes)
8025 goto restart;
8026
b2f3eebe 8027out2:
2a1e274a 8028 /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
ddbc84f3
AP
8029 for (nid = 0; nid < MAX_NUMNODES; nid++) {
8030 unsigned long start_pfn, end_pfn;
8031
2a1e274a
MG
8032 zone_movable_pfn[nid] =
8033 roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
66918dcd 8034
ddbc84f3
AP
8035 get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
8036 if (zone_movable_pfn[nid] >= end_pfn)
8037 zone_movable_pfn[nid] = 0;
8038 }
8039
20e6926d 8040out:
66918dcd 8041 /* restore the node_state */
4b0ef1fe 8042 node_states[N_MEMORY] = saved_node_state;
2a1e274a
MG
8043}
8044
4b0ef1fe
LJ
8045/* Any regular or high memory on that node ? */
8046static void check_for_memory(pg_data_t *pgdat, int nid)
37b07e41 8047{
37b07e41
LS
8048 enum zone_type zone_type;
8049
4b0ef1fe 8050 for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
37b07e41 8051 struct zone *zone = &pgdat->node_zones[zone_type];
b38a8725 8052 if (populated_zone(zone)) {
7b0e0c0e
OS
8053 if (IS_ENABLED(CONFIG_HIGHMEM))
8054 node_set_state(nid, N_HIGH_MEMORY);
8055 if (zone_type <= ZONE_NORMAL)
4b0ef1fe 8056 node_set_state(nid, N_NORMAL_MEMORY);
d0048b0e
BL
8057 break;
8058 }
37b07e41 8059 }
37b07e41
LS
8060}
8061
51930df5 8062/*
f0953a1b 8063 * Some architectures, e.g. ARC may have ZONE_HIGHMEM below ZONE_NORMAL. For
51930df5
MR
8064 * such cases we allow max_zone_pfn sorted in the descending order
8065 */
8066bool __weak arch_has_descending_max_zone_pfns(void)
8067{
8068 return false;
8069}
8070
c713216d 8071/**
9691a071 8072 * free_area_init - Initialise all pg_data_t and zone data
88ca3b94 8073 * @max_zone_pfn: an array of max PFNs for each zone
c713216d
MG
8074 *
8075 * This will call free_area_init_node() for each active node in the system.
7d018176 8076 * Using the page ranges provided by memblock_set_node(), the size of each
c713216d
MG
8077 * zone in each node and their holes is calculated. If the maximum PFN
8078 * between two adjacent zones match, it is assumed that the zone is empty.
8079 * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
8080 * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
8081 * starts where the previous one ended. For example, ZONE_DMA32 starts
8082 * at arch_max_dma_pfn.
8083 */
9691a071 8084void __init free_area_init(unsigned long *max_zone_pfn)
c713216d 8085{
c13291a5 8086 unsigned long start_pfn, end_pfn;
51930df5
MR
8087 int i, nid, zone;
8088 bool descending;
a6af2bc3 8089
c713216d
MG
8090 /* Record where the zone boundaries are */
8091 memset(arch_zone_lowest_possible_pfn, 0,
8092 sizeof(arch_zone_lowest_possible_pfn));
8093 memset(arch_zone_highest_possible_pfn, 0,
8094 sizeof(arch_zone_highest_possible_pfn));
90cae1fe
OH
8095
8096 start_pfn = find_min_pfn_with_active_regions();
51930df5 8097 descending = arch_has_descending_max_zone_pfns();
90cae1fe
OH
8098
8099 for (i = 0; i < MAX_NR_ZONES; i++) {
51930df5
MR
8100 if (descending)
8101 zone = MAX_NR_ZONES - i - 1;
8102 else
8103 zone = i;
8104
8105 if (zone == ZONE_MOVABLE)
2a1e274a 8106 continue;
90cae1fe 8107
51930df5
MR
8108 end_pfn = max(max_zone_pfn[zone], start_pfn);
8109 arch_zone_lowest_possible_pfn[zone] = start_pfn;
8110 arch_zone_highest_possible_pfn[zone] = end_pfn;
90cae1fe
OH
8111
8112 start_pfn = end_pfn;
c713216d 8113 }
2a1e274a
MG
8114
8115 /* Find the PFNs that ZONE_MOVABLE begins at in each node */
8116 memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
b224ef85 8117 find_zone_movable_pfns_for_nodes();
c713216d 8118
c713216d 8119 /* Print out the zone ranges */
f88dfff5 8120 pr_info("Zone ranges:\n");
2a1e274a
MG
8121 for (i = 0; i < MAX_NR_ZONES; i++) {
8122 if (i == ZONE_MOVABLE)
8123 continue;
f88dfff5 8124 pr_info(" %-8s ", zone_names[i]);
72f0ba02
DR
8125 if (arch_zone_lowest_possible_pfn[i] ==
8126 arch_zone_highest_possible_pfn[i])
f88dfff5 8127 pr_cont("empty\n");
72f0ba02 8128 else
8d29e18a
JG
8129 pr_cont("[mem %#018Lx-%#018Lx]\n",
8130 (u64)arch_zone_lowest_possible_pfn[i]
8131 << PAGE_SHIFT,
8132 ((u64)arch_zone_highest_possible_pfn[i]
a62e2f4f 8133 << PAGE_SHIFT) - 1);
2a1e274a
MG
8134 }
8135
8136 /* Print out the PFNs ZONE_MOVABLE begins at in each node */
f88dfff5 8137 pr_info("Movable zone start for each node\n");
2a1e274a
MG
8138 for (i = 0; i < MAX_NUMNODES; i++) {
8139 if (zone_movable_pfn[i])
8d29e18a
JG
8140 pr_info(" Node %d: %#018Lx\n", i,
8141 (u64)zone_movable_pfn[i] << PAGE_SHIFT);
2a1e274a 8142 }
c713216d 8143
f46edbd1
DW
8144 /*
8145 * Print out the early node map, and initialize the
8146 * subsection-map relative to active online memory ranges to
8147 * enable future "sub-section" extensions of the memory map.
8148 */
f88dfff5 8149 pr_info("Early memory node ranges\n");
f46edbd1 8150 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
8d29e18a
JG
8151 pr_info(" node %3d: [mem %#018Lx-%#018Lx]\n", nid,
8152 (u64)start_pfn << PAGE_SHIFT,
8153 ((u64)end_pfn << PAGE_SHIFT) - 1);
f46edbd1
DW
8154 subsection_map_init(start_pfn, end_pfn - start_pfn);
8155 }
c713216d
MG
8156
8157 /* Initialise every node */
708614e6 8158 mminit_verify_pageflags_layout();
8ef82866 8159 setup_nr_node_ids();
09f49dca
MH
8160 for_each_node(nid) {
8161 pg_data_t *pgdat;
8162
8163 if (!node_online(nid)) {
8164 pr_info("Initializing node %d as memoryless\n", nid);
8165
8166 /* Allocator not initialized yet */
8167 pgdat = arch_alloc_nodedata(nid);
8168 if (!pgdat) {
8169 pr_err("Cannot allocate %zuB for node %d.\n",
8170 sizeof(*pgdat), nid);
8171 continue;
8172 }
8173 arch_refresh_nodedata(nid, pgdat);
8174 free_area_init_memoryless_node(nid);
8175
8176 /*
8177 * We do not want to confuse userspace by sysfs
8178 * files/directories for node without any memory
8179 * attached to it, so this node is not marked as
8180 * N_MEMORY and not marked online so that no sysfs
8181 * hierarchy will be created via register_one_node for
8182 * it. The pgdat will get fully initialized by
8183 * hotadd_init_pgdat() when memory is hotplugged into
8184 * this node.
8185 */
8186 continue;
8187 }
8188
8189 pgdat = NODE_DATA(nid);
854e8848 8190 free_area_init_node(nid);
37b07e41
LS
8191
8192 /* Any memory on that node */
8193 if (pgdat->node_present_pages)
4b0ef1fe
LJ
8194 node_set_state(nid, N_MEMORY);
8195 check_for_memory(pgdat, nid);
c713216d 8196 }
122e093c
MR
8197
8198 memmap_init();
c713216d 8199}
2a1e274a 8200
a5c6d650
DR
8201static int __init cmdline_parse_core(char *p, unsigned long *core,
8202 unsigned long *percent)
2a1e274a
MG
8203{
8204 unsigned long long coremem;
a5c6d650
DR
8205 char *endptr;
8206
2a1e274a
MG
8207 if (!p)
8208 return -EINVAL;
8209
a5c6d650
DR
8210 /* Value may be a percentage of total memory, otherwise bytes */
8211 coremem = simple_strtoull(p, &endptr, 0);
8212 if (*endptr == '%') {
8213 /* Paranoid check for percent values greater than 100 */
8214 WARN_ON(coremem > 100);
2a1e274a 8215
a5c6d650
DR
8216 *percent = coremem;
8217 } else {
8218 coremem = memparse(p, &p);
8219 /* Paranoid check that UL is enough for the coremem value */
8220 WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
2a1e274a 8221
a5c6d650
DR
8222 *core = coremem >> PAGE_SHIFT;
8223 *percent = 0UL;
8224 }
2a1e274a
MG
8225 return 0;
8226}
ed7ed365 8227
7e63efef
MG
8228/*
8229 * kernelcore=size sets the amount of memory for use for allocations that
8230 * cannot be reclaimed or migrated.
8231 */
8232static int __init cmdline_parse_kernelcore(char *p)
8233{
342332e6
TI
8234 /* parse kernelcore=mirror */
8235 if (parse_option_str(p, "mirror")) {
8236 mirrored_kernelcore = true;
8237 return 0;
8238 }
8239
a5c6d650
DR
8240 return cmdline_parse_core(p, &required_kernelcore,
8241 &required_kernelcore_percent);
7e63efef
MG
8242}
8243
8244/*
8245 * movablecore=size sets the amount of memory for use for allocations that
8246 * can be reclaimed or migrated.
8247 */
8248static int __init cmdline_parse_movablecore(char *p)
8249{
a5c6d650
DR
8250 return cmdline_parse_core(p, &required_movablecore,
8251 &required_movablecore_percent);
7e63efef
MG
8252}
8253
ed7ed365 8254early_param("kernelcore", cmdline_parse_kernelcore);
7e63efef 8255early_param("movablecore", cmdline_parse_movablecore);
ed7ed365 8256
c3d5f5f0
JL
8257void adjust_managed_page_count(struct page *page, long count)
8258{
9705bea5 8259 atomic_long_add(count, &page_zone(page)->managed_pages);
ca79b0c2 8260 totalram_pages_add(count);
3dcc0571
JL
8261#ifdef CONFIG_HIGHMEM
8262 if (PageHighMem(page))
ca79b0c2 8263 totalhigh_pages_add(count);
3dcc0571 8264#endif
c3d5f5f0 8265}
3dcc0571 8266EXPORT_SYMBOL(adjust_managed_page_count);
c3d5f5f0 8267
e5cb113f 8268unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
69afade7 8269{
11199692
JL
8270 void *pos;
8271 unsigned long pages = 0;
69afade7 8272
11199692
JL
8273 start = (void *)PAGE_ALIGN((unsigned long)start);
8274 end = (void *)((unsigned long)end & PAGE_MASK);
8275 for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
0d834328
DH
8276 struct page *page = virt_to_page(pos);
8277 void *direct_map_addr;
8278
8279 /*
8280 * 'direct_map_addr' might be different from 'pos'
8281 * because some architectures' virt_to_page()
8282 * work with aliases. Getting the direct map
8283 * address ensures that we get a _writeable_
8284 * alias for the memset().
8285 */
8286 direct_map_addr = page_address(page);
c746170d
VF
8287 /*
8288 * Perform a kasan-unchecked memset() since this memory
8289 * has not been initialized.
8290 */
8291 direct_map_addr = kasan_reset_tag(direct_map_addr);
dbe67df4 8292 if ((unsigned int)poison <= 0xFF)
0d834328
DH
8293 memset(direct_map_addr, poison, PAGE_SIZE);
8294
8295 free_reserved_page(page);
69afade7
JL
8296 }
8297
8298 if (pages && s)
ff7ed9e4 8299 pr_info("Freeing %s memory: %ldK\n", s, K(pages));
69afade7
JL
8300
8301 return pages;
8302}
8303
1f9d03c5 8304void __init mem_init_print_info(void)
7ee3d4e8
JL
8305{
8306 unsigned long physpages, codesize, datasize, rosize, bss_size;
8307 unsigned long init_code_size, init_data_size;
8308
8309 physpages = get_num_physpages();
8310 codesize = _etext - _stext;
8311 datasize = _edata - _sdata;
8312 rosize = __end_rodata - __start_rodata;
8313 bss_size = __bss_stop - __bss_start;
8314 init_data_size = __init_end - __init_begin;
8315 init_code_size = _einittext - _sinittext;
8316
8317 /*
8318 * Detect special cases and adjust section sizes accordingly:
8319 * 1) .init.* may be embedded into .data sections
8320 * 2) .init.text.* may be out of [__init_begin, __init_end],
8321 * please refer to arch/tile/kernel/vmlinux.lds.S.
8322 * 3) .rodata.* may be embedded into .text or .data sections.
8323 */
8324#define adj_init_size(start, end, size, pos, adj) \
b8af2941 8325 do { \
ca831f29 8326 if (&start[0] <= &pos[0] && &pos[0] < &end[0] && size > adj) \
b8af2941
PK
8327 size -= adj; \
8328 } while (0)
7ee3d4e8
JL
8329
8330 adj_init_size(__init_begin, __init_end, init_data_size,
8331 _sinittext, init_code_size);
8332 adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
8333 adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
8334 adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
8335 adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
8336
8337#undef adj_init_size
8338
756a025f 8339 pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
7ee3d4e8 8340#ifdef CONFIG_HIGHMEM
756a025f 8341 ", %luK highmem"
7ee3d4e8 8342#endif
1f9d03c5 8343 ")\n",
ff7ed9e4 8344 K(nr_free_pages()), K(physpages),
756a025f
JP
8345 codesize >> 10, datasize >> 10, rosize >> 10,
8346 (init_data_size + init_code_size) >> 10, bss_size >> 10,
ff7ed9e4
ML
8347 K(physpages - totalram_pages() - totalcma_pages),
8348 K(totalcma_pages)
7ee3d4e8 8349#ifdef CONFIG_HIGHMEM
ff7ed9e4 8350 , K(totalhigh_pages())
7ee3d4e8 8351#endif
1f9d03c5 8352 );
7ee3d4e8
JL
8353}
8354
0e0b864e 8355/**
88ca3b94
RD
8356 * set_dma_reserve - set the specified number of pages reserved in the first zone
8357 * @new_dma_reserve: The number of pages to mark reserved
0e0b864e 8358 *
013110a7 8359 * The per-cpu batchsize and zone watermarks are determined by managed_pages.
0e0b864e
MG
8360 * In the DMA zone, a significant percentage may be consumed by kernel image
8361 * and other unfreeable allocations which can skew the watermarks badly. This
88ca3b94
RD
8362 * function may optionally be used to account for unfreeable pages in the
8363 * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
8364 * smaller per-cpu batchsize.
0e0b864e
MG
8365 */
8366void __init set_dma_reserve(unsigned long new_dma_reserve)
8367{
8368 dma_reserve = new_dma_reserve;
8369}
8370
005fd4bb 8371static int page_alloc_cpu_dead(unsigned int cpu)
1da177e4 8372{
04f8cfea 8373 struct zone *zone;
1da177e4 8374
005fd4bb 8375 lru_add_drain_cpu(cpu);
adb11e78 8376 mlock_page_drain_remote(cpu);
005fd4bb 8377 drain_pages(cpu);
9f8f2172 8378
005fd4bb
SAS
8379 /*
8380 * Spill the event counters of the dead processor
8381 * into the current processors event counters.
8382 * This artificially elevates the count of the current
8383 * processor.
8384 */
8385 vm_events_fold_cpu(cpu);
9f8f2172 8386
005fd4bb
SAS
8387 /*
8388 * Zero the differential counters of the dead processor
8389 * so that the vm statistics are consistent.
8390 *
8391 * This is only okay since the processor is dead and cannot
8392 * race with what we are doing.
8393 */
8394 cpu_vm_stats_fold(cpu);
04f8cfea
MG
8395
8396 for_each_populated_zone(zone)
8397 zone_pcp_update(zone, 0);
8398
8399 return 0;
8400}
8401
8402static int page_alloc_cpu_online(unsigned int cpu)
8403{
8404 struct zone *zone;
8405
8406 for_each_populated_zone(zone)
8407 zone_pcp_update(zone, 1);
005fd4bb 8408 return 0;
1da177e4 8409}
1da177e4 8410
e03a5125
NP
8411#ifdef CONFIG_NUMA
8412int hashdist = HASHDIST_DEFAULT;
8413
8414static int __init set_hashdist(char *str)
8415{
8416 if (!str)
8417 return 0;
8418 hashdist = simple_strtoul(str, &str, 0);
8419 return 1;
8420}
8421__setup("hashdist=", set_hashdist);
8422#endif
8423
1da177e4
LT
8424void __init page_alloc_init(void)
8425{
005fd4bb
SAS
8426 int ret;
8427
e03a5125
NP
8428#ifdef CONFIG_NUMA
8429 if (num_node_state(N_MEMORY) == 1)
8430 hashdist = 0;
8431#endif
8432
04f8cfea
MG
8433 ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC,
8434 "mm/page_alloc:pcp",
8435 page_alloc_cpu_online,
005fd4bb
SAS
8436 page_alloc_cpu_dead);
8437 WARN_ON(ret < 0);
1da177e4
LT
8438}
8439
cb45b0e9 8440/*
34b10060 8441 * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
cb45b0e9
HA
8442 * or min_free_kbytes changes.
8443 */
8444static void calculate_totalreserve_pages(void)
8445{
8446 struct pglist_data *pgdat;
8447 unsigned long reserve_pages = 0;
2f6726e5 8448 enum zone_type i, j;
cb45b0e9
HA
8449
8450 for_each_online_pgdat(pgdat) {
281e3726
MG
8451
8452 pgdat->totalreserve_pages = 0;
8453
cb45b0e9
HA
8454 for (i = 0; i < MAX_NR_ZONES; i++) {
8455 struct zone *zone = pgdat->node_zones + i;
3484b2de 8456 long max = 0;
9705bea5 8457 unsigned long managed_pages = zone_managed_pages(zone);
cb45b0e9
HA
8458
8459 /* Find valid and maximum lowmem_reserve in the zone */
8460 for (j = i; j < MAX_NR_ZONES; j++) {
8461 if (zone->lowmem_reserve[j] > max)
8462 max = zone->lowmem_reserve[j];
8463 }
8464
41858966
MG
8465 /* we treat the high watermark as reserved pages. */
8466 max += high_wmark_pages(zone);
cb45b0e9 8467
3d6357de
AK
8468 if (max > managed_pages)
8469 max = managed_pages;
a8d01437 8470
281e3726 8471 pgdat->totalreserve_pages += max;
a8d01437 8472
cb45b0e9
HA
8473 reserve_pages += max;
8474 }
8475 }
8476 totalreserve_pages = reserve_pages;
8477}
8478
1da177e4
LT
8479/*
8480 * setup_per_zone_lowmem_reserve - called whenever
34b10060 8481 * sysctl_lowmem_reserve_ratio changes. Ensures that each zone
1da177e4
LT
8482 * has a correct pages reserved value, so an adequate number of
8483 * pages are left in the zone after a successful __alloc_pages().
8484 */
8485static void setup_per_zone_lowmem_reserve(void)
8486{
8487 struct pglist_data *pgdat;
470c61d7 8488 enum zone_type i, j;
1da177e4 8489
ec936fc5 8490 for_each_online_pgdat(pgdat) {
470c61d7
LS
8491 for (i = 0; i < MAX_NR_ZONES - 1; i++) {
8492 struct zone *zone = &pgdat->node_zones[i];
8493 int ratio = sysctl_lowmem_reserve_ratio[i];
8494 bool clear = !ratio || !zone_managed_pages(zone);
8495 unsigned long managed_pages = 0;
8496
8497 for (j = i + 1; j < MAX_NR_ZONES; j++) {
f7ec1044
LS
8498 struct zone *upper_zone = &pgdat->node_zones[j];
8499
8500 managed_pages += zone_managed_pages(upper_zone);
470c61d7 8501
f7ec1044
LS
8502 if (clear)
8503 zone->lowmem_reserve[j] = 0;
8504 else
470c61d7 8505 zone->lowmem_reserve[j] = managed_pages / ratio;
1da177e4
LT
8506 }
8507 }
8508 }
cb45b0e9
HA
8509
8510 /* update totalreserve_pages */
8511 calculate_totalreserve_pages();
1da177e4
LT
8512}
8513
cfd3da1e 8514static void __setup_per_zone_wmarks(void)
1da177e4
LT
8515{
8516 unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
8517 unsigned long lowmem_pages = 0;
8518 struct zone *zone;
8519 unsigned long flags;
8520
8521 /* Calculate total number of !ZONE_HIGHMEM pages */
8522 for_each_zone(zone) {
8523 if (!is_highmem(zone))
9705bea5 8524 lowmem_pages += zone_managed_pages(zone);
1da177e4
LT
8525 }
8526
8527 for_each_zone(zone) {
ac924c60
AM
8528 u64 tmp;
8529
1125b4e3 8530 spin_lock_irqsave(&zone->lock, flags);
9705bea5 8531 tmp = (u64)pages_min * zone_managed_pages(zone);
ac924c60 8532 do_div(tmp, lowmem_pages);
1da177e4
LT
8533 if (is_highmem(zone)) {
8534 /*
669ed175
NP
8535 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
8536 * need highmem pages, so cap pages_min to a small
8537 * value here.
8538 *
41858966 8539 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
8bb4e7a2 8540 * deltas control async page reclaim, and so should
669ed175 8541 * not be capped for highmem.
1da177e4 8542 */
90ae8d67 8543 unsigned long min_pages;
1da177e4 8544
9705bea5 8545 min_pages = zone_managed_pages(zone) / 1024;
90ae8d67 8546 min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
a9214443 8547 zone->_watermark[WMARK_MIN] = min_pages;
1da177e4 8548 } else {
669ed175
NP
8549 /*
8550 * If it's a lowmem zone, reserve a number of pages
1da177e4
LT
8551 * proportionate to the zone's size.
8552 */
a9214443 8553 zone->_watermark[WMARK_MIN] = tmp;
1da177e4
LT
8554 }
8555
795ae7a0
JW
8556 /*
8557 * Set the kswapd watermarks distance according to the
8558 * scale factor in proportion to available memory, but
8559 * ensure a minimum size on small systems.
8560 */
8561 tmp = max_t(u64, tmp >> 2,
9705bea5 8562 mult_frac(zone_managed_pages(zone),
795ae7a0
JW
8563 watermark_scale_factor, 10000));
8564
aa092591 8565 zone->watermark_boost = 0;
a9214443 8566 zone->_watermark[WMARK_LOW] = min_wmark_pages(zone) + tmp;
c574bbe9
HY
8567 zone->_watermark[WMARK_HIGH] = low_wmark_pages(zone) + tmp;
8568 zone->_watermark[WMARK_PROMO] = high_wmark_pages(zone) + tmp;
49f223a9 8569
1125b4e3 8570 spin_unlock_irqrestore(&zone->lock, flags);
1da177e4 8571 }
cb45b0e9
HA
8572
8573 /* update totalreserve_pages */
8574 calculate_totalreserve_pages();
1da177e4
LT
8575}
8576
cfd3da1e
MG
8577/**
8578 * setup_per_zone_wmarks - called when min_free_kbytes changes
8579 * or when memory is hot-{added|removed}
8580 *
8581 * Ensures that the watermark[min,low,high] values for each zone are set
8582 * correctly with respect to min_free_kbytes.
8583 */
8584void setup_per_zone_wmarks(void)
8585{
b92ca18e 8586 struct zone *zone;
b93e0f32
MH
8587 static DEFINE_SPINLOCK(lock);
8588
8589 spin_lock(&lock);
cfd3da1e 8590 __setup_per_zone_wmarks();
b93e0f32 8591 spin_unlock(&lock);
b92ca18e
MG
8592
8593 /*
8594 * The watermark size have changed so update the pcpu batch
8595 * and high limits or the limits may be inappropriate.
8596 */
8597 for_each_zone(zone)
04f8cfea 8598 zone_pcp_update(zone, 0);
cfd3da1e
MG
8599}
8600
1da177e4
LT
8601/*
8602 * Initialise min_free_kbytes.
8603 *
8604 * For small machines we want it small (128k min). For large machines
8beeae86 8605 * we want it large (256MB max). But it is not linear, because network
1da177e4
LT
8606 * bandwidth does not increase linearly with machine size. We use
8607 *
b8af2941 8608 * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
1da177e4
LT
8609 * min_free_kbytes = sqrt(lowmem_kbytes * 16)
8610 *
8611 * which yields
8612 *
8613 * 16MB: 512k
8614 * 32MB: 724k
8615 * 64MB: 1024k
8616 * 128MB: 1448k
8617 * 256MB: 2048k
8618 * 512MB: 2896k
8619 * 1024MB: 4096k
8620 * 2048MB: 5792k
8621 * 4096MB: 8192k
8622 * 8192MB: 11584k
8623 * 16384MB: 16384k
8624 */
bd3400ea 8625void calculate_min_free_kbytes(void)
1da177e4
LT
8626{
8627 unsigned long lowmem_kbytes;
5f12733e 8628 int new_min_free_kbytes;
1da177e4
LT
8629
8630 lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
5f12733e
MH
8631 new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
8632
59d336bd
WS
8633 if (new_min_free_kbytes > user_min_free_kbytes)
8634 min_free_kbytes = clamp(new_min_free_kbytes, 128, 262144);
8635 else
5f12733e
MH
8636 pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
8637 new_min_free_kbytes, user_min_free_kbytes);
59d336bd 8638
bd3400ea
LF
8639}
8640
8641int __meminit init_per_zone_wmark_min(void)
8642{
8643 calculate_min_free_kbytes();
bc75d33f 8644 setup_per_zone_wmarks();
a6cccdc3 8645 refresh_zone_stat_thresholds();
1da177e4 8646 setup_per_zone_lowmem_reserve();
6423aa81
JK
8647
8648#ifdef CONFIG_NUMA
8649 setup_min_unmapped_ratio();
8650 setup_min_slab_ratio();
8651#endif
8652
4aab2be0
VB
8653 khugepaged_min_free_kbytes_update();
8654
1da177e4
LT
8655 return 0;
8656}
e08d3fdf 8657postcore_initcall(init_per_zone_wmark_min)
1da177e4
LT
8658
8659/*
b8af2941 8660 * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
1da177e4
LT
8661 * that we can call two helper functions whenever min_free_kbytes
8662 * changes.
8663 */
cccad5b9 8664int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
32927393 8665 void *buffer, size_t *length, loff_t *ppos)
1da177e4 8666{
da8c757b
HP
8667 int rc;
8668
8669 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8670 if (rc)
8671 return rc;
8672
5f12733e
MH
8673 if (write) {
8674 user_min_free_kbytes = min_free_kbytes;
bc75d33f 8675 setup_per_zone_wmarks();
5f12733e 8676 }
1da177e4
LT
8677 return 0;
8678}
8679
795ae7a0 8680int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write,
32927393 8681 void *buffer, size_t *length, loff_t *ppos)
795ae7a0
JW
8682{
8683 int rc;
8684
8685 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8686 if (rc)
8687 return rc;
8688
8689 if (write)
8690 setup_per_zone_wmarks();
8691
8692 return 0;
8693}
8694
9614634f 8695#ifdef CONFIG_NUMA
6423aa81 8696static void setup_min_unmapped_ratio(void)
9614634f 8697{
6423aa81 8698 pg_data_t *pgdat;
9614634f 8699 struct zone *zone;
9614634f 8700
a5f5f91d 8701 for_each_online_pgdat(pgdat)
81cbcbc2 8702 pgdat->min_unmapped_pages = 0;
a5f5f91d 8703
9614634f 8704 for_each_zone(zone)
9705bea5
AK
8705 zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
8706 sysctl_min_unmapped_ratio) / 100;
9614634f 8707}
0ff38490 8708
6423aa81
JK
8709
8710int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
32927393 8711 void *buffer, size_t *length, loff_t *ppos)
0ff38490 8712{
0ff38490
CL
8713 int rc;
8714
8d65af78 8715 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
0ff38490
CL
8716 if (rc)
8717 return rc;
8718
6423aa81
JK
8719 setup_min_unmapped_ratio();
8720
8721 return 0;
8722}
8723
8724static void setup_min_slab_ratio(void)
8725{
8726 pg_data_t *pgdat;
8727 struct zone *zone;
8728
a5f5f91d
MG
8729 for_each_online_pgdat(pgdat)
8730 pgdat->min_slab_pages = 0;
8731
0ff38490 8732 for_each_zone(zone)
9705bea5
AK
8733 zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
8734 sysctl_min_slab_ratio) / 100;
6423aa81
JK
8735}
8736
8737int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
32927393 8738 void *buffer, size_t *length, loff_t *ppos)
6423aa81
JK
8739{
8740 int rc;
8741
8742 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
8743 if (rc)
8744 return rc;
8745
8746 setup_min_slab_ratio();
8747
0ff38490
CL
8748 return 0;
8749}
9614634f
CL
8750#endif
8751
1da177e4
LT
8752/*
8753 * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
8754 * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
8755 * whenever sysctl_lowmem_reserve_ratio changes.
8756 *
8757 * The reserve ratio obviously has absolutely no relation with the
41858966 8758 * minimum watermarks. The lowmem reserve ratio can only make sense
1da177e4
LT
8759 * if in function of the boot time zone sizes.
8760 */
cccad5b9 8761int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
32927393 8762 void *buffer, size_t *length, loff_t *ppos)
1da177e4 8763{
86aaf255
BH
8764 int i;
8765
8d65af78 8766 proc_dointvec_minmax(table, write, buffer, length, ppos);
86aaf255
BH
8767
8768 for (i = 0; i < MAX_NR_ZONES; i++) {
8769 if (sysctl_lowmem_reserve_ratio[i] < 1)
8770 sysctl_lowmem_reserve_ratio[i] = 0;
8771 }
8772
1da177e4
LT
8773 setup_per_zone_lowmem_reserve();
8774 return 0;
8775}
8776
8ad4b1fb 8777/*
74f44822
MG
8778 * percpu_pagelist_high_fraction - changes the pcp->high for each zone on each
8779 * cpu. It is the fraction of total pages in each zone that a hot per cpu
b8af2941 8780 * pagelist can have before it gets flushed back to buddy allocator.
8ad4b1fb 8781 */
74f44822
MG
8782int percpu_pagelist_high_fraction_sysctl_handler(struct ctl_table *table,
8783 int write, void *buffer, size_t *length, loff_t *ppos)
8ad4b1fb
RS
8784{
8785 struct zone *zone;
74f44822 8786 int old_percpu_pagelist_high_fraction;
8ad4b1fb
RS
8787 int ret;
8788
7cd2b0a3 8789 mutex_lock(&pcp_batch_high_lock);
74f44822 8790 old_percpu_pagelist_high_fraction = percpu_pagelist_high_fraction;
7cd2b0a3 8791
8d65af78 8792 ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
7cd2b0a3
DR
8793 if (!write || ret < 0)
8794 goto out;
8795
8796 /* Sanity checking to avoid pcp imbalance */
74f44822
MG
8797 if (percpu_pagelist_high_fraction &&
8798 percpu_pagelist_high_fraction < MIN_PERCPU_PAGELIST_HIGH_FRACTION) {
8799 percpu_pagelist_high_fraction = old_percpu_pagelist_high_fraction;
7cd2b0a3
DR
8800 ret = -EINVAL;
8801 goto out;
8802 }
8803
8804 /* No change? */
74f44822 8805 if (percpu_pagelist_high_fraction == old_percpu_pagelist_high_fraction)
7cd2b0a3 8806 goto out;
c8e251fa 8807
cb1ef534 8808 for_each_populated_zone(zone)
74f44822 8809 zone_set_pageset_high_and_batch(zone, 0);
7cd2b0a3 8810out:
c8e251fa 8811 mutex_unlock(&pcp_batch_high_lock);
7cd2b0a3 8812 return ret;
8ad4b1fb
RS
8813}
8814
f6f34b43
SD
8815#ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES
8816/*
8817 * Returns the number of pages that arch has reserved but
8818 * is not known to alloc_large_system_hash().
8819 */
8820static unsigned long __init arch_reserved_kernel_pages(void)
8821{
8822 return 0;
8823}
8824#endif
8825
9017217b
PT
8826/*
8827 * Adaptive scale is meant to reduce sizes of hash tables on large memory
8828 * machines. As memory size is increased the scale is also increased but at
8829 * slower pace. Starting from ADAPT_SCALE_BASE (64G), every time memory
8830 * quadruples the scale is increased by one, which means the size of hash table
8831 * only doubles, instead of quadrupling as well.
8832 * Because 32-bit systems cannot have large physical memory, where this scaling
8833 * makes sense, it is disabled on such platforms.
8834 */
8835#if __BITS_PER_LONG > 32
8836#define ADAPT_SCALE_BASE (64ul << 30)
8837#define ADAPT_SCALE_SHIFT 2
8838#define ADAPT_SCALE_NPAGES (ADAPT_SCALE_BASE >> PAGE_SHIFT)
8839#endif
8840
1da177e4
LT
8841/*
8842 * allocate a large system hash table from bootmem
8843 * - it is assumed that the hash table must contain an exact power-of-2
8844 * quantity of entries
8845 * - limit is the number of hash buckets, not the total allocation size
8846 */
8847void *__init alloc_large_system_hash(const char *tablename,
8848 unsigned long bucketsize,
8849 unsigned long numentries,
8850 int scale,
8851 int flags,
8852 unsigned int *_hash_shift,
8853 unsigned int *_hash_mask,
31fe62b9
TB
8854 unsigned long low_limit,
8855 unsigned long high_limit)
1da177e4 8856{
31fe62b9 8857 unsigned long long max = high_limit;
1da177e4
LT
8858 unsigned long log2qty, size;
8859 void *table = NULL;
3749a8f0 8860 gfp_t gfp_flags;
ec11408a 8861 bool virt;
121e6f32 8862 bool huge;
1da177e4
LT
8863
8864 /* allow the kernel cmdline to have a say */
8865 if (!numentries) {
8866 /* round applicable memory size up to nearest megabyte */
04903664 8867 numentries = nr_kernel_pages;
f6f34b43 8868 numentries -= arch_reserved_kernel_pages();
a7e83318
JZ
8869
8870 /* It isn't necessary when PAGE_SIZE >= 1MB */
8871 if (PAGE_SHIFT < 20)
8872 numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
1da177e4 8873
9017217b
PT
8874#if __BITS_PER_LONG > 32
8875 if (!high_limit) {
8876 unsigned long adapt;
8877
8878 for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
8879 adapt <<= ADAPT_SCALE_SHIFT)
8880 scale++;
8881 }
8882#endif
8883
1da177e4
LT
8884 /* limit to 1 bucket per 2^scale bytes of low memory */
8885 if (scale > PAGE_SHIFT)
8886 numentries >>= (scale - PAGE_SHIFT);
8887 else
8888 numentries <<= (PAGE_SHIFT - scale);
9ab37b8f
PM
8889
8890 /* Make sure we've got at least a 0-order allocation.. */
2c85f51d
JB
8891 if (unlikely(flags & HASH_SMALL)) {
8892 /* Makes no sense without HASH_EARLY */
8893 WARN_ON(!(flags & HASH_EARLY));
8894 if (!(numentries >> *_hash_shift)) {
8895 numentries = 1UL << *_hash_shift;
8896 BUG_ON(!numentries);
8897 }
8898 } else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
9ab37b8f 8899 numentries = PAGE_SIZE / bucketsize;
1da177e4 8900 }
6e692ed3 8901 numentries = roundup_pow_of_two(numentries);
1da177e4
LT
8902
8903 /* limit allocation size to 1/16 total memory by default */
8904 if (max == 0) {
8905 max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
8906 do_div(max, bucketsize);
8907 }
074b8517 8908 max = min(max, 0x80000000ULL);
1da177e4 8909
31fe62b9
TB
8910 if (numentries < low_limit)
8911 numentries = low_limit;
1da177e4
LT
8912 if (numentries > max)
8913 numentries = max;
8914
f0d1b0b3 8915 log2qty = ilog2(numentries);
1da177e4 8916
3749a8f0 8917 gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
1da177e4 8918 do {
ec11408a 8919 virt = false;
1da177e4 8920 size = bucketsize << log2qty;
ea1f5f37
PT
8921 if (flags & HASH_EARLY) {
8922 if (flags & HASH_ZERO)
26fb3dae 8923 table = memblock_alloc(size, SMP_CACHE_BYTES);
ea1f5f37 8924 else
7e1c4e27
MR
8925 table = memblock_alloc_raw(size,
8926 SMP_CACHE_BYTES);
ec11408a 8927 } else if (get_order(size) >= MAX_ORDER || hashdist) {
f2edd118 8928 table = vmalloc_huge(size, gfp_flags);
ec11408a 8929 virt = true;
084f7e23
ED
8930 if (table)
8931 huge = is_vm_area_hugepages(table);
ea1f5f37 8932 } else {
1037b83b
ED
8933 /*
8934 * If bucketsize is not a power-of-two, we may free
a1dd268c
MG
8935 * some pages at the end of hash table which
8936 * alloc_pages_exact() automatically does
1037b83b 8937 */
ec11408a
NP
8938 table = alloc_pages_exact(size, gfp_flags);
8939 kmemleak_alloc(table, size, 1, gfp_flags);
1da177e4
LT
8940 }
8941 } while (!table && size > PAGE_SIZE && --log2qty);
8942
8943 if (!table)
8944 panic("Failed to allocate %s hash table\n", tablename);
8945
ec11408a
NP
8946 pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n",
8947 tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size,
121e6f32 8948 virt ? (huge ? "vmalloc hugepage" : "vmalloc") : "linear");
1da177e4
LT
8949
8950 if (_hash_shift)
8951 *_hash_shift = log2qty;
8952 if (_hash_mask)
8953 *_hash_mask = (1 << log2qty) - 1;
8954
8955 return table;
8956}
a117e66e 8957
8df995f6 8958#ifdef CONFIG_CONTIG_ALLOC
041d3a8c
MN
8959static unsigned long pfn_max_align_down(unsigned long pfn)
8960{
b3d40a2b 8961 return ALIGN_DOWN(pfn, MAX_ORDER_NR_PAGES);
041d3a8c
MN
8962}
8963
8964static unsigned long pfn_max_align_up(unsigned long pfn)
8965{
b3d40a2b 8966 return ALIGN(pfn, MAX_ORDER_NR_PAGES);
041d3a8c
MN
8967}
8968
a1394bdd
MK
8969#if defined(CONFIG_DYNAMIC_DEBUG) || \
8970 (defined(CONFIG_DYNAMIC_DEBUG_CORE) && defined(DYNAMIC_DEBUG_MODULE))
8971/* Usage: See admin-guide/dynamic-debug-howto.rst */
8972static void alloc_contig_dump_pages(struct list_head *page_list)
8973{
8974 DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure");
8975
8976 if (DYNAMIC_DEBUG_BRANCH(descriptor)) {
8977 struct page *page;
8978
8979 dump_stack();
8980 list_for_each_entry(page, page_list, lru)
8981 dump_page(page, "migration failure");
8982 }
8983}
8984#else
8985static inline void alloc_contig_dump_pages(struct list_head *page_list)
8986{
8987}
8988#endif
8989
041d3a8c 8990/* [start, end) must belong to a single zone. */
b2c9e2fb 8991int __alloc_contig_migrate_range(struct compact_control *cc,
bb13ffeb 8992 unsigned long start, unsigned long end)
041d3a8c
MN
8993{
8994 /* This function is based on compact_zone() from compaction.c. */
730ec8c0 8995 unsigned int nr_reclaimed;
041d3a8c
MN
8996 unsigned long pfn = start;
8997 unsigned int tries = 0;
8998 int ret = 0;
8b94e0b8
JK
8999 struct migration_target_control mtc = {
9000 .nid = zone_to_nid(cc->zone),
9001 .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
9002 };
041d3a8c 9003
361a2a22 9004 lru_cache_disable();
041d3a8c 9005
bb13ffeb 9006 while (pfn < end || !list_empty(&cc->migratepages)) {
041d3a8c
MN
9007 if (fatal_signal_pending(current)) {
9008 ret = -EINTR;
9009 break;
9010 }
9011
bb13ffeb
MG
9012 if (list_empty(&cc->migratepages)) {
9013 cc->nr_migratepages = 0;
c2ad7a1f
OS
9014 ret = isolate_migratepages_range(cc, pfn, end);
9015 if (ret && ret != -EAGAIN)
041d3a8c 9016 break;
c2ad7a1f 9017 pfn = cc->migrate_pfn;
041d3a8c
MN
9018 tries = 0;
9019 } else if (++tries == 5) {
c8e28b47 9020 ret = -EBUSY;
041d3a8c
MN
9021 break;
9022 }
9023
beb51eaa
MK
9024 nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
9025 &cc->migratepages);
9026 cc->nr_migratepages -= nr_reclaimed;
02c6de8d 9027
8b94e0b8 9028 ret = migrate_pages(&cc->migratepages, alloc_migration_target,
5ac95884 9029 NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE, NULL);
c8e28b47
OS
9030
9031 /*
9032 * On -ENOMEM, migrate_pages() bails out right away. It is pointless
9033 * to retry again over this error, so do the same here.
9034 */
9035 if (ret == -ENOMEM)
9036 break;
041d3a8c 9037 }
d479960e 9038
361a2a22 9039 lru_cache_enable();
2a6f5124 9040 if (ret < 0) {
151e084a
MK
9041 if (ret == -EBUSY)
9042 alloc_contig_dump_pages(&cc->migratepages);
2a6f5124
SP
9043 putback_movable_pages(&cc->migratepages);
9044 return ret;
9045 }
9046 return 0;
041d3a8c
MN
9047}
9048
9049/**
9050 * alloc_contig_range() -- tries to allocate given range of pages
9051 * @start: start PFN to allocate
9052 * @end: one-past-the-last PFN to allocate
f0953a1b 9053 * @migratetype: migratetype of the underlying pageblocks (either
0815f3d8
MN
9054 * #MIGRATE_MOVABLE or #MIGRATE_CMA). All pageblocks
9055 * in range must have the same migratetype and it must
9056 * be either of the two.
ca96b625 9057 * @gfp_mask: GFP mask to use during compaction
041d3a8c
MN
9058 *
9059 * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
2c7452a0 9060 * aligned. The PFN range must belong to a single zone.
041d3a8c 9061 *
2c7452a0
MK
9062 * The first thing this routine does is attempt to MIGRATE_ISOLATE all
9063 * pageblocks in the range. Once isolated, the pageblocks should not
9064 * be modified by others.
041d3a8c 9065 *
a862f68a 9066 * Return: zero on success or negative error code. On success all
041d3a8c
MN
9067 * pages which PFN is in [start, end) are allocated for the caller and
9068 * need to be freed with free_contig_range().
9069 */
0815f3d8 9070int alloc_contig_range(unsigned long start, unsigned long end,
ca96b625 9071 unsigned migratetype, gfp_t gfp_mask)
041d3a8c 9072{
041d3a8c 9073 unsigned long outer_start, outer_end;
b2c9e2fb 9074 int order;
d00181b9 9075 int ret = 0;
041d3a8c 9076
bb13ffeb
MG
9077 struct compact_control cc = {
9078 .nr_migratepages = 0,
9079 .order = -1,
9080 .zone = page_zone(pfn_to_page(start)),
e0b9daeb 9081 .mode = MIGRATE_SYNC,
bb13ffeb 9082 .ignore_skip_hint = true,
2583d671 9083 .no_set_skip_hint = true,
7dea19f9 9084 .gfp_mask = current_gfp_context(gfp_mask),
b06eda09 9085 .alloc_contig = true,
bb13ffeb
MG
9086 };
9087 INIT_LIST_HEAD(&cc.migratepages);
9088
041d3a8c
MN
9089 /*
9090 * What we do here is we mark all pageblocks in range as
9091 * MIGRATE_ISOLATE. Because pageblock and max order pages may
9092 * have different sizes, and due to the way page allocator
b2c9e2fb 9093 * work, start_isolate_page_range() has special handlings for this.
041d3a8c
MN
9094 *
9095 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
9096 * migrate the pages from an unaligned range (ie. pages that
b2c9e2fb 9097 * we are interested in). This will put all the pages in
041d3a8c
MN
9098 * range back to page allocator as MIGRATE_ISOLATE.
9099 *
9100 * When this is done, we take the pages in range from page
9101 * allocator removing them from the buddy system. This way
9102 * page allocator will never consider using them.
9103 *
9104 * This lets us mark the pageblocks back as
9105 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
9106 * aligned range but not in the unaligned, original range are
9107 * put back to page allocator so that buddy can use them.
9108 */
9109
9110 ret = start_isolate_page_range(pfn_max_align_down(start),
b2c9e2fb 9111 pfn_max_align_up(end), migratetype, 0, gfp_mask);
3fa0c7c7 9112 if (ret)
b2c9e2fb 9113 goto done;
041d3a8c 9114
7612921f
VB
9115 drain_all_pages(cc.zone);
9116
8ef5849f
JK
9117 /*
9118 * In case of -EBUSY, we'd like to know which page causes problem.
63cd4489
MK
9119 * So, just fall through. test_pages_isolated() has a tracepoint
9120 * which will report the busy page.
9121 *
9122 * It is possible that busy pages could become available before
9123 * the call to test_pages_isolated, and the range will actually be
9124 * allocated. So, if we fall through be sure to clear ret so that
9125 * -EBUSY is not accidentally used or returned to caller.
8ef5849f 9126 */
bb13ffeb 9127 ret = __alloc_contig_migrate_range(&cc, start, end);
8ef5849f 9128 if (ret && ret != -EBUSY)
041d3a8c 9129 goto done;
68d68ff6 9130 ret = 0;
041d3a8c
MN
9131
9132 /*
b2c9e2fb 9133 * Pages from [start, end) are within a pageblock_nr_pages
041d3a8c
MN
9134 * aligned blocks that are marked as MIGRATE_ISOLATE. What's
9135 * more, all pages in [start, end) are free in page allocator.
9136 * What we are going to do is to allocate all pages from
9137 * [start, end) (that is remove them from page allocator).
9138 *
9139 * The only problem is that pages at the beginning and at the
9140 * end of interesting range may be not aligned with pages that
9141 * page allocator holds, ie. they can be part of higher order
9142 * pages. Because of this, we reserve the bigger range and
9143 * once this is done free the pages we are not interested in.
9144 *
9145 * We don't have to hold zone->lock here because the pages are
9146 * isolated thus they won't get removed from buddy.
9147 */
9148
041d3a8c
MN
9149 order = 0;
9150 outer_start = start;
9151 while (!PageBuddy(pfn_to_page(outer_start))) {
9152 if (++order >= MAX_ORDER) {
8ef5849f
JK
9153 outer_start = start;
9154 break;
041d3a8c
MN
9155 }
9156 outer_start &= ~0UL << order;
9157 }
9158
8ef5849f 9159 if (outer_start != start) {
ab130f91 9160 order = buddy_order(pfn_to_page(outer_start));
8ef5849f
JK
9161
9162 /*
9163 * outer_start page could be small order buddy page and
9164 * it doesn't include start page. Adjust outer_start
9165 * in this case to report failed page properly
9166 * on tracepoint in test_pages_isolated()
9167 */
9168 if (outer_start + (1UL << order) <= start)
9169 outer_start = start;
9170 }
9171
041d3a8c 9172 /* Make sure the range is really isolated. */
756d25be 9173 if (test_pages_isolated(outer_start, end, 0)) {
041d3a8c
MN
9174 ret = -EBUSY;
9175 goto done;
9176 }
9177
49f223a9 9178 /* Grab isolated pages from freelists. */
bb13ffeb 9179 outer_end = isolate_freepages_range(&cc, outer_start, end);
041d3a8c
MN
9180 if (!outer_end) {
9181 ret = -EBUSY;
9182 goto done;
9183 }
9184
9185 /* Free head and tail (if any) */
9186 if (start != outer_start)
9187 free_contig_range(outer_start, start - outer_start);
9188 if (end != outer_end)
9189 free_contig_range(end, outer_end - end);
9190
9191done:
9192 undo_isolate_page_range(pfn_max_align_down(start),
0815f3d8 9193 pfn_max_align_up(end), migratetype);
041d3a8c
MN
9194 return ret;
9195}
255f5985 9196EXPORT_SYMBOL(alloc_contig_range);
5e27a2df
AK
9197
9198static int __alloc_contig_pages(unsigned long start_pfn,
9199 unsigned long nr_pages, gfp_t gfp_mask)
9200{
9201 unsigned long end_pfn = start_pfn + nr_pages;
9202
9203 return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE,
9204 gfp_mask);
9205}
9206
9207static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn,
9208 unsigned long nr_pages)
9209{
9210 unsigned long i, end_pfn = start_pfn + nr_pages;
9211 struct page *page;
9212
9213 for (i = start_pfn; i < end_pfn; i++) {
9214 page = pfn_to_online_page(i);
9215 if (!page)
9216 return false;
9217
9218 if (page_zone(page) != z)
9219 return false;
9220
9221 if (PageReserved(page))
9222 return false;
5e27a2df
AK
9223 }
9224 return true;
9225}
9226
9227static bool zone_spans_last_pfn(const struct zone *zone,
9228 unsigned long start_pfn, unsigned long nr_pages)
9229{
9230 unsigned long last_pfn = start_pfn + nr_pages - 1;
9231
9232 return zone_spans_pfn(zone, last_pfn);
9233}
9234
9235/**
9236 * alloc_contig_pages() -- tries to find and allocate contiguous range of pages
9237 * @nr_pages: Number of contiguous pages to allocate
9238 * @gfp_mask: GFP mask to limit search and used during compaction
9239 * @nid: Target node
9240 * @nodemask: Mask for other possible nodes
9241 *
9242 * This routine is a wrapper around alloc_contig_range(). It scans over zones
9243 * on an applicable zonelist to find a contiguous pfn range which can then be
9244 * tried for allocation with alloc_contig_range(). This routine is intended
9245 * for allocation requests which can not be fulfilled with the buddy allocator.
9246 *
9247 * The allocated memory is always aligned to a page boundary. If nr_pages is a
eaab8e75
AK
9248 * power of two, then allocated range is also guaranteed to be aligned to same
9249 * nr_pages (e.g. 1GB request would be aligned to 1GB).
5e27a2df
AK
9250 *
9251 * Allocated pages can be freed with free_contig_range() or by manually calling
9252 * __free_page() on each allocated page.
9253 *
9254 * Return: pointer to contiguous pages on success, or NULL if not successful.
9255 */
9256struct page *alloc_contig_pages(unsigned long nr_pages, gfp_t gfp_mask,
9257 int nid, nodemask_t *nodemask)
9258{
9259 unsigned long ret, pfn, flags;
9260 struct zonelist *zonelist;
9261 struct zone *zone;
9262 struct zoneref *z;
9263
9264 zonelist = node_zonelist(nid, gfp_mask);
9265 for_each_zone_zonelist_nodemask(zone, z, zonelist,
9266 gfp_zone(gfp_mask), nodemask) {
9267 spin_lock_irqsave(&zone->lock, flags);
9268
9269 pfn = ALIGN(zone->zone_start_pfn, nr_pages);
9270 while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
9271 if (pfn_range_valid_contig(zone, pfn, nr_pages)) {
9272 /*
9273 * We release the zone lock here because
9274 * alloc_contig_range() will also lock the zone
9275 * at some point. If there's an allocation
9276 * spinning on this lock, it may win the race
9277 * and cause alloc_contig_range() to fail...
9278 */
9279 spin_unlock_irqrestore(&zone->lock, flags);
9280 ret = __alloc_contig_pages(pfn, nr_pages,
9281 gfp_mask);
9282 if (!ret)
9283 return pfn_to_page(pfn);
9284 spin_lock_irqsave(&zone->lock, flags);
9285 }
9286 pfn += nr_pages;
9287 }
9288 spin_unlock_irqrestore(&zone->lock, flags);
9289 }
9290 return NULL;
9291}
4eb0716e 9292#endif /* CONFIG_CONTIG_ALLOC */
041d3a8c 9293
78fa5150 9294void free_contig_range(unsigned long pfn, unsigned long nr_pages)
041d3a8c 9295{
78fa5150 9296 unsigned long count = 0;
bcc2b02f
MS
9297
9298 for (; nr_pages--; pfn++) {
9299 struct page *page = pfn_to_page(pfn);
9300
9301 count += page_count(page) != 1;
9302 __free_page(page);
9303 }
78fa5150 9304 WARN(count != 0, "%lu pages are still in use!\n", count);
041d3a8c 9305}
255f5985 9306EXPORT_SYMBOL(free_contig_range);
041d3a8c 9307
0a647f38
CS
9308/*
9309 * The zone indicated has a new number of managed_pages; batch sizes and percpu
f0953a1b 9310 * page high values need to be recalculated.
0a647f38 9311 */
04f8cfea 9312void zone_pcp_update(struct zone *zone, int cpu_online)
4ed7e022 9313{
c8e251fa 9314 mutex_lock(&pcp_batch_high_lock);
04f8cfea 9315 zone_set_pageset_high_and_batch(zone, cpu_online);
c8e251fa 9316 mutex_unlock(&pcp_batch_high_lock);
4ed7e022 9317}
4ed7e022 9318
ec6e8c7e
VB
9319/*
9320 * Effectively disable pcplists for the zone by setting the high limit to 0
9321 * and draining all cpus. A concurrent page freeing on another CPU that's about
9322 * to put the page on pcplist will either finish before the drain and the page
9323 * will be drained, or observe the new high limit and skip the pcplist.
9324 *
9325 * Must be paired with a call to zone_pcp_enable().
9326 */
9327void zone_pcp_disable(struct zone *zone)
9328{
9329 mutex_lock(&pcp_batch_high_lock);
9330 __zone_set_pageset_high_and_batch(zone, 0, 1);
9331 __drain_all_pages(zone, true);
9332}
9333
9334void zone_pcp_enable(struct zone *zone)
9335{
9336 __zone_set_pageset_high_and_batch(zone, zone->pageset_high, zone->pageset_batch);
9337 mutex_unlock(&pcp_batch_high_lock);
9338}
9339
340175b7
JL
9340void zone_pcp_reset(struct zone *zone)
9341{
5a883813 9342 int cpu;
28f836b6 9343 struct per_cpu_zonestat *pzstats;
340175b7 9344
28f836b6 9345 if (zone->per_cpu_pageset != &boot_pageset) {
5a883813 9346 for_each_online_cpu(cpu) {
28f836b6
MG
9347 pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
9348 drain_zonestat(zone, pzstats);
5a883813 9349 }
28f836b6
MG
9350 free_percpu(zone->per_cpu_pageset);
9351 free_percpu(zone->per_cpu_zonestats);
9352 zone->per_cpu_pageset = &boot_pageset;
9353 zone->per_cpu_zonestats = &boot_zonestats;
340175b7 9354 }
340175b7
JL
9355}
9356
6dcd73d7 9357#ifdef CONFIG_MEMORY_HOTREMOVE
0c0e6195 9358/*
257bea71
DH
9359 * All pages in the range must be in a single zone, must not contain holes,
9360 * must span full sections, and must be isolated before calling this function.
0c0e6195 9361 */
257bea71 9362void __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
0c0e6195 9363{
257bea71 9364 unsigned long pfn = start_pfn;
0c0e6195
KH
9365 struct page *page;
9366 struct zone *zone;
0ee5f4f3 9367 unsigned int order;
0c0e6195 9368 unsigned long flags;
5557c766 9369
2d070eab 9370 offline_mem_sections(pfn, end_pfn);
0c0e6195
KH
9371 zone = page_zone(pfn_to_page(pfn));
9372 spin_lock_irqsave(&zone->lock, flags);
0c0e6195 9373 while (pfn < end_pfn) {
0c0e6195 9374 page = pfn_to_page(pfn);
b023f468
WC
9375 /*
9376 * The HWPoisoned page may be not in buddy system, and
9377 * page_count() is not 0.
9378 */
9379 if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
9380 pfn++;
b023f468
WC
9381 continue;
9382 }
aa218795
DH
9383 /*
9384 * At this point all remaining PageOffline() pages have a
9385 * reference count of 0 and can simply be skipped.
9386 */
9387 if (PageOffline(page)) {
9388 BUG_ON(page_count(page));
9389 BUG_ON(PageBuddy(page));
9390 pfn++;
aa218795
DH
9391 continue;
9392 }
b023f468 9393
0c0e6195
KH
9394 BUG_ON(page_count(page));
9395 BUG_ON(!PageBuddy(page));
ab130f91 9396 order = buddy_order(page);
6ab01363 9397 del_page_from_free_list(page, zone, order);
0c0e6195
KH
9398 pfn += (1 << order);
9399 }
9400 spin_unlock_irqrestore(&zone->lock, flags);
9401}
9402#endif
8d22ba1b 9403
8446b59b
ED
9404/*
9405 * This function returns a stable result only if called under zone lock.
9406 */
8d22ba1b
WF
9407bool is_free_buddy_page(struct page *page)
9408{
8d22ba1b 9409 unsigned long pfn = page_to_pfn(page);
7aeb09f9 9410 unsigned int order;
8d22ba1b 9411
8d22ba1b
WF
9412 for (order = 0; order < MAX_ORDER; order++) {
9413 struct page *page_head = page - (pfn & ((1 << order) - 1));
9414
8446b59b
ED
9415 if (PageBuddy(page_head) &&
9416 buddy_order_unsafe(page_head) >= order)
8d22ba1b
WF
9417 break;
9418 }
8d22ba1b
WF
9419
9420 return order < MAX_ORDER;
9421}
a581865e 9422EXPORT_SYMBOL(is_free_buddy_page);
d4ae9916
NH
9423
9424#ifdef CONFIG_MEMORY_FAILURE
9425/*
06be6ff3
OS
9426 * Break down a higher-order page in sub-pages, and keep our target out of
9427 * buddy allocator.
d4ae9916 9428 */
06be6ff3
OS
9429static void break_down_buddy_pages(struct zone *zone, struct page *page,
9430 struct page *target, int low, int high,
9431 int migratetype)
9432{
9433 unsigned long size = 1 << high;
9434 struct page *current_buddy, *next_page;
9435
9436 while (high > low) {
9437 high--;
9438 size >>= 1;
9439
9440 if (target >= &page[size]) {
9441 next_page = page + size;
9442 current_buddy = page;
9443 } else {
9444 next_page = page;
9445 current_buddy = page + size;
9446 }
9447
9448 if (set_page_guard(zone, current_buddy, high, migratetype))
9449 continue;
9450
9451 if (current_buddy != target) {
9452 add_to_free_list(current_buddy, zone, high, migratetype);
ab130f91 9453 set_buddy_order(current_buddy, high);
06be6ff3
OS
9454 page = next_page;
9455 }
9456 }
9457}
9458
9459/*
9460 * Take a page that will be marked as poisoned off the buddy allocator.
9461 */
9462bool take_page_off_buddy(struct page *page)
d4ae9916
NH
9463{
9464 struct zone *zone = page_zone(page);
9465 unsigned long pfn = page_to_pfn(page);
9466 unsigned long flags;
9467 unsigned int order;
06be6ff3 9468 bool ret = false;
d4ae9916
NH
9469
9470 spin_lock_irqsave(&zone->lock, flags);
9471 for (order = 0; order < MAX_ORDER; order++) {
9472 struct page *page_head = page - (pfn & ((1 << order) - 1));
ab130f91 9473 int page_order = buddy_order(page_head);
d4ae9916 9474
ab130f91 9475 if (PageBuddy(page_head) && page_order >= order) {
06be6ff3
OS
9476 unsigned long pfn_head = page_to_pfn(page_head);
9477 int migratetype = get_pfnblock_migratetype(page_head,
9478 pfn_head);
9479
ab130f91 9480 del_page_from_free_list(page_head, zone, page_order);
06be6ff3 9481 break_down_buddy_pages(zone, page_head, page, 0,
ab130f91 9482 page_order, migratetype);
bf181c58 9483 SetPageHWPoisonTakenOff(page);
bac9c6fa
DH
9484 if (!is_migrate_isolate(migratetype))
9485 __mod_zone_freepage_state(zone, -1, migratetype);
06be6ff3 9486 ret = true;
d4ae9916
NH
9487 break;
9488 }
06be6ff3
OS
9489 if (page_count(page_head) > 0)
9490 break;
d4ae9916
NH
9491 }
9492 spin_unlock_irqrestore(&zone->lock, flags);
06be6ff3 9493 return ret;
d4ae9916 9494}
bf181c58
NH
9495
9496/*
9497 * Cancel takeoff done by take_page_off_buddy().
9498 */
9499bool put_page_back_buddy(struct page *page)
9500{
9501 struct zone *zone = page_zone(page);
9502 unsigned long pfn = page_to_pfn(page);
9503 unsigned long flags;
9504 int migratetype = get_pfnblock_migratetype(page, pfn);
9505 bool ret = false;
9506
9507 spin_lock_irqsave(&zone->lock, flags);
9508 if (put_page_testzero(page)) {
9509 ClearPageHWPoisonTakenOff(page);
9510 __free_one_page(page, pfn, zone, 0, migratetype, FPI_NONE);
9511 if (TestClearPageHWPoison(page)) {
9512 num_poisoned_pages_dec();
9513 ret = true;
9514 }
9515 }
9516 spin_unlock_irqrestore(&zone->lock, flags);
9517
9518 return ret;
9519}
d4ae9916 9520#endif
62b31070
BH
9521
9522#ifdef CONFIG_ZONE_DMA
9523bool has_managed_dma(void)
9524{
9525 struct pglist_data *pgdat;
9526
9527 for_each_online_pgdat(pgdat) {
9528 struct zone *zone = &pgdat->node_zones[ZONE_DMA];
9529
9530 if (managed_zone(zone))
9531 return true;
9532 }
9533 return false;
9534}
9535#endif /* CONFIG_ZONE_DMA */