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