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