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