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