xref: /linux/mm/page_alloc.c (revision 69050f8d6d075dc01af7a5f2f550a8067510366f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *
4  *  Manages the free list, the system allocates free pages here.
5  *  Note that kmalloc() lives in slab.c
6  *
7  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
8  *  Swap reorganised 29.12.95, Stephen Tweedie
9  *  Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
10  *  Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999
11  *  Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999
12  *  Zone balancing, Kanoj Sarcar, SGI, Jan 2000
13  *  Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002
14  *          (lots of bits borrowed from Ingo Molnar & Andrew Morton)
15  */
16 
17 #include <linux/stddef.h>
18 #include <linux/mm.h>
19 #include <linux/highmem.h>
20 #include <linux/interrupt.h>
21 #include <linux/jiffies.h>
22 #include <linux/compiler.h>
23 #include <linux/kernel.h>
24 #include <linux/kasan.h>
25 #include <linux/kmsan.h>
26 #include <linux/module.h>
27 #include <linux/suspend.h>
28 #include <linux/ratelimit.h>
29 #include <linux/oom.h>
30 #include <linux/topology.h>
31 #include <linux/sysctl.h>
32 #include <linux/cpu.h>
33 #include <linux/cpuset.h>
34 #include <linux/pagevec.h>
35 #include <linux/memory_hotplug.h>
36 #include <linux/nodemask.h>
37 #include <linux/vmstat.h>
38 #include <linux/fault-inject.h>
39 #include <linux/compaction.h>
40 #include <trace/events/kmem.h>
41 #include <trace/events/oom.h>
42 #include <linux/prefetch.h>
43 #include <linux/mm_inline.h>
44 #include <linux/mmu_notifier.h>
45 #include <linux/migrate.h>
46 #include <linux/sched/mm.h>
47 #include <linux/page_owner.h>
48 #include <linux/page_table_check.h>
49 #include <linux/memcontrol.h>
50 #include <linux/ftrace.h>
51 #include <linux/lockdep.h>
52 #include <linux/psi.h>
53 #include <linux/khugepaged.h>
54 #include <linux/delayacct.h>
55 #include <linux/cacheinfo.h>
56 #include <linux/pgalloc_tag.h>
57 #include <asm/div64.h>
58 #include "internal.h"
59 #include "shuffle.h"
60 #include "page_reporting.h"
61 
62 /* Free Page Internal flags: for internal, non-pcp variants of free_pages(). */
63 typedef int __bitwise fpi_t;
64 
65 /* No special request */
66 #define FPI_NONE		((__force fpi_t)0)
67 
68 /*
69  * Skip free page reporting notification for the (possibly merged) page.
70  * This does not hinder free page reporting from grabbing the page,
71  * reporting it and marking it "reported" -  it only skips notifying
72  * the free page reporting infrastructure about a newly freed page. For
73  * example, used when temporarily pulling a page from a freelist and
74  * putting it back unmodified.
75  */
76 #define FPI_SKIP_REPORT_NOTIFY	((__force fpi_t)BIT(0))
77 
78 /*
79  * Place the (possibly merged) page to the tail of the freelist. Will ignore
80  * page shuffling (relevant code - e.g., memory onlining - is expected to
81  * shuffle the whole zone).
82  *
83  * Note: No code should rely on this flag for correctness - it's purely
84  *       to allow for optimizations when handing back either fresh pages
85  *       (memory onlining) or untouched pages (page isolation, free page
86  *       reporting).
87  */
88 #define FPI_TO_TAIL		((__force fpi_t)BIT(1))
89 
90 /* Free the page without taking locks. Rely on trylock only. */
91 #define FPI_TRYLOCK		((__force fpi_t)BIT(2))
92 
93 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
94 static DEFINE_MUTEX(pcp_batch_high_lock);
95 #define MIN_PERCPU_PAGELIST_HIGH_FRACTION (8)
96 
97 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT_RT)
98 /*
99  * On SMP, spin_trylock is sufficient protection.
100  * On PREEMPT_RT, spin_trylock is equivalent on both SMP and UP.
101  * Pass flags to a no-op inline function to typecheck and silence the unused
102  * variable warning.
103  */
104 static inline void __pcp_trylock_noop(unsigned long *flags) { }
105 #define pcp_trylock_prepare(flags)	__pcp_trylock_noop(&(flags))
106 #define pcp_trylock_finish(flags)	__pcp_trylock_noop(&(flags))
107 #else
108 
109 /* UP spin_trylock always succeeds so disable IRQs to prevent re-entrancy. */
110 #define pcp_trylock_prepare(flags)	local_irq_save(flags)
111 #define pcp_trylock_finish(flags)	local_irq_restore(flags)
112 #endif
113 
114 /*
115  * Locking a pcp requires a PCP lookup followed by a spinlock. To avoid
116  * a migration causing the wrong PCP to be locked and remote memory being
117  * potentially allocated, pin the task to the CPU for the lookup+lock.
118  * preempt_disable is used on !RT because it is faster than migrate_disable.
119  * migrate_disable is used on RT because otherwise RT spinlock usage is
120  * interfered with and a high priority task cannot preempt the allocator.
121  */
122 #ifndef CONFIG_PREEMPT_RT
123 #define pcpu_task_pin()		preempt_disable()
124 #define pcpu_task_unpin()	preempt_enable()
125 #else
126 #define pcpu_task_pin()		migrate_disable()
127 #define pcpu_task_unpin()	migrate_enable()
128 #endif
129 
130 /*
131  * Generic helper to lookup and a per-cpu variable with an embedded spinlock.
132  * Return value should be used with equivalent unlock helper.
133  */
134 #define pcpu_spin_trylock(type, member, ptr)				\
135 ({									\
136 	type *_ret;							\
137 	pcpu_task_pin();						\
138 	_ret = this_cpu_ptr(ptr);					\
139 	if (!spin_trylock(&_ret->member)) {				\
140 		pcpu_task_unpin();					\
141 		_ret = NULL;						\
142 	}								\
143 	_ret;								\
144 })
145 
146 #define pcpu_spin_unlock(member, ptr)					\
147 ({									\
148 	spin_unlock(&ptr->member);					\
149 	pcpu_task_unpin();						\
150 })
151 
152 /* struct per_cpu_pages specific helpers. */
153 #define pcp_spin_trylock(ptr, UP_flags)					\
154 ({									\
155 	struct per_cpu_pages *__ret;					\
156 	pcp_trylock_prepare(UP_flags);					\
157 	__ret = pcpu_spin_trylock(struct per_cpu_pages, lock, ptr);	\
158 	if (!__ret)							\
159 		pcp_trylock_finish(UP_flags);				\
160 	__ret;								\
161 })
162 
163 #define pcp_spin_unlock(ptr, UP_flags)					\
164 ({									\
165 	pcpu_spin_unlock(lock, ptr);					\
166 	pcp_trylock_finish(UP_flags);					\
167 })
168 
169 /*
170  * With the UP spinlock implementation, when we spin_lock(&pcp->lock) (for i.e.
171  * a potentially remote cpu drain) and get interrupted by an operation that
172  * attempts pcp_spin_trylock(), we can't rely on the trylock failure due to UP
173  * spinlock assumptions making the trylock a no-op. So we have to turn that
174  * spin_lock() to a spin_lock_irqsave(). This works because on UP there are no
175  * remote cpu's so we can only be locking the only existing local one.
176  */
177 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT_RT)
178 static inline void __flags_noop(unsigned long *flags) { }
179 #define pcp_spin_lock_maybe_irqsave(ptr, flags)		\
180 ({							\
181 	 __flags_noop(&(flags));			\
182 	 spin_lock(&(ptr)->lock);			\
183 })
184 #define pcp_spin_unlock_maybe_irqrestore(ptr, flags)	\
185 ({							\
186 	 spin_unlock(&(ptr)->lock);			\
187 	 __flags_noop(&(flags));			\
188 })
189 #else
190 #define pcp_spin_lock_maybe_irqsave(ptr, flags)		\
191 		spin_lock_irqsave(&(ptr)->lock, flags)
192 #define pcp_spin_unlock_maybe_irqrestore(ptr, flags)	\
193 		spin_unlock_irqrestore(&(ptr)->lock, flags)
194 #endif
195 
196 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
197 DEFINE_PER_CPU(int, numa_node);
198 EXPORT_PER_CPU_SYMBOL(numa_node);
199 #endif
200 
201 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
202 
203 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
204 /*
205  * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
206  * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
207  * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
208  * defined in <linux/topology.h>.
209  */
210 DEFINE_PER_CPU(int, _numa_mem_);		/* Kernel "local memory" node */
211 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
212 #endif
213 
214 static DEFINE_MUTEX(pcpu_drain_mutex);
215 
216 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
217 volatile unsigned long latent_entropy __latent_entropy;
218 EXPORT_SYMBOL(latent_entropy);
219 #endif
220 
221 /*
222  * Array of node states.
223  */
224 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
225 	[N_POSSIBLE] = NODE_MASK_ALL,
226 	[N_ONLINE] = { { [0] = 1UL } },
227 #ifndef CONFIG_NUMA
228 	[N_NORMAL_MEMORY] = { { [0] = 1UL } },
229 #ifdef CONFIG_HIGHMEM
230 	[N_HIGH_MEMORY] = { { [0] = 1UL } },
231 #endif
232 	[N_MEMORY] = { { [0] = 1UL } },
233 	[N_CPU] = { { [0] = 1UL } },
234 #endif	/* NUMA */
235 };
236 EXPORT_SYMBOL(node_states);
237 
238 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
239 
240 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
241 unsigned int pageblock_order __read_mostly;
242 #endif
243 
244 static void __free_pages_ok(struct page *page, unsigned int order,
245 			    fpi_t fpi_flags);
246 
247 /*
248  * results with 256, 32 in the lowmem_reserve sysctl:
249  *	1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
250  *	1G machine -> (16M dma, 784M normal, 224M high)
251  *	NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
252  *	HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
253  *	HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
254  *
255  * TBD: should special case ZONE_DMA32 machines here - in those we normally
256  * don't need any ZONE_NORMAL reservation
257  */
258 static int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
259 #ifdef CONFIG_ZONE_DMA
260 	[ZONE_DMA] = 256,
261 #endif
262 #ifdef CONFIG_ZONE_DMA32
263 	[ZONE_DMA32] = 256,
264 #endif
265 	[ZONE_NORMAL] = 32,
266 #ifdef CONFIG_HIGHMEM
267 	[ZONE_HIGHMEM] = 0,
268 #endif
269 	[ZONE_MOVABLE] = 0,
270 };
271 
272 char * const zone_names[MAX_NR_ZONES] = {
273 #ifdef CONFIG_ZONE_DMA
274 	 "DMA",
275 #endif
276 #ifdef CONFIG_ZONE_DMA32
277 	 "DMA32",
278 #endif
279 	 "Normal",
280 #ifdef CONFIG_HIGHMEM
281 	 "HighMem",
282 #endif
283 	 "Movable",
284 #ifdef CONFIG_ZONE_DEVICE
285 	 "Device",
286 #endif
287 };
288 
289 const char * const migratetype_names[MIGRATE_TYPES] = {
290 	"Unmovable",
291 	"Movable",
292 	"Reclaimable",
293 	"HighAtomic",
294 #ifdef CONFIG_CMA
295 	"CMA",
296 #endif
297 #ifdef CONFIG_MEMORY_ISOLATION
298 	"Isolate",
299 #endif
300 };
301 
302 int min_free_kbytes = 1024;
303 int user_min_free_kbytes = -1;
304 static int watermark_boost_factor __read_mostly = 15000;
305 static int watermark_scale_factor = 10;
306 int defrag_mode;
307 
308 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
309 int movable_zone;
310 EXPORT_SYMBOL(movable_zone);
311 
312 #if MAX_NUMNODES > 1
313 unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
314 unsigned int nr_online_nodes __read_mostly = 1;
315 EXPORT_SYMBOL(nr_node_ids);
316 EXPORT_SYMBOL(nr_online_nodes);
317 #endif
318 
319 static bool page_contains_unaccepted(struct page *page, unsigned int order);
320 static bool cond_accept_memory(struct zone *zone, unsigned int order,
321 			       int alloc_flags);
322 static bool __free_unaccepted(struct page *page);
323 
324 int page_group_by_mobility_disabled __read_mostly;
325 
326 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
327 /*
328  * During boot we initialize deferred pages on-demand, as needed, but once
329  * page_alloc_init_late() has finished, the deferred pages are all initialized,
330  * and we can permanently disable that path.
331  */
332 DEFINE_STATIC_KEY_TRUE(deferred_pages);
333 
334 static inline bool deferred_pages_enabled(void)
335 {
336 	return static_branch_unlikely(&deferred_pages);
337 }
338 
339 /*
340  * deferred_grow_zone() is __init, but it is called from
341  * get_page_from_freelist() during early boot until deferred_pages permanently
342  * disables this call. This is why we have refdata wrapper to avoid warning,
343  * and to ensure that the function body gets unloaded.
344  */
345 static bool __ref
346 _deferred_grow_zone(struct zone *zone, unsigned int order)
347 {
348 	return deferred_grow_zone(zone, order);
349 }
350 #else
351 static inline bool deferred_pages_enabled(void)
352 {
353 	return false;
354 }
355 
356 static inline bool _deferred_grow_zone(struct zone *zone, unsigned int order)
357 {
358 	return false;
359 }
360 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
361 
362 /* Return a pointer to the bitmap storing bits affecting a block of pages */
363 static inline unsigned long *get_pageblock_bitmap(const struct page *page,
364 							unsigned long pfn)
365 {
366 #ifdef CONFIG_SPARSEMEM
367 	return section_to_usemap(__pfn_to_section(pfn));
368 #else
369 	return page_zone(page)->pageblock_flags;
370 #endif /* CONFIG_SPARSEMEM */
371 }
372 
373 static inline int pfn_to_bitidx(const struct page *page, unsigned long pfn)
374 {
375 #ifdef CONFIG_SPARSEMEM
376 	pfn &= (PAGES_PER_SECTION-1);
377 #else
378 	pfn = pfn - pageblock_start_pfn(page_zone(page)->zone_start_pfn);
379 #endif /* CONFIG_SPARSEMEM */
380 	return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
381 }
382 
383 static __always_inline bool is_standalone_pb_bit(enum pageblock_bits pb_bit)
384 {
385 	return pb_bit >= PB_compact_skip && pb_bit < __NR_PAGEBLOCK_BITS;
386 }
387 
388 static __always_inline void
389 get_pfnblock_bitmap_bitidx(const struct page *page, unsigned long pfn,
390 			   unsigned long **bitmap_word, unsigned long *bitidx)
391 {
392 	unsigned long *bitmap;
393 	unsigned long word_bitidx;
394 
395 #ifdef CONFIG_MEMORY_ISOLATION
396 	BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 8);
397 #else
398 	BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
399 #endif
400 	BUILD_BUG_ON(__MIGRATE_TYPE_END > MIGRATETYPE_MASK);
401 	VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
402 
403 	bitmap = get_pageblock_bitmap(page, pfn);
404 	*bitidx = pfn_to_bitidx(page, pfn);
405 	word_bitidx = *bitidx / BITS_PER_LONG;
406 	*bitidx &= (BITS_PER_LONG - 1);
407 	*bitmap_word = &bitmap[word_bitidx];
408 }
409 
410 
411 /**
412  * __get_pfnblock_flags_mask - Return the requested group of flags for
413  * a pageblock_nr_pages block of pages
414  * @page: The page within the block of interest
415  * @pfn: The target page frame number
416  * @mask: mask of bits that the caller is interested in
417  *
418  * Return: pageblock_bits flags
419  */
420 static unsigned long __get_pfnblock_flags_mask(const struct page *page,
421 					       unsigned long pfn,
422 					       unsigned long mask)
423 {
424 	unsigned long *bitmap_word;
425 	unsigned long bitidx;
426 	unsigned long word;
427 
428 	get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx);
429 	/*
430 	 * This races, without locks, with set_pfnblock_migratetype(). Ensure
431 	 * a consistent read of the memory array, so that results, even though
432 	 * racy, are not corrupted.
433 	 */
434 	word = READ_ONCE(*bitmap_word);
435 	return (word >> bitidx) & mask;
436 }
437 
438 /**
439  * get_pfnblock_bit - Check if a standalone bit of a pageblock is set
440  * @page: The page within the block of interest
441  * @pfn: The target page frame number
442  * @pb_bit: pageblock bit to check
443  *
444  * Return: true if the bit is set, otherwise false
445  */
446 bool get_pfnblock_bit(const struct page *page, unsigned long pfn,
447 		      enum pageblock_bits pb_bit)
448 {
449 	unsigned long *bitmap_word;
450 	unsigned long bitidx;
451 
452 	if (WARN_ON_ONCE(!is_standalone_pb_bit(pb_bit)))
453 		return false;
454 
455 	get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx);
456 
457 	return test_bit(bitidx + pb_bit, bitmap_word);
458 }
459 
460 /**
461  * get_pfnblock_migratetype - Return the migratetype of a pageblock
462  * @page: The page within the block of interest
463  * @pfn: The target page frame number
464  *
465  * Return: The migratetype of the pageblock
466  *
467  * Use get_pfnblock_migratetype() if caller already has both @page and @pfn
468  * to save a call to page_to_pfn().
469  */
470 __always_inline enum migratetype
471 get_pfnblock_migratetype(const struct page *page, unsigned long pfn)
472 {
473 	unsigned long mask = MIGRATETYPE_AND_ISO_MASK;
474 	unsigned long flags;
475 
476 	flags = __get_pfnblock_flags_mask(page, pfn, mask);
477 
478 #ifdef CONFIG_MEMORY_ISOLATION
479 	if (flags & BIT(PB_migrate_isolate))
480 		return MIGRATE_ISOLATE;
481 #endif
482 	return flags & MIGRATETYPE_MASK;
483 }
484 
485 /**
486  * __set_pfnblock_flags_mask - Set the requested group of flags for
487  * a pageblock_nr_pages block of pages
488  * @page: The page within the block of interest
489  * @pfn: The target page frame number
490  * @flags: The flags to set
491  * @mask: mask of bits that the caller is interested in
492  */
493 static void __set_pfnblock_flags_mask(struct page *page, unsigned long pfn,
494 				      unsigned long flags, unsigned long mask)
495 {
496 	unsigned long *bitmap_word;
497 	unsigned long bitidx;
498 	unsigned long word;
499 
500 	get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx);
501 
502 	mask <<= bitidx;
503 	flags <<= bitidx;
504 
505 	word = READ_ONCE(*bitmap_word);
506 	do {
507 	} while (!try_cmpxchg(bitmap_word, &word, (word & ~mask) | flags));
508 }
509 
510 /**
511  * set_pfnblock_bit - Set a standalone bit of a pageblock
512  * @page: The page within the block of interest
513  * @pfn: The target page frame number
514  * @pb_bit: pageblock bit to set
515  */
516 void set_pfnblock_bit(const struct page *page, unsigned long pfn,
517 		      enum pageblock_bits pb_bit)
518 {
519 	unsigned long *bitmap_word;
520 	unsigned long bitidx;
521 
522 	if (WARN_ON_ONCE(!is_standalone_pb_bit(pb_bit)))
523 		return;
524 
525 	get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx);
526 
527 	set_bit(bitidx + pb_bit, bitmap_word);
528 }
529 
530 /**
531  * clear_pfnblock_bit - Clear a standalone bit of a pageblock
532  * @page: The page within the block of interest
533  * @pfn: The target page frame number
534  * @pb_bit: pageblock bit to clear
535  */
536 void clear_pfnblock_bit(const struct page *page, unsigned long pfn,
537 			enum pageblock_bits pb_bit)
538 {
539 	unsigned long *bitmap_word;
540 	unsigned long bitidx;
541 
542 	if (WARN_ON_ONCE(!is_standalone_pb_bit(pb_bit)))
543 		return;
544 
545 	get_pfnblock_bitmap_bitidx(page, pfn, &bitmap_word, &bitidx);
546 
547 	clear_bit(bitidx + pb_bit, bitmap_word);
548 }
549 
550 /**
551  * set_pageblock_migratetype - Set the migratetype of a pageblock
552  * @page: The page within the block of interest
553  * @migratetype: migratetype to set
554  */
555 static void set_pageblock_migratetype(struct page *page,
556 				      enum migratetype migratetype)
557 {
558 	if (unlikely(page_group_by_mobility_disabled &&
559 		     migratetype < MIGRATE_PCPTYPES))
560 		migratetype = MIGRATE_UNMOVABLE;
561 
562 #ifdef CONFIG_MEMORY_ISOLATION
563 	if (migratetype == MIGRATE_ISOLATE) {
564 		VM_WARN_ONCE(1,
565 			"Use set_pageblock_isolate() for pageblock isolation");
566 		return;
567 	}
568 	VM_WARN_ONCE(get_pageblock_isolate(page),
569 		     "Use clear_pageblock_isolate() to unisolate pageblock");
570 	/* MIGRATETYPE_AND_ISO_MASK clears PB_migrate_isolate if it is set */
571 #endif
572 	__set_pfnblock_flags_mask(page, page_to_pfn(page),
573 				  (unsigned long)migratetype,
574 				  MIGRATETYPE_AND_ISO_MASK);
575 }
576 
577 void __meminit init_pageblock_migratetype(struct page *page,
578 					  enum migratetype migratetype,
579 					  bool isolate)
580 {
581 	unsigned long flags;
582 
583 	if (unlikely(page_group_by_mobility_disabled &&
584 		     migratetype < MIGRATE_PCPTYPES))
585 		migratetype = MIGRATE_UNMOVABLE;
586 
587 	flags = migratetype;
588 
589 #ifdef CONFIG_MEMORY_ISOLATION
590 	if (migratetype == MIGRATE_ISOLATE) {
591 		VM_WARN_ONCE(
592 			1,
593 			"Set isolate=true to isolate pageblock with a migratetype");
594 		return;
595 	}
596 	if (isolate)
597 		flags |= BIT(PB_migrate_isolate);
598 #endif
599 	__set_pfnblock_flags_mask(page, page_to_pfn(page), flags,
600 				  MIGRATETYPE_AND_ISO_MASK);
601 }
602 
603 #ifdef CONFIG_DEBUG_VM
604 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
605 {
606 	int ret;
607 	unsigned seq;
608 	unsigned long pfn = page_to_pfn(page);
609 	unsigned long sp, start_pfn;
610 
611 	do {
612 		seq = zone_span_seqbegin(zone);
613 		start_pfn = zone->zone_start_pfn;
614 		sp = zone->spanned_pages;
615 		ret = !zone_spans_pfn(zone, pfn);
616 	} while (zone_span_seqretry(zone, seq));
617 
618 	if (ret)
619 		pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
620 			pfn, zone_to_nid(zone), zone->name,
621 			start_pfn, start_pfn + sp);
622 
623 	return ret;
624 }
625 
626 /*
627  * Temporary debugging check for pages not lying within a given zone.
628  */
629 static bool __maybe_unused bad_range(struct zone *zone, struct page *page)
630 {
631 	if (page_outside_zone_boundaries(zone, page))
632 		return true;
633 	if (zone != page_zone(page))
634 		return true;
635 
636 	return false;
637 }
638 #else
639 static inline bool __maybe_unused bad_range(struct zone *zone, struct page *page)
640 {
641 	return false;
642 }
643 #endif
644 
645 static void bad_page(struct page *page, const char *reason)
646 {
647 	static unsigned long resume;
648 	static unsigned long nr_shown;
649 	static unsigned long nr_unshown;
650 
651 	/*
652 	 * Allow a burst of 60 reports, then keep quiet for that minute;
653 	 * or allow a steady drip of one report per second.
654 	 */
655 	if (nr_shown == 60) {
656 		if (time_before(jiffies, resume)) {
657 			nr_unshown++;
658 			goto out;
659 		}
660 		if (nr_unshown) {
661 			pr_alert(
662 			      "BUG: Bad page state: %lu messages suppressed\n",
663 				nr_unshown);
664 			nr_unshown = 0;
665 		}
666 		nr_shown = 0;
667 	}
668 	if (nr_shown++ == 0)
669 		resume = jiffies + 60 * HZ;
670 
671 	pr_alert("BUG: Bad page state in process %s  pfn:%05lx\n",
672 		current->comm, page_to_pfn(page));
673 	dump_page(page, reason);
674 
675 	print_modules();
676 	dump_stack();
677 out:
678 	/* Leave bad fields for debug, except PageBuddy could make trouble */
679 	if (PageBuddy(page))
680 		__ClearPageBuddy(page);
681 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
682 }
683 
684 static inline unsigned int order_to_pindex(int migratetype, int order)
685 {
686 
687 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
688 	bool movable;
689 	if (order > PAGE_ALLOC_COSTLY_ORDER) {
690 		VM_BUG_ON(order != HPAGE_PMD_ORDER);
691 
692 		movable = migratetype == MIGRATE_MOVABLE;
693 
694 		return NR_LOWORDER_PCP_LISTS + movable;
695 	}
696 #else
697 	VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER);
698 #endif
699 
700 	return (MIGRATE_PCPTYPES * order) + migratetype;
701 }
702 
703 static inline int pindex_to_order(unsigned int pindex)
704 {
705 	int order = pindex / MIGRATE_PCPTYPES;
706 
707 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
708 	if (pindex >= NR_LOWORDER_PCP_LISTS)
709 		order = HPAGE_PMD_ORDER;
710 #else
711 	VM_BUG_ON(order > PAGE_ALLOC_COSTLY_ORDER);
712 #endif
713 
714 	return order;
715 }
716 
717 static inline bool pcp_allowed_order(unsigned int order)
718 {
719 	if (order <= PAGE_ALLOC_COSTLY_ORDER)
720 		return true;
721 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
722 	if (order == HPAGE_PMD_ORDER)
723 		return true;
724 #endif
725 	return false;
726 }
727 
728 /*
729  * Higher-order pages are called "compound pages".  They are structured thusly:
730  *
731  * The first PAGE_SIZE page is called the "head page" and have PG_head set.
732  *
733  * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
734  * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
735  *
736  * The first tail page's ->compound_order holds the order of allocation.
737  * This usage means that zero-order pages may not be compound.
738  */
739 
740 void prep_compound_page(struct page *page, unsigned int order)
741 {
742 	int i;
743 	int nr_pages = 1 << order;
744 
745 	__SetPageHead(page);
746 	for (i = 1; i < nr_pages; i++)
747 		prep_compound_tail(page, i);
748 
749 	prep_compound_head(page, order);
750 }
751 
752 static inline void set_buddy_order(struct page *page, unsigned int order)
753 {
754 	set_page_private(page, order);
755 	__SetPageBuddy(page);
756 }
757 
758 #ifdef CONFIG_COMPACTION
759 static inline struct capture_control *task_capc(struct zone *zone)
760 {
761 	struct capture_control *capc = current->capture_control;
762 
763 	return unlikely(capc) &&
764 		!(current->flags & PF_KTHREAD) &&
765 		!capc->page &&
766 		capc->cc->zone == zone ? capc : NULL;
767 }
768 
769 static inline bool
770 compaction_capture(struct capture_control *capc, struct page *page,
771 		   int order, int migratetype)
772 {
773 	if (!capc || order != capc->cc->order)
774 		return false;
775 
776 	/* Do not accidentally pollute CMA or isolated regions*/
777 	if (is_migrate_cma(migratetype) ||
778 	    is_migrate_isolate(migratetype))
779 		return false;
780 
781 	/*
782 	 * Do not let lower order allocations pollute a movable pageblock
783 	 * unless compaction is also requesting movable pages.
784 	 * This might let an unmovable request use a reclaimable pageblock
785 	 * and vice-versa but no more than normal fallback logic which can
786 	 * have trouble finding a high-order free page.
787 	 */
788 	if (order < pageblock_order && migratetype == MIGRATE_MOVABLE &&
789 	    capc->cc->migratetype != MIGRATE_MOVABLE)
790 		return false;
791 
792 	if (migratetype != capc->cc->migratetype)
793 		trace_mm_page_alloc_extfrag(page, capc->cc->order, order,
794 					    capc->cc->migratetype, migratetype);
795 
796 	capc->page = page;
797 	return true;
798 }
799 
800 #else
801 static inline struct capture_control *task_capc(struct zone *zone)
802 {
803 	return NULL;
804 }
805 
806 static inline bool
807 compaction_capture(struct capture_control *capc, struct page *page,
808 		   int order, int migratetype)
809 {
810 	return false;
811 }
812 #endif /* CONFIG_COMPACTION */
813 
814 static inline void account_freepages(struct zone *zone, int nr_pages,
815 				     int migratetype)
816 {
817 	lockdep_assert_held(&zone->lock);
818 
819 	if (is_migrate_isolate(migratetype))
820 		return;
821 
822 	__mod_zone_page_state(zone, NR_FREE_PAGES, nr_pages);
823 
824 	if (is_migrate_cma(migratetype))
825 		__mod_zone_page_state(zone, NR_FREE_CMA_PAGES, nr_pages);
826 	else if (migratetype == MIGRATE_HIGHATOMIC)
827 		WRITE_ONCE(zone->nr_free_highatomic,
828 			   zone->nr_free_highatomic + nr_pages);
829 }
830 
831 /* Used for pages not on another list */
832 static inline void __add_to_free_list(struct page *page, struct zone *zone,
833 				      unsigned int order, int migratetype,
834 				      bool tail)
835 {
836 	struct free_area *area = &zone->free_area[order];
837 	int nr_pages = 1 << order;
838 
839 	VM_WARN_ONCE(get_pageblock_migratetype(page) != migratetype,
840 		     "page type is %d, passed migratetype is %d (nr=%d)\n",
841 		     get_pageblock_migratetype(page), migratetype, nr_pages);
842 
843 	if (tail)
844 		list_add_tail(&page->buddy_list, &area->free_list[migratetype]);
845 	else
846 		list_add(&page->buddy_list, &area->free_list[migratetype]);
847 	area->nr_free++;
848 
849 	if (order >= pageblock_order && !is_migrate_isolate(migratetype))
850 		__mod_zone_page_state(zone, NR_FREE_PAGES_BLOCKS, nr_pages);
851 }
852 
853 /*
854  * Used for pages which are on another list. Move the pages to the tail
855  * of the list - so the moved pages won't immediately be considered for
856  * allocation again (e.g., optimization for memory onlining).
857  */
858 static inline void move_to_free_list(struct page *page, struct zone *zone,
859 				     unsigned int order, int old_mt, int new_mt)
860 {
861 	struct free_area *area = &zone->free_area[order];
862 	int nr_pages = 1 << order;
863 
864 	/* Free page moving can fail, so it happens before the type update */
865 	VM_WARN_ONCE(get_pageblock_migratetype(page) != old_mt,
866 		     "page type is %d, passed migratetype is %d (nr=%d)\n",
867 		     get_pageblock_migratetype(page), old_mt, nr_pages);
868 
869 	list_move_tail(&page->buddy_list, &area->free_list[new_mt]);
870 
871 	account_freepages(zone, -nr_pages, old_mt);
872 	account_freepages(zone, nr_pages, new_mt);
873 
874 	if (order >= pageblock_order &&
875 	    is_migrate_isolate(old_mt) != is_migrate_isolate(new_mt)) {
876 		if (!is_migrate_isolate(old_mt))
877 			nr_pages = -nr_pages;
878 		__mod_zone_page_state(zone, NR_FREE_PAGES_BLOCKS, nr_pages);
879 	}
880 }
881 
882 static inline void __del_page_from_free_list(struct page *page, struct zone *zone,
883 					     unsigned int order, int migratetype)
884 {
885 	int nr_pages = 1 << order;
886 
887         VM_WARN_ONCE(get_pageblock_migratetype(page) != migratetype,
888 		     "page type is %d, passed migratetype is %d (nr=%d)\n",
889 		     get_pageblock_migratetype(page), migratetype, nr_pages);
890 
891 	/* clear reported state and update reported page count */
892 	if (page_reported(page))
893 		__ClearPageReported(page);
894 
895 	list_del(&page->buddy_list);
896 	__ClearPageBuddy(page);
897 	set_page_private(page, 0);
898 	zone->free_area[order].nr_free--;
899 
900 	if (order >= pageblock_order && !is_migrate_isolate(migratetype))
901 		__mod_zone_page_state(zone, NR_FREE_PAGES_BLOCKS, -nr_pages);
902 }
903 
904 static inline void del_page_from_free_list(struct page *page, struct zone *zone,
905 					   unsigned int order, int migratetype)
906 {
907 	__del_page_from_free_list(page, zone, order, migratetype);
908 	account_freepages(zone, -(1 << order), migratetype);
909 }
910 
911 static inline struct page *get_page_from_free_area(struct free_area *area,
912 					    int migratetype)
913 {
914 	return list_first_entry_or_null(&area->free_list[migratetype],
915 					struct page, buddy_list);
916 }
917 
918 /*
919  * If this is less than the 2nd largest possible page, check if the buddy
920  * of the next-higher order is free. If it is, it's possible
921  * that pages are being freed that will coalesce soon. In case,
922  * that is happening, add the free page to the tail of the list
923  * so it's less likely to be used soon and more likely to be merged
924  * as a 2-level higher order page
925  */
926 static inline bool
927 buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
928 		   struct page *page, unsigned int order)
929 {
930 	unsigned long higher_page_pfn;
931 	struct page *higher_page;
932 
933 	if (order >= MAX_PAGE_ORDER - 1)
934 		return false;
935 
936 	higher_page_pfn = buddy_pfn & pfn;
937 	higher_page = page + (higher_page_pfn - pfn);
938 
939 	return find_buddy_page_pfn(higher_page, higher_page_pfn, order + 1,
940 			NULL) != NULL;
941 }
942 
943 static void change_pageblock_range(struct page *pageblock_page,
944 				   int start_order, int migratetype)
945 {
946 	int nr_pageblocks = 1 << (start_order - pageblock_order);
947 
948 	while (nr_pageblocks--) {
949 		set_pageblock_migratetype(pageblock_page, migratetype);
950 		pageblock_page += pageblock_nr_pages;
951 	}
952 }
953 
954 /*
955  * Freeing function for a buddy system allocator.
956  *
957  * The concept of a buddy system is to maintain direct-mapped table
958  * (containing bit values) for memory blocks of various "orders".
959  * The bottom level table contains the map for the smallest allocatable
960  * units of memory (here, pages), and each level above it describes
961  * pairs of units from the levels below, hence, "buddies".
962  * At a high level, all that happens here is marking the table entry
963  * at the bottom level available, and propagating the changes upward
964  * as necessary, plus some accounting needed to play nicely with other
965  * parts of the VM system.
966  * At each level, we keep a list of pages, which are heads of continuous
967  * free pages of length of (1 << order) and marked with PageBuddy.
968  * Page's order is recorded in page_private(page) field.
969  * So when we are allocating or freeing one, we can derive the state of the
970  * other.  That is, if we allocate a small block, and both were
971  * free, the remainder of the region must be split into blocks.
972  * If a block is freed, and its buddy is also free, then this
973  * triggers coalescing into a block of larger size.
974  *
975  * -- nyc
976  */
977 
978 static inline void __free_one_page(struct page *page,
979 		unsigned long pfn,
980 		struct zone *zone, unsigned int order,
981 		int migratetype, fpi_t fpi_flags)
982 {
983 	struct capture_control *capc = task_capc(zone);
984 	unsigned long buddy_pfn = 0;
985 	unsigned long combined_pfn;
986 	struct page *buddy;
987 	bool to_tail;
988 
989 	VM_BUG_ON(!zone_is_initialized(zone));
990 	VM_BUG_ON_PAGE(page->flags.f & PAGE_FLAGS_CHECK_AT_PREP, page);
991 
992 	VM_BUG_ON(migratetype == -1);
993 	VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
994 	VM_BUG_ON_PAGE(bad_range(zone, page), page);
995 
996 	account_freepages(zone, 1 << order, migratetype);
997 
998 	while (order < MAX_PAGE_ORDER) {
999 		int buddy_mt = migratetype;
1000 
1001 		if (compaction_capture(capc, page, order, migratetype)) {
1002 			account_freepages(zone, -(1 << order), migratetype);
1003 			return;
1004 		}
1005 
1006 		buddy = find_buddy_page_pfn(page, pfn, order, &buddy_pfn);
1007 		if (!buddy)
1008 			goto done_merging;
1009 
1010 		if (unlikely(order >= pageblock_order)) {
1011 			/*
1012 			 * We want to prevent merge between freepages on pageblock
1013 			 * without fallbacks and normal pageblock. Without this,
1014 			 * pageblock isolation could cause incorrect freepage or CMA
1015 			 * accounting or HIGHATOMIC accounting.
1016 			 */
1017 			buddy_mt = get_pfnblock_migratetype(buddy, buddy_pfn);
1018 
1019 			if (migratetype != buddy_mt &&
1020 			    (!migratetype_is_mergeable(migratetype) ||
1021 			     !migratetype_is_mergeable(buddy_mt)))
1022 				goto done_merging;
1023 		}
1024 
1025 		/*
1026 		 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
1027 		 * merge with it and move up one order.
1028 		 */
1029 		if (page_is_guard(buddy))
1030 			clear_page_guard(zone, buddy, order);
1031 		else
1032 			__del_page_from_free_list(buddy, zone, order, buddy_mt);
1033 
1034 		if (unlikely(buddy_mt != migratetype)) {
1035 			/*
1036 			 * Match buddy type. This ensures that an
1037 			 * expand() down the line puts the sub-blocks
1038 			 * on the right freelists.
1039 			 */
1040 			change_pageblock_range(buddy, order, migratetype);
1041 		}
1042 
1043 		combined_pfn = buddy_pfn & pfn;
1044 		page = page + (combined_pfn - pfn);
1045 		pfn = combined_pfn;
1046 		order++;
1047 	}
1048 
1049 done_merging:
1050 	set_buddy_order(page, order);
1051 
1052 	if (fpi_flags & FPI_TO_TAIL)
1053 		to_tail = true;
1054 	else if (is_shuffle_order(order))
1055 		to_tail = shuffle_pick_tail();
1056 	else
1057 		to_tail = buddy_merge_likely(pfn, buddy_pfn, page, order);
1058 
1059 	__add_to_free_list(page, zone, order, migratetype, to_tail);
1060 
1061 	/* Notify page reporting subsystem of freed page */
1062 	if (!(fpi_flags & FPI_SKIP_REPORT_NOTIFY))
1063 		page_reporting_notify_free(order);
1064 }
1065 
1066 /*
1067  * A bad page could be due to a number of fields. Instead of multiple branches,
1068  * try and check multiple fields with one check. The caller must do a detailed
1069  * check if necessary.
1070  */
1071 static inline bool page_expected_state(struct page *page,
1072 					unsigned long check_flags)
1073 {
1074 	if (unlikely(atomic_read(&page->_mapcount) != -1))
1075 		return false;
1076 
1077 	if (unlikely((unsigned long)page->mapping |
1078 			page_ref_count(page) |
1079 #ifdef CONFIG_MEMCG
1080 			page->memcg_data |
1081 #endif
1082 			page_pool_page_is_pp(page) |
1083 			(page->flags.f & check_flags)))
1084 		return false;
1085 
1086 	return true;
1087 }
1088 
1089 static const char *page_bad_reason(struct page *page, unsigned long flags)
1090 {
1091 	const char *bad_reason = NULL;
1092 
1093 	if (unlikely(atomic_read(&page->_mapcount) != -1))
1094 		bad_reason = "nonzero mapcount";
1095 	if (unlikely(page->mapping != NULL))
1096 		bad_reason = "non-NULL mapping";
1097 	if (unlikely(page_ref_count(page) != 0))
1098 		bad_reason = "nonzero _refcount";
1099 	if (unlikely(page->flags.f & flags)) {
1100 		if (flags == PAGE_FLAGS_CHECK_AT_PREP)
1101 			bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag(s) set";
1102 		else
1103 			bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
1104 	}
1105 #ifdef CONFIG_MEMCG
1106 	if (unlikely(page->memcg_data))
1107 		bad_reason = "page still charged to cgroup";
1108 #endif
1109 	if (unlikely(page_pool_page_is_pp(page)))
1110 		bad_reason = "page_pool leak";
1111 	return bad_reason;
1112 }
1113 
1114 static inline bool free_page_is_bad(struct page *page)
1115 {
1116 	if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
1117 		return false;
1118 
1119 	/* Something has gone sideways, find it */
1120 	bad_page(page, page_bad_reason(page, PAGE_FLAGS_CHECK_AT_FREE));
1121 	return true;
1122 }
1123 
1124 static inline bool is_check_pages_enabled(void)
1125 {
1126 	return static_branch_unlikely(&check_pages_enabled);
1127 }
1128 
1129 static int free_tail_page_prepare(struct page *head_page, struct page *page)
1130 {
1131 	struct folio *folio = (struct folio *)head_page;
1132 	int ret = 1;
1133 
1134 	/*
1135 	 * We rely page->lru.next never has bit 0 set, unless the page
1136 	 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
1137 	 */
1138 	BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
1139 
1140 	if (!is_check_pages_enabled()) {
1141 		ret = 0;
1142 		goto out;
1143 	}
1144 	switch (page - head_page) {
1145 	case 1:
1146 		/* the first tail page: these may be in place of ->mapping */
1147 		if (unlikely(folio_large_mapcount(folio))) {
1148 			bad_page(page, "nonzero large_mapcount");
1149 			goto out;
1150 		}
1151 		if (IS_ENABLED(CONFIG_PAGE_MAPCOUNT) &&
1152 		    unlikely(atomic_read(&folio->_nr_pages_mapped))) {
1153 			bad_page(page, "nonzero nr_pages_mapped");
1154 			goto out;
1155 		}
1156 		if (IS_ENABLED(CONFIG_MM_ID)) {
1157 			if (unlikely(folio->_mm_id_mapcount[0] != -1)) {
1158 				bad_page(page, "nonzero mm mapcount 0");
1159 				goto out;
1160 			}
1161 			if (unlikely(folio->_mm_id_mapcount[1] != -1)) {
1162 				bad_page(page, "nonzero mm mapcount 1");
1163 				goto out;
1164 			}
1165 		}
1166 		if (IS_ENABLED(CONFIG_64BIT)) {
1167 			if (unlikely(atomic_read(&folio->_entire_mapcount) + 1)) {
1168 				bad_page(page, "nonzero entire_mapcount");
1169 				goto out;
1170 			}
1171 			if (unlikely(atomic_read(&folio->_pincount))) {
1172 				bad_page(page, "nonzero pincount");
1173 				goto out;
1174 			}
1175 		}
1176 		break;
1177 	case 2:
1178 		/* the second tail page: deferred_list overlaps ->mapping */
1179 		if (unlikely(!list_empty(&folio->_deferred_list))) {
1180 			bad_page(page, "on deferred list");
1181 			goto out;
1182 		}
1183 		if (!IS_ENABLED(CONFIG_64BIT)) {
1184 			if (unlikely(atomic_read(&folio->_entire_mapcount) + 1)) {
1185 				bad_page(page, "nonzero entire_mapcount");
1186 				goto out;
1187 			}
1188 			if (unlikely(atomic_read(&folio->_pincount))) {
1189 				bad_page(page, "nonzero pincount");
1190 				goto out;
1191 			}
1192 		}
1193 		break;
1194 	case 3:
1195 		/* the third tail page: hugetlb specifics overlap ->mappings */
1196 		if (IS_ENABLED(CONFIG_HUGETLB_PAGE))
1197 			break;
1198 		fallthrough;
1199 	default:
1200 		if (page->mapping != TAIL_MAPPING) {
1201 			bad_page(page, "corrupted mapping in tail page");
1202 			goto out;
1203 		}
1204 		break;
1205 	}
1206 	if (unlikely(!PageTail(page))) {
1207 		bad_page(page, "PageTail not set");
1208 		goto out;
1209 	}
1210 	if (unlikely(compound_head(page) != head_page)) {
1211 		bad_page(page, "compound_head not consistent");
1212 		goto out;
1213 	}
1214 	ret = 0;
1215 out:
1216 	page->mapping = NULL;
1217 	clear_compound_head(page);
1218 	return ret;
1219 }
1220 
1221 /*
1222  * Skip KASAN memory poisoning when either:
1223  *
1224  * 1. For generic KASAN: deferred memory initialization has not yet completed.
1225  *    Tag-based KASAN modes skip pages freed via deferred memory initialization
1226  *    using page tags instead (see below).
1227  * 2. For tag-based KASAN modes: the page has a match-all KASAN tag, indicating
1228  *    that error detection is disabled for accesses via the page address.
1229  *
1230  * Pages will have match-all tags in the following circumstances:
1231  *
1232  * 1. Pages are being initialized for the first time, including during deferred
1233  *    memory init; see the call to page_kasan_tag_reset in __init_single_page.
1234  * 2. The allocation was not unpoisoned due to __GFP_SKIP_KASAN, with the
1235  *    exception of pages unpoisoned by kasan_unpoison_vmalloc.
1236  * 3. The allocation was excluded from being checked due to sampling,
1237  *    see the call to kasan_unpoison_pages.
1238  *
1239  * Poisoning pages during deferred memory init will greatly lengthen the
1240  * process and cause problem in large memory systems as the deferred pages
1241  * initialization is done with interrupt disabled.
1242  *
1243  * Assuming that there will be no reference to those newly initialized
1244  * pages before they are ever allocated, this should have no effect on
1245  * KASAN memory tracking as the poison will be properly inserted at page
1246  * allocation time. The only corner case is when pages are allocated by
1247  * on-demand allocation and then freed again before the deferred pages
1248  * initialization is done, but this is not likely to happen.
1249  */
1250 static inline bool should_skip_kasan_poison(struct page *page)
1251 {
1252 	if (IS_ENABLED(CONFIG_KASAN_GENERIC))
1253 		return deferred_pages_enabled();
1254 
1255 	return page_kasan_tag(page) == KASAN_TAG_KERNEL;
1256 }
1257 
1258 static void kernel_init_pages(struct page *page, int numpages)
1259 {
1260 	int i;
1261 
1262 	/* s390's use of memset() could override KASAN redzones. */
1263 	kasan_disable_current();
1264 	for (i = 0; i < numpages; i++)
1265 		clear_highpage_kasan_tagged(page + i);
1266 	kasan_enable_current();
1267 }
1268 
1269 #ifdef CONFIG_MEM_ALLOC_PROFILING
1270 
1271 /* Should be called only if mem_alloc_profiling_enabled() */
1272 void __clear_page_tag_ref(struct page *page)
1273 {
1274 	union pgtag_ref_handle handle;
1275 	union codetag_ref ref;
1276 
1277 	if (get_page_tag_ref(page, &ref, &handle)) {
1278 		set_codetag_empty(&ref);
1279 		update_page_tag_ref(handle, &ref);
1280 		put_page_tag_ref(handle);
1281 	}
1282 }
1283 
1284 /* Should be called only if mem_alloc_profiling_enabled() */
1285 static noinline
1286 void __pgalloc_tag_add(struct page *page, struct task_struct *task,
1287 		       unsigned int nr)
1288 {
1289 	union pgtag_ref_handle handle;
1290 	union codetag_ref ref;
1291 
1292 	if (get_page_tag_ref(page, &ref, &handle)) {
1293 		alloc_tag_add(&ref, task->alloc_tag, PAGE_SIZE * nr);
1294 		update_page_tag_ref(handle, &ref);
1295 		put_page_tag_ref(handle);
1296 	}
1297 }
1298 
1299 static inline void pgalloc_tag_add(struct page *page, struct task_struct *task,
1300 				   unsigned int nr)
1301 {
1302 	if (mem_alloc_profiling_enabled())
1303 		__pgalloc_tag_add(page, task, nr);
1304 }
1305 
1306 /* Should be called only if mem_alloc_profiling_enabled() */
1307 static noinline
1308 void __pgalloc_tag_sub(struct page *page, unsigned int nr)
1309 {
1310 	union pgtag_ref_handle handle;
1311 	union codetag_ref ref;
1312 
1313 	if (get_page_tag_ref(page, &ref, &handle)) {
1314 		alloc_tag_sub(&ref, PAGE_SIZE * nr);
1315 		update_page_tag_ref(handle, &ref);
1316 		put_page_tag_ref(handle);
1317 	}
1318 }
1319 
1320 static inline void pgalloc_tag_sub(struct page *page, unsigned int nr)
1321 {
1322 	if (mem_alloc_profiling_enabled())
1323 		__pgalloc_tag_sub(page, nr);
1324 }
1325 
1326 /* When tag is not NULL, assuming mem_alloc_profiling_enabled */
1327 static inline void pgalloc_tag_sub_pages(struct alloc_tag *tag, unsigned int nr)
1328 {
1329 	if (tag)
1330 		this_cpu_sub(tag->counters->bytes, PAGE_SIZE * nr);
1331 }
1332 
1333 #else /* CONFIG_MEM_ALLOC_PROFILING */
1334 
1335 static inline void pgalloc_tag_add(struct page *page, struct task_struct *task,
1336 				   unsigned int nr) {}
1337 static inline void pgalloc_tag_sub(struct page *page, unsigned int nr) {}
1338 static inline void pgalloc_tag_sub_pages(struct alloc_tag *tag, unsigned int nr) {}
1339 
1340 #endif /* CONFIG_MEM_ALLOC_PROFILING */
1341 
1342 __always_inline bool __free_pages_prepare(struct page *page,
1343 					  unsigned int order, fpi_t fpi_flags)
1344 {
1345 	int bad = 0;
1346 	bool skip_kasan_poison = should_skip_kasan_poison(page);
1347 	bool init = want_init_on_free();
1348 	bool compound = PageCompound(page);
1349 	struct folio *folio = page_folio(page);
1350 
1351 	VM_BUG_ON_PAGE(PageTail(page), page);
1352 
1353 	trace_mm_page_free(page, order);
1354 	kmsan_free_page(page, order);
1355 
1356 	if (memcg_kmem_online() && PageMemcgKmem(page))
1357 		__memcg_kmem_uncharge_page(page, order);
1358 
1359 	/*
1360 	 * In rare cases, when truncation or holepunching raced with
1361 	 * munlock after VM_LOCKED was cleared, Mlocked may still be
1362 	 * found set here.  This does not indicate a problem, unless
1363 	 * "unevictable_pgs_cleared" appears worryingly large.
1364 	 */
1365 	if (unlikely(folio_test_mlocked(folio))) {
1366 		long nr_pages = folio_nr_pages(folio);
1367 
1368 		__folio_clear_mlocked(folio);
1369 		zone_stat_mod_folio(folio, NR_MLOCK, -nr_pages);
1370 		count_vm_events(UNEVICTABLE_PGCLEARED, nr_pages);
1371 	}
1372 
1373 	if (unlikely(PageHWPoison(page)) && !order) {
1374 		/* Do not let hwpoison pages hit pcplists/buddy */
1375 		reset_page_owner(page, order);
1376 		page_table_check_free(page, order);
1377 		pgalloc_tag_sub(page, 1 << order);
1378 
1379 		/*
1380 		 * The page is isolated and accounted for.
1381 		 * Mark the codetag as empty to avoid accounting error
1382 		 * when the page is freed by unpoison_memory().
1383 		 */
1384 		clear_page_tag_ref(page);
1385 		return false;
1386 	}
1387 
1388 	VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1389 
1390 	/*
1391 	 * Check tail pages before head page information is cleared to
1392 	 * avoid checking PageCompound for order-0 pages.
1393 	 */
1394 	if (unlikely(order)) {
1395 		int i;
1396 
1397 		if (compound) {
1398 			page[1].flags.f &= ~PAGE_FLAGS_SECOND;
1399 #ifdef NR_PAGES_IN_LARGE_FOLIO
1400 			folio->_nr_pages = 0;
1401 #endif
1402 		}
1403 		for (i = 1; i < (1 << order); i++) {
1404 			if (compound)
1405 				bad += free_tail_page_prepare(page, page + i);
1406 			if (is_check_pages_enabled()) {
1407 				if (free_page_is_bad(page + i)) {
1408 					bad++;
1409 					continue;
1410 				}
1411 			}
1412 			(page + i)->flags.f &= ~PAGE_FLAGS_CHECK_AT_PREP;
1413 		}
1414 	}
1415 	if (folio_test_anon(folio)) {
1416 		mod_mthp_stat(order, MTHP_STAT_NR_ANON, -1);
1417 		folio->mapping = NULL;
1418 	}
1419 	if (unlikely(page_has_type(page)))
1420 		/* Reset the page_type (which overlays _mapcount) */
1421 		page->page_type = UINT_MAX;
1422 
1423 	if (is_check_pages_enabled()) {
1424 		if (free_page_is_bad(page))
1425 			bad++;
1426 		if (bad)
1427 			return false;
1428 	}
1429 
1430 	page_cpupid_reset_last(page);
1431 	page->flags.f &= ~PAGE_FLAGS_CHECK_AT_PREP;
1432 	page->private = 0;
1433 	reset_page_owner(page, order);
1434 	page_table_check_free(page, order);
1435 	pgalloc_tag_sub(page, 1 << order);
1436 
1437 	if (!PageHighMem(page) && !(fpi_flags & FPI_TRYLOCK)) {
1438 		debug_check_no_locks_freed(page_address(page),
1439 					   PAGE_SIZE << order);
1440 		debug_check_no_obj_freed(page_address(page),
1441 					   PAGE_SIZE << order);
1442 	}
1443 
1444 	kernel_poison_pages(page, 1 << order);
1445 
1446 	/*
1447 	 * As memory initialization might be integrated into KASAN,
1448 	 * KASAN poisoning and memory initialization code must be
1449 	 * kept together to avoid discrepancies in behavior.
1450 	 *
1451 	 * With hardware tag-based KASAN, memory tags must be set before the
1452 	 * page becomes unavailable via debug_pagealloc or arch_free_page.
1453 	 */
1454 	if (!skip_kasan_poison) {
1455 		kasan_poison_pages(page, order, init);
1456 
1457 		/* Memory is already initialized if KASAN did it internally. */
1458 		if (kasan_has_integrated_init())
1459 			init = false;
1460 	}
1461 	if (init)
1462 		kernel_init_pages(page, 1 << order);
1463 
1464 	/*
1465 	 * arch_free_page() can make the page's contents inaccessible.  s390
1466 	 * does this.  So nothing which can access the page's contents should
1467 	 * happen after this.
1468 	 */
1469 	arch_free_page(page, order);
1470 
1471 	debug_pagealloc_unmap_pages(page, 1 << order);
1472 
1473 	return true;
1474 }
1475 
1476 bool free_pages_prepare(struct page *page, unsigned int order)
1477 {
1478 	return __free_pages_prepare(page, order, FPI_NONE);
1479 }
1480 
1481 /*
1482  * Frees a number of pages from the PCP lists
1483  * Assumes all pages on list are in same zone.
1484  * count is the number of pages to free.
1485  */
1486 static void free_pcppages_bulk(struct zone *zone, int count,
1487 					struct per_cpu_pages *pcp,
1488 					int pindex)
1489 {
1490 	unsigned long flags;
1491 	unsigned int order;
1492 	struct page *page;
1493 
1494 	/*
1495 	 * Ensure proper count is passed which otherwise would stuck in the
1496 	 * below while (list_empty(list)) loop.
1497 	 */
1498 	count = min(pcp->count, count);
1499 
1500 	/* Ensure requested pindex is drained first. */
1501 	pindex = pindex - 1;
1502 
1503 	spin_lock_irqsave(&zone->lock, flags);
1504 
1505 	while (count > 0) {
1506 		struct list_head *list;
1507 		int nr_pages;
1508 
1509 		/* Remove pages from lists in a round-robin fashion. */
1510 		do {
1511 			if (++pindex > NR_PCP_LISTS - 1)
1512 				pindex = 0;
1513 			list = &pcp->lists[pindex];
1514 		} while (list_empty(list));
1515 
1516 		order = pindex_to_order(pindex);
1517 		nr_pages = 1 << order;
1518 		do {
1519 			unsigned long pfn;
1520 			int mt;
1521 
1522 			page = list_last_entry(list, struct page, pcp_list);
1523 			pfn = page_to_pfn(page);
1524 			mt = get_pfnblock_migratetype(page, pfn);
1525 
1526 			/* must delete to avoid corrupting pcp list */
1527 			list_del(&page->pcp_list);
1528 			count -= nr_pages;
1529 			pcp->count -= nr_pages;
1530 
1531 			__free_one_page(page, pfn, zone, order, mt, FPI_NONE);
1532 			trace_mm_page_pcpu_drain(page, order, mt);
1533 		} while (count > 0 && !list_empty(list));
1534 	}
1535 
1536 	spin_unlock_irqrestore(&zone->lock, flags);
1537 }
1538 
1539 /* Split a multi-block free page into its individual pageblocks. */
1540 static void split_large_buddy(struct zone *zone, struct page *page,
1541 			      unsigned long pfn, int order, fpi_t fpi)
1542 {
1543 	unsigned long end = pfn + (1 << order);
1544 
1545 	VM_WARN_ON_ONCE(!IS_ALIGNED(pfn, 1 << order));
1546 	/* Caller removed page from freelist, buddy info cleared! */
1547 	VM_WARN_ON_ONCE(PageBuddy(page));
1548 
1549 	if (order > pageblock_order)
1550 		order = pageblock_order;
1551 
1552 	do {
1553 		int mt = get_pfnblock_migratetype(page, pfn);
1554 
1555 		__free_one_page(page, pfn, zone, order, mt, fpi);
1556 		pfn += 1 << order;
1557 		if (pfn == end)
1558 			break;
1559 		page = pfn_to_page(pfn);
1560 	} while (1);
1561 }
1562 
1563 static void add_page_to_zone_llist(struct zone *zone, struct page *page,
1564 				   unsigned int order)
1565 {
1566 	/* Remember the order */
1567 	page->private = order;
1568 	/* Add the page to the free list */
1569 	llist_add(&page->pcp_llist, &zone->trylock_free_pages);
1570 }
1571 
1572 static void free_one_page(struct zone *zone, struct page *page,
1573 			  unsigned long pfn, unsigned int order,
1574 			  fpi_t fpi_flags)
1575 {
1576 	struct llist_head *llhead;
1577 	unsigned long flags;
1578 
1579 	if (unlikely(fpi_flags & FPI_TRYLOCK)) {
1580 		if (!spin_trylock_irqsave(&zone->lock, flags)) {
1581 			add_page_to_zone_llist(zone, page, order);
1582 			return;
1583 		}
1584 	} else {
1585 		spin_lock_irqsave(&zone->lock, flags);
1586 	}
1587 
1588 	/* The lock succeeded. Process deferred pages. */
1589 	llhead = &zone->trylock_free_pages;
1590 	if (unlikely(!llist_empty(llhead) && !(fpi_flags & FPI_TRYLOCK))) {
1591 		struct llist_node *llnode;
1592 		struct page *p, *tmp;
1593 
1594 		llnode = llist_del_all(llhead);
1595 		llist_for_each_entry_safe(p, tmp, llnode, pcp_llist) {
1596 			unsigned int p_order = p->private;
1597 
1598 			split_large_buddy(zone, p, page_to_pfn(p), p_order, fpi_flags);
1599 			__count_vm_events(PGFREE, 1 << p_order);
1600 		}
1601 	}
1602 	split_large_buddy(zone, page, pfn, order, fpi_flags);
1603 	spin_unlock_irqrestore(&zone->lock, flags);
1604 
1605 	__count_vm_events(PGFREE, 1 << order);
1606 }
1607 
1608 static void __free_pages_ok(struct page *page, unsigned int order,
1609 			    fpi_t fpi_flags)
1610 {
1611 	unsigned long pfn = page_to_pfn(page);
1612 	struct zone *zone = page_zone(page);
1613 
1614 	if (__free_pages_prepare(page, order, fpi_flags))
1615 		free_one_page(zone, page, pfn, order, fpi_flags);
1616 }
1617 
1618 void __meminit __free_pages_core(struct page *page, unsigned int order,
1619 		enum meminit_context context)
1620 {
1621 	unsigned int nr_pages = 1 << order;
1622 	struct page *p = page;
1623 	unsigned int loop;
1624 
1625 	/*
1626 	 * When initializing the memmap, __init_single_page() sets the refcount
1627 	 * of all pages to 1 ("allocated"/"not free"). We have to set the
1628 	 * refcount of all involved pages to 0.
1629 	 *
1630 	 * Note that hotplugged memory pages are initialized to PageOffline().
1631 	 * Pages freed from memblock might be marked as reserved.
1632 	 */
1633 	if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG) &&
1634 	    unlikely(context == MEMINIT_HOTPLUG)) {
1635 		for (loop = 0; loop < nr_pages; loop++, p++) {
1636 			VM_WARN_ON_ONCE(PageReserved(p));
1637 			__ClearPageOffline(p);
1638 			set_page_count(p, 0);
1639 		}
1640 
1641 		adjust_managed_page_count(page, nr_pages);
1642 	} else {
1643 		for (loop = 0; loop < nr_pages; loop++, p++) {
1644 			__ClearPageReserved(p);
1645 			set_page_count(p, 0);
1646 		}
1647 
1648 		/* memblock adjusts totalram_pages() manually. */
1649 		atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
1650 	}
1651 
1652 	if (page_contains_unaccepted(page, order)) {
1653 		if (order == MAX_PAGE_ORDER && __free_unaccepted(page))
1654 			return;
1655 
1656 		accept_memory(page_to_phys(page), PAGE_SIZE << order);
1657 	}
1658 
1659 	/*
1660 	 * Bypass PCP and place fresh pages right to the tail, primarily
1661 	 * relevant for memory onlining.
1662 	 */
1663 	__free_pages_ok(page, order, FPI_TO_TAIL);
1664 }
1665 
1666 /*
1667  * Check that the whole (or subset of) a pageblock given by the interval of
1668  * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1669  * with the migration of free compaction scanner.
1670  *
1671  * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1672  *
1673  * It's possible on some configurations to have a setup like node0 node1 node0
1674  * i.e. it's possible that all pages within a zones range of pages do not
1675  * belong to a single zone. We assume that a border between node0 and node1
1676  * can occur within a single pageblock, but not a node0 node1 node0
1677  * interleaving within a single pageblock. It is therefore sufficient to check
1678  * the first and last page of a pageblock and avoid checking each individual
1679  * page in a pageblock.
1680  *
1681  * Note: the function may return non-NULL struct page even for a page block
1682  * which contains a memory hole (i.e. there is no physical memory for a subset
1683  * of the pfn range). For example, if the pageblock order is MAX_PAGE_ORDER, which
1684  * will fall into 2 sub-sections, and the end pfn of the pageblock may be hole
1685  * even though the start pfn is online and valid. This should be safe most of
1686  * the time because struct pages are still initialized via init_unavailable_range()
1687  * and pfn walkers shouldn't touch any physical memory range for which they do
1688  * not recognize any specific metadata in struct pages.
1689  */
1690 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1691 				     unsigned long end_pfn, struct zone *zone)
1692 {
1693 	struct page *start_page;
1694 	struct page *end_page;
1695 
1696 	/* end_pfn is one past the range we are checking */
1697 	end_pfn--;
1698 
1699 	if (!pfn_valid(end_pfn))
1700 		return NULL;
1701 
1702 	start_page = pfn_to_online_page(start_pfn);
1703 	if (!start_page)
1704 		return NULL;
1705 
1706 	if (page_zone(start_page) != zone)
1707 		return NULL;
1708 
1709 	end_page = pfn_to_page(end_pfn);
1710 
1711 	/* This gives a shorter code than deriving page_zone(end_page) */
1712 	if (page_zone_id(start_page) != page_zone_id(end_page))
1713 		return NULL;
1714 
1715 	return start_page;
1716 }
1717 
1718 /*
1719  * The order of subdivision here is critical for the IO subsystem.
1720  * Please do not alter this order without good reasons and regression
1721  * testing. Specifically, as large blocks of memory are subdivided,
1722  * the order in which smaller blocks are delivered depends on the order
1723  * they're subdivided in this function. This is the primary factor
1724  * influencing the order in which pages are delivered to the IO
1725  * subsystem according to empirical testing, and this is also justified
1726  * by considering the behavior of a buddy system containing a single
1727  * large block of memory acted on by a series of small allocations.
1728  * This behavior is a critical factor in sglist merging's success.
1729  *
1730  * -- nyc
1731  */
1732 static inline unsigned int expand(struct zone *zone, struct page *page, int low,
1733 				  int high, int migratetype)
1734 {
1735 	unsigned int size = 1 << high;
1736 	unsigned int nr_added = 0;
1737 
1738 	while (high > low) {
1739 		high--;
1740 		size >>= 1;
1741 		VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
1742 
1743 		/*
1744 		 * Mark as guard pages (or page), that will allow to
1745 		 * merge back to allocator when buddy will be freed.
1746 		 * Corresponding page table entries will not be touched,
1747 		 * pages will stay not present in virtual address space
1748 		 */
1749 		if (set_page_guard(zone, &page[size], high))
1750 			continue;
1751 
1752 		__add_to_free_list(&page[size], zone, high, migratetype, false);
1753 		set_buddy_order(&page[size], high);
1754 		nr_added += size;
1755 	}
1756 
1757 	return nr_added;
1758 }
1759 
1760 static __always_inline void page_del_and_expand(struct zone *zone,
1761 						struct page *page, int low,
1762 						int high, int migratetype)
1763 {
1764 	int nr_pages = 1 << high;
1765 
1766 	__del_page_from_free_list(page, zone, high, migratetype);
1767 	nr_pages -= expand(zone, page, low, high, migratetype);
1768 	account_freepages(zone, -nr_pages, migratetype);
1769 }
1770 
1771 static void check_new_page_bad(struct page *page)
1772 {
1773 	if (unlikely(PageHWPoison(page))) {
1774 		/* Don't complain about hwpoisoned pages */
1775 		if (PageBuddy(page))
1776 			__ClearPageBuddy(page);
1777 		return;
1778 	}
1779 
1780 	bad_page(page,
1781 		 page_bad_reason(page, PAGE_FLAGS_CHECK_AT_PREP));
1782 }
1783 
1784 /*
1785  * This page is about to be returned from the page allocator
1786  */
1787 static bool check_new_page(struct page *page)
1788 {
1789 	if (likely(page_expected_state(page,
1790 				PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
1791 		return false;
1792 
1793 	check_new_page_bad(page);
1794 	return true;
1795 }
1796 
1797 static inline bool check_new_pages(struct page *page, unsigned int order)
1798 {
1799 	if (is_check_pages_enabled()) {
1800 		for (int i = 0; i < (1 << order); i++) {
1801 			struct page *p = page + i;
1802 
1803 			if (check_new_page(p))
1804 				return true;
1805 		}
1806 	}
1807 
1808 	return false;
1809 }
1810 
1811 static inline bool should_skip_kasan_unpoison(gfp_t flags)
1812 {
1813 	/* Don't skip if a software KASAN mode is enabled. */
1814 	if (IS_ENABLED(CONFIG_KASAN_GENERIC) ||
1815 	    IS_ENABLED(CONFIG_KASAN_SW_TAGS))
1816 		return false;
1817 
1818 	/* Skip, if hardware tag-based KASAN is not enabled. */
1819 	if (!kasan_hw_tags_enabled())
1820 		return true;
1821 
1822 	/*
1823 	 * With hardware tag-based KASAN enabled, skip if this has been
1824 	 * requested via __GFP_SKIP_KASAN.
1825 	 */
1826 	return flags & __GFP_SKIP_KASAN;
1827 }
1828 
1829 static inline bool should_skip_init(gfp_t flags)
1830 {
1831 	/* Don't skip, if hardware tag-based KASAN is not enabled. */
1832 	if (!kasan_hw_tags_enabled())
1833 		return false;
1834 
1835 	/* For hardware tag-based KASAN, skip if requested. */
1836 	return (flags & __GFP_SKIP_ZERO);
1837 }
1838 
1839 inline void post_alloc_hook(struct page *page, unsigned int order,
1840 				gfp_t gfp_flags)
1841 {
1842 	bool init = !want_init_on_free() && want_init_on_alloc(gfp_flags) &&
1843 			!should_skip_init(gfp_flags);
1844 	bool zero_tags = init && (gfp_flags & __GFP_ZEROTAGS);
1845 	int i;
1846 
1847 	set_page_private(page, 0);
1848 
1849 	arch_alloc_page(page, order);
1850 	debug_pagealloc_map_pages(page, 1 << order);
1851 
1852 	/*
1853 	 * Page unpoisoning must happen before memory initialization.
1854 	 * Otherwise, the poison pattern will be overwritten for __GFP_ZERO
1855 	 * allocations and the page unpoisoning code will complain.
1856 	 */
1857 	kernel_unpoison_pages(page, 1 << order);
1858 
1859 	/*
1860 	 * As memory initialization might be integrated into KASAN,
1861 	 * KASAN unpoisoning and memory initialization code must be
1862 	 * kept together to avoid discrepancies in behavior.
1863 	 */
1864 
1865 	/*
1866 	 * If memory tags should be zeroed
1867 	 * (which happens only when memory should be initialized as well).
1868 	 */
1869 	if (zero_tags)
1870 		init = !tag_clear_highpages(page, 1 << order);
1871 
1872 	if (!should_skip_kasan_unpoison(gfp_flags) &&
1873 	    kasan_unpoison_pages(page, order, init)) {
1874 		/* Take note that memory was initialized by KASAN. */
1875 		if (kasan_has_integrated_init())
1876 			init = false;
1877 	} else {
1878 		/*
1879 		 * If memory tags have not been set by KASAN, reset the page
1880 		 * tags to ensure page_address() dereferencing does not fault.
1881 		 */
1882 		for (i = 0; i != 1 << order; ++i)
1883 			page_kasan_tag_reset(page + i);
1884 	}
1885 	/* If memory is still not initialized, initialize it now. */
1886 	if (init)
1887 		kernel_init_pages(page, 1 << order);
1888 
1889 	set_page_owner(page, order, gfp_flags);
1890 	page_table_check_alloc(page, order);
1891 	pgalloc_tag_add(page, current, 1 << order);
1892 }
1893 
1894 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
1895 							unsigned int alloc_flags)
1896 {
1897 	post_alloc_hook(page, order, gfp_flags);
1898 
1899 	if (order && (gfp_flags & __GFP_COMP))
1900 		prep_compound_page(page, order);
1901 
1902 	/*
1903 	 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
1904 	 * allocate the page. The expectation is that the caller is taking
1905 	 * steps that will free more memory. The caller should avoid the page
1906 	 * being used for !PFMEMALLOC purposes.
1907 	 */
1908 	if (alloc_flags & ALLOC_NO_WATERMARKS)
1909 		set_page_pfmemalloc(page);
1910 	else
1911 		clear_page_pfmemalloc(page);
1912 }
1913 
1914 /*
1915  * Go through the free lists for the given migratetype and remove
1916  * the smallest available page from the freelists
1917  */
1918 static __always_inline
1919 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
1920 						int migratetype)
1921 {
1922 	unsigned int current_order;
1923 	struct free_area *area;
1924 	struct page *page;
1925 
1926 	/* Find a page of the appropriate size in the preferred list */
1927 	for (current_order = order; current_order < NR_PAGE_ORDERS; ++current_order) {
1928 		area = &(zone->free_area[current_order]);
1929 		page = get_page_from_free_area(area, migratetype);
1930 		if (!page)
1931 			continue;
1932 
1933 		page_del_and_expand(zone, page, order, current_order,
1934 				    migratetype);
1935 		trace_mm_page_alloc_zone_locked(page, order, migratetype,
1936 				pcp_allowed_order(order) &&
1937 				migratetype < MIGRATE_PCPTYPES);
1938 		return page;
1939 	}
1940 
1941 	return NULL;
1942 }
1943 
1944 
1945 /*
1946  * This array describes the order lists are fallen back to when
1947  * the free lists for the desirable migrate type are depleted
1948  *
1949  * The other migratetypes do not have fallbacks.
1950  */
1951 static int fallbacks[MIGRATE_PCPTYPES][MIGRATE_PCPTYPES - 1] = {
1952 	[MIGRATE_UNMOVABLE]   = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE   },
1953 	[MIGRATE_MOVABLE]     = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE },
1954 	[MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE,   MIGRATE_MOVABLE   },
1955 };
1956 
1957 #ifdef CONFIG_CMA
1958 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1959 					unsigned int order)
1960 {
1961 	return __rmqueue_smallest(zone, order, MIGRATE_CMA);
1962 }
1963 #else
1964 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
1965 					unsigned int order) { return NULL; }
1966 #endif
1967 
1968 /*
1969  * Move all free pages of a block to new type's freelist. Caller needs to
1970  * change the block type.
1971  */
1972 static int __move_freepages_block(struct zone *zone, unsigned long start_pfn,
1973 				  int old_mt, int new_mt)
1974 {
1975 	struct page *page;
1976 	unsigned long pfn, end_pfn;
1977 	unsigned int order;
1978 	int pages_moved = 0;
1979 
1980 	VM_WARN_ON(start_pfn & (pageblock_nr_pages - 1));
1981 	end_pfn = pageblock_end_pfn(start_pfn);
1982 
1983 	for (pfn = start_pfn; pfn < end_pfn;) {
1984 		page = pfn_to_page(pfn);
1985 		if (!PageBuddy(page)) {
1986 			pfn++;
1987 			continue;
1988 		}
1989 
1990 		/* Make sure we are not inadvertently changing nodes */
1991 		VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
1992 		VM_BUG_ON_PAGE(page_zone(page) != zone, page);
1993 
1994 		order = buddy_order(page);
1995 
1996 		move_to_free_list(page, zone, order, old_mt, new_mt);
1997 
1998 		pfn += 1 << order;
1999 		pages_moved += 1 << order;
2000 	}
2001 
2002 	return pages_moved;
2003 }
2004 
2005 static bool prep_move_freepages_block(struct zone *zone, struct page *page,
2006 				      unsigned long *start_pfn,
2007 				      int *num_free, int *num_movable)
2008 {
2009 	unsigned long pfn, start, end;
2010 
2011 	pfn = page_to_pfn(page);
2012 	start = pageblock_start_pfn(pfn);
2013 	end = pageblock_end_pfn(pfn);
2014 
2015 	/*
2016 	 * The caller only has the lock for @zone, don't touch ranges
2017 	 * that straddle into other zones. While we could move part of
2018 	 * the range that's inside the zone, this call is usually
2019 	 * accompanied by other operations such as migratetype updates
2020 	 * which also should be locked.
2021 	 */
2022 	if (!zone_spans_pfn(zone, start))
2023 		return false;
2024 	if (!zone_spans_pfn(zone, end - 1))
2025 		return false;
2026 
2027 	*start_pfn = start;
2028 
2029 	if (num_free) {
2030 		*num_free = 0;
2031 		*num_movable = 0;
2032 		for (pfn = start; pfn < end;) {
2033 			page = pfn_to_page(pfn);
2034 			if (PageBuddy(page)) {
2035 				int nr = 1 << buddy_order(page);
2036 
2037 				*num_free += nr;
2038 				pfn += nr;
2039 				continue;
2040 			}
2041 			/*
2042 			 * We assume that pages that could be isolated for
2043 			 * migration are movable. But we don't actually try
2044 			 * isolating, as that would be expensive.
2045 			 */
2046 			if (PageLRU(page) || page_has_movable_ops(page))
2047 				(*num_movable)++;
2048 			pfn++;
2049 		}
2050 	}
2051 
2052 	return true;
2053 }
2054 
2055 static int move_freepages_block(struct zone *zone, struct page *page,
2056 				int old_mt, int new_mt)
2057 {
2058 	unsigned long start_pfn;
2059 	int res;
2060 
2061 	if (!prep_move_freepages_block(zone, page, &start_pfn, NULL, NULL))
2062 		return -1;
2063 
2064 	res = __move_freepages_block(zone, start_pfn, old_mt, new_mt);
2065 	set_pageblock_migratetype(pfn_to_page(start_pfn), new_mt);
2066 
2067 	return res;
2068 
2069 }
2070 
2071 #ifdef CONFIG_MEMORY_ISOLATION
2072 /* Look for a buddy that straddles start_pfn */
2073 static unsigned long find_large_buddy(unsigned long start_pfn)
2074 {
2075 	/*
2076 	 * If start_pfn is not an order-0 PageBuddy, next PageBuddy containing
2077 	 * start_pfn has minimal order of __ffs(start_pfn) + 1. Start checking
2078 	 * the order with __ffs(start_pfn). If start_pfn is order-0 PageBuddy,
2079 	 * the starting order does not matter.
2080 	 */
2081 	int order = start_pfn ? __ffs(start_pfn) : MAX_PAGE_ORDER;
2082 	struct page *page;
2083 	unsigned long pfn = start_pfn;
2084 
2085 	while (!PageBuddy(page = pfn_to_page(pfn))) {
2086 		/* Nothing found */
2087 		if (++order > MAX_PAGE_ORDER)
2088 			return start_pfn;
2089 		pfn &= ~0UL << order;
2090 	}
2091 
2092 	/*
2093 	 * Found a preceding buddy, but does it straddle?
2094 	 */
2095 	if (pfn + (1 << buddy_order(page)) > start_pfn)
2096 		return pfn;
2097 
2098 	/* Nothing found */
2099 	return start_pfn;
2100 }
2101 
2102 static inline void toggle_pageblock_isolate(struct page *page, bool isolate)
2103 {
2104 	if (isolate)
2105 		set_pageblock_isolate(page);
2106 	else
2107 		clear_pageblock_isolate(page);
2108 }
2109 
2110 /**
2111  * __move_freepages_block_isolate - move free pages in block for page isolation
2112  * @zone: the zone
2113  * @page: the pageblock page
2114  * @isolate: to isolate the given pageblock or unisolate it
2115  *
2116  * This is similar to move_freepages_block(), but handles the special
2117  * case encountered in page isolation, where the block of interest
2118  * might be part of a larger buddy spanning multiple pageblocks.
2119  *
2120  * Unlike the regular page allocator path, which moves pages while
2121  * stealing buddies off the freelist, page isolation is interested in
2122  * arbitrary pfn ranges that may have overlapping buddies on both ends.
2123  *
2124  * This function handles that. Straddling buddies are split into
2125  * individual pageblocks. Only the block of interest is moved.
2126  *
2127  * Returns %true if pages could be moved, %false otherwise.
2128  */
2129 static bool __move_freepages_block_isolate(struct zone *zone,
2130 		struct page *page, bool isolate)
2131 {
2132 	unsigned long start_pfn, buddy_pfn;
2133 	int from_mt;
2134 	int to_mt;
2135 	struct page *buddy;
2136 
2137 	if (isolate == get_pageblock_isolate(page)) {
2138 		VM_WARN_ONCE(1, "%s a pageblock that is already in that state",
2139 			     isolate ? "Isolate" : "Unisolate");
2140 		return false;
2141 	}
2142 
2143 	if (!prep_move_freepages_block(zone, page, &start_pfn, NULL, NULL))
2144 		return false;
2145 
2146 	/* No splits needed if buddies can't span multiple blocks */
2147 	if (pageblock_order == MAX_PAGE_ORDER)
2148 		goto move;
2149 
2150 	buddy_pfn = find_large_buddy(start_pfn);
2151 	buddy = pfn_to_page(buddy_pfn);
2152 	/* We're a part of a larger buddy */
2153 	if (PageBuddy(buddy) && buddy_order(buddy) > pageblock_order) {
2154 		int order = buddy_order(buddy);
2155 
2156 		del_page_from_free_list(buddy, zone, order,
2157 					get_pfnblock_migratetype(buddy, buddy_pfn));
2158 		toggle_pageblock_isolate(page, isolate);
2159 		split_large_buddy(zone, buddy, buddy_pfn, order, FPI_NONE);
2160 		return true;
2161 	}
2162 
2163 move:
2164 	/* Use MIGRATETYPE_MASK to get non-isolate migratetype */
2165 	if (isolate) {
2166 		from_mt = __get_pfnblock_flags_mask(page, page_to_pfn(page),
2167 						    MIGRATETYPE_MASK);
2168 		to_mt = MIGRATE_ISOLATE;
2169 	} else {
2170 		from_mt = MIGRATE_ISOLATE;
2171 		to_mt = __get_pfnblock_flags_mask(page, page_to_pfn(page),
2172 						  MIGRATETYPE_MASK);
2173 	}
2174 
2175 	__move_freepages_block(zone, start_pfn, from_mt, to_mt);
2176 	toggle_pageblock_isolate(pfn_to_page(start_pfn), isolate);
2177 
2178 	return true;
2179 }
2180 
2181 bool pageblock_isolate_and_move_free_pages(struct zone *zone, struct page *page)
2182 {
2183 	return __move_freepages_block_isolate(zone, page, true);
2184 }
2185 
2186 bool pageblock_unisolate_and_move_free_pages(struct zone *zone, struct page *page)
2187 {
2188 	return __move_freepages_block_isolate(zone, page, false);
2189 }
2190 
2191 #endif /* CONFIG_MEMORY_ISOLATION */
2192 
2193 static inline bool boost_watermark(struct zone *zone)
2194 {
2195 	unsigned long max_boost;
2196 
2197 	if (!watermark_boost_factor)
2198 		return false;
2199 	/*
2200 	 * Don't bother in zones that are unlikely to produce results.
2201 	 * On small machines, including kdump capture kernels running
2202 	 * in a small area, boosting the watermark can cause an out of
2203 	 * memory situation immediately.
2204 	 */
2205 	if ((pageblock_nr_pages * 4) > zone_managed_pages(zone))
2206 		return false;
2207 
2208 	max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
2209 			watermark_boost_factor, 10000);
2210 
2211 	/*
2212 	 * high watermark may be uninitialised if fragmentation occurs
2213 	 * very early in boot so do not boost. We do not fall
2214 	 * through and boost by pageblock_nr_pages as failing
2215 	 * allocations that early means that reclaim is not going
2216 	 * to help and it may even be impossible to reclaim the
2217 	 * boosted watermark resulting in a hang.
2218 	 */
2219 	if (!max_boost)
2220 		return false;
2221 
2222 	max_boost = max(pageblock_nr_pages, max_boost);
2223 
2224 	zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
2225 		max_boost);
2226 
2227 	return true;
2228 }
2229 
2230 /*
2231  * When we are falling back to another migratetype during allocation, should we
2232  * try to claim an entire block to satisfy further allocations, instead of
2233  * polluting multiple pageblocks?
2234  */
2235 static bool should_try_claim_block(unsigned int order, int start_mt)
2236 {
2237 	/*
2238 	 * Leaving this order check is intended, although there is
2239 	 * relaxed order check in next check. The reason is that
2240 	 * we can actually claim the whole pageblock if this condition met,
2241 	 * but, below check doesn't guarantee it and that is just heuristic
2242 	 * so could be changed anytime.
2243 	 */
2244 	if (order >= pageblock_order)
2245 		return true;
2246 
2247 	/*
2248 	 * Above a certain threshold, always try to claim, as it's likely there
2249 	 * will be more free pages in the pageblock.
2250 	 */
2251 	if (order >= pageblock_order / 2)
2252 		return true;
2253 
2254 	/*
2255 	 * Unmovable/reclaimable allocations would cause permanent
2256 	 * fragmentations if they fell back to allocating from a movable block
2257 	 * (polluting it), so we try to claim the whole block regardless of the
2258 	 * allocation size. Later movable allocations can always steal from this
2259 	 * block, which is less problematic.
2260 	 */
2261 	if (start_mt == MIGRATE_RECLAIMABLE || start_mt == MIGRATE_UNMOVABLE)
2262 		return true;
2263 
2264 	if (page_group_by_mobility_disabled)
2265 		return true;
2266 
2267 	/*
2268 	 * Movable pages won't cause permanent fragmentation, so when you alloc
2269 	 * small pages, we just need to temporarily steal unmovable or
2270 	 * reclaimable pages that are closest to the request size. After a
2271 	 * while, memory compaction may occur to form large contiguous pages,
2272 	 * and the next movable allocation may not need to steal.
2273 	 */
2274 	return false;
2275 }
2276 
2277 /*
2278  * Check whether there is a suitable fallback freepage with requested order.
2279  * If claimable is true, this function returns fallback_mt only if
2280  * we would do this whole-block claiming. This would help to reduce
2281  * fragmentation due to mixed migratetype pages in one pageblock.
2282  */
2283 int find_suitable_fallback(struct free_area *area, unsigned int order,
2284 			   int migratetype, bool claimable)
2285 {
2286 	int i;
2287 
2288 	if (claimable && !should_try_claim_block(order, migratetype))
2289 		return -2;
2290 
2291 	if (area->nr_free == 0)
2292 		return -1;
2293 
2294 	for (i = 0; i < MIGRATE_PCPTYPES - 1 ; i++) {
2295 		int fallback_mt = fallbacks[migratetype][i];
2296 
2297 		if (!free_area_empty(area, fallback_mt))
2298 			return fallback_mt;
2299 	}
2300 
2301 	return -1;
2302 }
2303 
2304 /*
2305  * This function implements actual block claiming behaviour. If order is large
2306  * enough, we can claim the whole pageblock for the requested migratetype. If
2307  * not, we check the pageblock for constituent pages; if at least half of the
2308  * pages are free or compatible, we can still claim the whole block, so pages
2309  * freed in the future will be put on the correct free list.
2310  */
2311 static struct page *
2312 try_to_claim_block(struct zone *zone, struct page *page,
2313 		   int current_order, int order, int start_type,
2314 		   int block_type, unsigned int alloc_flags)
2315 {
2316 	int free_pages, movable_pages, alike_pages;
2317 	unsigned long start_pfn;
2318 
2319 	/* Take ownership for orders >= pageblock_order */
2320 	if (current_order >= pageblock_order) {
2321 		unsigned int nr_added;
2322 
2323 		del_page_from_free_list(page, zone, current_order, block_type);
2324 		change_pageblock_range(page, current_order, start_type);
2325 		nr_added = expand(zone, page, order, current_order, start_type);
2326 		account_freepages(zone, nr_added, start_type);
2327 		return page;
2328 	}
2329 
2330 	/*
2331 	 * Boost watermarks to increase reclaim pressure to reduce the
2332 	 * likelihood of future fallbacks. Wake kswapd now as the node
2333 	 * may be balanced overall and kswapd will not wake naturally.
2334 	 */
2335 	if (boost_watermark(zone) && (alloc_flags & ALLOC_KSWAPD))
2336 		set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
2337 
2338 	/* moving whole block can fail due to zone boundary conditions */
2339 	if (!prep_move_freepages_block(zone, page, &start_pfn, &free_pages,
2340 				       &movable_pages))
2341 		return NULL;
2342 
2343 	/*
2344 	 * Determine how many pages are compatible with our allocation.
2345 	 * For movable allocation, it's the number of movable pages which
2346 	 * we just obtained. For other types it's a bit more tricky.
2347 	 */
2348 	if (start_type == MIGRATE_MOVABLE) {
2349 		alike_pages = movable_pages;
2350 	} else {
2351 		/*
2352 		 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2353 		 * to MOVABLE pageblock, consider all non-movable pages as
2354 		 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2355 		 * vice versa, be conservative since we can't distinguish the
2356 		 * exact migratetype of non-movable pages.
2357 		 */
2358 		if (block_type == MIGRATE_MOVABLE)
2359 			alike_pages = pageblock_nr_pages
2360 						- (free_pages + movable_pages);
2361 		else
2362 			alike_pages = 0;
2363 	}
2364 	/*
2365 	 * If a sufficient number of pages in the block are either free or of
2366 	 * compatible migratability as our allocation, claim the whole block.
2367 	 */
2368 	if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2369 			page_group_by_mobility_disabled) {
2370 		__move_freepages_block(zone, start_pfn, block_type, start_type);
2371 		set_pageblock_migratetype(pfn_to_page(start_pfn), start_type);
2372 		return __rmqueue_smallest(zone, order, start_type);
2373 	}
2374 
2375 	return NULL;
2376 }
2377 
2378 /*
2379  * Try to allocate from some fallback migratetype by claiming the entire block,
2380  * i.e. converting it to the allocation's start migratetype.
2381  *
2382  * The use of signed ints for order and current_order is a deliberate
2383  * deviation from the rest of this file, to make the for loop
2384  * condition simpler.
2385  */
2386 static __always_inline struct page *
2387 __rmqueue_claim(struct zone *zone, int order, int start_migratetype,
2388 						unsigned int alloc_flags)
2389 {
2390 	struct free_area *area;
2391 	int current_order;
2392 	int min_order = order;
2393 	struct page *page;
2394 	int fallback_mt;
2395 
2396 	/*
2397 	 * Do not steal pages from freelists belonging to other pageblocks
2398 	 * i.e. orders < pageblock_order. If there are no local zones free,
2399 	 * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2400 	 */
2401 	if (order < pageblock_order && alloc_flags & ALLOC_NOFRAGMENT)
2402 		min_order = pageblock_order;
2403 
2404 	/*
2405 	 * Find the largest available free page in the other list. This roughly
2406 	 * approximates finding the pageblock with the most free pages, which
2407 	 * would be too costly to do exactly.
2408 	 */
2409 	for (current_order = MAX_PAGE_ORDER; current_order >= min_order;
2410 				--current_order) {
2411 		area = &(zone->free_area[current_order]);
2412 		fallback_mt = find_suitable_fallback(area, current_order,
2413 						     start_migratetype, true);
2414 
2415 		/* No block in that order */
2416 		if (fallback_mt == -1)
2417 			continue;
2418 
2419 		/* Advanced into orders too low to claim, abort */
2420 		if (fallback_mt == -2)
2421 			break;
2422 
2423 		page = get_page_from_free_area(area, fallback_mt);
2424 		page = try_to_claim_block(zone, page, current_order, order,
2425 					  start_migratetype, fallback_mt,
2426 					  alloc_flags);
2427 		if (page) {
2428 			trace_mm_page_alloc_extfrag(page, order, current_order,
2429 						    start_migratetype, fallback_mt);
2430 			return page;
2431 		}
2432 	}
2433 
2434 	return NULL;
2435 }
2436 
2437 /*
2438  * Try to steal a single page from some fallback migratetype. Leave the rest of
2439  * the block as its current migratetype, potentially causing fragmentation.
2440  */
2441 static __always_inline struct page *
2442 __rmqueue_steal(struct zone *zone, int order, int start_migratetype)
2443 {
2444 	struct free_area *area;
2445 	int current_order;
2446 	struct page *page;
2447 	int fallback_mt;
2448 
2449 	for (current_order = order; current_order < NR_PAGE_ORDERS; current_order++) {
2450 		area = &(zone->free_area[current_order]);
2451 		fallback_mt = find_suitable_fallback(area, current_order,
2452 						     start_migratetype, false);
2453 		if (fallback_mt == -1)
2454 			continue;
2455 
2456 		page = get_page_from_free_area(area, fallback_mt);
2457 		page_del_and_expand(zone, page, order, current_order, fallback_mt);
2458 		trace_mm_page_alloc_extfrag(page, order, current_order,
2459 					    start_migratetype, fallback_mt);
2460 		return page;
2461 	}
2462 
2463 	return NULL;
2464 }
2465 
2466 enum rmqueue_mode {
2467 	RMQUEUE_NORMAL,
2468 	RMQUEUE_CMA,
2469 	RMQUEUE_CLAIM,
2470 	RMQUEUE_STEAL,
2471 };
2472 
2473 /*
2474  * Do the hard work of removing an element from the buddy allocator.
2475  * Call me with the zone->lock already held.
2476  */
2477 static __always_inline struct page *
2478 __rmqueue(struct zone *zone, unsigned int order, int migratetype,
2479 	  unsigned int alloc_flags, enum rmqueue_mode *mode)
2480 {
2481 	struct page *page;
2482 
2483 	if (IS_ENABLED(CONFIG_CMA)) {
2484 		/*
2485 		 * Balance movable allocations between regular and CMA areas by
2486 		 * allocating from CMA when over half of the zone's free memory
2487 		 * is in the CMA area.
2488 		 */
2489 		if (alloc_flags & ALLOC_CMA &&
2490 		    zone_page_state(zone, NR_FREE_CMA_PAGES) >
2491 		    zone_page_state(zone, NR_FREE_PAGES) / 2) {
2492 			page = __rmqueue_cma_fallback(zone, order);
2493 			if (page)
2494 				return page;
2495 		}
2496 	}
2497 
2498 	/*
2499 	 * First try the freelists of the requested migratetype, then try
2500 	 * fallbacks modes with increasing levels of fragmentation risk.
2501 	 *
2502 	 * The fallback logic is expensive and rmqueue_bulk() calls in
2503 	 * a loop with the zone->lock held, meaning the freelists are
2504 	 * not subject to any outside changes. Remember in *mode where
2505 	 * we found pay dirt, to save us the search on the next call.
2506 	 */
2507 	switch (*mode) {
2508 	case RMQUEUE_NORMAL:
2509 		page = __rmqueue_smallest(zone, order, migratetype);
2510 		if (page)
2511 			return page;
2512 		fallthrough;
2513 	case RMQUEUE_CMA:
2514 		if (alloc_flags & ALLOC_CMA) {
2515 			page = __rmqueue_cma_fallback(zone, order);
2516 			if (page) {
2517 				*mode = RMQUEUE_CMA;
2518 				return page;
2519 			}
2520 		}
2521 		fallthrough;
2522 	case RMQUEUE_CLAIM:
2523 		page = __rmqueue_claim(zone, order, migratetype, alloc_flags);
2524 		if (page) {
2525 			/* Replenished preferred freelist, back to normal mode. */
2526 			*mode = RMQUEUE_NORMAL;
2527 			return page;
2528 		}
2529 		fallthrough;
2530 	case RMQUEUE_STEAL:
2531 		if (!(alloc_flags & ALLOC_NOFRAGMENT)) {
2532 			page = __rmqueue_steal(zone, order, migratetype);
2533 			if (page) {
2534 				*mode = RMQUEUE_STEAL;
2535 				return page;
2536 			}
2537 		}
2538 	}
2539 	return NULL;
2540 }
2541 
2542 /*
2543  * Obtain a specified number of elements from the buddy allocator, all under
2544  * a single hold of the lock, for efficiency.  Add them to the supplied list.
2545  * Returns the number of new pages which were placed at *list.
2546  */
2547 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2548 			unsigned long count, struct list_head *list,
2549 			int migratetype, unsigned int alloc_flags)
2550 {
2551 	enum rmqueue_mode rmqm = RMQUEUE_NORMAL;
2552 	unsigned long flags;
2553 	int i;
2554 
2555 	if (unlikely(alloc_flags & ALLOC_TRYLOCK)) {
2556 		if (!spin_trylock_irqsave(&zone->lock, flags))
2557 			return 0;
2558 	} else {
2559 		spin_lock_irqsave(&zone->lock, flags);
2560 	}
2561 	for (i = 0; i < count; ++i) {
2562 		struct page *page = __rmqueue(zone, order, migratetype,
2563 					      alloc_flags, &rmqm);
2564 		if (unlikely(page == NULL))
2565 			break;
2566 
2567 		/*
2568 		 * Split buddy pages returned by expand() are received here in
2569 		 * physical page order. The page is added to the tail of
2570 		 * caller's list. From the callers perspective, the linked list
2571 		 * is ordered by page number under some conditions. This is
2572 		 * useful for IO devices that can forward direction from the
2573 		 * head, thus also in the physical page order. This is useful
2574 		 * for IO devices that can merge IO requests if the physical
2575 		 * pages are ordered properly.
2576 		 */
2577 		list_add_tail(&page->pcp_list, list);
2578 	}
2579 	spin_unlock_irqrestore(&zone->lock, flags);
2580 
2581 	return i;
2582 }
2583 
2584 /*
2585  * Called from the vmstat counter updater to decay the PCP high.
2586  * Return whether there are addition works to do.
2587  */
2588 bool decay_pcp_high(struct zone *zone, struct per_cpu_pages *pcp)
2589 {
2590 	int high_min, to_drain, to_drain_batched, batch;
2591 	unsigned long UP_flags;
2592 	bool todo = false;
2593 
2594 	high_min = READ_ONCE(pcp->high_min);
2595 	batch = READ_ONCE(pcp->batch);
2596 	/*
2597 	 * Decrease pcp->high periodically to try to free possible
2598 	 * idle PCP pages.  And, avoid to free too many pages to
2599 	 * control latency.  This caps pcp->high decrement too.
2600 	 */
2601 	if (pcp->high > high_min) {
2602 		pcp->high = max3(pcp->count - (batch << CONFIG_PCP_BATCH_SCALE_MAX),
2603 				 pcp->high - (pcp->high >> 3), high_min);
2604 		if (pcp->high > high_min)
2605 			todo = true;
2606 	}
2607 
2608 	to_drain = pcp->count - pcp->high;
2609 	while (to_drain > 0) {
2610 		to_drain_batched = min(to_drain, batch);
2611 		pcp_spin_lock_maybe_irqsave(pcp, UP_flags);
2612 		free_pcppages_bulk(zone, to_drain_batched, pcp, 0);
2613 		pcp_spin_unlock_maybe_irqrestore(pcp, UP_flags);
2614 		todo = true;
2615 
2616 		to_drain -= to_drain_batched;
2617 	}
2618 
2619 	return todo;
2620 }
2621 
2622 #ifdef CONFIG_NUMA
2623 /*
2624  * Called from the vmstat counter updater to drain pagesets of this
2625  * currently executing processor on remote nodes after they have
2626  * expired.
2627  */
2628 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2629 {
2630 	unsigned long UP_flags;
2631 	int to_drain, batch;
2632 
2633 	batch = READ_ONCE(pcp->batch);
2634 	to_drain = min(pcp->count, batch);
2635 	if (to_drain > 0) {
2636 		pcp_spin_lock_maybe_irqsave(pcp, UP_flags);
2637 		free_pcppages_bulk(zone, to_drain, pcp, 0);
2638 		pcp_spin_unlock_maybe_irqrestore(pcp, UP_flags);
2639 	}
2640 }
2641 #endif
2642 
2643 /*
2644  * Drain pcplists of the indicated processor and zone.
2645  */
2646 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2647 {
2648 	struct per_cpu_pages *pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
2649 	unsigned long UP_flags;
2650 	int count;
2651 
2652 	do {
2653 		pcp_spin_lock_maybe_irqsave(pcp, UP_flags);
2654 		count = pcp->count;
2655 		if (count) {
2656 			int to_drain = min(count,
2657 				pcp->batch << CONFIG_PCP_BATCH_SCALE_MAX);
2658 
2659 			free_pcppages_bulk(zone, to_drain, pcp, 0);
2660 			count -= to_drain;
2661 		}
2662 		pcp_spin_unlock_maybe_irqrestore(pcp, UP_flags);
2663 	} while (count);
2664 }
2665 
2666 /*
2667  * Drain pcplists of all zones on the indicated processor.
2668  */
2669 static void drain_pages(unsigned int cpu)
2670 {
2671 	struct zone *zone;
2672 
2673 	for_each_populated_zone(zone) {
2674 		drain_pages_zone(cpu, zone);
2675 	}
2676 }
2677 
2678 /*
2679  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2680  */
2681 void drain_local_pages(struct zone *zone)
2682 {
2683 	int cpu = smp_processor_id();
2684 
2685 	if (zone)
2686 		drain_pages_zone(cpu, zone);
2687 	else
2688 		drain_pages(cpu);
2689 }
2690 
2691 /*
2692  * The implementation of drain_all_pages(), exposing an extra parameter to
2693  * drain on all cpus.
2694  *
2695  * drain_all_pages() is optimized to only execute on cpus where pcplists are
2696  * not empty. The check for non-emptiness can however race with a free to
2697  * pcplist that has not yet increased the pcp->count from 0 to 1. Callers
2698  * that need the guarantee that every CPU has drained can disable the
2699  * optimizing racy check.
2700  */
2701 static void __drain_all_pages(struct zone *zone, bool force_all_cpus)
2702 {
2703 	int cpu;
2704 
2705 	/*
2706 	 * Allocate in the BSS so we won't require allocation in
2707 	 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2708 	 */
2709 	static cpumask_t cpus_with_pcps;
2710 
2711 	/*
2712 	 * Do not drain if one is already in progress unless it's specific to
2713 	 * a zone. Such callers are primarily CMA and memory hotplug and need
2714 	 * the drain to be complete when the call returns.
2715 	 */
2716 	if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
2717 		if (!zone)
2718 			return;
2719 		mutex_lock(&pcpu_drain_mutex);
2720 	}
2721 
2722 	/*
2723 	 * We don't care about racing with CPU hotplug event
2724 	 * as offline notification will cause the notified
2725 	 * cpu to drain that CPU pcps and on_each_cpu_mask
2726 	 * disables preemption as part of its processing
2727 	 */
2728 	for_each_online_cpu(cpu) {
2729 		struct per_cpu_pages *pcp;
2730 		struct zone *z;
2731 		bool has_pcps = false;
2732 
2733 		if (force_all_cpus) {
2734 			/*
2735 			 * The pcp.count check is racy, some callers need a
2736 			 * guarantee that no cpu is missed.
2737 			 */
2738 			has_pcps = true;
2739 		} else if (zone) {
2740 			pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
2741 			if (pcp->count)
2742 				has_pcps = true;
2743 		} else {
2744 			for_each_populated_zone(z) {
2745 				pcp = per_cpu_ptr(z->per_cpu_pageset, cpu);
2746 				if (pcp->count) {
2747 					has_pcps = true;
2748 					break;
2749 				}
2750 			}
2751 		}
2752 
2753 		if (has_pcps)
2754 			cpumask_set_cpu(cpu, &cpus_with_pcps);
2755 		else
2756 			cpumask_clear_cpu(cpu, &cpus_with_pcps);
2757 	}
2758 
2759 	for_each_cpu(cpu, &cpus_with_pcps) {
2760 		if (zone)
2761 			drain_pages_zone(cpu, zone);
2762 		else
2763 			drain_pages(cpu);
2764 	}
2765 
2766 	mutex_unlock(&pcpu_drain_mutex);
2767 }
2768 
2769 /*
2770  * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2771  *
2772  * When zone parameter is non-NULL, spill just the single zone's pages.
2773  */
2774 void drain_all_pages(struct zone *zone)
2775 {
2776 	__drain_all_pages(zone, false);
2777 }
2778 
2779 static int nr_pcp_free(struct per_cpu_pages *pcp, int batch, int high, bool free_high)
2780 {
2781 	int min_nr_free, max_nr_free;
2782 
2783 	/* Free as much as possible if batch freeing high-order pages. */
2784 	if (unlikely(free_high))
2785 		return min(pcp->count, batch << CONFIG_PCP_BATCH_SCALE_MAX);
2786 
2787 	/* Check for PCP disabled or boot pageset */
2788 	if (unlikely(high < batch))
2789 		return 1;
2790 
2791 	/* Leave at least pcp->batch pages on the list */
2792 	min_nr_free = batch;
2793 	max_nr_free = high - batch;
2794 
2795 	/*
2796 	 * Increase the batch number to the number of the consecutive
2797 	 * freed pages to reduce zone lock contention.
2798 	 */
2799 	batch = clamp_t(int, pcp->free_count, min_nr_free, max_nr_free);
2800 
2801 	return batch;
2802 }
2803 
2804 static int nr_pcp_high(struct per_cpu_pages *pcp, struct zone *zone,
2805 		       int batch, bool free_high)
2806 {
2807 	int high, high_min, high_max;
2808 
2809 	high_min = READ_ONCE(pcp->high_min);
2810 	high_max = READ_ONCE(pcp->high_max);
2811 	high = pcp->high = clamp(pcp->high, high_min, high_max);
2812 
2813 	if (unlikely(!high))
2814 		return 0;
2815 
2816 	if (unlikely(free_high)) {
2817 		pcp->high = max(high - (batch << CONFIG_PCP_BATCH_SCALE_MAX),
2818 				high_min);
2819 		return 0;
2820 	}
2821 
2822 	/*
2823 	 * If reclaim is active, limit the number of pages that can be
2824 	 * stored on pcp lists
2825 	 */
2826 	if (test_bit(ZONE_RECLAIM_ACTIVE, &zone->flags)) {
2827 		int free_count = max_t(int, pcp->free_count, batch);
2828 
2829 		pcp->high = max(high - free_count, high_min);
2830 		return min(batch << 2, pcp->high);
2831 	}
2832 
2833 	if (high_min == high_max)
2834 		return high;
2835 
2836 	if (test_bit(ZONE_BELOW_HIGH, &zone->flags)) {
2837 		int free_count = max_t(int, pcp->free_count, batch);
2838 
2839 		pcp->high = max(high - free_count, high_min);
2840 		high = max(pcp->count, high_min);
2841 	} else if (pcp->count >= high) {
2842 		int need_high = pcp->free_count + batch;
2843 
2844 		/* pcp->high should be large enough to hold batch freed pages */
2845 		if (pcp->high < need_high)
2846 			pcp->high = clamp(need_high, high_min, high_max);
2847 	}
2848 
2849 	return high;
2850 }
2851 
2852 /*
2853  * Tune pcp alloc factor and adjust count & free_count. Free pages to bring the
2854  * pcp's watermarks below high.
2855  *
2856  * May return a freed pcp, if during page freeing the pcp spinlock cannot be
2857  * reacquired. Return true if pcp is locked, false otherwise.
2858  */
2859 static bool free_frozen_page_commit(struct zone *zone,
2860 		struct per_cpu_pages *pcp, struct page *page, int migratetype,
2861 		unsigned int order, fpi_t fpi_flags, unsigned long *UP_flags)
2862 {
2863 	int high, batch;
2864 	int to_free, to_free_batched;
2865 	int pindex;
2866 	int cpu = smp_processor_id();
2867 	int ret = true;
2868 	bool free_high = false;
2869 
2870 	/*
2871 	 * On freeing, reduce the number of pages that are batch allocated.
2872 	 * See nr_pcp_alloc() where alloc_factor is increased for subsequent
2873 	 * allocations.
2874 	 */
2875 	pcp->alloc_factor >>= 1;
2876 	__count_vm_events(PGFREE, 1 << order);
2877 	pindex = order_to_pindex(migratetype, order);
2878 	list_add(&page->pcp_list, &pcp->lists[pindex]);
2879 	pcp->count += 1 << order;
2880 
2881 	batch = READ_ONCE(pcp->batch);
2882 	/*
2883 	 * As high-order pages other than THP's stored on PCP can contribute
2884 	 * to fragmentation, limit the number stored when PCP is heavily
2885 	 * freeing without allocation. The remainder after bulk freeing
2886 	 * stops will be drained from vmstat refresh context.
2887 	 */
2888 	if (order && order <= PAGE_ALLOC_COSTLY_ORDER) {
2889 		free_high = (pcp->free_count >= (batch + pcp->high_min / 2) &&
2890 			     (pcp->flags & PCPF_PREV_FREE_HIGH_ORDER) &&
2891 			     (!(pcp->flags & PCPF_FREE_HIGH_BATCH) ||
2892 			      pcp->count >= batch));
2893 		pcp->flags |= PCPF_PREV_FREE_HIGH_ORDER;
2894 	} else if (pcp->flags & PCPF_PREV_FREE_HIGH_ORDER) {
2895 		pcp->flags &= ~PCPF_PREV_FREE_HIGH_ORDER;
2896 	}
2897 	if (pcp->free_count < (batch << CONFIG_PCP_BATCH_SCALE_MAX))
2898 		pcp->free_count += (1 << order);
2899 
2900 	if (unlikely(fpi_flags & FPI_TRYLOCK)) {
2901 		/*
2902 		 * Do not attempt to take a zone lock. Let pcp->count get
2903 		 * over high mark temporarily.
2904 		 */
2905 		return true;
2906 	}
2907 
2908 	high = nr_pcp_high(pcp, zone, batch, free_high);
2909 	if (pcp->count < high)
2910 		return true;
2911 
2912 	to_free = nr_pcp_free(pcp, batch, high, free_high);
2913 	while (to_free > 0 && pcp->count > 0) {
2914 		to_free_batched = min(to_free, batch);
2915 		free_pcppages_bulk(zone, to_free_batched, pcp, pindex);
2916 		to_free -= to_free_batched;
2917 
2918 		if (to_free == 0 || pcp->count == 0)
2919 			break;
2920 
2921 		pcp_spin_unlock(pcp, *UP_flags);
2922 
2923 		pcp = pcp_spin_trylock(zone->per_cpu_pageset, *UP_flags);
2924 		if (!pcp) {
2925 			ret = false;
2926 			break;
2927 		}
2928 
2929 		/*
2930 		 * Check if this thread has been migrated to a different CPU.
2931 		 * If that is the case, give up and indicate that the pcp is
2932 		 * returned in an unlocked state.
2933 		 */
2934 		if (smp_processor_id() != cpu) {
2935 			pcp_spin_unlock(pcp, *UP_flags);
2936 			ret = false;
2937 			break;
2938 		}
2939 	}
2940 
2941 	if (test_bit(ZONE_BELOW_HIGH, &zone->flags) &&
2942 	    zone_watermark_ok(zone, 0, high_wmark_pages(zone),
2943 			      ZONE_MOVABLE, 0)) {
2944 		struct pglist_data *pgdat = zone->zone_pgdat;
2945 		clear_bit(ZONE_BELOW_HIGH, &zone->flags);
2946 
2947 		/*
2948 		 * Assume that memory pressure on this node is gone and may be
2949 		 * in a reclaimable state. If a memory fallback node exists,
2950 		 * direct reclaim may not have been triggered, causing a
2951 		 * 'hopeless node' to stay in that state for a while.  Let
2952 		 * kswapd work again by resetting kswapd_failures.
2953 		 */
2954 		if (kswapd_test_hopeless(pgdat) &&
2955 		    next_memory_node(pgdat->node_id) < MAX_NUMNODES)
2956 			kswapd_clear_hopeless(pgdat, KSWAPD_CLEAR_HOPELESS_PCP);
2957 	}
2958 	return ret;
2959 }
2960 
2961 /*
2962  * Free a pcp page
2963  */
2964 static void __free_frozen_pages(struct page *page, unsigned int order,
2965 				fpi_t fpi_flags)
2966 {
2967 	unsigned long UP_flags;
2968 	struct per_cpu_pages *pcp;
2969 	struct zone *zone;
2970 	unsigned long pfn = page_to_pfn(page);
2971 	int migratetype;
2972 
2973 	if (!pcp_allowed_order(order)) {
2974 		__free_pages_ok(page, order, fpi_flags);
2975 		return;
2976 	}
2977 
2978 	if (!__free_pages_prepare(page, order, fpi_flags))
2979 		return;
2980 
2981 	/*
2982 	 * We only track unmovable, reclaimable and movable on pcp lists.
2983 	 * Place ISOLATE pages on the isolated list because they are being
2984 	 * offlined but treat HIGHATOMIC and CMA as movable pages so we can
2985 	 * get those areas back if necessary. Otherwise, we may have to free
2986 	 * excessively into the page allocator
2987 	 */
2988 	zone = page_zone(page);
2989 	migratetype = get_pfnblock_migratetype(page, pfn);
2990 	if (unlikely(migratetype >= MIGRATE_PCPTYPES)) {
2991 		if (unlikely(is_migrate_isolate(migratetype))) {
2992 			free_one_page(zone, page, pfn, order, fpi_flags);
2993 			return;
2994 		}
2995 		migratetype = MIGRATE_MOVABLE;
2996 	}
2997 
2998 	if (unlikely((fpi_flags & FPI_TRYLOCK) && IS_ENABLED(CONFIG_PREEMPT_RT)
2999 		     && (in_nmi() || in_hardirq()))) {
3000 		add_page_to_zone_llist(zone, page, order);
3001 		return;
3002 	}
3003 	pcp = pcp_spin_trylock(zone->per_cpu_pageset, UP_flags);
3004 	if (pcp) {
3005 		if (!free_frozen_page_commit(zone, pcp, page, migratetype,
3006 						order, fpi_flags, &UP_flags))
3007 			return;
3008 		pcp_spin_unlock(pcp, UP_flags);
3009 	} else {
3010 		free_one_page(zone, page, pfn, order, fpi_flags);
3011 	}
3012 }
3013 
3014 void free_frozen_pages(struct page *page, unsigned int order)
3015 {
3016 	__free_frozen_pages(page, order, FPI_NONE);
3017 }
3018 
3019 void free_frozen_pages_nolock(struct page *page, unsigned int order)
3020 {
3021 	__free_frozen_pages(page, order, FPI_TRYLOCK);
3022 }
3023 
3024 /*
3025  * Free a batch of folios
3026  */
3027 void free_unref_folios(struct folio_batch *folios)
3028 {
3029 	unsigned long UP_flags;
3030 	struct per_cpu_pages *pcp = NULL;
3031 	struct zone *locked_zone = NULL;
3032 	int i, j;
3033 
3034 	/* Prepare folios for freeing */
3035 	for (i = 0, j = 0; i < folios->nr; i++) {
3036 		struct folio *folio = folios->folios[i];
3037 		unsigned long pfn = folio_pfn(folio);
3038 		unsigned int order = folio_order(folio);
3039 
3040 		if (!__free_pages_prepare(&folio->page, order, FPI_NONE))
3041 			continue;
3042 		/*
3043 		 * Free orders not handled on the PCP directly to the
3044 		 * allocator.
3045 		 */
3046 		if (!pcp_allowed_order(order)) {
3047 			free_one_page(folio_zone(folio), &folio->page,
3048 				      pfn, order, FPI_NONE);
3049 			continue;
3050 		}
3051 		folio->private = (void *)(unsigned long)order;
3052 		if (j != i)
3053 			folios->folios[j] = folio;
3054 		j++;
3055 	}
3056 	folios->nr = j;
3057 
3058 	for (i = 0; i < folios->nr; i++) {
3059 		struct folio *folio = folios->folios[i];
3060 		struct zone *zone = folio_zone(folio);
3061 		unsigned long pfn = folio_pfn(folio);
3062 		unsigned int order = (unsigned long)folio->private;
3063 		int migratetype;
3064 
3065 		folio->private = NULL;
3066 		migratetype = get_pfnblock_migratetype(&folio->page, pfn);
3067 
3068 		/* Different zone requires a different pcp lock */
3069 		if (zone != locked_zone ||
3070 		    is_migrate_isolate(migratetype)) {
3071 			if (pcp) {
3072 				pcp_spin_unlock(pcp, UP_flags);
3073 				locked_zone = NULL;
3074 				pcp = NULL;
3075 			}
3076 
3077 			/*
3078 			 * Free isolated pages directly to the
3079 			 * allocator, see comment in free_frozen_pages.
3080 			 */
3081 			if (is_migrate_isolate(migratetype)) {
3082 				free_one_page(zone, &folio->page, pfn,
3083 					      order, FPI_NONE);
3084 				continue;
3085 			}
3086 
3087 			/*
3088 			 * trylock is necessary as folios may be getting freed
3089 			 * from IRQ or SoftIRQ context after an IO completion.
3090 			 */
3091 			pcp = pcp_spin_trylock(zone->per_cpu_pageset, UP_flags);
3092 			if (unlikely(!pcp)) {
3093 				free_one_page(zone, &folio->page, pfn,
3094 					      order, FPI_NONE);
3095 				continue;
3096 			}
3097 			locked_zone = zone;
3098 		}
3099 
3100 		/*
3101 		 * Non-isolated types over MIGRATE_PCPTYPES get added
3102 		 * to the MIGRATE_MOVABLE pcp list.
3103 		 */
3104 		if (unlikely(migratetype >= MIGRATE_PCPTYPES))
3105 			migratetype = MIGRATE_MOVABLE;
3106 
3107 		trace_mm_page_free_batched(&folio->page);
3108 		if (!free_frozen_page_commit(zone, pcp, &folio->page,
3109 				migratetype, order, FPI_NONE, &UP_flags)) {
3110 			pcp = NULL;
3111 			locked_zone = NULL;
3112 		}
3113 	}
3114 
3115 	if (pcp)
3116 		pcp_spin_unlock(pcp, UP_flags);
3117 	folio_batch_reinit(folios);
3118 }
3119 
3120 static void __split_page(struct page *page, unsigned int order)
3121 {
3122 	VM_WARN_ON_PAGE(PageCompound(page), page);
3123 
3124 	split_page_owner(page, order, 0);
3125 	pgalloc_tag_split(page_folio(page), order, 0);
3126 	split_page_memcg(page, order);
3127 }
3128 
3129 /*
3130  * split_page takes a non-compound higher-order page, and splits it into
3131  * n (1<<order) sub-pages: page[0..n]
3132  * Each sub-page must be freed individually.
3133  *
3134  * Note: this is probably too low level an operation for use in drivers.
3135  * Please consult with lkml before using this in your driver.
3136  */
3137 void split_page(struct page *page, unsigned int order)
3138 {
3139 	int i;
3140 
3141 	VM_WARN_ON_PAGE(!page_count(page), page);
3142 
3143 	for (i = 1; i < (1 << order); i++)
3144 		set_page_refcounted(page + i);
3145 
3146 	__split_page(page, order);
3147 }
3148 EXPORT_SYMBOL_GPL(split_page);
3149 
3150 int __isolate_free_page(struct page *page, unsigned int order)
3151 {
3152 	struct zone *zone = page_zone(page);
3153 	int mt = get_pageblock_migratetype(page);
3154 
3155 	if (!is_migrate_isolate(mt)) {
3156 		unsigned long watermark;
3157 		/*
3158 		 * Obey watermarks as if the page was being allocated. We can
3159 		 * emulate a high-order watermark check with a raised order-0
3160 		 * watermark, because we already know our high-order page
3161 		 * exists.
3162 		 */
3163 		watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
3164 		if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
3165 			return 0;
3166 	}
3167 
3168 	del_page_from_free_list(page, zone, order, mt);
3169 
3170 	/*
3171 	 * Set the pageblock if the isolated page is at least half of a
3172 	 * pageblock
3173 	 */
3174 	if (order >= pageblock_order - 1) {
3175 		struct page *endpage = page + (1 << order) - 1;
3176 		for (; page < endpage; page += pageblock_nr_pages) {
3177 			int mt = get_pageblock_migratetype(page);
3178 			/*
3179 			 * Only change normal pageblocks (i.e., they can merge
3180 			 * with others)
3181 			 */
3182 			if (migratetype_is_mergeable(mt))
3183 				move_freepages_block(zone, page, mt,
3184 						     MIGRATE_MOVABLE);
3185 		}
3186 	}
3187 
3188 	return 1UL << order;
3189 }
3190 
3191 /**
3192  * __putback_isolated_page - Return a now-isolated page back where we got it
3193  * @page: Page that was isolated
3194  * @order: Order of the isolated page
3195  * @mt: The page's pageblock's migratetype
3196  *
3197  * This function is meant to return a page pulled from the free lists via
3198  * __isolate_free_page back to the free lists they were pulled from.
3199  */
3200 void __putback_isolated_page(struct page *page, unsigned int order, int mt)
3201 {
3202 	struct zone *zone = page_zone(page);
3203 
3204 	/* zone lock should be held when this function is called */
3205 	lockdep_assert_held(&zone->lock);
3206 
3207 	/* Return isolated page to tail of freelist. */
3208 	__free_one_page(page, page_to_pfn(page), zone, order, mt,
3209 			FPI_SKIP_REPORT_NOTIFY | FPI_TO_TAIL);
3210 }
3211 
3212 /*
3213  * Update NUMA hit/miss statistics
3214  */
3215 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z,
3216 				   long nr_account)
3217 {
3218 #ifdef CONFIG_NUMA
3219 	enum numa_stat_item local_stat = NUMA_LOCAL;
3220 
3221 	/* skip numa counters update if numa stats is disabled */
3222 	if (!static_branch_likely(&vm_numa_stat_key))
3223 		return;
3224 
3225 	if (zone_to_nid(z) != numa_node_id())
3226 		local_stat = NUMA_OTHER;
3227 
3228 	if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3229 		__count_numa_events(z, NUMA_HIT, nr_account);
3230 	else {
3231 		__count_numa_events(z, NUMA_MISS, nr_account);
3232 		__count_numa_events(preferred_zone, NUMA_FOREIGN, nr_account);
3233 	}
3234 	__count_numa_events(z, local_stat, nr_account);
3235 #endif
3236 }
3237 
3238 static __always_inline
3239 struct page *rmqueue_buddy(struct zone *preferred_zone, struct zone *zone,
3240 			   unsigned int order, unsigned int alloc_flags,
3241 			   int migratetype)
3242 {
3243 	struct page *page;
3244 	unsigned long flags;
3245 
3246 	do {
3247 		page = NULL;
3248 		if (unlikely(alloc_flags & ALLOC_TRYLOCK)) {
3249 			if (!spin_trylock_irqsave(&zone->lock, flags))
3250 				return NULL;
3251 		} else {
3252 			spin_lock_irqsave(&zone->lock, flags);
3253 		}
3254 		if (alloc_flags & ALLOC_HIGHATOMIC)
3255 			page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3256 		if (!page) {
3257 			enum rmqueue_mode rmqm = RMQUEUE_NORMAL;
3258 
3259 			page = __rmqueue(zone, order, migratetype, alloc_flags, &rmqm);
3260 
3261 			/*
3262 			 * If the allocation fails, allow OOM handling and
3263 			 * order-0 (atomic) allocs access to HIGHATOMIC
3264 			 * reserves as failing now is worse than failing a
3265 			 * high-order atomic allocation in the future.
3266 			 */
3267 			if (!page && (alloc_flags & (ALLOC_OOM|ALLOC_NON_BLOCK)))
3268 				page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3269 
3270 			if (!page) {
3271 				spin_unlock_irqrestore(&zone->lock, flags);
3272 				return NULL;
3273 			}
3274 		}
3275 		spin_unlock_irqrestore(&zone->lock, flags);
3276 	} while (check_new_pages(page, order));
3277 
3278 	__count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3279 	zone_statistics(preferred_zone, zone, 1);
3280 
3281 	return page;
3282 }
3283 
3284 static int nr_pcp_alloc(struct per_cpu_pages *pcp, struct zone *zone, int order)
3285 {
3286 	int high, base_batch, batch, max_nr_alloc;
3287 	int high_max, high_min;
3288 
3289 	base_batch = READ_ONCE(pcp->batch);
3290 	high_min = READ_ONCE(pcp->high_min);
3291 	high_max = READ_ONCE(pcp->high_max);
3292 	high = pcp->high = clamp(pcp->high, high_min, high_max);
3293 
3294 	/* Check for PCP disabled or boot pageset */
3295 	if (unlikely(high < base_batch))
3296 		return 1;
3297 
3298 	if (order)
3299 		batch = base_batch;
3300 	else
3301 		batch = (base_batch << pcp->alloc_factor);
3302 
3303 	/*
3304 	 * If we had larger pcp->high, we could avoid to allocate from
3305 	 * zone.
3306 	 */
3307 	if (high_min != high_max && !test_bit(ZONE_BELOW_HIGH, &zone->flags))
3308 		high = pcp->high = min(high + batch, high_max);
3309 
3310 	if (!order) {
3311 		max_nr_alloc = max(high - pcp->count - base_batch, base_batch);
3312 		/*
3313 		 * Double the number of pages allocated each time there is
3314 		 * subsequent allocation of order-0 pages without any freeing.
3315 		 */
3316 		if (batch <= max_nr_alloc &&
3317 		    pcp->alloc_factor < CONFIG_PCP_BATCH_SCALE_MAX)
3318 			pcp->alloc_factor++;
3319 		batch = min(batch, max_nr_alloc);
3320 	}
3321 
3322 	/*
3323 	 * Scale batch relative to order if batch implies free pages
3324 	 * can be stored on the PCP. Batch can be 1 for small zones or
3325 	 * for boot pagesets which should never store free pages as
3326 	 * the pages may belong to arbitrary zones.
3327 	 */
3328 	if (batch > 1)
3329 		batch = max(batch >> order, 2);
3330 
3331 	return batch;
3332 }
3333 
3334 /* Remove page from the per-cpu list, caller must protect the list */
3335 static inline
3336 struct page *__rmqueue_pcplist(struct zone *zone, unsigned int order,
3337 			int migratetype,
3338 			unsigned int alloc_flags,
3339 			struct per_cpu_pages *pcp,
3340 			struct list_head *list)
3341 {
3342 	struct page *page;
3343 
3344 	do {
3345 		if (list_empty(list)) {
3346 			int batch = nr_pcp_alloc(pcp, zone, order);
3347 			int alloced;
3348 
3349 			alloced = rmqueue_bulk(zone, order,
3350 					batch, list,
3351 					migratetype, alloc_flags);
3352 
3353 			pcp->count += alloced << order;
3354 			if (unlikely(list_empty(list)))
3355 				return NULL;
3356 		}
3357 
3358 		page = list_first_entry(list, struct page, pcp_list);
3359 		list_del(&page->pcp_list);
3360 		pcp->count -= 1 << order;
3361 	} while (check_new_pages(page, order));
3362 
3363 	return page;
3364 }
3365 
3366 /* Lock and remove page from the per-cpu list */
3367 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
3368 			struct zone *zone, unsigned int order,
3369 			int migratetype, unsigned int alloc_flags)
3370 {
3371 	struct per_cpu_pages *pcp;
3372 	struct list_head *list;
3373 	struct page *page;
3374 	unsigned long UP_flags;
3375 
3376 	/* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */
3377 	pcp = pcp_spin_trylock(zone->per_cpu_pageset, UP_flags);
3378 	if (!pcp)
3379 		return NULL;
3380 
3381 	/*
3382 	 * On allocation, reduce the number of pages that are batch freed.
3383 	 * See nr_pcp_free() where free_factor is increased for subsequent
3384 	 * frees.
3385 	 */
3386 	pcp->free_count >>= 1;
3387 	list = &pcp->lists[order_to_pindex(migratetype, order)];
3388 	page = __rmqueue_pcplist(zone, order, migratetype, alloc_flags, pcp, list);
3389 	pcp_spin_unlock(pcp, UP_flags);
3390 	if (page) {
3391 		__count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3392 		zone_statistics(preferred_zone, zone, 1);
3393 	}
3394 	return page;
3395 }
3396 
3397 /*
3398  * Allocate a page from the given zone.
3399  * Use pcplists for THP or "cheap" high-order allocations.
3400  */
3401 
3402 /*
3403  * Do not instrument rmqueue() with KMSAN. This function may call
3404  * __msan_poison_alloca() through a call to set_pfnblock_migratetype().
3405  * If __msan_poison_alloca() attempts to allocate pages for the stack depot, it
3406  * may call rmqueue() again, which will result in a deadlock.
3407  */
3408 __no_sanitize_memory
3409 static inline
3410 struct page *rmqueue(struct zone *preferred_zone,
3411 			struct zone *zone, unsigned int order,
3412 			gfp_t gfp_flags, unsigned int alloc_flags,
3413 			int migratetype)
3414 {
3415 	struct page *page;
3416 
3417 	if (likely(pcp_allowed_order(order))) {
3418 		page = rmqueue_pcplist(preferred_zone, zone, order,
3419 				       migratetype, alloc_flags);
3420 		if (likely(page))
3421 			goto out;
3422 	}
3423 
3424 	page = rmqueue_buddy(preferred_zone, zone, order, alloc_flags,
3425 							migratetype);
3426 
3427 out:
3428 	/* Separate test+clear to avoid unnecessary atomics */
3429 	if ((alloc_flags & ALLOC_KSWAPD) &&
3430 	    unlikely(test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags))) {
3431 		clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3432 		wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3433 	}
3434 
3435 	VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3436 	return page;
3437 }
3438 
3439 /*
3440  * Reserve the pageblock(s) surrounding an allocation request for
3441  * exclusive use of high-order atomic allocations if there are no
3442  * empty page blocks that contain a page with a suitable order
3443  */
3444 static void reserve_highatomic_pageblock(struct page *page, int order,
3445 					 struct zone *zone)
3446 {
3447 	int mt;
3448 	unsigned long max_managed, flags;
3449 
3450 	/*
3451 	 * The number reserved as: minimum is 1 pageblock, maximum is
3452 	 * roughly 1% of a zone. But if 1% of a zone falls below a
3453 	 * pageblock size, then don't reserve any pageblocks.
3454 	 * Check is race-prone but harmless.
3455 	 */
3456 	if ((zone_managed_pages(zone) / 100) < pageblock_nr_pages)
3457 		return;
3458 	max_managed = ALIGN((zone_managed_pages(zone) / 100), pageblock_nr_pages);
3459 	if (zone->nr_reserved_highatomic >= max_managed)
3460 		return;
3461 
3462 	spin_lock_irqsave(&zone->lock, flags);
3463 
3464 	/* Recheck the nr_reserved_highatomic limit under the lock */
3465 	if (zone->nr_reserved_highatomic >= max_managed)
3466 		goto out_unlock;
3467 
3468 	/* Yoink! */
3469 	mt = get_pageblock_migratetype(page);
3470 	/* Only reserve normal pageblocks (i.e., they can merge with others) */
3471 	if (!migratetype_is_mergeable(mt))
3472 		goto out_unlock;
3473 
3474 	if (order < pageblock_order) {
3475 		if (move_freepages_block(zone, page, mt, MIGRATE_HIGHATOMIC) == -1)
3476 			goto out_unlock;
3477 		zone->nr_reserved_highatomic += pageblock_nr_pages;
3478 	} else {
3479 		change_pageblock_range(page, order, MIGRATE_HIGHATOMIC);
3480 		zone->nr_reserved_highatomic += 1 << order;
3481 	}
3482 
3483 out_unlock:
3484 	spin_unlock_irqrestore(&zone->lock, flags);
3485 }
3486 
3487 /*
3488  * Used when an allocation is about to fail under memory pressure. This
3489  * potentially hurts the reliability of high-order allocations when under
3490  * intense memory pressure but failed atomic allocations should be easier
3491  * to recover from than an OOM.
3492  *
3493  * If @force is true, try to unreserve pageblocks even though highatomic
3494  * pageblock is exhausted.
3495  */
3496 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
3497 						bool force)
3498 {
3499 	struct zonelist *zonelist = ac->zonelist;
3500 	unsigned long flags;
3501 	struct zoneref *z;
3502 	struct zone *zone;
3503 	struct page *page;
3504 	int order;
3505 	int ret;
3506 
3507 	for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->highest_zoneidx,
3508 								ac->nodemask) {
3509 		/*
3510 		 * Preserve at least one pageblock unless memory pressure
3511 		 * is really high.
3512 		 */
3513 		if (!force && zone->nr_reserved_highatomic <=
3514 					pageblock_nr_pages)
3515 			continue;
3516 
3517 		spin_lock_irqsave(&zone->lock, flags);
3518 		for (order = 0; order < NR_PAGE_ORDERS; order++) {
3519 			struct free_area *area = &(zone->free_area[order]);
3520 			unsigned long size;
3521 
3522 			page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
3523 			if (!page)
3524 				continue;
3525 
3526 			size = max(pageblock_nr_pages, 1UL << order);
3527 			/*
3528 			 * It should never happen but changes to
3529 			 * locking could inadvertently allow a per-cpu
3530 			 * drain to add pages to MIGRATE_HIGHATOMIC
3531 			 * while unreserving so be safe and watch for
3532 			 * underflows.
3533 			 */
3534 			if (WARN_ON_ONCE(size > zone->nr_reserved_highatomic))
3535 				size = zone->nr_reserved_highatomic;
3536 			zone->nr_reserved_highatomic -= size;
3537 
3538 			/*
3539 			 * Convert to ac->migratetype and avoid the normal
3540 			 * pageblock stealing heuristics. Minimally, the caller
3541 			 * is doing the work and needs the pages. More
3542 			 * importantly, if the block was always converted to
3543 			 * MIGRATE_UNMOVABLE or another type then the number
3544 			 * of pageblocks that cannot be completely freed
3545 			 * may increase.
3546 			 */
3547 			if (order < pageblock_order)
3548 				ret = move_freepages_block(zone, page,
3549 							   MIGRATE_HIGHATOMIC,
3550 							   ac->migratetype);
3551 			else {
3552 				move_to_free_list(page, zone, order,
3553 						  MIGRATE_HIGHATOMIC,
3554 						  ac->migratetype);
3555 				change_pageblock_range(page, order,
3556 						       ac->migratetype);
3557 				ret = 1;
3558 			}
3559 			/*
3560 			 * Reserving the block(s) already succeeded,
3561 			 * so this should not fail on zone boundaries.
3562 			 */
3563 			WARN_ON_ONCE(ret == -1);
3564 			if (ret > 0) {
3565 				spin_unlock_irqrestore(&zone->lock, flags);
3566 				return ret;
3567 			}
3568 		}
3569 		spin_unlock_irqrestore(&zone->lock, flags);
3570 	}
3571 
3572 	return false;
3573 }
3574 
3575 static inline long __zone_watermark_unusable_free(struct zone *z,
3576 				unsigned int order, unsigned int alloc_flags)
3577 {
3578 	long unusable_free = (1 << order) - 1;
3579 
3580 	/*
3581 	 * If the caller does not have rights to reserves below the min
3582 	 * watermark then subtract the free pages reserved for highatomic.
3583 	 */
3584 	if (likely(!(alloc_flags & ALLOC_RESERVES)))
3585 		unusable_free += READ_ONCE(z->nr_free_highatomic);
3586 
3587 #ifdef CONFIG_CMA
3588 	/* If allocation can't use CMA areas don't use free CMA pages */
3589 	if (!(alloc_flags & ALLOC_CMA))
3590 		unusable_free += zone_page_state(z, NR_FREE_CMA_PAGES);
3591 #endif
3592 
3593 	return unusable_free;
3594 }
3595 
3596 /*
3597  * Return true if free base pages are above 'mark'. For high-order checks it
3598  * will return true of the order-0 watermark is reached and there is at least
3599  * one free page of a suitable size. Checking now avoids taking the zone lock
3600  * to check in the allocation paths if no pages are free.
3601  */
3602 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3603 			 int highest_zoneidx, unsigned int alloc_flags,
3604 			 long free_pages)
3605 {
3606 	long min = mark;
3607 	int o;
3608 
3609 	/* free_pages may go negative - that's OK */
3610 	free_pages -= __zone_watermark_unusable_free(z, order, alloc_flags);
3611 
3612 	if (unlikely(alloc_flags & ALLOC_RESERVES)) {
3613 		/*
3614 		 * __GFP_HIGH allows access to 50% of the min reserve as well
3615 		 * as OOM.
3616 		 */
3617 		if (alloc_flags & ALLOC_MIN_RESERVE) {
3618 			min -= min / 2;
3619 
3620 			/*
3621 			 * Non-blocking allocations (e.g. GFP_ATOMIC) can
3622 			 * access more reserves than just __GFP_HIGH. Other
3623 			 * non-blocking allocations requests such as GFP_NOWAIT
3624 			 * or (GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) do not get
3625 			 * access to the min reserve.
3626 			 */
3627 			if (alloc_flags & ALLOC_NON_BLOCK)
3628 				min -= min / 4;
3629 		}
3630 
3631 		/*
3632 		 * OOM victims can try even harder than the normal reserve
3633 		 * users on the grounds that it's definitely going to be in
3634 		 * the exit path shortly and free memory. Any allocation it
3635 		 * makes during the free path will be small and short-lived.
3636 		 */
3637 		if (alloc_flags & ALLOC_OOM)
3638 			min -= min / 2;
3639 	}
3640 
3641 	/*
3642 	 * Check watermarks for an order-0 allocation request. If these
3643 	 * are not met, then a high-order request also cannot go ahead
3644 	 * even if a suitable page happened to be free.
3645 	 */
3646 	if (free_pages <= min + z->lowmem_reserve[highest_zoneidx])
3647 		return false;
3648 
3649 	/* If this is an order-0 request then the watermark is fine */
3650 	if (!order)
3651 		return true;
3652 
3653 	/* For a high-order request, check at least one suitable page is free */
3654 	for (o = order; o < NR_PAGE_ORDERS; o++) {
3655 		struct free_area *area = &z->free_area[o];
3656 		int mt;
3657 
3658 		if (!area->nr_free)
3659 			continue;
3660 
3661 		for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3662 			if (!free_area_empty(area, mt))
3663 				return true;
3664 		}
3665 
3666 #ifdef CONFIG_CMA
3667 		if ((alloc_flags & ALLOC_CMA) &&
3668 		    !free_area_empty(area, MIGRATE_CMA)) {
3669 			return true;
3670 		}
3671 #endif
3672 		if ((alloc_flags & (ALLOC_HIGHATOMIC|ALLOC_OOM)) &&
3673 		    !free_area_empty(area, MIGRATE_HIGHATOMIC)) {
3674 			return true;
3675 		}
3676 	}
3677 	return false;
3678 }
3679 
3680 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3681 		      int highest_zoneidx, unsigned int alloc_flags)
3682 {
3683 	return __zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3684 					zone_page_state(z, NR_FREE_PAGES));
3685 }
3686 
3687 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3688 				unsigned long mark, int highest_zoneidx,
3689 				unsigned int alloc_flags, gfp_t gfp_mask)
3690 {
3691 	long free_pages;
3692 
3693 	free_pages = zone_page_state(z, NR_FREE_PAGES);
3694 
3695 	/*
3696 	 * Fast check for order-0 only. If this fails then the reserves
3697 	 * need to be calculated.
3698 	 */
3699 	if (!order) {
3700 		long usable_free;
3701 		long reserved;
3702 
3703 		usable_free = free_pages;
3704 		reserved = __zone_watermark_unusable_free(z, 0, alloc_flags);
3705 
3706 		/* reserved may over estimate high-atomic reserves. */
3707 		usable_free -= min(usable_free, reserved);
3708 		if (usable_free > mark + z->lowmem_reserve[highest_zoneidx])
3709 			return true;
3710 	}
3711 
3712 	if (__zone_watermark_ok(z, order, mark, highest_zoneidx, alloc_flags,
3713 					free_pages))
3714 		return true;
3715 
3716 	/*
3717 	 * Ignore watermark boosting for __GFP_HIGH order-0 allocations
3718 	 * when checking the min watermark. The min watermark is the
3719 	 * point where boosting is ignored so that kswapd is woken up
3720 	 * when below the low watermark.
3721 	 */
3722 	if (unlikely(!order && (alloc_flags & ALLOC_MIN_RESERVE) && z->watermark_boost
3723 		&& ((alloc_flags & ALLOC_WMARK_MASK) == WMARK_MIN))) {
3724 		mark = z->_watermark[WMARK_MIN];
3725 		return __zone_watermark_ok(z, order, mark, highest_zoneidx,
3726 					alloc_flags, free_pages);
3727 	}
3728 
3729 	return false;
3730 }
3731 
3732 #ifdef CONFIG_NUMA
3733 int __read_mostly node_reclaim_distance = RECLAIM_DISTANCE;
3734 
3735 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3736 {
3737 	return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3738 				node_reclaim_distance;
3739 }
3740 #else	/* CONFIG_NUMA */
3741 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3742 {
3743 	return true;
3744 }
3745 #endif	/* CONFIG_NUMA */
3746 
3747 /*
3748  * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3749  * fragmentation is subtle. If the preferred zone was HIGHMEM then
3750  * premature use of a lower zone may cause lowmem pressure problems that
3751  * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3752  * probably too small. It only makes sense to spread allocations to avoid
3753  * fragmentation between the Normal and DMA32 zones.
3754  */
3755 static inline unsigned int
3756 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3757 {
3758 	unsigned int alloc_flags;
3759 
3760 	/*
3761 	 * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
3762 	 * to save a branch.
3763 	 */
3764 	alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
3765 
3766 	if (defrag_mode) {
3767 		alloc_flags |= ALLOC_NOFRAGMENT;
3768 		return alloc_flags;
3769 	}
3770 
3771 #ifdef CONFIG_ZONE_DMA32
3772 	if (!zone)
3773 		return alloc_flags;
3774 
3775 	if (zone_idx(zone) != ZONE_NORMAL)
3776 		return alloc_flags;
3777 
3778 	/*
3779 	 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3780 	 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3781 	 * on UMA that if Normal is populated then so is DMA32.
3782 	 */
3783 	BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3784 	if (nr_online_nodes > 1 && !populated_zone(--zone))
3785 		return alloc_flags;
3786 
3787 	alloc_flags |= ALLOC_NOFRAGMENT;
3788 #endif /* CONFIG_ZONE_DMA32 */
3789 	return alloc_flags;
3790 }
3791 
3792 /* Must be called after current_gfp_context() which can change gfp_mask */
3793 static inline unsigned int gfp_to_alloc_flags_cma(gfp_t gfp_mask,
3794 						  unsigned int alloc_flags)
3795 {
3796 #ifdef CONFIG_CMA
3797 	if (gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE)
3798 		alloc_flags |= ALLOC_CMA;
3799 #endif
3800 	return alloc_flags;
3801 }
3802 
3803 /*
3804  * get_page_from_freelist goes through the zonelist trying to allocate
3805  * a page.
3806  */
3807 static struct page *
3808 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3809 						const struct alloc_context *ac)
3810 {
3811 	struct zoneref *z;
3812 	struct zone *zone;
3813 	struct pglist_data *last_pgdat = NULL;
3814 	bool last_pgdat_dirty_ok = false;
3815 	bool no_fallback;
3816 	bool skip_kswapd_nodes = nr_online_nodes > 1;
3817 	bool skipped_kswapd_nodes = false;
3818 
3819 retry:
3820 	/*
3821 	 * Scan zonelist, looking for a zone with enough free.
3822 	 * See also cpuset_current_node_allowed() comment in kernel/cgroup/cpuset.c.
3823 	 */
3824 	no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3825 	z = ac->preferred_zoneref;
3826 	for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx,
3827 					ac->nodemask) {
3828 		struct page *page;
3829 		unsigned long mark;
3830 
3831 		if (cpusets_enabled() &&
3832 			(alloc_flags & ALLOC_CPUSET) &&
3833 			!__cpuset_zone_allowed(zone, gfp_mask))
3834 				continue;
3835 		/*
3836 		 * When allocating a page cache page for writing, we
3837 		 * want to get it from a node that is within its dirty
3838 		 * limit, such that no single node holds more than its
3839 		 * proportional share of globally allowed dirty pages.
3840 		 * The dirty limits take into account the node's
3841 		 * lowmem reserves and high watermark so that kswapd
3842 		 * should be able to balance it without having to
3843 		 * write pages from its LRU list.
3844 		 *
3845 		 * XXX: For now, allow allocations to potentially
3846 		 * exceed the per-node dirty limit in the slowpath
3847 		 * (spread_dirty_pages unset) before going into reclaim,
3848 		 * which is important when on a NUMA setup the allowed
3849 		 * nodes are together not big enough to reach the
3850 		 * global limit.  The proper fix for these situations
3851 		 * will require awareness of nodes in the
3852 		 * dirty-throttling and the flusher threads.
3853 		 */
3854 		if (ac->spread_dirty_pages) {
3855 			if (last_pgdat != zone->zone_pgdat) {
3856 				last_pgdat = zone->zone_pgdat;
3857 				last_pgdat_dirty_ok = node_dirty_ok(zone->zone_pgdat);
3858 			}
3859 
3860 			if (!last_pgdat_dirty_ok)
3861 				continue;
3862 		}
3863 
3864 		if (no_fallback && !defrag_mode && nr_online_nodes > 1 &&
3865 		    zone != zonelist_zone(ac->preferred_zoneref)) {
3866 			int local_nid;
3867 
3868 			/*
3869 			 * If moving to a remote node, retry but allow
3870 			 * fragmenting fallbacks. Locality is more important
3871 			 * than fragmentation avoidance.
3872 			 */
3873 			local_nid = zonelist_node_idx(ac->preferred_zoneref);
3874 			if (zone_to_nid(zone) != local_nid) {
3875 				alloc_flags &= ~ALLOC_NOFRAGMENT;
3876 				goto retry;
3877 			}
3878 		}
3879 
3880 		/*
3881 		 * If kswapd is already active on a node, keep looking
3882 		 * for other nodes that might be idle. This can happen
3883 		 * if another process has NUMA bindings and is causing
3884 		 * kswapd wakeups on only some nodes. Avoid accidental
3885 		 * "node_reclaim_mode"-like behavior in this case.
3886 		 */
3887 		if (skip_kswapd_nodes &&
3888 		    !waitqueue_active(&zone->zone_pgdat->kswapd_wait)) {
3889 			skipped_kswapd_nodes = true;
3890 			continue;
3891 		}
3892 
3893 		cond_accept_memory(zone, order, alloc_flags);
3894 
3895 		/*
3896 		 * Detect whether the number of free pages is below high
3897 		 * watermark.  If so, we will decrease pcp->high and free
3898 		 * PCP pages in free path to reduce the possibility of
3899 		 * premature page reclaiming.  Detection is done here to
3900 		 * avoid to do that in hotter free path.
3901 		 */
3902 		if (test_bit(ZONE_BELOW_HIGH, &zone->flags))
3903 			goto check_alloc_wmark;
3904 
3905 		mark = high_wmark_pages(zone);
3906 		if (zone_watermark_fast(zone, order, mark,
3907 					ac->highest_zoneidx, alloc_flags,
3908 					gfp_mask))
3909 			goto try_this_zone;
3910 		else
3911 			set_bit(ZONE_BELOW_HIGH, &zone->flags);
3912 
3913 check_alloc_wmark:
3914 		mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
3915 		if (!zone_watermark_fast(zone, order, mark,
3916 				       ac->highest_zoneidx, alloc_flags,
3917 				       gfp_mask)) {
3918 			int ret;
3919 
3920 			if (cond_accept_memory(zone, order, alloc_flags))
3921 				goto try_this_zone;
3922 
3923 			/*
3924 			 * Watermark failed for this zone, but see if we can
3925 			 * grow this zone if it contains deferred pages.
3926 			 */
3927 			if (deferred_pages_enabled()) {
3928 				if (_deferred_grow_zone(zone, order))
3929 					goto try_this_zone;
3930 			}
3931 			/* Checked here to keep the fast path fast */
3932 			BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3933 			if (alloc_flags & ALLOC_NO_WATERMARKS)
3934 				goto try_this_zone;
3935 
3936 			if (!node_reclaim_enabled() ||
3937 			    !zone_allows_reclaim(zonelist_zone(ac->preferred_zoneref), zone))
3938 				continue;
3939 
3940 			ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3941 			switch (ret) {
3942 			case NODE_RECLAIM_NOSCAN:
3943 				/* did not scan */
3944 				continue;
3945 			case NODE_RECLAIM_FULL:
3946 				/* scanned but unreclaimable */
3947 				continue;
3948 			default:
3949 				/* did we reclaim enough */
3950 				if (zone_watermark_ok(zone, order, mark,
3951 					ac->highest_zoneidx, alloc_flags))
3952 					goto try_this_zone;
3953 
3954 				continue;
3955 			}
3956 		}
3957 
3958 try_this_zone:
3959 		page = rmqueue(zonelist_zone(ac->preferred_zoneref), zone, order,
3960 				gfp_mask, alloc_flags, ac->migratetype);
3961 		if (page) {
3962 			prep_new_page(page, order, gfp_mask, alloc_flags);
3963 
3964 			/*
3965 			 * If this is a high-order atomic allocation then check
3966 			 * if the pageblock should be reserved for the future
3967 			 */
3968 			if (unlikely(alloc_flags & ALLOC_HIGHATOMIC))
3969 				reserve_highatomic_pageblock(page, order, zone);
3970 
3971 			return page;
3972 		} else {
3973 			if (cond_accept_memory(zone, order, alloc_flags))
3974 				goto try_this_zone;
3975 
3976 			/* Try again if zone has deferred pages */
3977 			if (deferred_pages_enabled()) {
3978 				if (_deferred_grow_zone(zone, order))
3979 					goto try_this_zone;
3980 			}
3981 		}
3982 	}
3983 
3984 	/*
3985 	 * If we skipped over nodes with active kswapds and found no
3986 	 * idle nodes, retry and place anywhere the watermarks permit.
3987 	 */
3988 	if (skip_kswapd_nodes && skipped_kswapd_nodes) {
3989 		skip_kswapd_nodes = false;
3990 		goto retry;
3991 	}
3992 
3993 	/*
3994 	 * It's possible on a UMA machine to get through all zones that are
3995 	 * fragmented. If avoiding fragmentation, reset and try again.
3996 	 */
3997 	if (no_fallback && !defrag_mode) {
3998 		alloc_flags &= ~ALLOC_NOFRAGMENT;
3999 		goto retry;
4000 	}
4001 
4002 	return NULL;
4003 }
4004 
4005 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
4006 {
4007 	unsigned int filter = SHOW_MEM_FILTER_NODES;
4008 
4009 	/*
4010 	 * This documents exceptions given to allocations in certain
4011 	 * contexts that are allowed to allocate outside current's set
4012 	 * of allowed nodes.
4013 	 */
4014 	if (!(gfp_mask & __GFP_NOMEMALLOC))
4015 		if (tsk_is_oom_victim(current) ||
4016 		    (current->flags & (PF_MEMALLOC | PF_EXITING)))
4017 			filter &= ~SHOW_MEM_FILTER_NODES;
4018 	if (!in_task() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
4019 		filter &= ~SHOW_MEM_FILTER_NODES;
4020 
4021 	__show_mem(filter, nodemask, gfp_zone(gfp_mask));
4022 	mem_cgroup_show_protected_memory(NULL);
4023 }
4024 
4025 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
4026 {
4027 	struct va_format vaf;
4028 	va_list args;
4029 	static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
4030 
4031 	if ((gfp_mask & __GFP_NOWARN) ||
4032 	     !__ratelimit(&nopage_rs) ||
4033 	     ((gfp_mask & __GFP_DMA) && !has_managed_dma()))
4034 		return;
4035 
4036 	va_start(args, fmt);
4037 	vaf.fmt = fmt;
4038 	vaf.va = &args;
4039 	pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
4040 			current->comm, &vaf, gfp_mask, &gfp_mask,
4041 			nodemask_pr_args(nodemask));
4042 	va_end(args);
4043 
4044 	cpuset_print_current_mems_allowed();
4045 	pr_cont("\n");
4046 	dump_stack();
4047 	warn_alloc_show_mem(gfp_mask, nodemask);
4048 }
4049 
4050 static inline struct page *
4051 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
4052 			      unsigned int alloc_flags,
4053 			      const struct alloc_context *ac)
4054 {
4055 	struct page *page;
4056 
4057 	page = get_page_from_freelist(gfp_mask, order,
4058 			alloc_flags|ALLOC_CPUSET, ac);
4059 	/*
4060 	 * fallback to ignore cpuset restriction if our nodes
4061 	 * are depleted
4062 	 */
4063 	if (!page)
4064 		page = get_page_from_freelist(gfp_mask, order,
4065 				alloc_flags, ac);
4066 	return page;
4067 }
4068 
4069 static inline struct page *
4070 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
4071 	const struct alloc_context *ac, unsigned long *did_some_progress)
4072 {
4073 	struct oom_control oc = {
4074 		.zonelist = ac->zonelist,
4075 		.nodemask = ac->nodemask,
4076 		.memcg = NULL,
4077 		.gfp_mask = gfp_mask,
4078 		.order = order,
4079 	};
4080 	struct page *page;
4081 
4082 	*did_some_progress = 0;
4083 
4084 	/*
4085 	 * Acquire the oom lock.  If that fails, somebody else is
4086 	 * making progress for us.
4087 	 */
4088 	if (!mutex_trylock(&oom_lock)) {
4089 		*did_some_progress = 1;
4090 		schedule_timeout_uninterruptible(1);
4091 		return NULL;
4092 	}
4093 
4094 	/*
4095 	 * Go through the zonelist yet one more time, keep very high watermark
4096 	 * here, this is only to catch a parallel oom killing, we must fail if
4097 	 * we're still under heavy pressure. But make sure that this reclaim
4098 	 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
4099 	 * allocation which will never fail due to oom_lock already held.
4100 	 */
4101 	page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
4102 				      ~__GFP_DIRECT_RECLAIM, order,
4103 				      ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
4104 	if (page)
4105 		goto out;
4106 
4107 	/* Coredumps can quickly deplete all memory reserves */
4108 	if (current->flags & PF_DUMPCORE)
4109 		goto out;
4110 	/* The OOM killer will not help higher order allocs */
4111 	if (order > PAGE_ALLOC_COSTLY_ORDER)
4112 		goto out;
4113 	/*
4114 	 * We have already exhausted all our reclaim opportunities without any
4115 	 * success so it is time to admit defeat. We will skip the OOM killer
4116 	 * because it is very likely that the caller has a more reasonable
4117 	 * fallback than shooting a random task.
4118 	 *
4119 	 * The OOM killer may not free memory on a specific node.
4120 	 */
4121 	if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE))
4122 		goto out;
4123 	/* The OOM killer does not needlessly kill tasks for lowmem */
4124 	if (ac->highest_zoneidx < ZONE_NORMAL)
4125 		goto out;
4126 	if (pm_suspended_storage())
4127 		goto out;
4128 	/*
4129 	 * XXX: GFP_NOFS allocations should rather fail than rely on
4130 	 * other request to make a forward progress.
4131 	 * We are in an unfortunate situation where out_of_memory cannot
4132 	 * do much for this context but let's try it to at least get
4133 	 * access to memory reserved if the current task is killed (see
4134 	 * out_of_memory). Once filesystems are ready to handle allocation
4135 	 * failures more gracefully we should just bail out here.
4136 	 */
4137 
4138 	/* Exhausted what can be done so it's blame time */
4139 	if (out_of_memory(&oc) ||
4140 	    WARN_ON_ONCE_GFP(gfp_mask & __GFP_NOFAIL, gfp_mask)) {
4141 		*did_some_progress = 1;
4142 
4143 		/*
4144 		 * Help non-failing allocations by giving them access to memory
4145 		 * reserves
4146 		 */
4147 		if (gfp_mask & __GFP_NOFAIL)
4148 			page = __alloc_pages_cpuset_fallback(gfp_mask, order,
4149 					ALLOC_NO_WATERMARKS, ac);
4150 	}
4151 out:
4152 	mutex_unlock(&oom_lock);
4153 	return page;
4154 }
4155 
4156 /*
4157  * Maximum number of compaction retries with a progress before OOM
4158  * killer is consider as the only way to move forward.
4159  */
4160 #define MAX_COMPACT_RETRIES 16
4161 
4162 #ifdef CONFIG_COMPACTION
4163 /* Try memory compaction for high-order allocations before reclaim */
4164 static struct page *
4165 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4166 		unsigned int alloc_flags, const struct alloc_context *ac,
4167 		enum compact_priority prio, enum compact_result *compact_result)
4168 {
4169 	struct page *page = NULL;
4170 	unsigned long pflags;
4171 	unsigned int noreclaim_flag;
4172 
4173 	if (!order)
4174 		return NULL;
4175 
4176 	psi_memstall_enter(&pflags);
4177 	delayacct_compact_start();
4178 	noreclaim_flag = memalloc_noreclaim_save();
4179 
4180 	*compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
4181 								prio, &page);
4182 
4183 	memalloc_noreclaim_restore(noreclaim_flag);
4184 	psi_memstall_leave(&pflags);
4185 	delayacct_compact_end();
4186 
4187 	if (*compact_result == COMPACT_SKIPPED)
4188 		return NULL;
4189 	/*
4190 	 * At least in one zone compaction wasn't deferred or skipped, so let's
4191 	 * count a compaction stall
4192 	 */
4193 	count_vm_event(COMPACTSTALL);
4194 
4195 	/* Prep a captured page if available */
4196 	if (page)
4197 		prep_new_page(page, order, gfp_mask, alloc_flags);
4198 
4199 	/* Try get a page from the freelist if available */
4200 	if (!page)
4201 		page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4202 
4203 	if (page) {
4204 		struct zone *zone = page_zone(page);
4205 
4206 		zone->compact_blockskip_flush = false;
4207 		compaction_defer_reset(zone, order, true);
4208 		count_vm_event(COMPACTSUCCESS);
4209 		return page;
4210 	}
4211 
4212 	/*
4213 	 * It's bad if compaction run occurs and fails. The most likely reason
4214 	 * is that pages exist, but not enough to satisfy watermarks.
4215 	 */
4216 	count_vm_event(COMPACTFAIL);
4217 
4218 	cond_resched();
4219 
4220 	return NULL;
4221 }
4222 
4223 static inline bool
4224 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
4225 		     enum compact_result compact_result,
4226 		     enum compact_priority *compact_priority,
4227 		     int *compaction_retries)
4228 {
4229 	int max_retries = MAX_COMPACT_RETRIES;
4230 	int min_priority;
4231 	bool ret = false;
4232 	int retries = *compaction_retries;
4233 	enum compact_priority priority = *compact_priority;
4234 
4235 	if (!order)
4236 		return false;
4237 
4238 	if (fatal_signal_pending(current))
4239 		return false;
4240 
4241 	/*
4242 	 * Compaction was skipped due to a lack of free order-0
4243 	 * migration targets. Continue if reclaim can help.
4244 	 */
4245 	if (compact_result == COMPACT_SKIPPED) {
4246 		ret = compaction_zonelist_suitable(ac, order, alloc_flags);
4247 		goto out;
4248 	}
4249 
4250 	/*
4251 	 * Compaction managed to coalesce some page blocks, but the
4252 	 * allocation failed presumably due to a race. Retry some.
4253 	 */
4254 	if (compact_result == COMPACT_SUCCESS) {
4255 		/*
4256 		 * !costly requests are much more important than
4257 		 * __GFP_RETRY_MAYFAIL costly ones because they are de
4258 		 * facto nofail and invoke OOM killer to move on while
4259 		 * costly can fail and users are ready to cope with
4260 		 * that. 1/4 retries is rather arbitrary but we would
4261 		 * need much more detailed feedback from compaction to
4262 		 * make a better decision.
4263 		 */
4264 		if (order > PAGE_ALLOC_COSTLY_ORDER)
4265 			max_retries /= 4;
4266 
4267 		if (++(*compaction_retries) <= max_retries) {
4268 			ret = true;
4269 			goto out;
4270 		}
4271 	}
4272 
4273 	/*
4274 	 * Compaction failed. Retry with increasing priority.
4275 	 */
4276 	min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
4277 			MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
4278 
4279 	if (*compact_priority > min_priority) {
4280 		(*compact_priority)--;
4281 		*compaction_retries = 0;
4282 		ret = true;
4283 	}
4284 out:
4285 	trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
4286 	return ret;
4287 }
4288 #else
4289 static inline struct page *
4290 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4291 		unsigned int alloc_flags, const struct alloc_context *ac,
4292 		enum compact_priority prio, enum compact_result *compact_result)
4293 {
4294 	*compact_result = COMPACT_SKIPPED;
4295 	return NULL;
4296 }
4297 
4298 static inline bool
4299 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
4300 		     enum compact_result compact_result,
4301 		     enum compact_priority *compact_priority,
4302 		     int *compaction_retries)
4303 {
4304 	struct zone *zone;
4305 	struct zoneref *z;
4306 
4307 	if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
4308 		return false;
4309 
4310 	/*
4311 	 * There are setups with compaction disabled which would prefer to loop
4312 	 * inside the allocator rather than hit the oom killer prematurely.
4313 	 * Let's give them a good hope and keep retrying while the order-0
4314 	 * watermarks are OK.
4315 	 */
4316 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4317 				ac->highest_zoneidx, ac->nodemask) {
4318 		if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
4319 					ac->highest_zoneidx, alloc_flags))
4320 			return true;
4321 	}
4322 	return false;
4323 }
4324 #endif /* CONFIG_COMPACTION */
4325 
4326 #ifdef CONFIG_LOCKDEP
4327 static struct lockdep_map __fs_reclaim_map =
4328 	STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
4329 
4330 static bool __need_reclaim(gfp_t gfp_mask)
4331 {
4332 	/* no reclaim without waiting on it */
4333 	if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
4334 		return false;
4335 
4336 	/* this guy won't enter reclaim */
4337 	if (current->flags & PF_MEMALLOC)
4338 		return false;
4339 
4340 	if (gfp_mask & __GFP_NOLOCKDEP)
4341 		return false;
4342 
4343 	return true;
4344 }
4345 
4346 void __fs_reclaim_acquire(unsigned long ip)
4347 {
4348 	lock_acquire_exclusive(&__fs_reclaim_map, 0, 0, NULL, ip);
4349 }
4350 
4351 void __fs_reclaim_release(unsigned long ip)
4352 {
4353 	lock_release(&__fs_reclaim_map, ip);
4354 }
4355 
4356 void fs_reclaim_acquire(gfp_t gfp_mask)
4357 {
4358 	gfp_mask = current_gfp_context(gfp_mask);
4359 
4360 	if (__need_reclaim(gfp_mask)) {
4361 		if (gfp_mask & __GFP_FS)
4362 			__fs_reclaim_acquire(_RET_IP_);
4363 
4364 #ifdef CONFIG_MMU_NOTIFIER
4365 		lock_map_acquire(&__mmu_notifier_invalidate_range_start_map);
4366 		lock_map_release(&__mmu_notifier_invalidate_range_start_map);
4367 #endif
4368 
4369 	}
4370 }
4371 EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
4372 
4373 void fs_reclaim_release(gfp_t gfp_mask)
4374 {
4375 	gfp_mask = current_gfp_context(gfp_mask);
4376 
4377 	if (__need_reclaim(gfp_mask)) {
4378 		if (gfp_mask & __GFP_FS)
4379 			__fs_reclaim_release(_RET_IP_);
4380 	}
4381 }
4382 EXPORT_SYMBOL_GPL(fs_reclaim_release);
4383 #endif
4384 
4385 /*
4386  * Zonelists may change due to hotplug during allocation. Detect when zonelists
4387  * have been rebuilt so allocation retries. Reader side does not lock and
4388  * retries the allocation if zonelist changes. Writer side is protected by the
4389  * embedded spin_lock.
4390  */
4391 static DEFINE_SEQLOCK(zonelist_update_seq);
4392 
4393 static unsigned int zonelist_iter_begin(void)
4394 {
4395 	if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
4396 		return read_seqbegin(&zonelist_update_seq);
4397 
4398 	return 0;
4399 }
4400 
4401 static unsigned int check_retry_zonelist(unsigned int seq)
4402 {
4403 	if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
4404 		return read_seqretry(&zonelist_update_seq, seq);
4405 
4406 	return seq;
4407 }
4408 
4409 /* Perform direct synchronous page reclaim */
4410 static unsigned long
4411 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
4412 					const struct alloc_context *ac)
4413 {
4414 	unsigned int noreclaim_flag;
4415 	unsigned long progress;
4416 
4417 	cond_resched();
4418 
4419 	/* We now go into synchronous reclaim */
4420 	cpuset_memory_pressure_bump();
4421 	fs_reclaim_acquire(gfp_mask);
4422 	noreclaim_flag = memalloc_noreclaim_save();
4423 
4424 	progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
4425 								ac->nodemask);
4426 
4427 	memalloc_noreclaim_restore(noreclaim_flag);
4428 	fs_reclaim_release(gfp_mask);
4429 
4430 	cond_resched();
4431 
4432 	return progress;
4433 }
4434 
4435 /* The really slow allocator path where we enter direct reclaim */
4436 static inline struct page *
4437 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
4438 		unsigned int alloc_flags, const struct alloc_context *ac,
4439 		unsigned long *did_some_progress)
4440 {
4441 	struct page *page = NULL;
4442 	unsigned long pflags;
4443 	bool drained = false;
4444 
4445 	psi_memstall_enter(&pflags);
4446 	*did_some_progress = __perform_reclaim(gfp_mask, order, ac);
4447 	if (unlikely(!(*did_some_progress)))
4448 		goto out;
4449 
4450 retry:
4451 	page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4452 
4453 	/*
4454 	 * If an allocation failed after direct reclaim, it could be because
4455 	 * pages are pinned on the per-cpu lists or in high alloc reserves.
4456 	 * Shrink them and try again
4457 	 */
4458 	if (!page && !drained) {
4459 		unreserve_highatomic_pageblock(ac, false);
4460 		drain_all_pages(NULL);
4461 		drained = true;
4462 		goto retry;
4463 	}
4464 out:
4465 	psi_memstall_leave(&pflags);
4466 
4467 	return page;
4468 }
4469 
4470 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
4471 			     const struct alloc_context *ac)
4472 {
4473 	struct zoneref *z;
4474 	struct zone *zone;
4475 	pg_data_t *last_pgdat = NULL;
4476 	enum zone_type highest_zoneidx = ac->highest_zoneidx;
4477 	unsigned int reclaim_order;
4478 
4479 	if (defrag_mode)
4480 		reclaim_order = max(order, pageblock_order);
4481 	else
4482 		reclaim_order = order;
4483 
4484 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx,
4485 					ac->nodemask) {
4486 		if (!managed_zone(zone))
4487 			continue;
4488 		if (last_pgdat == zone->zone_pgdat)
4489 			continue;
4490 		wakeup_kswapd(zone, gfp_mask, reclaim_order, highest_zoneidx);
4491 		last_pgdat = zone->zone_pgdat;
4492 	}
4493 }
4494 
4495 static inline unsigned int
4496 gfp_to_alloc_flags(gfp_t gfp_mask, unsigned int order)
4497 {
4498 	unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
4499 
4500 	/*
4501 	 * __GFP_HIGH is assumed to be the same as ALLOC_MIN_RESERVE
4502 	 * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
4503 	 * to save two branches.
4504 	 */
4505 	BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_MIN_RESERVE);
4506 	BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD);
4507 
4508 	/*
4509 	 * The caller may dip into page reserves a bit more if the caller
4510 	 * cannot run direct reclaim, or if the caller has realtime scheduling
4511 	 * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
4512 	 * set both ALLOC_NON_BLOCK and ALLOC_MIN_RESERVE(__GFP_HIGH).
4513 	 */
4514 	alloc_flags |= (__force int)
4515 		(gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM));
4516 
4517 	if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) {
4518 		/*
4519 		 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4520 		 * if it can't schedule.
4521 		 */
4522 		if (!(gfp_mask & __GFP_NOMEMALLOC)) {
4523 			alloc_flags |= ALLOC_NON_BLOCK;
4524 
4525 			if (order > 0 && (alloc_flags & ALLOC_MIN_RESERVE))
4526 				alloc_flags |= ALLOC_HIGHATOMIC;
4527 		}
4528 
4529 		/*
4530 		 * Ignore cpuset mems for non-blocking __GFP_HIGH (probably
4531 		 * GFP_ATOMIC) rather than fail, see the comment for
4532 		 * cpuset_current_node_allowed().
4533 		 */
4534 		if (alloc_flags & ALLOC_MIN_RESERVE)
4535 			alloc_flags &= ~ALLOC_CPUSET;
4536 	} else if (unlikely(rt_or_dl_task(current)) && in_task())
4537 		alloc_flags |= ALLOC_MIN_RESERVE;
4538 
4539 	alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, alloc_flags);
4540 
4541 	if (defrag_mode)
4542 		alloc_flags |= ALLOC_NOFRAGMENT;
4543 
4544 	return alloc_flags;
4545 }
4546 
4547 static bool oom_reserves_allowed(struct task_struct *tsk)
4548 {
4549 	if (!tsk_is_oom_victim(tsk))
4550 		return false;
4551 
4552 	/*
4553 	 * !MMU doesn't have oom reaper so give access to memory reserves
4554 	 * only to the thread with TIF_MEMDIE set
4555 	 */
4556 	if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
4557 		return false;
4558 
4559 	return true;
4560 }
4561 
4562 /*
4563  * Distinguish requests which really need access to full memory
4564  * reserves from oom victims which can live with a portion of it
4565  */
4566 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4567 {
4568 	if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4569 		return 0;
4570 	if (gfp_mask & __GFP_MEMALLOC)
4571 		return ALLOC_NO_WATERMARKS;
4572 	if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
4573 		return ALLOC_NO_WATERMARKS;
4574 	if (!in_interrupt()) {
4575 		if (current->flags & PF_MEMALLOC)
4576 			return ALLOC_NO_WATERMARKS;
4577 		else if (oom_reserves_allowed(current))
4578 			return ALLOC_OOM;
4579 	}
4580 
4581 	return 0;
4582 }
4583 
4584 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4585 {
4586 	return !!__gfp_pfmemalloc_flags(gfp_mask);
4587 }
4588 
4589 /*
4590  * Checks whether it makes sense to retry the reclaim to make a forward progress
4591  * for the given allocation request.
4592  *
4593  * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4594  * without success, or when we couldn't even meet the watermark if we
4595  * reclaimed all remaining pages on the LRU lists.
4596  *
4597  * Returns true if a retry is viable or false to enter the oom path.
4598  */
4599 static inline bool
4600 should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4601 		     struct alloc_context *ac, int alloc_flags,
4602 		     bool did_some_progress, int *no_progress_loops)
4603 {
4604 	struct zone *zone;
4605 	struct zoneref *z;
4606 	bool ret = false;
4607 
4608 	/*
4609 	 * Costly allocations might have made a progress but this doesn't mean
4610 	 * their order will become available due to high fragmentation so
4611 	 * always increment the no progress counter for them
4612 	 */
4613 	if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4614 		*no_progress_loops = 0;
4615 	else
4616 		(*no_progress_loops)++;
4617 
4618 	if (*no_progress_loops > MAX_RECLAIM_RETRIES)
4619 		goto out;
4620 
4621 
4622 	/*
4623 	 * Keep reclaiming pages while there is a chance this will lead
4624 	 * somewhere.  If none of the target zones can satisfy our allocation
4625 	 * request even if all reclaimable pages are considered then we are
4626 	 * screwed and have to go OOM.
4627 	 */
4628 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4629 				ac->highest_zoneidx, ac->nodemask) {
4630 		unsigned long available;
4631 		unsigned long reclaimable;
4632 		unsigned long min_wmark = min_wmark_pages(zone);
4633 		bool wmark;
4634 
4635 		if (cpusets_enabled() &&
4636 			(alloc_flags & ALLOC_CPUSET) &&
4637 			!__cpuset_zone_allowed(zone, gfp_mask))
4638 				continue;
4639 
4640 		available = reclaimable = zone_reclaimable_pages(zone);
4641 		available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
4642 
4643 		/*
4644 		 * Would the allocation succeed if we reclaimed all
4645 		 * reclaimable pages?
4646 		 */
4647 		wmark = __zone_watermark_ok(zone, order, min_wmark,
4648 				ac->highest_zoneidx, alloc_flags, available);
4649 		trace_reclaim_retry_zone(z, order, reclaimable,
4650 				available, min_wmark, *no_progress_loops, wmark);
4651 		if (wmark) {
4652 			ret = true;
4653 			break;
4654 		}
4655 	}
4656 
4657 	/*
4658 	 * Memory allocation/reclaim might be called from a WQ context and the
4659 	 * current implementation of the WQ concurrency control doesn't
4660 	 * recognize that a particular WQ is congested if the worker thread is
4661 	 * looping without ever sleeping. Therefore we have to do a short sleep
4662 	 * here rather than calling cond_resched().
4663 	 */
4664 	if (current->flags & PF_WQ_WORKER)
4665 		schedule_timeout_uninterruptible(1);
4666 	else
4667 		cond_resched();
4668 out:
4669 	/* Before OOM, exhaust highatomic_reserve */
4670 	if (!ret)
4671 		return unreserve_highatomic_pageblock(ac, true);
4672 
4673 	return ret;
4674 }
4675 
4676 static inline bool
4677 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4678 {
4679 	/*
4680 	 * It's possible that cpuset's mems_allowed and the nodemask from
4681 	 * mempolicy don't intersect. This should be normally dealt with by
4682 	 * policy_nodemask(), but it's possible to race with cpuset update in
4683 	 * such a way the check therein was true, and then it became false
4684 	 * before we got our cpuset_mems_cookie here.
4685 	 * This assumes that for all allocations, ac->nodemask can come only
4686 	 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4687 	 * when it does not intersect with the cpuset restrictions) or the
4688 	 * caller can deal with a violated nodemask.
4689 	 */
4690 	if (cpusets_enabled() && ac->nodemask &&
4691 			!cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4692 		ac->nodemask = NULL;
4693 		return true;
4694 	}
4695 
4696 	/*
4697 	 * When updating a task's mems_allowed or mempolicy nodemask, it is
4698 	 * possible to race with parallel threads in such a way that our
4699 	 * allocation can fail while the mask is being updated. If we are about
4700 	 * to fail, check if the cpuset changed during allocation and if so,
4701 	 * retry.
4702 	 */
4703 	if (read_mems_allowed_retry(cpuset_mems_cookie))
4704 		return true;
4705 
4706 	return false;
4707 }
4708 
4709 static inline struct page *
4710 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
4711 						struct alloc_context *ac)
4712 {
4713 	bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
4714 	bool can_compact = can_direct_reclaim && gfp_compaction_allowed(gfp_mask);
4715 	bool nofail = gfp_mask & __GFP_NOFAIL;
4716 	const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
4717 	struct page *page = NULL;
4718 	unsigned int alloc_flags;
4719 	unsigned long did_some_progress;
4720 	enum compact_priority compact_priority;
4721 	enum compact_result compact_result;
4722 	int compaction_retries;
4723 	int no_progress_loops;
4724 	unsigned int cpuset_mems_cookie;
4725 	unsigned int zonelist_iter_cookie;
4726 	int reserve_flags;
4727 	bool compact_first = false;
4728 	bool can_retry_reserves = true;
4729 
4730 	if (unlikely(nofail)) {
4731 		/*
4732 		 * Also we don't support __GFP_NOFAIL without __GFP_DIRECT_RECLAIM,
4733 		 * otherwise, we may result in lockup.
4734 		 */
4735 		WARN_ON_ONCE(!can_direct_reclaim);
4736 		/*
4737 		 * PF_MEMALLOC request from this context is rather bizarre
4738 		 * because we cannot reclaim anything and only can loop waiting
4739 		 * for somebody to do a work for us.
4740 		 */
4741 		WARN_ON_ONCE(current->flags & PF_MEMALLOC);
4742 	}
4743 
4744 restart:
4745 	compaction_retries = 0;
4746 	no_progress_loops = 0;
4747 	compact_result = COMPACT_SKIPPED;
4748 	compact_priority = DEF_COMPACT_PRIORITY;
4749 	cpuset_mems_cookie = read_mems_allowed_begin();
4750 	zonelist_iter_cookie = zonelist_iter_begin();
4751 
4752 	/*
4753 	 * For costly allocations, try direct compaction first, as it's likely
4754 	 * that we have enough base pages and don't need to reclaim. For non-
4755 	 * movable high-order allocations, do that as well, as compaction will
4756 	 * try prevent permanent fragmentation by migrating from blocks of the
4757 	 * same migratetype.
4758 	 */
4759 	if (can_compact && (costly_order || (order > 0 &&
4760 					ac->migratetype != MIGRATE_MOVABLE))) {
4761 		compact_first = true;
4762 		compact_priority = INIT_COMPACT_PRIORITY;
4763 	}
4764 
4765 	/*
4766 	 * The fast path uses conservative alloc_flags to succeed only until
4767 	 * kswapd needs to be woken up, and to avoid the cost of setting up
4768 	 * alloc_flags precisely. So we do that now.
4769 	 */
4770 	alloc_flags = gfp_to_alloc_flags(gfp_mask, order);
4771 
4772 	/*
4773 	 * We need to recalculate the starting point for the zonelist iterator
4774 	 * because we might have used different nodemask in the fast path, or
4775 	 * there was a cpuset modification and we are retrying - otherwise we
4776 	 * could end up iterating over non-eligible zones endlessly.
4777 	 */
4778 	ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4779 					ac->highest_zoneidx, ac->nodemask);
4780 	if (!zonelist_zone(ac->preferred_zoneref))
4781 		goto nopage;
4782 
4783 	/*
4784 	 * Check for insane configurations where the cpuset doesn't contain
4785 	 * any suitable zone to satisfy the request - e.g. non-movable
4786 	 * GFP_HIGHUSER allocations from MOVABLE nodes only.
4787 	 */
4788 	if (cpusets_insane_config() && (gfp_mask & __GFP_HARDWALL)) {
4789 		struct zoneref *z = first_zones_zonelist(ac->zonelist,
4790 					ac->highest_zoneidx,
4791 					&cpuset_current_mems_allowed);
4792 		if (!zonelist_zone(z))
4793 			goto nopage;
4794 	}
4795 
4796 retry:
4797 	/* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4798 	if (alloc_flags & ALLOC_KSWAPD)
4799 		wake_all_kswapds(order, gfp_mask, ac);
4800 
4801 	/*
4802 	 * The adjusted alloc_flags might result in immediate success, so try
4803 	 * that first
4804 	 */
4805 	page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4806 	if (page)
4807 		goto got_pg;
4808 
4809 	reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
4810 	if (reserve_flags)
4811 		alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, reserve_flags) |
4812 					  (alloc_flags & ALLOC_KSWAPD);
4813 
4814 	/*
4815 	 * Reset the nodemask and zonelist iterators if memory policies can be
4816 	 * ignored. These allocations are high priority and system rather than
4817 	 * user oriented.
4818 	 */
4819 	if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
4820 		ac->nodemask = NULL;
4821 		ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4822 					ac->highest_zoneidx, ac->nodemask);
4823 
4824 		/*
4825 		 * The first time we adjust anything due to being allowed to
4826 		 * ignore memory policies or watermarks, retry immediately. This
4827 		 * allows us to keep the first allocation attempt optimistic so
4828 		 * it can succeed in a zone that is still above watermarks.
4829 		 */
4830 		if (can_retry_reserves) {
4831 			can_retry_reserves = false;
4832 			goto retry;
4833 		}
4834 	}
4835 
4836 	/* Caller is not willing to reclaim, we can't balance anything */
4837 	if (!can_direct_reclaim)
4838 		goto nopage;
4839 
4840 	/* Avoid recursion of direct reclaim */
4841 	if (current->flags & PF_MEMALLOC)
4842 		goto nopage;
4843 
4844 	/* Try direct reclaim and then allocating */
4845 	if (!compact_first) {
4846 		page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags,
4847 							ac, &did_some_progress);
4848 		if (page)
4849 			goto got_pg;
4850 	}
4851 
4852 	/* Try direct compaction and then allocating */
4853 	page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
4854 					compact_priority, &compact_result);
4855 	if (page)
4856 		goto got_pg;
4857 
4858 	if (compact_first) {
4859 		/*
4860 		 * THP page faults may attempt local node only first, but are
4861 		 * then allowed to only compact, not reclaim, see
4862 		 * alloc_pages_mpol().
4863 		 *
4864 		 * Compaction has failed above and we don't want such THP
4865 		 * allocations to put reclaim pressure on a single node in a
4866 		 * situation where other nodes might have plenty of available
4867 		 * memory.
4868 		 */
4869 		if (gfp_has_flags(gfp_mask, __GFP_NORETRY | __GFP_THISNODE))
4870 			goto nopage;
4871 
4872 		/*
4873 		 * For the initial compaction attempt we have lowered its
4874 		 * priority. Restore it for further retries, if those are
4875 		 * allowed. With __GFP_NORETRY there will be a single round of
4876 		 * reclaim and compaction with the lowered priority.
4877 		 */
4878 		if (!(gfp_mask & __GFP_NORETRY))
4879 			compact_priority = DEF_COMPACT_PRIORITY;
4880 
4881 		compact_first = false;
4882 		goto retry;
4883 	}
4884 
4885 	/* Do not loop if specifically requested */
4886 	if (gfp_mask & __GFP_NORETRY)
4887 		goto nopage;
4888 
4889 	/*
4890 	 * Do not retry costly high order allocations unless they are
4891 	 * __GFP_RETRY_MAYFAIL and we can compact
4892 	 */
4893 	if (costly_order && (!can_compact ||
4894 			     !(gfp_mask & __GFP_RETRY_MAYFAIL)))
4895 		goto nopage;
4896 
4897 	/*
4898 	 * Deal with possible cpuset update races or zonelist updates to avoid
4899 	 * infinite retries. No "goto retry;" can be placed above this check
4900 	 * unless it can execute just once.
4901 	 */
4902 	if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
4903 	    check_retry_zonelist(zonelist_iter_cookie))
4904 		goto restart;
4905 
4906 	if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
4907 				 did_some_progress > 0, &no_progress_loops))
4908 		goto retry;
4909 
4910 	/*
4911 	 * It doesn't make any sense to retry for the compaction if the order-0
4912 	 * reclaim is not able to make any progress because the current
4913 	 * implementation of the compaction depends on the sufficient amount
4914 	 * of free memory (see __compaction_suitable)
4915 	 */
4916 	if (did_some_progress > 0 && can_compact &&
4917 			should_compact_retry(ac, order, alloc_flags,
4918 				compact_result, &compact_priority,
4919 				&compaction_retries))
4920 		goto retry;
4921 
4922 	/* Reclaim/compaction failed to prevent the fallback */
4923 	if (defrag_mode && (alloc_flags & ALLOC_NOFRAGMENT)) {
4924 		alloc_flags &= ~ALLOC_NOFRAGMENT;
4925 		goto retry;
4926 	}
4927 
4928 	/*
4929 	 * Deal with possible cpuset update races or zonelist updates to avoid
4930 	 * a unnecessary OOM kill.
4931 	 */
4932 	if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
4933 	    check_retry_zonelist(zonelist_iter_cookie))
4934 		goto restart;
4935 
4936 	/* Reclaim has failed us, start killing things */
4937 	page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
4938 	if (page)
4939 		goto got_pg;
4940 
4941 	/* Avoid allocations with no watermarks from looping endlessly */
4942 	if (tsk_is_oom_victim(current) &&
4943 	    (alloc_flags & ALLOC_OOM ||
4944 	     (gfp_mask & __GFP_NOMEMALLOC)))
4945 		goto nopage;
4946 
4947 	/* Retry as long as the OOM killer is making progress */
4948 	if (did_some_progress) {
4949 		no_progress_loops = 0;
4950 		goto retry;
4951 	}
4952 
4953 nopage:
4954 	/*
4955 	 * Deal with possible cpuset update races or zonelist updates to avoid
4956 	 * a unnecessary OOM kill.
4957 	 */
4958 	if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
4959 	    check_retry_zonelist(zonelist_iter_cookie))
4960 		goto restart;
4961 
4962 	/*
4963 	 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
4964 	 * we always retry
4965 	 */
4966 	if (unlikely(nofail)) {
4967 		/*
4968 		 * Lacking direct_reclaim we can't do anything to reclaim memory,
4969 		 * we disregard these unreasonable nofail requests and still
4970 		 * return NULL
4971 		 */
4972 		if (!can_direct_reclaim)
4973 			goto fail;
4974 
4975 		/*
4976 		 * Help non-failing allocations by giving some access to memory
4977 		 * reserves normally used for high priority non-blocking
4978 		 * allocations but do not use ALLOC_NO_WATERMARKS because this
4979 		 * could deplete whole memory reserves which would just make
4980 		 * the situation worse.
4981 		 */
4982 		page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_MIN_RESERVE, ac);
4983 		if (page)
4984 			goto got_pg;
4985 
4986 		cond_resched();
4987 		goto retry;
4988 	}
4989 fail:
4990 	warn_alloc(gfp_mask, ac->nodemask,
4991 			"page allocation failure: order:%u", order);
4992 got_pg:
4993 	return page;
4994 }
4995 
4996 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
4997 		int preferred_nid, nodemask_t *nodemask,
4998 		struct alloc_context *ac, gfp_t *alloc_gfp,
4999 		unsigned int *alloc_flags)
5000 {
5001 	ac->highest_zoneidx = gfp_zone(gfp_mask);
5002 	ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
5003 	ac->nodemask = nodemask;
5004 	ac->migratetype = gfp_migratetype(gfp_mask);
5005 
5006 	if (cpusets_enabled()) {
5007 		*alloc_gfp |= __GFP_HARDWALL;
5008 		/*
5009 		 * When we are in the interrupt context, it is irrelevant
5010 		 * to the current task context. It means that any node ok.
5011 		 */
5012 		if (in_task() && !ac->nodemask)
5013 			ac->nodemask = &cpuset_current_mems_allowed;
5014 		else
5015 			*alloc_flags |= ALLOC_CPUSET;
5016 	}
5017 
5018 	might_alloc(gfp_mask);
5019 
5020 	/*
5021 	 * Don't invoke should_fail logic, since it may call
5022 	 * get_random_u32() and printk() which need to spin_lock.
5023 	 */
5024 	if (!(*alloc_flags & ALLOC_TRYLOCK) &&
5025 	    should_fail_alloc_page(gfp_mask, order))
5026 		return false;
5027 
5028 	*alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, *alloc_flags);
5029 
5030 	/* Dirty zone balancing only done in the fast path */
5031 	ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
5032 
5033 	/*
5034 	 * The preferred zone is used for statistics but crucially it is
5035 	 * also used as the starting point for the zonelist iterator. It
5036 	 * may get reset for allocations that ignore memory policies.
5037 	 */
5038 	ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
5039 					ac->highest_zoneidx, ac->nodemask);
5040 
5041 	return true;
5042 }
5043 
5044 /*
5045  * __alloc_pages_bulk - Allocate a number of order-0 pages to an array
5046  * @gfp: GFP flags for the allocation
5047  * @preferred_nid: The preferred NUMA node ID to allocate from
5048  * @nodemask: Set of nodes to allocate from, may be NULL
5049  * @nr_pages: The number of pages desired in the array
5050  * @page_array: Array to store the pages
5051  *
5052  * This is a batched version of the page allocator that attempts to allocate
5053  * @nr_pages quickly.  Pages are added to @page_array.
5054  *
5055  * Note that only the elements in @page_array that were cleared to %NULL on
5056  * entry are populated with newly allocated pages. @nr_pages is the maximum
5057  * number of pages that will be stored in the array.
5058  *
5059  * Returns the number of pages in @page_array, including ones already
5060  * allocated on entry.  This can be less than the number requested in @nr_pages,
5061  * but all empty slots are filled from the beginning.  I.e., if all slots in
5062  * @page_array were set to %NULL on entry, the slots from 0 to the return value
5063  * - 1 will be filled.
5064  */
5065 unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
5066 			nodemask_t *nodemask, int nr_pages,
5067 			struct page **page_array)
5068 {
5069 	struct page *page;
5070 	unsigned long UP_flags;
5071 	struct zone *zone;
5072 	struct zoneref *z;
5073 	struct per_cpu_pages *pcp;
5074 	struct list_head *pcp_list;
5075 	struct alloc_context ac;
5076 	gfp_t alloc_gfp;
5077 	unsigned int alloc_flags = ALLOC_WMARK_LOW;
5078 	int nr_populated = 0, nr_account = 0;
5079 
5080 	/*
5081 	 * Skip populated array elements to determine if any pages need
5082 	 * to be allocated before disabling IRQs.
5083 	 */
5084 	while (nr_populated < nr_pages && page_array[nr_populated])
5085 		nr_populated++;
5086 
5087 	/* No pages requested? */
5088 	if (unlikely(nr_pages <= 0))
5089 		goto out;
5090 
5091 	/* Already populated array? */
5092 	if (unlikely(nr_pages - nr_populated == 0))
5093 		goto out;
5094 
5095 	/* Bulk allocator does not support memcg accounting. */
5096 	if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT))
5097 		goto failed;
5098 
5099 	/* Use the single page allocator for one page. */
5100 	if (nr_pages - nr_populated == 1)
5101 		goto failed;
5102 
5103 #ifdef CONFIG_PAGE_OWNER
5104 	/*
5105 	 * PAGE_OWNER may recurse into the allocator to allocate space to
5106 	 * save the stack with pagesets.lock held. Releasing/reacquiring
5107 	 * removes much of the performance benefit of bulk allocation so
5108 	 * force the caller to allocate one page at a time as it'll have
5109 	 * similar performance to added complexity to the bulk allocator.
5110 	 */
5111 	if (static_branch_unlikely(&page_owner_inited))
5112 		goto failed;
5113 #endif
5114 
5115 	/* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */
5116 	gfp &= gfp_allowed_mask;
5117 	alloc_gfp = gfp;
5118 	if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &alloc_gfp, &alloc_flags))
5119 		goto out;
5120 	gfp = alloc_gfp;
5121 
5122 	/* Find an allowed local zone that meets the low watermark. */
5123 	z = ac.preferred_zoneref;
5124 	for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) {
5125 		unsigned long mark;
5126 
5127 		if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) &&
5128 		    !__cpuset_zone_allowed(zone, gfp)) {
5129 			continue;
5130 		}
5131 
5132 		if (nr_online_nodes > 1 && zone != zonelist_zone(ac.preferred_zoneref) &&
5133 		    zone_to_nid(zone) != zonelist_node_idx(ac.preferred_zoneref)) {
5134 			goto failed;
5135 		}
5136 
5137 		cond_accept_memory(zone, 0, alloc_flags);
5138 retry_this_zone:
5139 		mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages;
5140 		if (zone_watermark_fast(zone, 0,  mark,
5141 				zonelist_zone_idx(ac.preferred_zoneref),
5142 				alloc_flags, gfp)) {
5143 			break;
5144 		}
5145 
5146 		if (cond_accept_memory(zone, 0, alloc_flags))
5147 			goto retry_this_zone;
5148 
5149 		/* Try again if zone has deferred pages */
5150 		if (deferred_pages_enabled()) {
5151 			if (_deferred_grow_zone(zone, 0))
5152 				goto retry_this_zone;
5153 		}
5154 	}
5155 
5156 	/*
5157 	 * If there are no allowed local zones that meets the watermarks then
5158 	 * try to allocate a single page and reclaim if necessary.
5159 	 */
5160 	if (unlikely(!zone))
5161 		goto failed;
5162 
5163 	/* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */
5164 	pcp = pcp_spin_trylock(zone->per_cpu_pageset, UP_flags);
5165 	if (!pcp)
5166 		goto failed;
5167 
5168 	/* Attempt the batch allocation */
5169 	pcp_list = &pcp->lists[order_to_pindex(ac.migratetype, 0)];
5170 	while (nr_populated < nr_pages) {
5171 
5172 		/* Skip existing pages */
5173 		if (page_array[nr_populated]) {
5174 			nr_populated++;
5175 			continue;
5176 		}
5177 
5178 		page = __rmqueue_pcplist(zone, 0, ac.migratetype, alloc_flags,
5179 								pcp, pcp_list);
5180 		if (unlikely(!page)) {
5181 			/* Try and allocate at least one page */
5182 			if (!nr_account) {
5183 				pcp_spin_unlock(pcp, UP_flags);
5184 				goto failed;
5185 			}
5186 			break;
5187 		}
5188 		nr_account++;
5189 
5190 		prep_new_page(page, 0, gfp, 0);
5191 		set_page_refcounted(page);
5192 		page_array[nr_populated++] = page;
5193 	}
5194 
5195 	pcp_spin_unlock(pcp, UP_flags);
5196 
5197 	__count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account);
5198 	zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account);
5199 
5200 out:
5201 	return nr_populated;
5202 
5203 failed:
5204 	page = __alloc_pages_noprof(gfp, 0, preferred_nid, nodemask);
5205 	if (page)
5206 		page_array[nr_populated++] = page;
5207 	goto out;
5208 }
5209 EXPORT_SYMBOL_GPL(alloc_pages_bulk_noprof);
5210 
5211 /*
5212  * This is the 'heart' of the zoned buddy allocator.
5213  */
5214 struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order,
5215 		int preferred_nid, nodemask_t *nodemask)
5216 {
5217 	struct page *page;
5218 	unsigned int alloc_flags = ALLOC_WMARK_LOW;
5219 	gfp_t alloc_gfp; /* The gfp_t that was actually used for allocation */
5220 	struct alloc_context ac = { };
5221 
5222 	/*
5223 	 * There are several places where we assume that the order value is sane
5224 	 * so bail out early if the request is out of bound.
5225 	 */
5226 	if (WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp))
5227 		return NULL;
5228 
5229 	gfp &= gfp_allowed_mask;
5230 	/*
5231 	 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
5232 	 * resp. GFP_NOIO which has to be inherited for all allocation requests
5233 	 * from a particular context which has been marked by
5234 	 * memalloc_no{fs,io}_{save,restore}. And PF_MEMALLOC_PIN which ensures
5235 	 * movable zones are not used during allocation.
5236 	 */
5237 	gfp = current_gfp_context(gfp);
5238 	alloc_gfp = gfp;
5239 	if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac,
5240 			&alloc_gfp, &alloc_flags))
5241 		return NULL;
5242 
5243 	/*
5244 	 * Forbid the first pass from falling back to types that fragment
5245 	 * memory until all local zones are considered.
5246 	 */
5247 	alloc_flags |= alloc_flags_nofragment(zonelist_zone(ac.preferred_zoneref), gfp);
5248 
5249 	/* First allocation attempt */
5250 	page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac);
5251 	if (likely(page))
5252 		goto out;
5253 
5254 	alloc_gfp = gfp;
5255 	ac.spread_dirty_pages = false;
5256 
5257 	/*
5258 	 * Restore the original nodemask if it was potentially replaced with
5259 	 * &cpuset_current_mems_allowed to optimize the fast-path attempt.
5260 	 */
5261 	ac.nodemask = nodemask;
5262 
5263 	page = __alloc_pages_slowpath(alloc_gfp, order, &ac);
5264 
5265 out:
5266 	if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT) && page &&
5267 	    unlikely(__memcg_kmem_charge_page(page, gfp, order) != 0)) {
5268 		free_frozen_pages(page, order);
5269 		page = NULL;
5270 	}
5271 
5272 	trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype);
5273 	kmsan_alloc_page(page, order, alloc_gfp);
5274 
5275 	return page;
5276 }
5277 EXPORT_SYMBOL(__alloc_frozen_pages_noprof);
5278 
5279 struct page *__alloc_pages_noprof(gfp_t gfp, unsigned int order,
5280 		int preferred_nid, nodemask_t *nodemask)
5281 {
5282 	struct page *page;
5283 
5284 	page = __alloc_frozen_pages_noprof(gfp, order, preferred_nid, nodemask);
5285 	if (page)
5286 		set_page_refcounted(page);
5287 	return page;
5288 }
5289 EXPORT_SYMBOL(__alloc_pages_noprof);
5290 
5291 struct folio *__folio_alloc_noprof(gfp_t gfp, unsigned int order, int preferred_nid,
5292 		nodemask_t *nodemask)
5293 {
5294 	struct page *page = __alloc_pages_noprof(gfp | __GFP_COMP, order,
5295 					preferred_nid, nodemask);
5296 	return page_rmappable_folio(page);
5297 }
5298 EXPORT_SYMBOL(__folio_alloc_noprof);
5299 
5300 /*
5301  * Common helper functions. Never use with __GFP_HIGHMEM because the returned
5302  * address cannot represent highmem pages. Use alloc_pages and then kmap if
5303  * you need to access high mem.
5304  */
5305 unsigned long get_free_pages_noprof(gfp_t gfp_mask, unsigned int order)
5306 {
5307 	struct page *page;
5308 
5309 	page = alloc_pages_noprof(gfp_mask & ~__GFP_HIGHMEM, order);
5310 	if (!page)
5311 		return 0;
5312 	return (unsigned long) page_address(page);
5313 }
5314 EXPORT_SYMBOL(get_free_pages_noprof);
5315 
5316 unsigned long get_zeroed_page_noprof(gfp_t gfp_mask)
5317 {
5318 	return get_free_pages_noprof(gfp_mask | __GFP_ZERO, 0);
5319 }
5320 EXPORT_SYMBOL(get_zeroed_page_noprof);
5321 
5322 static void ___free_pages(struct page *page, unsigned int order,
5323 			  fpi_t fpi_flags)
5324 {
5325 	/* get PageHead before we drop reference */
5326 	int head = PageHead(page);
5327 	/* get alloc tag in case the page is released by others */
5328 	struct alloc_tag *tag = pgalloc_tag_get(page);
5329 
5330 	if (put_page_testzero(page))
5331 		__free_frozen_pages(page, order, fpi_flags);
5332 	else if (!head) {
5333 		pgalloc_tag_sub_pages(tag, (1 << order) - 1);
5334 		while (order-- > 0) {
5335 			/*
5336 			 * The "tail" pages of this non-compound high-order
5337 			 * page will have no code tags, so to avoid warnings
5338 			 * mark them as empty.
5339 			 */
5340 			clear_page_tag_ref(page + (1 << order));
5341 			__free_frozen_pages(page + (1 << order), order,
5342 					    fpi_flags);
5343 		}
5344 	}
5345 }
5346 
5347 /**
5348  * __free_pages - Free pages allocated with alloc_pages().
5349  * @page: The page pointer returned from alloc_pages().
5350  * @order: The order of the allocation.
5351  *
5352  * This function can free multi-page allocations that are not compound
5353  * pages.  It does not check that the @order passed in matches that of
5354  * the allocation, so it is easy to leak memory.  Freeing more memory
5355  * than was allocated will probably emit a warning.
5356  *
5357  * If the last reference to this page is speculative, it will be released
5358  * by put_page() which only frees the first page of a non-compound
5359  * allocation.  To prevent the remaining pages from being leaked, we free
5360  * the subsequent pages here.  If you want to use the page's reference
5361  * count to decide when to free the allocation, you should allocate a
5362  * compound page, and use put_page() instead of __free_pages().
5363  *
5364  * Context: May be called in interrupt context or while holding a normal
5365  * spinlock, but not in NMI context or while holding a raw spinlock.
5366  */
5367 void __free_pages(struct page *page, unsigned int order)
5368 {
5369 	___free_pages(page, order, FPI_NONE);
5370 }
5371 EXPORT_SYMBOL(__free_pages);
5372 
5373 /*
5374  * Can be called while holding raw_spin_lock or from IRQ and NMI for any
5375  * page type (not only those that came from alloc_pages_nolock)
5376  */
5377 void free_pages_nolock(struct page *page, unsigned int order)
5378 {
5379 	___free_pages(page, order, FPI_TRYLOCK);
5380 }
5381 
5382 /**
5383  * free_pages - Free pages allocated with __get_free_pages().
5384  * @addr: The virtual address tied to a page returned from __get_free_pages().
5385  * @order: The order of the allocation.
5386  *
5387  * This function behaves the same as __free_pages(). Use this function
5388  * to free pages when you only have a valid virtual address. If you have
5389  * the page, call __free_pages() instead.
5390  */
5391 void free_pages(unsigned long addr, unsigned int order)
5392 {
5393 	if (addr != 0) {
5394 		VM_BUG_ON(!virt_addr_valid((void *)addr));
5395 		__free_pages(virt_to_page((void *)addr), order);
5396 	}
5397 }
5398 
5399 EXPORT_SYMBOL(free_pages);
5400 
5401 static void *make_alloc_exact(unsigned long addr, unsigned int order,
5402 		size_t size)
5403 {
5404 	if (addr) {
5405 		unsigned long nr = DIV_ROUND_UP(size, PAGE_SIZE);
5406 		struct page *page = virt_to_page((void *)addr);
5407 		struct page *last = page + nr;
5408 
5409 		__split_page(page, order);
5410 		while (page < --last)
5411 			set_page_refcounted(last);
5412 
5413 		last = page + (1UL << order);
5414 		for (page += nr; page < last; page++)
5415 			__free_pages_ok(page, 0, FPI_TO_TAIL);
5416 	}
5417 	return (void *)addr;
5418 }
5419 
5420 /**
5421  * alloc_pages_exact - allocate an exact number physically-contiguous pages.
5422  * @size: the number of bytes to allocate
5423  * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5424  *
5425  * This function is similar to alloc_pages(), except that it allocates the
5426  * minimum number of pages to satisfy the request.  alloc_pages() can only
5427  * allocate memory in power-of-two pages.
5428  *
5429  * This function is also limited by MAX_PAGE_ORDER.
5430  *
5431  * Memory allocated by this function must be released by free_pages_exact().
5432  *
5433  * Return: pointer to the allocated area or %NULL in case of error.
5434  */
5435 void *alloc_pages_exact_noprof(size_t size, gfp_t gfp_mask)
5436 {
5437 	unsigned int order = get_order(size);
5438 	unsigned long addr;
5439 
5440 	if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
5441 		gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
5442 
5443 	addr = get_free_pages_noprof(gfp_mask, order);
5444 	return make_alloc_exact(addr, order, size);
5445 }
5446 EXPORT_SYMBOL(alloc_pages_exact_noprof);
5447 
5448 /**
5449  * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
5450  *			   pages on a node.
5451  * @nid: the preferred node ID where memory should be allocated
5452  * @size: the number of bytes to allocate
5453  * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5454  *
5455  * Like alloc_pages_exact(), but try to allocate on node nid first before falling
5456  * back.
5457  *
5458  * Return: pointer to the allocated area or %NULL in case of error.
5459  */
5460 void * __meminit alloc_pages_exact_nid_noprof(int nid, size_t size, gfp_t gfp_mask)
5461 {
5462 	unsigned int order = get_order(size);
5463 	struct page *p;
5464 
5465 	if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
5466 		gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
5467 
5468 	p = alloc_pages_node_noprof(nid, gfp_mask, order);
5469 	if (!p)
5470 		return NULL;
5471 	return make_alloc_exact((unsigned long)page_address(p), order, size);
5472 }
5473 
5474 /**
5475  * free_pages_exact - release memory allocated via alloc_pages_exact()
5476  * @virt: the value returned by alloc_pages_exact.
5477  * @size: size of allocation, same value as passed to alloc_pages_exact().
5478  *
5479  * Release the memory allocated by a previous call to alloc_pages_exact.
5480  */
5481 void free_pages_exact(void *virt, size_t size)
5482 {
5483 	unsigned long addr = (unsigned long)virt;
5484 	unsigned long end = addr + PAGE_ALIGN(size);
5485 
5486 	while (addr < end) {
5487 		free_page(addr);
5488 		addr += PAGE_SIZE;
5489 	}
5490 }
5491 EXPORT_SYMBOL(free_pages_exact);
5492 
5493 /**
5494  * nr_free_zone_pages - count number of pages beyond high watermark
5495  * @offset: The zone index of the highest zone
5496  *
5497  * nr_free_zone_pages() counts the number of pages which are beyond the
5498  * high watermark within all zones at or below a given zone index.  For each
5499  * zone, the number of pages is calculated as:
5500  *
5501  *     nr_free_zone_pages = managed_pages - high_pages
5502  *
5503  * Return: number of pages beyond high watermark.
5504  */
5505 static unsigned long nr_free_zone_pages(int offset)
5506 {
5507 	struct zoneref *z;
5508 	struct zone *zone;
5509 
5510 	/* Just pick one node, since fallback list is circular */
5511 	unsigned long sum = 0;
5512 
5513 	struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
5514 
5515 	for_each_zone_zonelist(zone, z, zonelist, offset) {
5516 		unsigned long size = zone_managed_pages(zone);
5517 		unsigned long high = high_wmark_pages(zone);
5518 		if (size > high)
5519 			sum += size - high;
5520 	}
5521 
5522 	return sum;
5523 }
5524 
5525 /**
5526  * nr_free_buffer_pages - count number of pages beyond high watermark
5527  *
5528  * nr_free_buffer_pages() counts the number of pages which are beyond the high
5529  * watermark within ZONE_DMA and ZONE_NORMAL.
5530  *
5531  * Return: number of pages beyond high watermark within ZONE_DMA and
5532  * ZONE_NORMAL.
5533  */
5534 unsigned long nr_free_buffer_pages(void)
5535 {
5536 	return nr_free_zone_pages(gfp_zone(GFP_USER));
5537 }
5538 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
5539 
5540 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
5541 {
5542 	zoneref->zone = zone;
5543 	zoneref->zone_idx = zone_idx(zone);
5544 }
5545 
5546 /*
5547  * Builds allocation fallback zone lists.
5548  *
5549  * Add all populated zones of a node to the zonelist.
5550  */
5551 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
5552 {
5553 	struct zone *zone;
5554 	enum zone_type zone_type = MAX_NR_ZONES;
5555 	int nr_zones = 0;
5556 
5557 	do {
5558 		zone_type--;
5559 		zone = pgdat->node_zones + zone_type;
5560 		if (populated_zone(zone)) {
5561 			zoneref_set_zone(zone, &zonerefs[nr_zones++]);
5562 			check_highest_zone(zone_type);
5563 		}
5564 	} while (zone_type);
5565 
5566 	return nr_zones;
5567 }
5568 
5569 #ifdef CONFIG_NUMA
5570 
5571 static int __parse_numa_zonelist_order(char *s)
5572 {
5573 	/*
5574 	 * We used to support different zonelists modes but they turned
5575 	 * out to be just not useful. Let's keep the warning in place
5576 	 * if somebody still use the cmd line parameter so that we do
5577 	 * not fail it silently
5578 	 */
5579 	if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
5580 		pr_warn("Ignoring unsupported numa_zonelist_order value:  %s\n", s);
5581 		return -EINVAL;
5582 	}
5583 	return 0;
5584 }
5585 
5586 static char numa_zonelist_order[] = "Node";
5587 #define NUMA_ZONELIST_ORDER_LEN	16
5588 /*
5589  * sysctl handler for numa_zonelist_order
5590  */
5591 static int numa_zonelist_order_handler(const struct ctl_table *table, int write,
5592 		void *buffer, size_t *length, loff_t *ppos)
5593 {
5594 	if (write)
5595 		return __parse_numa_zonelist_order(buffer);
5596 	return proc_dostring(table, write, buffer, length, ppos);
5597 }
5598 
5599 static int node_load[MAX_NUMNODES];
5600 
5601 /**
5602  * find_next_best_node - find the next node that should appear in a given node's fallback list
5603  * @node: node whose fallback list we're appending
5604  * @used_node_mask: nodemask_t of already used nodes
5605  *
5606  * We use a number of factors to determine which is the next node that should
5607  * appear on a given node's fallback list.  The node should not have appeared
5608  * already in @node's fallback list, and it should be the next closest node
5609  * according to the distance array (which contains arbitrary distance values
5610  * from each node to each node in the system), and should also prefer nodes
5611  * with no CPUs, since presumably they'll have very little allocation pressure
5612  * on them otherwise.
5613  *
5614  * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
5615  */
5616 int find_next_best_node(int node, nodemask_t *used_node_mask)
5617 {
5618 	int n, val;
5619 	int min_val = INT_MAX;
5620 	int best_node = NUMA_NO_NODE;
5621 
5622 	/*
5623 	 * Use the local node if we haven't already, but for memoryless local
5624 	 * node, we should skip it and fall back to other nodes.
5625 	 */
5626 	if (!node_isset(node, *used_node_mask) && node_state(node, N_MEMORY)) {
5627 		node_set(node, *used_node_mask);
5628 		return node;
5629 	}
5630 
5631 	for_each_node_state(n, N_MEMORY) {
5632 
5633 		/* Don't want a node to appear more than once */
5634 		if (node_isset(n, *used_node_mask))
5635 			continue;
5636 
5637 		/* Use the distance array to find the distance */
5638 		val = node_distance(node, n);
5639 
5640 		/* Penalize nodes under us ("prefer the next node") */
5641 		val += (n < node);
5642 
5643 		/* Give preference to headless and unused nodes */
5644 		if (!cpumask_empty(cpumask_of_node(n)))
5645 			val += PENALTY_FOR_NODE_WITH_CPUS;
5646 
5647 		/* Slight preference for less loaded node */
5648 		val *= MAX_NUMNODES;
5649 		val += node_load[n];
5650 
5651 		if (val < min_val) {
5652 			min_val = val;
5653 			best_node = n;
5654 		}
5655 	}
5656 
5657 	if (best_node >= 0)
5658 		node_set(best_node, *used_node_mask);
5659 
5660 	return best_node;
5661 }
5662 
5663 
5664 /*
5665  * Build zonelists ordered by node and zones within node.
5666  * This results in maximum locality--normal zone overflows into local
5667  * DMA zone, if any--but risks exhausting DMA zone.
5668  */
5669 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
5670 		unsigned nr_nodes)
5671 {
5672 	struct zoneref *zonerefs;
5673 	int i;
5674 
5675 	zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5676 
5677 	for (i = 0; i < nr_nodes; i++) {
5678 		int nr_zones;
5679 
5680 		pg_data_t *node = NODE_DATA(node_order[i]);
5681 
5682 		nr_zones = build_zonerefs_node(node, zonerefs);
5683 		zonerefs += nr_zones;
5684 	}
5685 	zonerefs->zone = NULL;
5686 	zonerefs->zone_idx = 0;
5687 }
5688 
5689 /*
5690  * Build __GFP_THISNODE zonelists
5691  */
5692 static void build_thisnode_zonelists(pg_data_t *pgdat)
5693 {
5694 	struct zoneref *zonerefs;
5695 	int nr_zones;
5696 
5697 	zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
5698 	nr_zones = build_zonerefs_node(pgdat, zonerefs);
5699 	zonerefs += nr_zones;
5700 	zonerefs->zone = NULL;
5701 	zonerefs->zone_idx = 0;
5702 }
5703 
5704 static void build_zonelists(pg_data_t *pgdat)
5705 {
5706 	static int node_order[MAX_NUMNODES];
5707 	int node, nr_nodes = 0;
5708 	nodemask_t used_mask = NODE_MASK_NONE;
5709 	int local_node, prev_node;
5710 
5711 	/* NUMA-aware ordering of nodes */
5712 	local_node = pgdat->node_id;
5713 	prev_node = local_node;
5714 
5715 	memset(node_order, 0, sizeof(node_order));
5716 	while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
5717 		/*
5718 		 * We don't want to pressure a particular node.
5719 		 * So adding penalty to the first node in same
5720 		 * distance group to make it round-robin.
5721 		 */
5722 		if (node_distance(local_node, node) !=
5723 		    node_distance(local_node, prev_node))
5724 			node_load[node] += 1;
5725 
5726 		node_order[nr_nodes++] = node;
5727 		prev_node = node;
5728 	}
5729 
5730 	build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
5731 	build_thisnode_zonelists(pgdat);
5732 	pr_info("Fallback order for Node %d: ", local_node);
5733 	for (node = 0; node < nr_nodes; node++)
5734 		pr_cont("%d ", node_order[node]);
5735 	pr_cont("\n");
5736 }
5737 
5738 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5739 /*
5740  * Return node id of node used for "local" allocations.
5741  * I.e., first node id of first zone in arg node's generic zonelist.
5742  * Used for initializing percpu 'numa_mem', which is used primarily
5743  * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
5744  */
5745 int local_memory_node(int node)
5746 {
5747 	struct zoneref *z;
5748 
5749 	z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
5750 				   gfp_zone(GFP_KERNEL),
5751 				   NULL);
5752 	return zonelist_node_idx(z);
5753 }
5754 #endif
5755 
5756 static void setup_min_unmapped_ratio(void);
5757 static void setup_min_slab_ratio(void);
5758 #else	/* CONFIG_NUMA */
5759 
5760 static void build_zonelists(pg_data_t *pgdat)
5761 {
5762 	struct zoneref *zonerefs;
5763 	int nr_zones;
5764 
5765 	zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5766 	nr_zones = build_zonerefs_node(pgdat, zonerefs);
5767 	zonerefs += nr_zones;
5768 
5769 	zonerefs->zone = NULL;
5770 	zonerefs->zone_idx = 0;
5771 }
5772 
5773 #endif	/* CONFIG_NUMA */
5774 
5775 /*
5776  * Boot pageset table. One per cpu which is going to be used for all
5777  * zones and all nodes. The parameters will be set in such a way
5778  * that an item put on a list will immediately be handed over to
5779  * the buddy list. This is safe since pageset manipulation is done
5780  * with interrupts disabled.
5781  *
5782  * The boot_pagesets must be kept even after bootup is complete for
5783  * unused processors and/or zones. They do play a role for bootstrapping
5784  * hotplugged processors.
5785  *
5786  * zoneinfo_show() and maybe other functions do
5787  * not check if the processor is online before following the pageset pointer.
5788  * Other parts of the kernel may not check if the zone is available.
5789  */
5790 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats);
5791 /* These effectively disable the pcplists in the boot pageset completely */
5792 #define BOOT_PAGESET_HIGH	0
5793 #define BOOT_PAGESET_BATCH	1
5794 static DEFINE_PER_CPU(struct per_cpu_pages, boot_pageset);
5795 static DEFINE_PER_CPU(struct per_cpu_zonestat, boot_zonestats);
5796 
5797 static void __build_all_zonelists(void *data)
5798 {
5799 	int nid;
5800 	int __maybe_unused cpu;
5801 	pg_data_t *self = data;
5802 	unsigned long flags;
5803 
5804 	/*
5805 	 * The zonelist_update_seq must be acquired with irqsave because the
5806 	 * reader can be invoked from IRQ with GFP_ATOMIC.
5807 	 */
5808 	write_seqlock_irqsave(&zonelist_update_seq, flags);
5809 	/*
5810 	 * Also disable synchronous printk() to prevent any printk() from
5811 	 * trying to hold port->lock, for
5812 	 * tty_insert_flip_string_and_push_buffer() on other CPU might be
5813 	 * calling kmalloc(GFP_ATOMIC | __GFP_NOWARN) with port->lock held.
5814 	 */
5815 	printk_deferred_enter();
5816 
5817 #ifdef CONFIG_NUMA
5818 	memset(node_load, 0, sizeof(node_load));
5819 #endif
5820 
5821 	/*
5822 	 * This node is hotadded and no memory is yet present.   So just
5823 	 * building zonelists is fine - no need to touch other nodes.
5824 	 */
5825 	if (self && !node_online(self->node_id)) {
5826 		build_zonelists(self);
5827 	} else {
5828 		/*
5829 		 * All possible nodes have pgdat preallocated
5830 		 * in free_area_init
5831 		 */
5832 		for_each_node(nid) {
5833 			pg_data_t *pgdat = NODE_DATA(nid);
5834 
5835 			build_zonelists(pgdat);
5836 		}
5837 
5838 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5839 		/*
5840 		 * We now know the "local memory node" for each node--
5841 		 * i.e., the node of the first zone in the generic zonelist.
5842 		 * Set up numa_mem percpu variable for on-line cpus.  During
5843 		 * boot, only the boot cpu should be on-line;  we'll init the
5844 		 * secondary cpus' numa_mem as they come on-line.  During
5845 		 * node/memory hotplug, we'll fixup all on-line cpus.
5846 		 */
5847 		for_each_online_cpu(cpu)
5848 			set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
5849 #endif
5850 	}
5851 
5852 	printk_deferred_exit();
5853 	write_sequnlock_irqrestore(&zonelist_update_seq, flags);
5854 }
5855 
5856 static noinline void __init
5857 build_all_zonelists_init(void)
5858 {
5859 	int cpu;
5860 
5861 	__build_all_zonelists(NULL);
5862 
5863 	/*
5864 	 * Initialize the boot_pagesets that are going to be used
5865 	 * for bootstrapping processors. The real pagesets for
5866 	 * each zone will be allocated later when the per cpu
5867 	 * allocator is available.
5868 	 *
5869 	 * boot_pagesets are used also for bootstrapping offline
5870 	 * cpus if the system is already booted because the pagesets
5871 	 * are needed to initialize allocators on a specific cpu too.
5872 	 * F.e. the percpu allocator needs the page allocator which
5873 	 * needs the percpu allocator in order to allocate its pagesets
5874 	 * (a chicken-egg dilemma).
5875 	 */
5876 	for_each_possible_cpu(cpu)
5877 		per_cpu_pages_init(&per_cpu(boot_pageset, cpu), &per_cpu(boot_zonestats, cpu));
5878 
5879 	mminit_verify_zonelist();
5880 	cpuset_init_current_mems_allowed();
5881 }
5882 
5883 /*
5884  * unless system_state == SYSTEM_BOOTING.
5885  *
5886  * __ref due to call of __init annotated helper build_all_zonelists_init
5887  * [protected by SYSTEM_BOOTING].
5888  */
5889 void __ref build_all_zonelists(pg_data_t *pgdat)
5890 {
5891 	unsigned long vm_total_pages;
5892 
5893 	if (system_state == SYSTEM_BOOTING) {
5894 		build_all_zonelists_init();
5895 	} else {
5896 		__build_all_zonelists(pgdat);
5897 		/* cpuset refresh routine should be here */
5898 	}
5899 	/* Get the number of free pages beyond high watermark in all zones. */
5900 	vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
5901 	/*
5902 	 * Disable grouping by mobility if the number of pages in the
5903 	 * system is too low to allow the mechanism to work. It would be
5904 	 * more accurate, but expensive to check per-zone. This check is
5905 	 * made on memory-hotadd so a system can start with mobility
5906 	 * disabled and enable it later
5907 	 */
5908 	if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
5909 		page_group_by_mobility_disabled = 1;
5910 	else
5911 		page_group_by_mobility_disabled = 0;
5912 
5913 	pr_info("Built %u zonelists, mobility grouping %s.  Total pages: %ld\n",
5914 		nr_online_nodes,
5915 		str_off_on(page_group_by_mobility_disabled),
5916 		vm_total_pages);
5917 #ifdef CONFIG_NUMA
5918 	pr_info("Policy zone: %s\n", zone_names[policy_zone]);
5919 #endif
5920 }
5921 
5922 static int zone_batchsize(struct zone *zone)
5923 {
5924 #ifdef CONFIG_MMU
5925 	int batch;
5926 
5927 	/*
5928 	 * The number of pages to batch allocate is either ~0.025%
5929 	 * of the zone or 256KB, whichever is smaller. The batch
5930 	 * size is striking a balance between allocation latency
5931 	 * and zone lock contention.
5932 	 */
5933 	batch = min(zone_managed_pages(zone) >> 12, SZ_256K / PAGE_SIZE);
5934 	if (batch <= 1)
5935 		return 1;
5936 
5937 	/*
5938 	 * Clamp the batch to a 2^n - 1 value. Having a power
5939 	 * of 2 value was found to be more likely to have
5940 	 * suboptimal cache aliasing properties in some cases.
5941 	 *
5942 	 * For example if 2 tasks are alternately allocating
5943 	 * batches of pages, one task can end up with a lot
5944 	 * of pages of one half of the possible page colors
5945 	 * and the other with pages of the other colors.
5946 	 */
5947 	batch = rounddown_pow_of_two(batch + batch/2) - 1;
5948 
5949 	return batch;
5950 
5951 #else
5952 	/* The deferral and batching of frees should be suppressed under NOMMU
5953 	 * conditions.
5954 	 *
5955 	 * The problem is that NOMMU needs to be able to allocate large chunks
5956 	 * of contiguous memory as there's no hardware page translation to
5957 	 * assemble apparent contiguous memory from discontiguous pages.
5958 	 *
5959 	 * Queueing large contiguous runs of pages for batching, however,
5960 	 * causes the pages to actually be freed in smaller chunks.  As there
5961 	 * can be a significant delay between the individual batches being
5962 	 * recycled, this leads to the once large chunks of space being
5963 	 * fragmented and becoming unavailable for high-order allocations.
5964 	 */
5965 	return 1;
5966 #endif
5967 }
5968 
5969 static int percpu_pagelist_high_fraction;
5970 static int zone_highsize(struct zone *zone, int batch, int cpu_online,
5971 			 int high_fraction)
5972 {
5973 #ifdef CONFIG_MMU
5974 	int high;
5975 	int nr_split_cpus;
5976 	unsigned long total_pages;
5977 
5978 	if (!high_fraction) {
5979 		/*
5980 		 * By default, the high value of the pcp is based on the zone
5981 		 * low watermark so that if they are full then background
5982 		 * reclaim will not be started prematurely.
5983 		 */
5984 		total_pages = low_wmark_pages(zone);
5985 	} else {
5986 		/*
5987 		 * If percpu_pagelist_high_fraction is configured, the high
5988 		 * value is based on a fraction of the managed pages in the
5989 		 * zone.
5990 		 */
5991 		total_pages = zone_managed_pages(zone) / high_fraction;
5992 	}
5993 
5994 	/*
5995 	 * Split the high value across all online CPUs local to the zone. Note
5996 	 * that early in boot that CPUs may not be online yet and that during
5997 	 * CPU hotplug that the cpumask is not yet updated when a CPU is being
5998 	 * onlined. For memory nodes that have no CPUs, split the high value
5999 	 * across all online CPUs to mitigate the risk that reclaim is triggered
6000 	 * prematurely due to pages stored on pcp lists.
6001 	 */
6002 	nr_split_cpus = cpumask_weight(cpumask_of_node(zone_to_nid(zone))) + cpu_online;
6003 	if (!nr_split_cpus)
6004 		nr_split_cpus = num_online_cpus();
6005 	high = total_pages / nr_split_cpus;
6006 
6007 	/*
6008 	 * Ensure high is at least batch*4. The multiple is based on the
6009 	 * historical relationship between high and batch.
6010 	 */
6011 	high = max(high, batch << 2);
6012 
6013 	return high;
6014 #else
6015 	return 0;
6016 #endif
6017 }
6018 
6019 /*
6020  * pcp->high and pcp->batch values are related and generally batch is lower
6021  * than high. They are also related to pcp->count such that count is lower
6022  * than high, and as soon as it reaches high, the pcplist is flushed.
6023  *
6024  * However, guaranteeing these relations at all times would require e.g. write
6025  * barriers here but also careful usage of read barriers at the read side, and
6026  * thus be prone to error and bad for performance. Thus the update only prevents
6027  * store tearing. Any new users of pcp->batch, pcp->high_min and pcp->high_max
6028  * should ensure they can cope with those fields changing asynchronously, and
6029  * fully trust only the pcp->count field on the local CPU with interrupts
6030  * disabled.
6031  *
6032  * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
6033  * outside of boot time (or some other assurance that no concurrent updaters
6034  * exist).
6035  */
6036 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high_min,
6037 			   unsigned long high_max, unsigned long batch)
6038 {
6039 	WRITE_ONCE(pcp->batch, batch);
6040 	WRITE_ONCE(pcp->high_min, high_min);
6041 	WRITE_ONCE(pcp->high_max, high_max);
6042 }
6043 
6044 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats)
6045 {
6046 	int pindex;
6047 
6048 	memset(pcp, 0, sizeof(*pcp));
6049 	memset(pzstats, 0, sizeof(*pzstats));
6050 
6051 	spin_lock_init(&pcp->lock);
6052 	for (pindex = 0; pindex < NR_PCP_LISTS; pindex++)
6053 		INIT_LIST_HEAD(&pcp->lists[pindex]);
6054 
6055 	/*
6056 	 * Set batch and high values safe for a boot pageset. A true percpu
6057 	 * pageset's initialization will update them subsequently. Here we don't
6058 	 * need to be as careful as pageset_update() as nobody can access the
6059 	 * pageset yet.
6060 	 */
6061 	pcp->high_min = BOOT_PAGESET_HIGH;
6062 	pcp->high_max = BOOT_PAGESET_HIGH;
6063 	pcp->batch = BOOT_PAGESET_BATCH;
6064 }
6065 
6066 static void __zone_set_pageset_high_and_batch(struct zone *zone, unsigned long high_min,
6067 					      unsigned long high_max, unsigned long batch)
6068 {
6069 	struct per_cpu_pages *pcp;
6070 	int cpu;
6071 
6072 	for_each_possible_cpu(cpu) {
6073 		pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
6074 		pageset_update(pcp, high_min, high_max, batch);
6075 	}
6076 }
6077 
6078 /*
6079  * Calculate and set new high and batch values for all per-cpu pagesets of a
6080  * zone based on the zone's size.
6081  */
6082 static void zone_set_pageset_high_and_batch(struct zone *zone, int cpu_online)
6083 {
6084 	int new_high_min, new_high_max, new_batch;
6085 
6086 	new_batch = zone_batchsize(zone);
6087 	if (percpu_pagelist_high_fraction) {
6088 		new_high_min = zone_highsize(zone, new_batch, cpu_online,
6089 					     percpu_pagelist_high_fraction);
6090 		/*
6091 		 * PCP high is tuned manually, disable auto-tuning via
6092 		 * setting high_min and high_max to the manual value.
6093 		 */
6094 		new_high_max = new_high_min;
6095 	} else {
6096 		new_high_min = zone_highsize(zone, new_batch, cpu_online, 0);
6097 		new_high_max = zone_highsize(zone, new_batch, cpu_online,
6098 					     MIN_PERCPU_PAGELIST_HIGH_FRACTION);
6099 	}
6100 
6101 	if (zone->pageset_high_min == new_high_min &&
6102 	    zone->pageset_high_max == new_high_max &&
6103 	    zone->pageset_batch == new_batch)
6104 		return;
6105 
6106 	zone->pageset_high_min = new_high_min;
6107 	zone->pageset_high_max = new_high_max;
6108 	zone->pageset_batch = new_batch;
6109 
6110 	__zone_set_pageset_high_and_batch(zone, new_high_min, new_high_max,
6111 					  new_batch);
6112 }
6113 
6114 void __meminit setup_zone_pageset(struct zone *zone)
6115 {
6116 	int cpu;
6117 
6118 	/* Size may be 0 on !SMP && !NUMA */
6119 	if (sizeof(struct per_cpu_zonestat) > 0)
6120 		zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat);
6121 
6122 	zone->per_cpu_pageset = alloc_percpu(struct per_cpu_pages);
6123 	for_each_possible_cpu(cpu) {
6124 		struct per_cpu_pages *pcp;
6125 		struct per_cpu_zonestat *pzstats;
6126 
6127 		pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
6128 		pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
6129 		per_cpu_pages_init(pcp, pzstats);
6130 	}
6131 
6132 	zone_set_pageset_high_and_batch(zone, 0);
6133 }
6134 
6135 /*
6136  * The zone indicated has a new number of managed_pages; batch sizes and percpu
6137  * page high values need to be recalculated.
6138  */
6139 static void zone_pcp_update(struct zone *zone, int cpu_online)
6140 {
6141 	mutex_lock(&pcp_batch_high_lock);
6142 	zone_set_pageset_high_and_batch(zone, cpu_online);
6143 	mutex_unlock(&pcp_batch_high_lock);
6144 }
6145 
6146 static void zone_pcp_update_cacheinfo(struct zone *zone, unsigned int cpu)
6147 {
6148 	struct per_cpu_pages *pcp;
6149 	struct cpu_cacheinfo *cci;
6150 	unsigned long UP_flags;
6151 
6152 	pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
6153 	cci = get_cpu_cacheinfo(cpu);
6154 	/*
6155 	 * If data cache slice of CPU is large enough, "pcp->batch"
6156 	 * pages can be preserved in PCP before draining PCP for
6157 	 * consecutive high-order pages freeing without allocation.
6158 	 * This can reduce zone lock contention without hurting
6159 	 * cache-hot pages sharing.
6160 	 */
6161 	pcp_spin_lock_maybe_irqsave(pcp, UP_flags);
6162 	if ((cci->per_cpu_data_slice_size >> PAGE_SHIFT) > 3 * pcp->batch)
6163 		pcp->flags |= PCPF_FREE_HIGH_BATCH;
6164 	else
6165 		pcp->flags &= ~PCPF_FREE_HIGH_BATCH;
6166 	pcp_spin_unlock_maybe_irqrestore(pcp, UP_flags);
6167 }
6168 
6169 void setup_pcp_cacheinfo(unsigned int cpu)
6170 {
6171 	struct zone *zone;
6172 
6173 	for_each_populated_zone(zone)
6174 		zone_pcp_update_cacheinfo(zone, cpu);
6175 }
6176 
6177 /*
6178  * Allocate per cpu pagesets and initialize them.
6179  * Before this call only boot pagesets were available.
6180  */
6181 void __init setup_per_cpu_pageset(void)
6182 {
6183 	struct pglist_data *pgdat;
6184 	struct zone *zone;
6185 	int __maybe_unused cpu;
6186 
6187 	for_each_populated_zone(zone)
6188 		setup_zone_pageset(zone);
6189 
6190 #ifdef CONFIG_NUMA
6191 	/*
6192 	 * Unpopulated zones continue using the boot pagesets.
6193 	 * The numa stats for these pagesets need to be reset.
6194 	 * Otherwise, they will end up skewing the stats of
6195 	 * the nodes these zones are associated with.
6196 	 */
6197 	for_each_possible_cpu(cpu) {
6198 		struct per_cpu_zonestat *pzstats = &per_cpu(boot_zonestats, cpu);
6199 		memset(pzstats->vm_numa_event, 0,
6200 		       sizeof(pzstats->vm_numa_event));
6201 	}
6202 #endif
6203 
6204 	for_each_online_pgdat(pgdat)
6205 		pgdat->per_cpu_nodestats =
6206 			alloc_percpu(struct per_cpu_nodestat);
6207 }
6208 
6209 __meminit void zone_pcp_init(struct zone *zone)
6210 {
6211 	/*
6212 	 * per cpu subsystem is not up at this point. The following code
6213 	 * relies on the ability of the linker to provide the
6214 	 * offset of a (static) per cpu variable into the per cpu area.
6215 	 */
6216 	zone->per_cpu_pageset = &boot_pageset;
6217 	zone->per_cpu_zonestats = &boot_zonestats;
6218 	zone->pageset_high_min = BOOT_PAGESET_HIGH;
6219 	zone->pageset_high_max = BOOT_PAGESET_HIGH;
6220 	zone->pageset_batch = BOOT_PAGESET_BATCH;
6221 
6222 	if (populated_zone(zone))
6223 		pr_debug("  %s zone: %lu pages, LIFO batch:%u\n", zone->name,
6224 			 zone->present_pages, zone_batchsize(zone));
6225 }
6226 
6227 static void setup_per_zone_lowmem_reserve(void);
6228 
6229 void adjust_managed_page_count(struct page *page, long count)
6230 {
6231 	atomic_long_add(count, &page_zone(page)->managed_pages);
6232 	totalram_pages_add(count);
6233 	setup_per_zone_lowmem_reserve();
6234 }
6235 EXPORT_SYMBOL(adjust_managed_page_count);
6236 
6237 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
6238 {
6239 	void *pos;
6240 	unsigned long pages = 0;
6241 
6242 	start = (void *)PAGE_ALIGN((unsigned long)start);
6243 	end = (void *)((unsigned long)end & PAGE_MASK);
6244 	for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
6245 		struct page *page = virt_to_page(pos);
6246 		void *direct_map_addr;
6247 
6248 		/*
6249 		 * 'direct_map_addr' might be different from 'pos'
6250 		 * because some architectures' virt_to_page()
6251 		 * work with aliases.  Getting the direct map
6252 		 * address ensures that we get a _writeable_
6253 		 * alias for the memset().
6254 		 */
6255 		direct_map_addr = page_address(page);
6256 		/*
6257 		 * Perform a kasan-unchecked memset() since this memory
6258 		 * has not been initialized.
6259 		 */
6260 		direct_map_addr = kasan_reset_tag(direct_map_addr);
6261 		if ((unsigned int)poison <= 0xFF)
6262 			memset(direct_map_addr, poison, PAGE_SIZE);
6263 
6264 		free_reserved_page(page);
6265 	}
6266 
6267 	if (pages && s)
6268 		pr_info("Freeing %s memory: %ldK\n", s, K(pages));
6269 
6270 	return pages;
6271 }
6272 
6273 void free_reserved_page(struct page *page)
6274 {
6275 	clear_page_tag_ref(page);
6276 	ClearPageReserved(page);
6277 	init_page_count(page);
6278 	__free_page(page);
6279 	adjust_managed_page_count(page, 1);
6280 }
6281 EXPORT_SYMBOL(free_reserved_page);
6282 
6283 static int page_alloc_cpu_dead(unsigned int cpu)
6284 {
6285 	struct zone *zone;
6286 
6287 	lru_add_drain_cpu(cpu);
6288 	mlock_drain_remote(cpu);
6289 	drain_pages(cpu);
6290 
6291 	/*
6292 	 * Spill the event counters of the dead processor
6293 	 * into the current processors event counters.
6294 	 * This artificially elevates the count of the current
6295 	 * processor.
6296 	 */
6297 	vm_events_fold_cpu(cpu);
6298 
6299 	/*
6300 	 * Zero the differential counters of the dead processor
6301 	 * so that the vm statistics are consistent.
6302 	 *
6303 	 * This is only okay since the processor is dead and cannot
6304 	 * race with what we are doing.
6305 	 */
6306 	cpu_vm_stats_fold(cpu);
6307 
6308 	for_each_populated_zone(zone)
6309 		zone_pcp_update(zone, 0);
6310 
6311 	return 0;
6312 }
6313 
6314 static int page_alloc_cpu_online(unsigned int cpu)
6315 {
6316 	struct zone *zone;
6317 
6318 	for_each_populated_zone(zone)
6319 		zone_pcp_update(zone, 1);
6320 	return 0;
6321 }
6322 
6323 void __init page_alloc_init_cpuhp(void)
6324 {
6325 	int ret;
6326 
6327 	ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC,
6328 					"mm/page_alloc:pcp",
6329 					page_alloc_cpu_online,
6330 					page_alloc_cpu_dead);
6331 	WARN_ON(ret < 0);
6332 }
6333 
6334 /*
6335  * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
6336  *	or min_free_kbytes changes.
6337  */
6338 static void calculate_totalreserve_pages(void)
6339 {
6340 	struct pglist_data *pgdat;
6341 	unsigned long reserve_pages = 0;
6342 	enum zone_type i, j;
6343 
6344 	for_each_online_pgdat(pgdat) {
6345 
6346 		pgdat->totalreserve_pages = 0;
6347 
6348 		for (i = 0; i < MAX_NR_ZONES; i++) {
6349 			struct zone *zone = pgdat->node_zones + i;
6350 			long max = 0;
6351 			unsigned long managed_pages = zone_managed_pages(zone);
6352 
6353 			/*
6354 			 * lowmem_reserve[j] is monotonically non-decreasing
6355 			 * in j for a given zone (see
6356 			 * setup_per_zone_lowmem_reserve()). The maximum
6357 			 * valid reserve lives at the highest index with a
6358 			 * non-zero value, so scan backwards and stop at the
6359 			 * first hit.
6360 			 */
6361 			for (j = MAX_NR_ZONES - 1; j > i; j--) {
6362 				if (!zone->lowmem_reserve[j])
6363 					continue;
6364 
6365 				max = zone->lowmem_reserve[j];
6366 				break;
6367 			}
6368 			/* we treat the high watermark as reserved pages. */
6369 			max += high_wmark_pages(zone);
6370 
6371 			max = min_t(unsigned long, max, managed_pages);
6372 
6373 			pgdat->totalreserve_pages += max;
6374 
6375 			reserve_pages += max;
6376 		}
6377 	}
6378 	totalreserve_pages = reserve_pages;
6379 	trace_mm_calculate_totalreserve_pages(totalreserve_pages);
6380 }
6381 
6382 /*
6383  * setup_per_zone_lowmem_reserve - called whenever
6384  *	sysctl_lowmem_reserve_ratio changes.  Ensures that each zone
6385  *	has a correct pages reserved value, so an adequate number of
6386  *	pages are left in the zone after a successful __alloc_pages().
6387  */
6388 static void setup_per_zone_lowmem_reserve(void)
6389 {
6390 	struct pglist_data *pgdat;
6391 	enum zone_type i, j;
6392 	/*
6393 	 * For a given zone node_zones[i], lowmem_reserve[j] (j > i)
6394 	 * represents how many pages in zone i must effectively be kept
6395 	 * in reserve when deciding whether an allocation class that is
6396 	 * allowed to allocate from zones up to j may fall back into
6397 	 * zone i.
6398 	 *
6399 	 * As j increases, the allocation class can use a strictly larger
6400 	 * set of fallback zones and therefore must not be allowed to
6401 	 * deplete low zones more aggressively than a less flexible one.
6402 	 * As a result, lowmem_reserve[j] is required to be monotonically
6403 	 * non-decreasing in j for each zone i. Callers such as
6404 	 * calculate_totalreserve_pages() rely on this monotonicity when
6405 	 * selecting the maximum reserve entry.
6406 	 */
6407 	for_each_online_pgdat(pgdat) {
6408 		for (i = 0; i < MAX_NR_ZONES - 1; i++) {
6409 			struct zone *zone = &pgdat->node_zones[i];
6410 			int ratio = sysctl_lowmem_reserve_ratio[i];
6411 			bool clear = !ratio || !zone_managed_pages(zone);
6412 			unsigned long managed_pages = 0;
6413 
6414 			for (j = i + 1; j < MAX_NR_ZONES; j++) {
6415 				struct zone *upper_zone = &pgdat->node_zones[j];
6416 
6417 				managed_pages += zone_managed_pages(upper_zone);
6418 
6419 				if (clear)
6420 					zone->lowmem_reserve[j] = 0;
6421 				else
6422 					zone->lowmem_reserve[j] = managed_pages / ratio;
6423 				trace_mm_setup_per_zone_lowmem_reserve(zone, upper_zone,
6424 								       zone->lowmem_reserve[j]);
6425 			}
6426 		}
6427 	}
6428 
6429 	/* update totalreserve_pages */
6430 	calculate_totalreserve_pages();
6431 }
6432 
6433 static void __setup_per_zone_wmarks(void)
6434 {
6435 	unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
6436 	unsigned long lowmem_pages = 0;
6437 	struct zone *zone;
6438 	unsigned long flags;
6439 
6440 	/* Calculate total number of !ZONE_HIGHMEM and !ZONE_MOVABLE pages */
6441 	for_each_zone(zone) {
6442 		if (!is_highmem(zone) && zone_idx(zone) != ZONE_MOVABLE)
6443 			lowmem_pages += zone_managed_pages(zone);
6444 	}
6445 
6446 	for_each_zone(zone) {
6447 		u64 tmp;
6448 
6449 		spin_lock_irqsave(&zone->lock, flags);
6450 		tmp = (u64)pages_min * zone_managed_pages(zone);
6451 		tmp = div64_ul(tmp, lowmem_pages);
6452 		if (is_highmem(zone) || zone_idx(zone) == ZONE_MOVABLE) {
6453 			/*
6454 			 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
6455 			 * need highmem and movable zones pages, so cap pages_min
6456 			 * to a small  value here.
6457 			 *
6458 			 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
6459 			 * deltas control async page reclaim, and so should
6460 			 * not be capped for highmem and movable zones.
6461 			 */
6462 			unsigned long min_pages;
6463 
6464 			min_pages = zone_managed_pages(zone) / 1024;
6465 			min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
6466 			zone->_watermark[WMARK_MIN] = min_pages;
6467 		} else {
6468 			/*
6469 			 * If it's a lowmem zone, reserve a number of pages
6470 			 * proportionate to the zone's size.
6471 			 */
6472 			zone->_watermark[WMARK_MIN] = tmp;
6473 		}
6474 
6475 		/*
6476 		 * Set the kswapd watermarks distance according to the
6477 		 * scale factor in proportion to available memory, but
6478 		 * ensure a minimum size on small systems.
6479 		 */
6480 		tmp = max_t(u64, tmp >> 2,
6481 			    mult_frac(zone_managed_pages(zone),
6482 				      watermark_scale_factor, 10000));
6483 
6484 		zone->watermark_boost = 0;
6485 		zone->_watermark[WMARK_LOW]  = min_wmark_pages(zone) + tmp;
6486 		zone->_watermark[WMARK_HIGH] = low_wmark_pages(zone) + tmp;
6487 		zone->_watermark[WMARK_PROMO] = high_wmark_pages(zone) + tmp;
6488 		trace_mm_setup_per_zone_wmarks(zone);
6489 
6490 		spin_unlock_irqrestore(&zone->lock, flags);
6491 	}
6492 
6493 	/* update totalreserve_pages */
6494 	calculate_totalreserve_pages();
6495 }
6496 
6497 /**
6498  * setup_per_zone_wmarks - called when min_free_kbytes changes
6499  * or when memory is hot-{added|removed}
6500  *
6501  * Ensures that the watermark[min,low,high] values for each zone are set
6502  * correctly with respect to min_free_kbytes.
6503  */
6504 void setup_per_zone_wmarks(void)
6505 {
6506 	struct zone *zone;
6507 	static DEFINE_SPINLOCK(lock);
6508 
6509 	spin_lock(&lock);
6510 	__setup_per_zone_wmarks();
6511 	spin_unlock(&lock);
6512 
6513 	/*
6514 	 * The watermark size have changed so update the pcpu batch
6515 	 * and high limits or the limits may be inappropriate.
6516 	 */
6517 	for_each_zone(zone)
6518 		zone_pcp_update(zone, 0);
6519 }
6520 
6521 /*
6522  * Initialise min_free_kbytes.
6523  *
6524  * For small machines we want it small (128k min).  For large machines
6525  * we want it large (256MB max).  But it is not linear, because network
6526  * bandwidth does not increase linearly with machine size.  We use
6527  *
6528  *	min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
6529  *	min_free_kbytes = sqrt(lowmem_kbytes * 16)
6530  *
6531  * which yields
6532  *
6533  * 16MB:	512k
6534  * 32MB:	724k
6535  * 64MB:	1024k
6536  * 128MB:	1448k
6537  * 256MB:	2048k
6538  * 512MB:	2896k
6539  * 1024MB:	4096k
6540  * 2048MB:	5792k
6541  * 4096MB:	8192k
6542  * 8192MB:	11584k
6543  * 16384MB:	16384k
6544  */
6545 void calculate_min_free_kbytes(void)
6546 {
6547 	unsigned long lowmem_kbytes;
6548 	int new_min_free_kbytes;
6549 
6550 	lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
6551 	new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
6552 
6553 	if (new_min_free_kbytes > user_min_free_kbytes)
6554 		min_free_kbytes = clamp(new_min_free_kbytes, 128, 262144);
6555 	else
6556 		pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
6557 				new_min_free_kbytes, user_min_free_kbytes);
6558 
6559 }
6560 
6561 int __meminit init_per_zone_wmark_min(void)
6562 {
6563 	calculate_min_free_kbytes();
6564 	setup_per_zone_wmarks();
6565 	refresh_zone_stat_thresholds();
6566 	setup_per_zone_lowmem_reserve();
6567 
6568 #ifdef CONFIG_NUMA
6569 	setup_min_unmapped_ratio();
6570 	setup_min_slab_ratio();
6571 #endif
6572 
6573 	khugepaged_min_free_kbytes_update();
6574 
6575 	return 0;
6576 }
6577 postcore_initcall(init_per_zone_wmark_min)
6578 
6579 /*
6580  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
6581  *	that we can call two helper functions whenever min_free_kbytes
6582  *	changes.
6583  */
6584 static int min_free_kbytes_sysctl_handler(const struct ctl_table *table, int write,
6585 		void *buffer, size_t *length, loff_t *ppos)
6586 {
6587 	int rc;
6588 
6589 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6590 	if (rc)
6591 		return rc;
6592 
6593 	if (write) {
6594 		user_min_free_kbytes = min_free_kbytes;
6595 		setup_per_zone_wmarks();
6596 	}
6597 	return 0;
6598 }
6599 
6600 static int watermark_scale_factor_sysctl_handler(const struct ctl_table *table, int write,
6601 		void *buffer, size_t *length, loff_t *ppos)
6602 {
6603 	int rc;
6604 
6605 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6606 	if (rc)
6607 		return rc;
6608 
6609 	if (write)
6610 		setup_per_zone_wmarks();
6611 
6612 	return 0;
6613 }
6614 
6615 #ifdef CONFIG_NUMA
6616 static void setup_min_unmapped_ratio(void)
6617 {
6618 	pg_data_t *pgdat;
6619 	struct zone *zone;
6620 
6621 	for_each_online_pgdat(pgdat)
6622 		pgdat->min_unmapped_pages = 0;
6623 
6624 	for_each_zone(zone)
6625 		zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
6626 						         sysctl_min_unmapped_ratio) / 100;
6627 }
6628 
6629 
6630 static int sysctl_min_unmapped_ratio_sysctl_handler(const struct ctl_table *table, int write,
6631 		void *buffer, size_t *length, loff_t *ppos)
6632 {
6633 	int rc;
6634 
6635 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6636 	if (rc)
6637 		return rc;
6638 
6639 	setup_min_unmapped_ratio();
6640 
6641 	return 0;
6642 }
6643 
6644 static void setup_min_slab_ratio(void)
6645 {
6646 	pg_data_t *pgdat;
6647 	struct zone *zone;
6648 
6649 	for_each_online_pgdat(pgdat)
6650 		pgdat->min_slab_pages = 0;
6651 
6652 	for_each_zone(zone)
6653 		zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
6654 						     sysctl_min_slab_ratio) / 100;
6655 }
6656 
6657 static int sysctl_min_slab_ratio_sysctl_handler(const struct ctl_table *table, int write,
6658 		void *buffer, size_t *length, loff_t *ppos)
6659 {
6660 	int rc;
6661 
6662 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6663 	if (rc)
6664 		return rc;
6665 
6666 	setup_min_slab_ratio();
6667 
6668 	return 0;
6669 }
6670 #endif
6671 
6672 /*
6673  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
6674  *	proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
6675  *	whenever sysctl_lowmem_reserve_ratio changes.
6676  *
6677  * The reserve ratio obviously has absolutely no relation with the
6678  * minimum watermarks. The lowmem reserve ratio can only make sense
6679  * if in function of the boot time zone sizes.
6680  */
6681 static int lowmem_reserve_ratio_sysctl_handler(const struct ctl_table *table,
6682 		int write, void *buffer, size_t *length, loff_t *ppos)
6683 {
6684 	int i;
6685 
6686 	proc_dointvec_minmax(table, write, buffer, length, ppos);
6687 
6688 	for (i = 0; i < MAX_NR_ZONES; i++) {
6689 		if (sysctl_lowmem_reserve_ratio[i] < 1)
6690 			sysctl_lowmem_reserve_ratio[i] = 0;
6691 	}
6692 
6693 	setup_per_zone_lowmem_reserve();
6694 	return 0;
6695 }
6696 
6697 /*
6698  * percpu_pagelist_high_fraction - changes the pcp->high for each zone on each
6699  * cpu. It is the fraction of total pages in each zone that a hot per cpu
6700  * pagelist can have before it gets flushed back to buddy allocator.
6701  */
6702 static int percpu_pagelist_high_fraction_sysctl_handler(const struct ctl_table *table,
6703 		int write, void *buffer, size_t *length, loff_t *ppos)
6704 {
6705 	struct zone *zone;
6706 	int old_percpu_pagelist_high_fraction;
6707 	int ret;
6708 
6709 	/*
6710 	 * Avoid using pcp_batch_high_lock for reads as the value is read
6711 	 * atomically and a race with offlining is harmless.
6712 	 */
6713 
6714 	if (!write)
6715 		return proc_dointvec_minmax(table, write, buffer, length, ppos);
6716 
6717 	mutex_lock(&pcp_batch_high_lock);
6718 	old_percpu_pagelist_high_fraction = percpu_pagelist_high_fraction;
6719 
6720 	ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
6721 	if (ret < 0)
6722 		goto out;
6723 
6724 	/* Sanity checking to avoid pcp imbalance */
6725 	if (percpu_pagelist_high_fraction &&
6726 	    percpu_pagelist_high_fraction < MIN_PERCPU_PAGELIST_HIGH_FRACTION) {
6727 		percpu_pagelist_high_fraction = old_percpu_pagelist_high_fraction;
6728 		ret = -EINVAL;
6729 		goto out;
6730 	}
6731 
6732 	/* No change? */
6733 	if (percpu_pagelist_high_fraction == old_percpu_pagelist_high_fraction)
6734 		goto out;
6735 
6736 	for_each_populated_zone(zone)
6737 		zone_set_pageset_high_and_batch(zone, 0);
6738 out:
6739 	mutex_unlock(&pcp_batch_high_lock);
6740 	return ret;
6741 }
6742 
6743 static const struct ctl_table page_alloc_sysctl_table[] = {
6744 	{
6745 		.procname	= "min_free_kbytes",
6746 		.data		= &min_free_kbytes,
6747 		.maxlen		= sizeof(min_free_kbytes),
6748 		.mode		= 0644,
6749 		.proc_handler	= min_free_kbytes_sysctl_handler,
6750 		.extra1		= SYSCTL_ZERO,
6751 	},
6752 	{
6753 		.procname	= "watermark_boost_factor",
6754 		.data		= &watermark_boost_factor,
6755 		.maxlen		= sizeof(watermark_boost_factor),
6756 		.mode		= 0644,
6757 		.proc_handler	= proc_dointvec_minmax,
6758 		.extra1		= SYSCTL_ZERO,
6759 	},
6760 	{
6761 		.procname	= "watermark_scale_factor",
6762 		.data		= &watermark_scale_factor,
6763 		.maxlen		= sizeof(watermark_scale_factor),
6764 		.mode		= 0644,
6765 		.proc_handler	= watermark_scale_factor_sysctl_handler,
6766 		.extra1		= SYSCTL_ONE,
6767 		.extra2		= SYSCTL_THREE_THOUSAND,
6768 	},
6769 	{
6770 		.procname	= "defrag_mode",
6771 		.data		= &defrag_mode,
6772 		.maxlen		= sizeof(defrag_mode),
6773 		.mode		= 0644,
6774 		.proc_handler	= proc_dointvec_minmax,
6775 		.extra1		= SYSCTL_ZERO,
6776 		.extra2		= SYSCTL_ONE,
6777 	},
6778 	{
6779 		.procname	= "percpu_pagelist_high_fraction",
6780 		.data		= &percpu_pagelist_high_fraction,
6781 		.maxlen		= sizeof(percpu_pagelist_high_fraction),
6782 		.mode		= 0644,
6783 		.proc_handler	= percpu_pagelist_high_fraction_sysctl_handler,
6784 		.extra1		= SYSCTL_ZERO,
6785 	},
6786 	{
6787 		.procname	= "lowmem_reserve_ratio",
6788 		.data		= &sysctl_lowmem_reserve_ratio,
6789 		.maxlen		= sizeof(sysctl_lowmem_reserve_ratio),
6790 		.mode		= 0644,
6791 		.proc_handler	= lowmem_reserve_ratio_sysctl_handler,
6792 	},
6793 #ifdef CONFIG_NUMA
6794 	{
6795 		.procname	= "numa_zonelist_order",
6796 		.data		= &numa_zonelist_order,
6797 		.maxlen		= NUMA_ZONELIST_ORDER_LEN,
6798 		.mode		= 0644,
6799 		.proc_handler	= numa_zonelist_order_handler,
6800 	},
6801 	{
6802 		.procname	= "min_unmapped_ratio",
6803 		.data		= &sysctl_min_unmapped_ratio,
6804 		.maxlen		= sizeof(sysctl_min_unmapped_ratio),
6805 		.mode		= 0644,
6806 		.proc_handler	= sysctl_min_unmapped_ratio_sysctl_handler,
6807 		.extra1		= SYSCTL_ZERO,
6808 		.extra2		= SYSCTL_ONE_HUNDRED,
6809 	},
6810 	{
6811 		.procname	= "min_slab_ratio",
6812 		.data		= &sysctl_min_slab_ratio,
6813 		.maxlen		= sizeof(sysctl_min_slab_ratio),
6814 		.mode		= 0644,
6815 		.proc_handler	= sysctl_min_slab_ratio_sysctl_handler,
6816 		.extra1		= SYSCTL_ZERO,
6817 		.extra2		= SYSCTL_ONE_HUNDRED,
6818 	},
6819 #endif
6820 };
6821 
6822 void __init page_alloc_sysctl_init(void)
6823 {
6824 	register_sysctl_init("vm", page_alloc_sysctl_table);
6825 }
6826 
6827 #ifdef CONFIG_CONTIG_ALLOC
6828 /* Usage: See admin-guide/dynamic-debug-howto.rst */
6829 static void alloc_contig_dump_pages(struct list_head *page_list)
6830 {
6831 	DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure");
6832 
6833 	if (DYNAMIC_DEBUG_BRANCH(descriptor)) {
6834 		struct page *page;
6835 
6836 		dump_stack();
6837 		list_for_each_entry(page, page_list, lru)
6838 			dump_page(page, "migration failure");
6839 	}
6840 }
6841 
6842 /* [start, end) must belong to a single zone. */
6843 static int __alloc_contig_migrate_range(struct compact_control *cc,
6844 					unsigned long start, unsigned long end)
6845 {
6846 	/* This function is based on compact_zone() from compaction.c. */
6847 	unsigned int nr_reclaimed;
6848 	unsigned long pfn = start;
6849 	unsigned int tries = 0;
6850 	int ret = 0;
6851 	struct migration_target_control mtc = {
6852 		.nid = zone_to_nid(cc->zone),
6853 		.gfp_mask = cc->gfp_mask,
6854 		.reason = MR_CONTIG_RANGE,
6855 	};
6856 
6857 	lru_cache_disable();
6858 
6859 	while (pfn < end || !list_empty(&cc->migratepages)) {
6860 		if (fatal_signal_pending(current)) {
6861 			ret = -EINTR;
6862 			break;
6863 		}
6864 
6865 		if (list_empty(&cc->migratepages)) {
6866 			cc->nr_migratepages = 0;
6867 			ret = isolate_migratepages_range(cc, pfn, end);
6868 			if (ret && ret != -EAGAIN)
6869 				break;
6870 			pfn = cc->migrate_pfn;
6871 			tries = 0;
6872 		} else if (++tries == 5) {
6873 			ret = -EBUSY;
6874 			break;
6875 		}
6876 
6877 		nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6878 							&cc->migratepages);
6879 		cc->nr_migratepages -= nr_reclaimed;
6880 
6881 		ret = migrate_pages(&cc->migratepages, alloc_migration_target,
6882 			NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE, NULL);
6883 
6884 		/*
6885 		 * On -ENOMEM, migrate_pages() bails out right away. It is pointless
6886 		 * to retry again over this error, so do the same here.
6887 		 */
6888 		if (ret == -ENOMEM)
6889 			break;
6890 	}
6891 
6892 	lru_cache_enable();
6893 	if (ret < 0) {
6894 		if (!(cc->gfp_mask & __GFP_NOWARN) && ret == -EBUSY)
6895 			alloc_contig_dump_pages(&cc->migratepages);
6896 		putback_movable_pages(&cc->migratepages);
6897 	}
6898 
6899 	return (ret < 0) ? ret : 0;
6900 }
6901 
6902 static void split_free_frozen_pages(struct list_head *list, gfp_t gfp_mask)
6903 {
6904 	int order;
6905 
6906 	for (order = 0; order < NR_PAGE_ORDERS; order++) {
6907 		struct page *page, *next;
6908 		int nr_pages = 1 << order;
6909 
6910 		list_for_each_entry_safe(page, next, &list[order], lru) {
6911 			int i;
6912 
6913 			post_alloc_hook(page, order, gfp_mask);
6914 			if (!order)
6915 				continue;
6916 
6917 			__split_page(page, order);
6918 
6919 			/* Add all subpages to the order-0 head, in sequence. */
6920 			list_del(&page->lru);
6921 			for (i = 0; i < nr_pages; i++)
6922 				list_add_tail(&page[i].lru, &list[0]);
6923 		}
6924 	}
6925 }
6926 
6927 static int __alloc_contig_verify_gfp_mask(gfp_t gfp_mask, gfp_t *gfp_cc_mask)
6928 {
6929 	const gfp_t reclaim_mask = __GFP_IO | __GFP_FS | __GFP_RECLAIM;
6930 	const gfp_t action_mask = __GFP_COMP | __GFP_RETRY_MAYFAIL | __GFP_NOWARN |
6931 				  __GFP_ZERO | __GFP_ZEROTAGS | __GFP_SKIP_ZERO;
6932 	const gfp_t cc_action_mask = __GFP_RETRY_MAYFAIL | __GFP_NOWARN;
6933 
6934 	/*
6935 	 * We are given the range to allocate; node, mobility and placement
6936 	 * hints are irrelevant at this point. We'll simply ignore them.
6937 	 */
6938 	gfp_mask &= ~(GFP_ZONEMASK | __GFP_RECLAIMABLE | __GFP_WRITE |
6939 		      __GFP_HARDWALL | __GFP_THISNODE | __GFP_MOVABLE);
6940 
6941 	/*
6942 	 * We only support most reclaim flags (but not NOFAIL/NORETRY), and
6943 	 * selected action flags.
6944 	 */
6945 	if (gfp_mask & ~(reclaim_mask | action_mask))
6946 		return -EINVAL;
6947 
6948 	/*
6949 	 * Flags to control page compaction/migration/reclaim, to free up our
6950 	 * page range. Migratable pages are movable, __GFP_MOVABLE is implied
6951 	 * for them.
6952 	 *
6953 	 * Traditionally we always had __GFP_RETRY_MAYFAIL set, keep doing that
6954 	 * to not degrade callers.
6955 	 */
6956 	*gfp_cc_mask = (gfp_mask & (reclaim_mask | cc_action_mask)) |
6957 			__GFP_MOVABLE | __GFP_RETRY_MAYFAIL;
6958 	return 0;
6959 }
6960 
6961 static void __free_contig_frozen_range(unsigned long pfn, unsigned long nr_pages)
6962 {
6963 	for (; nr_pages--; pfn++)
6964 		free_frozen_pages(pfn_to_page(pfn), 0);
6965 }
6966 
6967 /**
6968  * alloc_contig_frozen_range() -- tries to allocate given range of frozen pages
6969  * @start:	start PFN to allocate
6970  * @end:	one-past-the-last PFN to allocate
6971  * @alloc_flags:	allocation information
6972  * @gfp_mask:	GFP mask. Node/zone/placement hints are ignored; only some
6973  *		action and reclaim modifiers are supported. Reclaim modifiers
6974  *		control allocation behavior during compaction/migration/reclaim.
6975  *
6976  * The PFN range does not have to be pageblock aligned. The PFN range must
6977  * belong to a single zone.
6978  *
6979  * The first thing this routine does is attempt to MIGRATE_ISOLATE all
6980  * pageblocks in the range.  Once isolated, the pageblocks should not
6981  * be modified by others.
6982  *
6983  * All frozen pages which PFN is in [start, end) are allocated for the
6984  * caller, and they could be freed with free_contig_frozen_range(),
6985  * free_frozen_pages() also could be used to free compound frozen pages
6986  * directly.
6987  *
6988  * Return: zero on success or negative error code.
6989  */
6990 int alloc_contig_frozen_range_noprof(unsigned long start, unsigned long end,
6991 		acr_flags_t alloc_flags, gfp_t gfp_mask)
6992 {
6993 	const unsigned int order = ilog2(end - start);
6994 	unsigned long outer_start, outer_end;
6995 	int ret = 0;
6996 
6997 	struct compact_control cc = {
6998 		.nr_migratepages = 0,
6999 		.order = -1,
7000 		.zone = page_zone(pfn_to_page(start)),
7001 		.mode = MIGRATE_SYNC,
7002 		.ignore_skip_hint = true,
7003 		.no_set_skip_hint = true,
7004 		.alloc_contig = true,
7005 	};
7006 	INIT_LIST_HEAD(&cc.migratepages);
7007 	enum pb_isolate_mode mode = (alloc_flags & ACR_FLAGS_CMA) ?
7008 					    PB_ISOLATE_MODE_CMA_ALLOC :
7009 					    PB_ISOLATE_MODE_OTHER;
7010 
7011 	/*
7012 	 * In contrast to the buddy, we allow for orders here that exceed
7013 	 * MAX_PAGE_ORDER, so we must manually make sure that we are not
7014 	 * exceeding the maximum folio order.
7015 	 */
7016 	if (WARN_ON_ONCE((gfp_mask & __GFP_COMP) && order > MAX_FOLIO_ORDER))
7017 		return -EINVAL;
7018 
7019 	gfp_mask = current_gfp_context(gfp_mask);
7020 	if (__alloc_contig_verify_gfp_mask(gfp_mask, (gfp_t *)&cc.gfp_mask))
7021 		return -EINVAL;
7022 
7023 	/*
7024 	 * What we do here is we mark all pageblocks in range as
7025 	 * MIGRATE_ISOLATE.  Because pageblock and max order pages may
7026 	 * have different sizes, and due to the way page allocator
7027 	 * work, start_isolate_page_range() has special handlings for this.
7028 	 *
7029 	 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
7030 	 * migrate the pages from an unaligned range (ie. pages that
7031 	 * we are interested in). This will put all the pages in
7032 	 * range back to page allocator as MIGRATE_ISOLATE.
7033 	 *
7034 	 * When this is done, we take the pages in range from page
7035 	 * allocator removing them from the buddy system.  This way
7036 	 * page allocator will never consider using them.
7037 	 *
7038 	 * This lets us mark the pageblocks back as
7039 	 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
7040 	 * aligned range but not in the unaligned, original range are
7041 	 * put back to page allocator so that buddy can use them.
7042 	 */
7043 
7044 	ret = start_isolate_page_range(start, end, mode);
7045 	if (ret)
7046 		goto done;
7047 
7048 	drain_all_pages(cc.zone);
7049 
7050 	/*
7051 	 * In case of -EBUSY, we'd like to know which page causes problem.
7052 	 * So, just fall through. test_pages_isolated() has a tracepoint
7053 	 * which will report the busy page.
7054 	 *
7055 	 * It is possible that busy pages could become available before
7056 	 * the call to test_pages_isolated, and the range will actually be
7057 	 * allocated.  So, if we fall through be sure to clear ret so that
7058 	 * -EBUSY is not accidentally used or returned to caller.
7059 	 */
7060 	ret = __alloc_contig_migrate_range(&cc, start, end);
7061 	if (ret && ret != -EBUSY)
7062 		goto done;
7063 
7064 	/*
7065 	 * When in-use hugetlb pages are migrated, they may simply be released
7066 	 * back into the free hugepage pool instead of being returned to the
7067 	 * buddy system.  After the migration of in-use huge pages is completed,
7068 	 * we will invoke replace_free_hugepage_folios() to ensure that these
7069 	 * hugepages are properly released to the buddy system.
7070 	 */
7071 	ret = replace_free_hugepage_folios(start, end);
7072 	if (ret)
7073 		goto done;
7074 
7075 	/*
7076 	 * Pages from [start, end) are within a pageblock_nr_pages
7077 	 * aligned blocks that are marked as MIGRATE_ISOLATE.  What's
7078 	 * more, all pages in [start, end) are free in page allocator.
7079 	 * What we are going to do is to allocate all pages from
7080 	 * [start, end) (that is remove them from page allocator).
7081 	 *
7082 	 * The only problem is that pages at the beginning and at the
7083 	 * end of interesting range may be not aligned with pages that
7084 	 * page allocator holds, ie. they can be part of higher order
7085 	 * pages.  Because of this, we reserve the bigger range and
7086 	 * once this is done free the pages we are not interested in.
7087 	 *
7088 	 * We don't have to hold zone->lock here because the pages are
7089 	 * isolated thus they won't get removed from buddy.
7090 	 */
7091 	outer_start = find_large_buddy(start);
7092 
7093 	/* Make sure the range is really isolated. */
7094 	if (test_pages_isolated(outer_start, end, mode)) {
7095 		ret = -EBUSY;
7096 		goto done;
7097 	}
7098 
7099 	/* Grab isolated pages from freelists. */
7100 	outer_end = isolate_freepages_range(&cc, outer_start, end);
7101 	if (!outer_end) {
7102 		ret = -EBUSY;
7103 		goto done;
7104 	}
7105 
7106 	if (!(gfp_mask & __GFP_COMP)) {
7107 		split_free_frozen_pages(cc.freepages, gfp_mask);
7108 
7109 		/* Free head and tail (if any) */
7110 		if (start != outer_start)
7111 			__free_contig_frozen_range(outer_start, start - outer_start);
7112 		if (end != outer_end)
7113 			__free_contig_frozen_range(end, outer_end - end);
7114 	} else if (start == outer_start && end == outer_end && is_power_of_2(end - start)) {
7115 		struct page *head = pfn_to_page(start);
7116 
7117 		check_new_pages(head, order);
7118 		prep_new_page(head, order, gfp_mask, 0);
7119 	} else {
7120 		ret = -EINVAL;
7121 		WARN(true, "PFN range: requested [%lu, %lu), allocated [%lu, %lu)\n",
7122 		     start, end, outer_start, outer_end);
7123 	}
7124 done:
7125 	undo_isolate_page_range(start, end);
7126 	return ret;
7127 }
7128 EXPORT_SYMBOL(alloc_contig_frozen_range_noprof);
7129 
7130 /**
7131  * alloc_contig_range() -- tries to allocate given range of pages
7132  * @start:	start PFN to allocate
7133  * @end:	one-past-the-last PFN to allocate
7134  * @alloc_flags:	allocation information
7135  * @gfp_mask:	GFP mask.
7136  *
7137  * This routine is a wrapper around alloc_contig_frozen_range(), it can't
7138  * be used to allocate compound pages, the refcount of each allocated page
7139  * will be set to one.
7140  *
7141  * All pages which PFN is in [start, end) are allocated for the caller,
7142  * and should be freed with free_contig_range() or by manually calling
7143  * __free_page() on each allocated page.
7144  *
7145  * Return: zero on success or negative error code.
7146  */
7147 int alloc_contig_range_noprof(unsigned long start, unsigned long end,
7148 			      acr_flags_t alloc_flags, gfp_t gfp_mask)
7149 {
7150 	int ret;
7151 
7152 	if (WARN_ON(gfp_mask & __GFP_COMP))
7153 		return -EINVAL;
7154 
7155 	ret = alloc_contig_frozen_range_noprof(start, end, alloc_flags, gfp_mask);
7156 	if (!ret)
7157 		set_pages_refcounted(pfn_to_page(start), end - start);
7158 
7159 	return ret;
7160 }
7161 EXPORT_SYMBOL(alloc_contig_range_noprof);
7162 
7163 static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn,
7164 				   unsigned long nr_pages, bool skip_hugetlb,
7165 				   bool *skipped_hugetlb)
7166 {
7167 	unsigned long end_pfn = start_pfn + nr_pages;
7168 	struct page *page;
7169 
7170 	while (start_pfn < end_pfn) {
7171 		unsigned long step = 1;
7172 
7173 		page = pfn_to_online_page(start_pfn);
7174 		if (!page)
7175 			return false;
7176 
7177 		if (page_zone(page) != z)
7178 			return false;
7179 
7180 		if (page_is_unmovable(z, page, PB_ISOLATE_MODE_OTHER, &step))
7181 			return false;
7182 
7183 		/*
7184 		 * Only consider ranges containing hugepages if those pages are
7185 		 * smaller than the requested contiguous region.  e.g.:
7186 		 *     Move 2MB pages to free up a 1GB range.
7187 		 *     Don't move 1GB pages to free up a 2MB range.
7188 		 *
7189 		 * This makes contiguous allocation more reliable if multiple
7190 		 * hugepage sizes are used without causing needless movement.
7191 		 */
7192 		if (PageHuge(page)) {
7193 			unsigned int order;
7194 
7195 			if (skip_hugetlb) {
7196 				*skipped_hugetlb = true;
7197 				return false;
7198 			}
7199 
7200 			page = compound_head(page);
7201 			order = compound_order(page);
7202 			if ((order >= MAX_FOLIO_ORDER) ||
7203 			    (nr_pages <= (1 << order)))
7204 				return false;
7205 		}
7206 
7207 		start_pfn += step;
7208 	}
7209 	return true;
7210 }
7211 
7212 static bool zone_spans_last_pfn(const struct zone *zone,
7213 				unsigned long start_pfn, unsigned long nr_pages)
7214 {
7215 	unsigned long last_pfn = start_pfn + nr_pages - 1;
7216 
7217 	return zone_spans_pfn(zone, last_pfn);
7218 }
7219 
7220 /**
7221  * alloc_contig_frozen_pages() -- tries to find and allocate contiguous range of frozen pages
7222  * @nr_pages:	Number of contiguous pages to allocate
7223  * @gfp_mask:	GFP mask. Node/zone/placement hints limit the search; only some
7224  *		action and reclaim modifiers are supported. Reclaim modifiers
7225  *		control allocation behavior during compaction/migration/reclaim.
7226  * @nid:	Target node
7227  * @nodemask:	Mask for other possible nodes
7228  *
7229  * This routine is a wrapper around alloc_contig_frozen_range(). It scans over
7230  * zones on an applicable zonelist to find a contiguous pfn range which can then
7231  * be tried for allocation with alloc_contig_frozen_range(). This routine is
7232  * intended for allocation requests which can not be fulfilled with the buddy
7233  * allocator.
7234  *
7235  * The allocated memory is always aligned to a page boundary. If nr_pages is a
7236  * power of two, then allocated range is also guaranteed to be aligned to same
7237  * nr_pages (e.g. 1GB request would be aligned to 1GB).
7238  *
7239  * Allocated frozen pages need be freed with free_contig_frozen_range(),
7240  * or by manually calling free_frozen_pages() on each allocated frozen
7241  * non-compound page, for compound frozen pages could be freed with
7242  * free_frozen_pages() directly.
7243  *
7244  * Return: pointer to contiguous frozen pages on success, or NULL if not successful.
7245  */
7246 struct page *alloc_contig_frozen_pages_noprof(unsigned long nr_pages,
7247 		gfp_t gfp_mask, int nid, nodemask_t *nodemask)
7248 {
7249 	unsigned long ret, pfn, flags;
7250 	struct zonelist *zonelist;
7251 	struct zone *zone;
7252 	struct zoneref *z;
7253 	bool skip_hugetlb = true;
7254 	bool skipped_hugetlb = false;
7255 
7256 retry:
7257 	zonelist = node_zonelist(nid, gfp_mask);
7258 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
7259 					gfp_zone(gfp_mask), nodemask) {
7260 		spin_lock_irqsave(&zone->lock, flags);
7261 
7262 		pfn = ALIGN(zone->zone_start_pfn, nr_pages);
7263 		while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
7264 			if (pfn_range_valid_contig(zone, pfn, nr_pages,
7265 						   skip_hugetlb,
7266 						   &skipped_hugetlb)) {
7267 				/*
7268 				 * We release the zone lock here because
7269 				 * alloc_contig_frozen_range() will also lock
7270 				 * the zone at some point. If there's an
7271 				 * allocation spinning on this lock, it may
7272 				 * win the race and cause allocation to fail.
7273 				 */
7274 				spin_unlock_irqrestore(&zone->lock, flags);
7275 				ret = alloc_contig_frozen_range_noprof(pfn,
7276 							pfn + nr_pages,
7277 							ACR_FLAGS_NONE,
7278 							gfp_mask);
7279 				if (!ret)
7280 					return pfn_to_page(pfn);
7281 				spin_lock_irqsave(&zone->lock, flags);
7282 			}
7283 			pfn += nr_pages;
7284 		}
7285 		spin_unlock_irqrestore(&zone->lock, flags);
7286 	}
7287 	/*
7288 	 * If we failed, retry the search, but treat regions with HugeTLB pages
7289 	 * as valid targets.  This retains fast-allocations on first pass
7290 	 * without trying to migrate HugeTLB pages (which may fail). On the
7291 	 * second pass, we will try moving HugeTLB pages when those pages are
7292 	 * smaller than the requested contiguous region size.
7293 	 */
7294 	if (skip_hugetlb && skipped_hugetlb) {
7295 		skip_hugetlb = false;
7296 		goto retry;
7297 	}
7298 	return NULL;
7299 }
7300 EXPORT_SYMBOL(alloc_contig_frozen_pages_noprof);
7301 
7302 /**
7303  * alloc_contig_pages() -- tries to find and allocate contiguous range of pages
7304  * @nr_pages:	Number of contiguous pages to allocate
7305  * @gfp_mask:	GFP mask.
7306  * @nid:	Target node
7307  * @nodemask:	Mask for other possible nodes
7308  *
7309  * This routine is a wrapper around alloc_contig_frozen_pages(), it can't
7310  * be used to allocate compound pages, the refcount of each allocated page
7311  * will be set to one.
7312  *
7313  * Allocated pages can be freed with free_contig_range() or by manually
7314  * calling __free_page() on each allocated page.
7315  *
7316  * Return: pointer to contiguous pages on success, or NULL if not successful.
7317  */
7318 struct page *alloc_contig_pages_noprof(unsigned long nr_pages, gfp_t gfp_mask,
7319 		int nid, nodemask_t *nodemask)
7320 {
7321 	struct page *page;
7322 
7323 	if (WARN_ON(gfp_mask & __GFP_COMP))
7324 		return NULL;
7325 
7326 	page = alloc_contig_frozen_pages_noprof(nr_pages, gfp_mask, nid,
7327 						nodemask);
7328 	if (page)
7329 		set_pages_refcounted(page, nr_pages);
7330 
7331 	return page;
7332 }
7333 EXPORT_SYMBOL(alloc_contig_pages_noprof);
7334 
7335 /**
7336  * free_contig_frozen_range() -- free the contiguous range of frozen pages
7337  * @pfn:	start PFN to free
7338  * @nr_pages:	Number of contiguous frozen pages to free
7339  *
7340  * This can be used to free the allocated compound/non-compound frozen pages.
7341  */
7342 void free_contig_frozen_range(unsigned long pfn, unsigned long nr_pages)
7343 {
7344 	struct page *first_page = pfn_to_page(pfn);
7345 	const unsigned int order = ilog2(nr_pages);
7346 
7347 	if (WARN_ON_ONCE(first_page != compound_head(first_page)))
7348 		return;
7349 
7350 	if (PageHead(first_page)) {
7351 		WARN_ON_ONCE(order != compound_order(first_page));
7352 		free_frozen_pages(first_page, order);
7353 		return;
7354 	}
7355 
7356 	__free_contig_frozen_range(pfn, nr_pages);
7357 }
7358 EXPORT_SYMBOL(free_contig_frozen_range);
7359 
7360 /**
7361  * free_contig_range() -- free the contiguous range of pages
7362  * @pfn:	start PFN to free
7363  * @nr_pages:	Number of contiguous pages to free
7364  *
7365  * This can be only used to free the allocated non-compound pages.
7366  */
7367 void free_contig_range(unsigned long pfn, unsigned long nr_pages)
7368 {
7369 	if (WARN_ON_ONCE(PageHead(pfn_to_page(pfn))))
7370 		return;
7371 
7372 	for (; nr_pages--; pfn++)
7373 		__free_page(pfn_to_page(pfn));
7374 }
7375 EXPORT_SYMBOL(free_contig_range);
7376 #endif /* CONFIG_CONTIG_ALLOC */
7377 
7378 /*
7379  * Effectively disable pcplists for the zone by setting the high limit to 0
7380  * and draining all cpus. A concurrent page freeing on another CPU that's about
7381  * to put the page on pcplist will either finish before the drain and the page
7382  * will be drained, or observe the new high limit and skip the pcplist.
7383  *
7384  * Must be paired with a call to zone_pcp_enable().
7385  */
7386 void zone_pcp_disable(struct zone *zone)
7387 {
7388 	mutex_lock(&pcp_batch_high_lock);
7389 	__zone_set_pageset_high_and_batch(zone, 0, 0, 1);
7390 	__drain_all_pages(zone, true);
7391 }
7392 
7393 void zone_pcp_enable(struct zone *zone)
7394 {
7395 	__zone_set_pageset_high_and_batch(zone, zone->pageset_high_min,
7396 		zone->pageset_high_max, zone->pageset_batch);
7397 	mutex_unlock(&pcp_batch_high_lock);
7398 }
7399 
7400 void zone_pcp_reset(struct zone *zone)
7401 {
7402 	int cpu;
7403 	struct per_cpu_zonestat *pzstats;
7404 
7405 	if (zone->per_cpu_pageset != &boot_pageset) {
7406 		for_each_online_cpu(cpu) {
7407 			pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
7408 			drain_zonestat(zone, pzstats);
7409 		}
7410 		free_percpu(zone->per_cpu_pageset);
7411 		zone->per_cpu_pageset = &boot_pageset;
7412 		if (zone->per_cpu_zonestats != &boot_zonestats) {
7413 			free_percpu(zone->per_cpu_zonestats);
7414 			zone->per_cpu_zonestats = &boot_zonestats;
7415 		}
7416 	}
7417 }
7418 
7419 #ifdef CONFIG_MEMORY_HOTREMOVE
7420 /*
7421  * All pages in the range must be in a single zone, must not contain holes,
7422  * must span full sections, and must be isolated before calling this function.
7423  *
7424  * Returns the number of managed (non-PageOffline()) pages in the range: the
7425  * number of pages for which memory offlining code must adjust managed page
7426  * counters using adjust_managed_page_count().
7427  */
7428 unsigned long __offline_isolated_pages(unsigned long start_pfn,
7429 		unsigned long end_pfn)
7430 {
7431 	unsigned long already_offline = 0, flags;
7432 	unsigned long pfn = start_pfn;
7433 	struct page *page;
7434 	struct zone *zone;
7435 	unsigned int order;
7436 
7437 	offline_mem_sections(pfn, end_pfn);
7438 	zone = page_zone(pfn_to_page(pfn));
7439 	spin_lock_irqsave(&zone->lock, flags);
7440 	while (pfn < end_pfn) {
7441 		page = pfn_to_page(pfn);
7442 		/*
7443 		 * The HWPoisoned page may be not in buddy system, and
7444 		 * page_count() is not 0.
7445 		 */
7446 		if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
7447 			pfn++;
7448 			continue;
7449 		}
7450 		/*
7451 		 * At this point all remaining PageOffline() pages have a
7452 		 * reference count of 0 and can simply be skipped.
7453 		 */
7454 		if (PageOffline(page)) {
7455 			BUG_ON(page_count(page));
7456 			BUG_ON(PageBuddy(page));
7457 			already_offline++;
7458 			pfn++;
7459 			continue;
7460 		}
7461 
7462 		BUG_ON(page_count(page));
7463 		BUG_ON(!PageBuddy(page));
7464 		VM_WARN_ON(get_pageblock_migratetype(page) != MIGRATE_ISOLATE);
7465 		order = buddy_order(page);
7466 		del_page_from_free_list(page, zone, order, MIGRATE_ISOLATE);
7467 		pfn += (1 << order);
7468 	}
7469 	spin_unlock_irqrestore(&zone->lock, flags);
7470 
7471 	return end_pfn - start_pfn - already_offline;
7472 }
7473 #endif
7474 
7475 /*
7476  * This function returns a stable result only if called under zone lock.
7477  */
7478 bool is_free_buddy_page(const struct page *page)
7479 {
7480 	unsigned long pfn = page_to_pfn(page);
7481 	unsigned int order;
7482 
7483 	for (order = 0; order < NR_PAGE_ORDERS; order++) {
7484 		const struct page *head = page - (pfn & ((1 << order) - 1));
7485 
7486 		if (PageBuddy(head) &&
7487 		    buddy_order_unsafe(head) >= order)
7488 			break;
7489 	}
7490 
7491 	return order <= MAX_PAGE_ORDER;
7492 }
7493 EXPORT_SYMBOL(is_free_buddy_page);
7494 
7495 #ifdef CONFIG_MEMORY_FAILURE
7496 static inline void add_to_free_list(struct page *page, struct zone *zone,
7497 				    unsigned int order, int migratetype,
7498 				    bool tail)
7499 {
7500 	__add_to_free_list(page, zone, order, migratetype, tail);
7501 	account_freepages(zone, 1 << order, migratetype);
7502 }
7503 
7504 /*
7505  * Break down a higher-order page in sub-pages, and keep our target out of
7506  * buddy allocator.
7507  */
7508 static void break_down_buddy_pages(struct zone *zone, struct page *page,
7509 				   struct page *target, int low, int high,
7510 				   int migratetype)
7511 {
7512 	unsigned long size = 1 << high;
7513 	struct page *current_buddy;
7514 
7515 	while (high > low) {
7516 		high--;
7517 		size >>= 1;
7518 
7519 		if (target >= &page[size]) {
7520 			current_buddy = page;
7521 			page = page + size;
7522 		} else {
7523 			current_buddy = page + size;
7524 		}
7525 
7526 		if (set_page_guard(zone, current_buddy, high))
7527 			continue;
7528 
7529 		add_to_free_list(current_buddy, zone, high, migratetype, false);
7530 		set_buddy_order(current_buddy, high);
7531 	}
7532 }
7533 
7534 /*
7535  * Take a page that will be marked as poisoned off the buddy allocator.
7536  */
7537 bool take_page_off_buddy(struct page *page)
7538 {
7539 	struct zone *zone = page_zone(page);
7540 	unsigned long pfn = page_to_pfn(page);
7541 	unsigned long flags;
7542 	unsigned int order;
7543 	bool ret = false;
7544 
7545 	spin_lock_irqsave(&zone->lock, flags);
7546 	for (order = 0; order < NR_PAGE_ORDERS; order++) {
7547 		struct page *page_head = page - (pfn & ((1 << order) - 1));
7548 		int page_order = buddy_order(page_head);
7549 
7550 		if (PageBuddy(page_head) && page_order >= order) {
7551 			unsigned long pfn_head = page_to_pfn(page_head);
7552 			int migratetype = get_pfnblock_migratetype(page_head,
7553 								   pfn_head);
7554 
7555 			del_page_from_free_list(page_head, zone, page_order,
7556 						migratetype);
7557 			break_down_buddy_pages(zone, page_head, page, 0,
7558 						page_order, migratetype);
7559 			SetPageHWPoisonTakenOff(page);
7560 			ret = true;
7561 			break;
7562 		}
7563 		if (page_count(page_head) > 0)
7564 			break;
7565 	}
7566 	spin_unlock_irqrestore(&zone->lock, flags);
7567 	return ret;
7568 }
7569 
7570 /*
7571  * Cancel takeoff done by take_page_off_buddy().
7572  */
7573 bool put_page_back_buddy(struct page *page)
7574 {
7575 	struct zone *zone = page_zone(page);
7576 	unsigned long flags;
7577 	bool ret = false;
7578 
7579 	spin_lock_irqsave(&zone->lock, flags);
7580 	if (put_page_testzero(page)) {
7581 		unsigned long pfn = page_to_pfn(page);
7582 		int migratetype = get_pfnblock_migratetype(page, pfn);
7583 
7584 		ClearPageHWPoisonTakenOff(page);
7585 		__free_one_page(page, pfn, zone, 0, migratetype, FPI_NONE);
7586 		if (TestClearPageHWPoison(page)) {
7587 			ret = true;
7588 		}
7589 	}
7590 	spin_unlock_irqrestore(&zone->lock, flags);
7591 
7592 	return ret;
7593 }
7594 #endif
7595 
7596 bool has_managed_zone(enum zone_type zone)
7597 {
7598 	struct pglist_data *pgdat;
7599 
7600 	for_each_online_pgdat(pgdat) {
7601 		if (managed_zone(&pgdat->node_zones[zone]))
7602 			return true;
7603 	}
7604 	return false;
7605 }
7606 
7607 #ifdef CONFIG_UNACCEPTED_MEMORY
7608 
7609 static bool lazy_accept = true;
7610 
7611 static int __init accept_memory_parse(char *p)
7612 {
7613 	if (!strcmp(p, "lazy")) {
7614 		lazy_accept = true;
7615 		return 0;
7616 	} else if (!strcmp(p, "eager")) {
7617 		lazy_accept = false;
7618 		return 0;
7619 	} else {
7620 		return -EINVAL;
7621 	}
7622 }
7623 early_param("accept_memory", accept_memory_parse);
7624 
7625 static bool page_contains_unaccepted(struct page *page, unsigned int order)
7626 {
7627 	phys_addr_t start = page_to_phys(page);
7628 
7629 	return range_contains_unaccepted_memory(start, PAGE_SIZE << order);
7630 }
7631 
7632 static void __accept_page(struct zone *zone, unsigned long *flags,
7633 			  struct page *page)
7634 {
7635 	list_del(&page->lru);
7636 	account_freepages(zone, -MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE);
7637 	__mod_zone_page_state(zone, NR_UNACCEPTED, -MAX_ORDER_NR_PAGES);
7638 	__ClearPageUnaccepted(page);
7639 	spin_unlock_irqrestore(&zone->lock, *flags);
7640 
7641 	accept_memory(page_to_phys(page), PAGE_SIZE << MAX_PAGE_ORDER);
7642 
7643 	__free_pages_ok(page, MAX_PAGE_ORDER, FPI_TO_TAIL);
7644 }
7645 
7646 void accept_page(struct page *page)
7647 {
7648 	struct zone *zone = page_zone(page);
7649 	unsigned long flags;
7650 
7651 	spin_lock_irqsave(&zone->lock, flags);
7652 	if (!PageUnaccepted(page)) {
7653 		spin_unlock_irqrestore(&zone->lock, flags);
7654 		return;
7655 	}
7656 
7657 	/* Unlocks zone->lock */
7658 	__accept_page(zone, &flags, page);
7659 }
7660 
7661 static bool try_to_accept_memory_one(struct zone *zone)
7662 {
7663 	unsigned long flags;
7664 	struct page *page;
7665 
7666 	spin_lock_irqsave(&zone->lock, flags);
7667 	page = list_first_entry_or_null(&zone->unaccepted_pages,
7668 					struct page, lru);
7669 	if (!page) {
7670 		spin_unlock_irqrestore(&zone->lock, flags);
7671 		return false;
7672 	}
7673 
7674 	/* Unlocks zone->lock */
7675 	__accept_page(zone, &flags, page);
7676 
7677 	return true;
7678 }
7679 
7680 static bool cond_accept_memory(struct zone *zone, unsigned int order,
7681 			       int alloc_flags)
7682 {
7683 	long to_accept, wmark;
7684 	bool ret = false;
7685 
7686 	if (list_empty(&zone->unaccepted_pages))
7687 		return false;
7688 
7689 	/* Bailout, since try_to_accept_memory_one() needs to take a lock */
7690 	if (alloc_flags & ALLOC_TRYLOCK)
7691 		return false;
7692 
7693 	wmark = promo_wmark_pages(zone);
7694 
7695 	/*
7696 	 * Watermarks have not been initialized yet.
7697 	 *
7698 	 * Accepting one MAX_ORDER page to ensure progress.
7699 	 */
7700 	if (!wmark)
7701 		return try_to_accept_memory_one(zone);
7702 
7703 	/* How much to accept to get to promo watermark? */
7704 	to_accept = wmark -
7705 		    (zone_page_state(zone, NR_FREE_PAGES) -
7706 		    __zone_watermark_unusable_free(zone, order, 0) -
7707 		    zone_page_state(zone, NR_UNACCEPTED));
7708 
7709 	while (to_accept > 0) {
7710 		if (!try_to_accept_memory_one(zone))
7711 			break;
7712 		ret = true;
7713 		to_accept -= MAX_ORDER_NR_PAGES;
7714 	}
7715 
7716 	return ret;
7717 }
7718 
7719 static bool __free_unaccepted(struct page *page)
7720 {
7721 	struct zone *zone = page_zone(page);
7722 	unsigned long flags;
7723 
7724 	if (!lazy_accept)
7725 		return false;
7726 
7727 	spin_lock_irqsave(&zone->lock, flags);
7728 	list_add_tail(&page->lru, &zone->unaccepted_pages);
7729 	account_freepages(zone, MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE);
7730 	__mod_zone_page_state(zone, NR_UNACCEPTED, MAX_ORDER_NR_PAGES);
7731 	__SetPageUnaccepted(page);
7732 	spin_unlock_irqrestore(&zone->lock, flags);
7733 
7734 	return true;
7735 }
7736 
7737 #else
7738 
7739 static bool page_contains_unaccepted(struct page *page, unsigned int order)
7740 {
7741 	return false;
7742 }
7743 
7744 static bool cond_accept_memory(struct zone *zone, unsigned int order,
7745 			       int alloc_flags)
7746 {
7747 	return false;
7748 }
7749 
7750 static bool __free_unaccepted(struct page *page)
7751 {
7752 	BUILD_BUG();
7753 	return false;
7754 }
7755 
7756 #endif /* CONFIG_UNACCEPTED_MEMORY */
7757 
7758 struct page *alloc_frozen_pages_nolock_noprof(gfp_t gfp_flags, int nid, unsigned int order)
7759 {
7760 	/*
7761 	 * Do not specify __GFP_DIRECT_RECLAIM, since direct claim is not allowed.
7762 	 * Do not specify __GFP_KSWAPD_RECLAIM either, since wake up of kswapd
7763 	 * is not safe in arbitrary context.
7764 	 *
7765 	 * These two are the conditions for gfpflags_allow_spinning() being true.
7766 	 *
7767 	 * Specify __GFP_NOWARN since failing alloc_pages_nolock() is not a reason
7768 	 * to warn. Also warn would trigger printk() which is unsafe from
7769 	 * various contexts. We cannot use printk_deferred_enter() to mitigate,
7770 	 * since the running context is unknown.
7771 	 *
7772 	 * Specify __GFP_ZERO to make sure that call to kmsan_alloc_page() below
7773 	 * is safe in any context. Also zeroing the page is mandatory for
7774 	 * BPF use cases.
7775 	 *
7776 	 * Though __GFP_NOMEMALLOC is not checked in the code path below,
7777 	 * specify it here to highlight that alloc_pages_nolock()
7778 	 * doesn't want to deplete reserves.
7779 	 */
7780 	gfp_t alloc_gfp = __GFP_NOWARN | __GFP_ZERO | __GFP_NOMEMALLOC | __GFP_COMP
7781 			| gfp_flags;
7782 	unsigned int alloc_flags = ALLOC_TRYLOCK;
7783 	struct alloc_context ac = { };
7784 	struct page *page;
7785 
7786 	VM_WARN_ON_ONCE(gfp_flags & ~__GFP_ACCOUNT);
7787 	/*
7788 	 * In PREEMPT_RT spin_trylock() will call raw_spin_lock() which is
7789 	 * unsafe in NMI. If spin_trylock() is called from hard IRQ the current
7790 	 * task may be waiting for one rt_spin_lock, but rt_spin_trylock() will
7791 	 * mark the task as the owner of another rt_spin_lock which will
7792 	 * confuse PI logic, so return immediately if called from hard IRQ or
7793 	 * NMI.
7794 	 *
7795 	 * Note, irqs_disabled() case is ok. This function can be called
7796 	 * from raw_spin_lock_irqsave region.
7797 	 */
7798 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && (in_nmi() || in_hardirq()))
7799 		return NULL;
7800 	if (!pcp_allowed_order(order))
7801 		return NULL;
7802 
7803 	/* Bailout, since _deferred_grow_zone() needs to take a lock */
7804 	if (deferred_pages_enabled())
7805 		return NULL;
7806 
7807 	if (nid == NUMA_NO_NODE)
7808 		nid = numa_node_id();
7809 
7810 	prepare_alloc_pages(alloc_gfp, order, nid, NULL, &ac,
7811 			    &alloc_gfp, &alloc_flags);
7812 
7813 	/*
7814 	 * Best effort allocation from percpu free list.
7815 	 * If it's empty attempt to spin_trylock zone->lock.
7816 	 */
7817 	page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac);
7818 
7819 	/* Unlike regular alloc_pages() there is no __alloc_pages_slowpath(). */
7820 
7821 	if (memcg_kmem_online() && page && (gfp_flags & __GFP_ACCOUNT) &&
7822 	    unlikely(__memcg_kmem_charge_page(page, alloc_gfp, order) != 0)) {
7823 		__free_frozen_pages(page, order, FPI_TRYLOCK);
7824 		page = NULL;
7825 	}
7826 	trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype);
7827 	kmsan_alloc_page(page, order, alloc_gfp);
7828 	return page;
7829 }
7830 /**
7831  * alloc_pages_nolock - opportunistic reentrant allocation from any context
7832  * @gfp_flags: GFP flags. Only __GFP_ACCOUNT allowed.
7833  * @nid: node to allocate from
7834  * @order: allocation order size
7835  *
7836  * Allocates pages of a given order from the given node. This is safe to
7837  * call from any context (from atomic, NMI, and also reentrant
7838  * allocator -> tracepoint -> alloc_pages_nolock_noprof).
7839  * Allocation is best effort and to be expected to fail easily so nobody should
7840  * rely on the success. Failures are not reported via warn_alloc().
7841  * See always fail conditions below.
7842  *
7843  * Return: allocated page or NULL on failure. NULL does not mean EBUSY or EAGAIN.
7844  * It means ENOMEM. There is no reason to call it again and expect !NULL.
7845  */
7846 struct page *alloc_pages_nolock_noprof(gfp_t gfp_flags, int nid, unsigned int order)
7847 {
7848 	struct page *page;
7849 
7850 	page = alloc_frozen_pages_nolock_noprof(gfp_flags, nid, order);
7851 	if (page)
7852 		set_page_refcounted(page);
7853 	return page;
7854 }
7855 EXPORT_SYMBOL_GPL(alloc_pages_nolock_noprof);
7856