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