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