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