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