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