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