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