xref: /linux/mm/page_alloc.c (revision 037ada7a3181300218e4fd78bef6a741cfa7f808)
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 #ifdef CONFIG_NUMA
3474 int __read_mostly node_reclaim_distance = RECLAIM_DISTANCE;
3475 
3476 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3477 {
3478 	return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3479 				node_reclaim_distance;
3480 }
3481 #else	/* CONFIG_NUMA */
3482 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3483 {
3484 	return true;
3485 }
3486 #endif	/* CONFIG_NUMA */
3487 
3488 /*
3489  * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3490  * fragmentation is subtle. If the preferred zone was HIGHMEM then
3491  * premature use of a lower zone may cause lowmem pressure problems that
3492  * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3493  * probably too small. It only makes sense to spread allocations to avoid
3494  * fragmentation between the Normal and DMA32 zones.
3495  */
3496 static inline unsigned int
3497 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3498 {
3499 	unsigned int alloc_flags;
3500 
3501 	/*
3502 	 * __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
3503 	 * to save a branch.
3504 	 */
3505 	alloc_flags = (__force int) (gfp_mask & __GFP_KSWAPD_RECLAIM);
3506 
3507 	if (defrag_mode) {
3508 		alloc_flags |= ALLOC_NOFRAGMENT;
3509 		return alloc_flags;
3510 	}
3511 
3512 #ifdef CONFIG_ZONE_DMA32
3513 	if (!zone)
3514 		return alloc_flags;
3515 
3516 	if (zone_idx(zone) != ZONE_NORMAL)
3517 		return alloc_flags;
3518 
3519 	/*
3520 	 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3521 	 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3522 	 * on UMA that if Normal is populated then so is DMA32.
3523 	 */
3524 	BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3525 	if (nr_online_nodes > 1 && !populated_zone(--zone))
3526 		return alloc_flags;
3527 
3528 	alloc_flags |= ALLOC_NOFRAGMENT;
3529 #endif /* CONFIG_ZONE_DMA32 */
3530 	return alloc_flags;
3531 }
3532 
3533 /* Must be called after current_gfp_context() which can change gfp_mask */
3534 static inline unsigned int gfp_to_alloc_flags_cma(gfp_t gfp_mask,
3535 						  unsigned int alloc_flags)
3536 {
3537 #ifdef CONFIG_CMA
3538 	if (gfp_migratetype(gfp_mask) == MIGRATE_MOVABLE)
3539 		alloc_flags |= ALLOC_CMA;
3540 #endif
3541 	return alloc_flags;
3542 }
3543 
3544 /*
3545  * get_page_from_freelist goes through the zonelist trying to allocate
3546  * a page.
3547  */
3548 static struct page *
3549 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3550 						const struct alloc_context *ac)
3551 {
3552 	struct zoneref *z;
3553 	struct zone *zone;
3554 	struct pglist_data *last_pgdat = NULL;
3555 	bool last_pgdat_dirty_ok = false;
3556 	bool no_fallback;
3557 
3558 retry:
3559 	/*
3560 	 * Scan zonelist, looking for a zone with enough free.
3561 	 * See also cpuset_node_allowed() comment in kernel/cgroup/cpuset.c.
3562 	 */
3563 	no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3564 	z = ac->preferred_zoneref;
3565 	for_next_zone_zonelist_nodemask(zone, z, ac->highest_zoneidx,
3566 					ac->nodemask) {
3567 		struct page *page;
3568 		unsigned long mark;
3569 
3570 		if (cpusets_enabled() &&
3571 			(alloc_flags & ALLOC_CPUSET) &&
3572 			!__cpuset_zone_allowed(zone, gfp_mask))
3573 				continue;
3574 		/*
3575 		 * When allocating a page cache page for writing, we
3576 		 * want to get it from a node that is within its dirty
3577 		 * limit, such that no single node holds more than its
3578 		 * proportional share of globally allowed dirty pages.
3579 		 * The dirty limits take into account the node's
3580 		 * lowmem reserves and high watermark so that kswapd
3581 		 * should be able to balance it without having to
3582 		 * write pages from its LRU list.
3583 		 *
3584 		 * XXX: For now, allow allocations to potentially
3585 		 * exceed the per-node dirty limit in the slowpath
3586 		 * (spread_dirty_pages unset) before going into reclaim,
3587 		 * which is important when on a NUMA setup the allowed
3588 		 * nodes are together not big enough to reach the
3589 		 * global limit.  The proper fix for these situations
3590 		 * will require awareness of nodes in the
3591 		 * dirty-throttling and the flusher threads.
3592 		 */
3593 		if (ac->spread_dirty_pages) {
3594 			if (last_pgdat != zone->zone_pgdat) {
3595 				last_pgdat = zone->zone_pgdat;
3596 				last_pgdat_dirty_ok = node_dirty_ok(zone->zone_pgdat);
3597 			}
3598 
3599 			if (!last_pgdat_dirty_ok)
3600 				continue;
3601 		}
3602 
3603 		if (no_fallback && !defrag_mode && nr_online_nodes > 1 &&
3604 		    zone != zonelist_zone(ac->preferred_zoneref)) {
3605 			int local_nid;
3606 
3607 			/*
3608 			 * If moving to a remote node, retry but allow
3609 			 * fragmenting fallbacks. Locality is more important
3610 			 * than fragmentation avoidance.
3611 			 */
3612 			local_nid = zonelist_node_idx(ac->preferred_zoneref);
3613 			if (zone_to_nid(zone) != local_nid) {
3614 				alloc_flags &= ~ALLOC_NOFRAGMENT;
3615 				goto retry;
3616 			}
3617 		}
3618 
3619 		cond_accept_memory(zone, order);
3620 
3621 		/*
3622 		 * Detect whether the number of free pages is below high
3623 		 * watermark.  If so, we will decrease pcp->high and free
3624 		 * PCP pages in free path to reduce the possibility of
3625 		 * premature page reclaiming.  Detection is done here to
3626 		 * avoid to do that in hotter free path.
3627 		 */
3628 		if (test_bit(ZONE_BELOW_HIGH, &zone->flags))
3629 			goto check_alloc_wmark;
3630 
3631 		mark = high_wmark_pages(zone);
3632 		if (zone_watermark_fast(zone, order, mark,
3633 					ac->highest_zoneidx, alloc_flags,
3634 					gfp_mask))
3635 			goto try_this_zone;
3636 		else
3637 			set_bit(ZONE_BELOW_HIGH, &zone->flags);
3638 
3639 check_alloc_wmark:
3640 		mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
3641 		if (!zone_watermark_fast(zone, order, mark,
3642 				       ac->highest_zoneidx, alloc_flags,
3643 				       gfp_mask)) {
3644 			int ret;
3645 
3646 			if (cond_accept_memory(zone, order))
3647 				goto try_this_zone;
3648 
3649 			/*
3650 			 * Watermark failed for this zone, but see if we can
3651 			 * grow this zone if it contains deferred pages.
3652 			 */
3653 			if (deferred_pages_enabled()) {
3654 				if (_deferred_grow_zone(zone, order))
3655 					goto try_this_zone;
3656 			}
3657 			/* Checked here to keep the fast path fast */
3658 			BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3659 			if (alloc_flags & ALLOC_NO_WATERMARKS)
3660 				goto try_this_zone;
3661 
3662 			if (!node_reclaim_enabled() ||
3663 			    !zone_allows_reclaim(zonelist_zone(ac->preferred_zoneref), zone))
3664 				continue;
3665 
3666 			ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3667 			switch (ret) {
3668 			case NODE_RECLAIM_NOSCAN:
3669 				/* did not scan */
3670 				continue;
3671 			case NODE_RECLAIM_FULL:
3672 				/* scanned but unreclaimable */
3673 				continue;
3674 			default:
3675 				/* did we reclaim enough */
3676 				if (zone_watermark_ok(zone, order, mark,
3677 					ac->highest_zoneidx, alloc_flags))
3678 					goto try_this_zone;
3679 
3680 				continue;
3681 			}
3682 		}
3683 
3684 try_this_zone:
3685 		page = rmqueue(zonelist_zone(ac->preferred_zoneref), zone, order,
3686 				gfp_mask, alloc_flags, ac->migratetype);
3687 		if (page) {
3688 			prep_new_page(page, order, gfp_mask, alloc_flags);
3689 
3690 			/*
3691 			 * If this is a high-order atomic allocation then check
3692 			 * if the pageblock should be reserved for the future
3693 			 */
3694 			if (unlikely(alloc_flags & ALLOC_HIGHATOMIC))
3695 				reserve_highatomic_pageblock(page, order, zone);
3696 
3697 			return page;
3698 		} else {
3699 			if (cond_accept_memory(zone, order))
3700 				goto try_this_zone;
3701 
3702 			/* Try again if zone has deferred pages */
3703 			if (deferred_pages_enabled()) {
3704 				if (_deferred_grow_zone(zone, order))
3705 					goto try_this_zone;
3706 			}
3707 		}
3708 	}
3709 
3710 	/*
3711 	 * It's possible on a UMA machine to get through all zones that are
3712 	 * fragmented. If avoiding fragmentation, reset and try again.
3713 	 */
3714 	if (no_fallback && !defrag_mode) {
3715 		alloc_flags &= ~ALLOC_NOFRAGMENT;
3716 		goto retry;
3717 	}
3718 
3719 	return NULL;
3720 }
3721 
3722 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
3723 {
3724 	unsigned int filter = SHOW_MEM_FILTER_NODES;
3725 
3726 	/*
3727 	 * This documents exceptions given to allocations in certain
3728 	 * contexts that are allowed to allocate outside current's set
3729 	 * of allowed nodes.
3730 	 */
3731 	if (!(gfp_mask & __GFP_NOMEMALLOC))
3732 		if (tsk_is_oom_victim(current) ||
3733 		    (current->flags & (PF_MEMALLOC | PF_EXITING)))
3734 			filter &= ~SHOW_MEM_FILTER_NODES;
3735 	if (!in_task() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
3736 		filter &= ~SHOW_MEM_FILTER_NODES;
3737 
3738 	__show_mem(filter, nodemask, gfp_zone(gfp_mask));
3739 }
3740 
3741 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
3742 {
3743 	struct va_format vaf;
3744 	va_list args;
3745 	static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
3746 
3747 	if ((gfp_mask & __GFP_NOWARN) ||
3748 	     !__ratelimit(&nopage_rs) ||
3749 	     ((gfp_mask & __GFP_DMA) && !has_managed_dma()))
3750 		return;
3751 
3752 	va_start(args, fmt);
3753 	vaf.fmt = fmt;
3754 	vaf.va = &args;
3755 	pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
3756 			current->comm, &vaf, gfp_mask, &gfp_mask,
3757 			nodemask_pr_args(nodemask));
3758 	va_end(args);
3759 
3760 	cpuset_print_current_mems_allowed();
3761 	pr_cont("\n");
3762 	dump_stack();
3763 	warn_alloc_show_mem(gfp_mask, nodemask);
3764 }
3765 
3766 static inline struct page *
3767 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
3768 			      unsigned int alloc_flags,
3769 			      const struct alloc_context *ac)
3770 {
3771 	struct page *page;
3772 
3773 	page = get_page_from_freelist(gfp_mask, order,
3774 			alloc_flags|ALLOC_CPUSET, ac);
3775 	/*
3776 	 * fallback to ignore cpuset restriction if our nodes
3777 	 * are depleted
3778 	 */
3779 	if (!page)
3780 		page = get_page_from_freelist(gfp_mask, order,
3781 				alloc_flags, ac);
3782 	return page;
3783 }
3784 
3785 static inline struct page *
3786 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
3787 	const struct alloc_context *ac, unsigned long *did_some_progress)
3788 {
3789 	struct oom_control oc = {
3790 		.zonelist = ac->zonelist,
3791 		.nodemask = ac->nodemask,
3792 		.memcg = NULL,
3793 		.gfp_mask = gfp_mask,
3794 		.order = order,
3795 	};
3796 	struct page *page;
3797 
3798 	*did_some_progress = 0;
3799 
3800 	/*
3801 	 * Acquire the oom lock.  If that fails, somebody else is
3802 	 * making progress for us.
3803 	 */
3804 	if (!mutex_trylock(&oom_lock)) {
3805 		*did_some_progress = 1;
3806 		schedule_timeout_uninterruptible(1);
3807 		return NULL;
3808 	}
3809 
3810 	/*
3811 	 * Go through the zonelist yet one more time, keep very high watermark
3812 	 * here, this is only to catch a parallel oom killing, we must fail if
3813 	 * we're still under heavy pressure. But make sure that this reclaim
3814 	 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
3815 	 * allocation which will never fail due to oom_lock already held.
3816 	 */
3817 	page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
3818 				      ~__GFP_DIRECT_RECLAIM, order,
3819 				      ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
3820 	if (page)
3821 		goto out;
3822 
3823 	/* Coredumps can quickly deplete all memory reserves */
3824 	if (current->flags & PF_DUMPCORE)
3825 		goto out;
3826 	/* The OOM killer will not help higher order allocs */
3827 	if (order > PAGE_ALLOC_COSTLY_ORDER)
3828 		goto out;
3829 	/*
3830 	 * We have already exhausted all our reclaim opportunities without any
3831 	 * success so it is time to admit defeat. We will skip the OOM killer
3832 	 * because it is very likely that the caller has a more reasonable
3833 	 * fallback than shooting a random task.
3834 	 *
3835 	 * The OOM killer may not free memory on a specific node.
3836 	 */
3837 	if (gfp_mask & (__GFP_RETRY_MAYFAIL | __GFP_THISNODE))
3838 		goto out;
3839 	/* The OOM killer does not needlessly kill tasks for lowmem */
3840 	if (ac->highest_zoneidx < ZONE_NORMAL)
3841 		goto out;
3842 	if (pm_suspended_storage())
3843 		goto out;
3844 	/*
3845 	 * XXX: GFP_NOFS allocations should rather fail than rely on
3846 	 * other request to make a forward progress.
3847 	 * We are in an unfortunate situation where out_of_memory cannot
3848 	 * do much for this context but let's try it to at least get
3849 	 * access to memory reserved if the current task is killed (see
3850 	 * out_of_memory). Once filesystems are ready to handle allocation
3851 	 * failures more gracefully we should just bail out here.
3852 	 */
3853 
3854 	/* Exhausted what can be done so it's blame time */
3855 	if (out_of_memory(&oc) ||
3856 	    WARN_ON_ONCE_GFP(gfp_mask & __GFP_NOFAIL, gfp_mask)) {
3857 		*did_some_progress = 1;
3858 
3859 		/*
3860 		 * Help non-failing allocations by giving them access to memory
3861 		 * reserves
3862 		 */
3863 		if (gfp_mask & __GFP_NOFAIL)
3864 			page = __alloc_pages_cpuset_fallback(gfp_mask, order,
3865 					ALLOC_NO_WATERMARKS, ac);
3866 	}
3867 out:
3868 	mutex_unlock(&oom_lock);
3869 	return page;
3870 }
3871 
3872 /*
3873  * Maximum number of compaction retries with a progress before OOM
3874  * killer is consider as the only way to move forward.
3875  */
3876 #define MAX_COMPACT_RETRIES 16
3877 
3878 #ifdef CONFIG_COMPACTION
3879 /* Try memory compaction for high-order allocations before reclaim */
3880 static struct page *
3881 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
3882 		unsigned int alloc_flags, const struct alloc_context *ac,
3883 		enum compact_priority prio, enum compact_result *compact_result)
3884 {
3885 	struct page *page = NULL;
3886 	unsigned long pflags;
3887 	unsigned int noreclaim_flag;
3888 
3889 	if (!order)
3890 		return NULL;
3891 
3892 	psi_memstall_enter(&pflags);
3893 	delayacct_compact_start();
3894 	noreclaim_flag = memalloc_noreclaim_save();
3895 
3896 	*compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
3897 								prio, &page);
3898 
3899 	memalloc_noreclaim_restore(noreclaim_flag);
3900 	psi_memstall_leave(&pflags);
3901 	delayacct_compact_end();
3902 
3903 	if (*compact_result == COMPACT_SKIPPED)
3904 		return NULL;
3905 	/*
3906 	 * At least in one zone compaction wasn't deferred or skipped, so let's
3907 	 * count a compaction stall
3908 	 */
3909 	count_vm_event(COMPACTSTALL);
3910 
3911 	/* Prep a captured page if available */
3912 	if (page)
3913 		prep_new_page(page, order, gfp_mask, alloc_flags);
3914 
3915 	/* Try get a page from the freelist if available */
3916 	if (!page)
3917 		page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
3918 
3919 	if (page) {
3920 		struct zone *zone = page_zone(page);
3921 
3922 		zone->compact_blockskip_flush = false;
3923 		compaction_defer_reset(zone, order, true);
3924 		count_vm_event(COMPACTSUCCESS);
3925 		return page;
3926 	}
3927 
3928 	/*
3929 	 * It's bad if compaction run occurs and fails. The most likely reason
3930 	 * is that pages exist, but not enough to satisfy watermarks.
3931 	 */
3932 	count_vm_event(COMPACTFAIL);
3933 
3934 	cond_resched();
3935 
3936 	return NULL;
3937 }
3938 
3939 static inline bool
3940 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
3941 		     enum compact_result compact_result,
3942 		     enum compact_priority *compact_priority,
3943 		     int *compaction_retries)
3944 {
3945 	int max_retries = MAX_COMPACT_RETRIES;
3946 	int min_priority;
3947 	bool ret = false;
3948 	int retries = *compaction_retries;
3949 	enum compact_priority priority = *compact_priority;
3950 
3951 	if (!order)
3952 		return false;
3953 
3954 	if (fatal_signal_pending(current))
3955 		return false;
3956 
3957 	/*
3958 	 * Compaction was skipped due to a lack of free order-0
3959 	 * migration targets. Continue if reclaim can help.
3960 	 */
3961 	if (compact_result == COMPACT_SKIPPED) {
3962 		ret = compaction_zonelist_suitable(ac, order, alloc_flags);
3963 		goto out;
3964 	}
3965 
3966 	/*
3967 	 * Compaction managed to coalesce some page blocks, but the
3968 	 * allocation failed presumably due to a race. Retry some.
3969 	 */
3970 	if (compact_result == COMPACT_SUCCESS) {
3971 		/*
3972 		 * !costly requests are much more important than
3973 		 * __GFP_RETRY_MAYFAIL costly ones because they are de
3974 		 * facto nofail and invoke OOM killer to move on while
3975 		 * costly can fail and users are ready to cope with
3976 		 * that. 1/4 retries is rather arbitrary but we would
3977 		 * need much more detailed feedback from compaction to
3978 		 * make a better decision.
3979 		 */
3980 		if (order > PAGE_ALLOC_COSTLY_ORDER)
3981 			max_retries /= 4;
3982 
3983 		if (++(*compaction_retries) <= max_retries) {
3984 			ret = true;
3985 			goto out;
3986 		}
3987 	}
3988 
3989 	/*
3990 	 * Compaction failed. Retry with increasing priority.
3991 	 */
3992 	min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
3993 			MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
3994 
3995 	if (*compact_priority > min_priority) {
3996 		(*compact_priority)--;
3997 		*compaction_retries = 0;
3998 		ret = true;
3999 	}
4000 out:
4001 	trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
4002 	return ret;
4003 }
4004 #else
4005 static inline struct page *
4006 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4007 		unsigned int alloc_flags, const struct alloc_context *ac,
4008 		enum compact_priority prio, enum compact_result *compact_result)
4009 {
4010 	*compact_result = COMPACT_SKIPPED;
4011 	return NULL;
4012 }
4013 
4014 static inline bool
4015 should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
4016 		     enum compact_result compact_result,
4017 		     enum compact_priority *compact_priority,
4018 		     int *compaction_retries)
4019 {
4020 	struct zone *zone;
4021 	struct zoneref *z;
4022 
4023 	if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
4024 		return false;
4025 
4026 	/*
4027 	 * There are setups with compaction disabled which would prefer to loop
4028 	 * inside the allocator rather than hit the oom killer prematurely.
4029 	 * Let's give them a good hope and keep retrying while the order-0
4030 	 * watermarks are OK.
4031 	 */
4032 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4033 				ac->highest_zoneidx, ac->nodemask) {
4034 		if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
4035 					ac->highest_zoneidx, alloc_flags))
4036 			return true;
4037 	}
4038 	return false;
4039 }
4040 #endif /* CONFIG_COMPACTION */
4041 
4042 #ifdef CONFIG_LOCKDEP
4043 static struct lockdep_map __fs_reclaim_map =
4044 	STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
4045 
4046 static bool __need_reclaim(gfp_t gfp_mask)
4047 {
4048 	/* no reclaim without waiting on it */
4049 	if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
4050 		return false;
4051 
4052 	/* this guy won't enter reclaim */
4053 	if (current->flags & PF_MEMALLOC)
4054 		return false;
4055 
4056 	if (gfp_mask & __GFP_NOLOCKDEP)
4057 		return false;
4058 
4059 	return true;
4060 }
4061 
4062 void __fs_reclaim_acquire(unsigned long ip)
4063 {
4064 	lock_acquire_exclusive(&__fs_reclaim_map, 0, 0, NULL, ip);
4065 }
4066 
4067 void __fs_reclaim_release(unsigned long ip)
4068 {
4069 	lock_release(&__fs_reclaim_map, ip);
4070 }
4071 
4072 void fs_reclaim_acquire(gfp_t gfp_mask)
4073 {
4074 	gfp_mask = current_gfp_context(gfp_mask);
4075 
4076 	if (__need_reclaim(gfp_mask)) {
4077 		if (gfp_mask & __GFP_FS)
4078 			__fs_reclaim_acquire(_RET_IP_);
4079 
4080 #ifdef CONFIG_MMU_NOTIFIER
4081 		lock_map_acquire(&__mmu_notifier_invalidate_range_start_map);
4082 		lock_map_release(&__mmu_notifier_invalidate_range_start_map);
4083 #endif
4084 
4085 	}
4086 }
4087 EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
4088 
4089 void fs_reclaim_release(gfp_t gfp_mask)
4090 {
4091 	gfp_mask = current_gfp_context(gfp_mask);
4092 
4093 	if (__need_reclaim(gfp_mask)) {
4094 		if (gfp_mask & __GFP_FS)
4095 			__fs_reclaim_release(_RET_IP_);
4096 	}
4097 }
4098 EXPORT_SYMBOL_GPL(fs_reclaim_release);
4099 #endif
4100 
4101 /*
4102  * Zonelists may change due to hotplug during allocation. Detect when zonelists
4103  * have been rebuilt so allocation retries. Reader side does not lock and
4104  * retries the allocation if zonelist changes. Writer side is protected by the
4105  * embedded spin_lock.
4106  */
4107 static DEFINE_SEQLOCK(zonelist_update_seq);
4108 
4109 static unsigned int zonelist_iter_begin(void)
4110 {
4111 	if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
4112 		return read_seqbegin(&zonelist_update_seq);
4113 
4114 	return 0;
4115 }
4116 
4117 static unsigned int check_retry_zonelist(unsigned int seq)
4118 {
4119 	if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
4120 		return read_seqretry(&zonelist_update_seq, seq);
4121 
4122 	return seq;
4123 }
4124 
4125 /* Perform direct synchronous page reclaim */
4126 static unsigned long
4127 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
4128 					const struct alloc_context *ac)
4129 {
4130 	unsigned int noreclaim_flag;
4131 	unsigned long progress;
4132 
4133 	cond_resched();
4134 
4135 	/* We now go into synchronous reclaim */
4136 	cpuset_memory_pressure_bump();
4137 	fs_reclaim_acquire(gfp_mask);
4138 	noreclaim_flag = memalloc_noreclaim_save();
4139 
4140 	progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
4141 								ac->nodemask);
4142 
4143 	memalloc_noreclaim_restore(noreclaim_flag);
4144 	fs_reclaim_release(gfp_mask);
4145 
4146 	cond_resched();
4147 
4148 	return progress;
4149 }
4150 
4151 /* The really slow allocator path where we enter direct reclaim */
4152 static inline struct page *
4153 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
4154 		unsigned int alloc_flags, const struct alloc_context *ac,
4155 		unsigned long *did_some_progress)
4156 {
4157 	struct page *page = NULL;
4158 	unsigned long pflags;
4159 	bool drained = false;
4160 
4161 	psi_memstall_enter(&pflags);
4162 	*did_some_progress = __perform_reclaim(gfp_mask, order, ac);
4163 	if (unlikely(!(*did_some_progress)))
4164 		goto out;
4165 
4166 retry:
4167 	page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4168 
4169 	/*
4170 	 * If an allocation failed after direct reclaim, it could be because
4171 	 * pages are pinned on the per-cpu lists or in high alloc reserves.
4172 	 * Shrink them and try again
4173 	 */
4174 	if (!page && !drained) {
4175 		unreserve_highatomic_pageblock(ac, false);
4176 		drain_all_pages(NULL);
4177 		drained = true;
4178 		goto retry;
4179 	}
4180 out:
4181 	psi_memstall_leave(&pflags);
4182 
4183 	return page;
4184 }
4185 
4186 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
4187 			     const struct alloc_context *ac)
4188 {
4189 	struct zoneref *z;
4190 	struct zone *zone;
4191 	pg_data_t *last_pgdat = NULL;
4192 	enum zone_type highest_zoneidx = ac->highest_zoneidx;
4193 	unsigned int reclaim_order;
4194 
4195 	if (defrag_mode)
4196 		reclaim_order = max(order, pageblock_order);
4197 	else
4198 		reclaim_order = order;
4199 
4200 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, highest_zoneidx,
4201 					ac->nodemask) {
4202 		if (!managed_zone(zone))
4203 			continue;
4204 		if (last_pgdat == zone->zone_pgdat)
4205 			continue;
4206 		wakeup_kswapd(zone, gfp_mask, reclaim_order, highest_zoneidx);
4207 		last_pgdat = zone->zone_pgdat;
4208 	}
4209 }
4210 
4211 static inline unsigned int
4212 gfp_to_alloc_flags(gfp_t gfp_mask, unsigned int order)
4213 {
4214 	unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
4215 
4216 	/*
4217 	 * __GFP_HIGH is assumed to be the same as ALLOC_MIN_RESERVE
4218 	 * and __GFP_KSWAPD_RECLAIM is assumed to be the same as ALLOC_KSWAPD
4219 	 * to save two branches.
4220 	 */
4221 	BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_MIN_RESERVE);
4222 	BUILD_BUG_ON(__GFP_KSWAPD_RECLAIM != (__force gfp_t) ALLOC_KSWAPD);
4223 
4224 	/*
4225 	 * The caller may dip into page reserves a bit more if the caller
4226 	 * cannot run direct reclaim, or if the caller has realtime scheduling
4227 	 * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
4228 	 * set both ALLOC_NON_BLOCK and ALLOC_MIN_RESERVE(__GFP_HIGH).
4229 	 */
4230 	alloc_flags |= (__force int)
4231 		(gfp_mask & (__GFP_HIGH | __GFP_KSWAPD_RECLAIM));
4232 
4233 	if (!(gfp_mask & __GFP_DIRECT_RECLAIM)) {
4234 		/*
4235 		 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4236 		 * if it can't schedule.
4237 		 */
4238 		if (!(gfp_mask & __GFP_NOMEMALLOC)) {
4239 			alloc_flags |= ALLOC_NON_BLOCK;
4240 
4241 			if (order > 0)
4242 				alloc_flags |= ALLOC_HIGHATOMIC;
4243 		}
4244 
4245 		/*
4246 		 * Ignore cpuset mems for non-blocking __GFP_HIGH (probably
4247 		 * GFP_ATOMIC) rather than fail, see the comment for
4248 		 * cpuset_node_allowed().
4249 		 */
4250 		if (alloc_flags & ALLOC_MIN_RESERVE)
4251 			alloc_flags &= ~ALLOC_CPUSET;
4252 	} else if (unlikely(rt_or_dl_task(current)) && in_task())
4253 		alloc_flags |= ALLOC_MIN_RESERVE;
4254 
4255 	alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, alloc_flags);
4256 
4257 	if (defrag_mode)
4258 		alloc_flags |= ALLOC_NOFRAGMENT;
4259 
4260 	return alloc_flags;
4261 }
4262 
4263 static bool oom_reserves_allowed(struct task_struct *tsk)
4264 {
4265 	if (!tsk_is_oom_victim(tsk))
4266 		return false;
4267 
4268 	/*
4269 	 * !MMU doesn't have oom reaper so give access to memory reserves
4270 	 * only to the thread with TIF_MEMDIE set
4271 	 */
4272 	if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
4273 		return false;
4274 
4275 	return true;
4276 }
4277 
4278 /*
4279  * Distinguish requests which really need access to full memory
4280  * reserves from oom victims which can live with a portion of it
4281  */
4282 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4283 {
4284 	if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4285 		return 0;
4286 	if (gfp_mask & __GFP_MEMALLOC)
4287 		return ALLOC_NO_WATERMARKS;
4288 	if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
4289 		return ALLOC_NO_WATERMARKS;
4290 	if (!in_interrupt()) {
4291 		if (current->flags & PF_MEMALLOC)
4292 			return ALLOC_NO_WATERMARKS;
4293 		else if (oom_reserves_allowed(current))
4294 			return ALLOC_OOM;
4295 	}
4296 
4297 	return 0;
4298 }
4299 
4300 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4301 {
4302 	return !!__gfp_pfmemalloc_flags(gfp_mask);
4303 }
4304 
4305 /*
4306  * Checks whether it makes sense to retry the reclaim to make a forward progress
4307  * for the given allocation request.
4308  *
4309  * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4310  * without success, or when we couldn't even meet the watermark if we
4311  * reclaimed all remaining pages on the LRU lists.
4312  *
4313  * Returns true if a retry is viable or false to enter the oom path.
4314  */
4315 static inline bool
4316 should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4317 		     struct alloc_context *ac, int alloc_flags,
4318 		     bool did_some_progress, int *no_progress_loops)
4319 {
4320 	struct zone *zone;
4321 	struct zoneref *z;
4322 	bool ret = false;
4323 
4324 	/*
4325 	 * Costly allocations might have made a progress but this doesn't mean
4326 	 * their order will become available due to high fragmentation so
4327 	 * always increment the no progress counter for them
4328 	 */
4329 	if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4330 		*no_progress_loops = 0;
4331 	else
4332 		(*no_progress_loops)++;
4333 
4334 	if (*no_progress_loops > MAX_RECLAIM_RETRIES)
4335 		goto out;
4336 
4337 
4338 	/*
4339 	 * Keep reclaiming pages while there is a chance this will lead
4340 	 * somewhere.  If none of the target zones can satisfy our allocation
4341 	 * request even if all reclaimable pages are considered then we are
4342 	 * screwed and have to go OOM.
4343 	 */
4344 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
4345 				ac->highest_zoneidx, ac->nodemask) {
4346 		unsigned long available;
4347 		unsigned long reclaimable;
4348 		unsigned long min_wmark = min_wmark_pages(zone);
4349 		bool wmark;
4350 
4351 		if (cpusets_enabled() &&
4352 			(alloc_flags & ALLOC_CPUSET) &&
4353 			!__cpuset_zone_allowed(zone, gfp_mask))
4354 				continue;
4355 
4356 		available = reclaimable = zone_reclaimable_pages(zone);
4357 		available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
4358 
4359 		/*
4360 		 * Would the allocation succeed if we reclaimed all
4361 		 * reclaimable pages?
4362 		 */
4363 		wmark = __zone_watermark_ok(zone, order, min_wmark,
4364 				ac->highest_zoneidx, alloc_flags, available);
4365 		trace_reclaim_retry_zone(z, order, reclaimable,
4366 				available, min_wmark, *no_progress_loops, wmark);
4367 		if (wmark) {
4368 			ret = true;
4369 			break;
4370 		}
4371 	}
4372 
4373 	/*
4374 	 * Memory allocation/reclaim might be called from a WQ context and the
4375 	 * current implementation of the WQ concurrency control doesn't
4376 	 * recognize that a particular WQ is congested if the worker thread is
4377 	 * looping without ever sleeping. Therefore we have to do a short sleep
4378 	 * here rather than calling cond_resched().
4379 	 */
4380 	if (current->flags & PF_WQ_WORKER)
4381 		schedule_timeout_uninterruptible(1);
4382 	else
4383 		cond_resched();
4384 out:
4385 	/* Before OOM, exhaust highatomic_reserve */
4386 	if (!ret)
4387 		return unreserve_highatomic_pageblock(ac, true);
4388 
4389 	return ret;
4390 }
4391 
4392 static inline bool
4393 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4394 {
4395 	/*
4396 	 * It's possible that cpuset's mems_allowed and the nodemask from
4397 	 * mempolicy don't intersect. This should be normally dealt with by
4398 	 * policy_nodemask(), but it's possible to race with cpuset update in
4399 	 * such a way the check therein was true, and then it became false
4400 	 * before we got our cpuset_mems_cookie here.
4401 	 * This assumes that for all allocations, ac->nodemask can come only
4402 	 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4403 	 * when it does not intersect with the cpuset restrictions) or the
4404 	 * caller can deal with a violated nodemask.
4405 	 */
4406 	if (cpusets_enabled() && ac->nodemask &&
4407 			!cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4408 		ac->nodemask = NULL;
4409 		return true;
4410 	}
4411 
4412 	/*
4413 	 * When updating a task's mems_allowed or mempolicy nodemask, it is
4414 	 * possible to race with parallel threads in such a way that our
4415 	 * allocation can fail while the mask is being updated. If we are about
4416 	 * to fail, check if the cpuset changed during allocation and if so,
4417 	 * retry.
4418 	 */
4419 	if (read_mems_allowed_retry(cpuset_mems_cookie))
4420 		return true;
4421 
4422 	return false;
4423 }
4424 
4425 static inline struct page *
4426 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
4427 						struct alloc_context *ac)
4428 {
4429 	bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
4430 	bool can_compact = gfp_compaction_allowed(gfp_mask);
4431 	bool nofail = gfp_mask & __GFP_NOFAIL;
4432 	const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
4433 	struct page *page = NULL;
4434 	unsigned int alloc_flags;
4435 	unsigned long did_some_progress;
4436 	enum compact_priority compact_priority;
4437 	enum compact_result compact_result;
4438 	int compaction_retries;
4439 	int no_progress_loops;
4440 	unsigned int cpuset_mems_cookie;
4441 	unsigned int zonelist_iter_cookie;
4442 	int reserve_flags;
4443 
4444 	if (unlikely(nofail)) {
4445 		/*
4446 		 * We most definitely don't want callers attempting to
4447 		 * allocate greater than order-1 page units with __GFP_NOFAIL.
4448 		 */
4449 		WARN_ON_ONCE(order > 1);
4450 		/*
4451 		 * Also we don't support __GFP_NOFAIL without __GFP_DIRECT_RECLAIM,
4452 		 * otherwise, we may result in lockup.
4453 		 */
4454 		WARN_ON_ONCE(!can_direct_reclaim);
4455 		/*
4456 		 * PF_MEMALLOC request from this context is rather bizarre
4457 		 * because we cannot reclaim anything and only can loop waiting
4458 		 * for somebody to do a work for us.
4459 		 */
4460 		WARN_ON_ONCE(current->flags & PF_MEMALLOC);
4461 	}
4462 
4463 restart:
4464 	compaction_retries = 0;
4465 	no_progress_loops = 0;
4466 	compact_result = COMPACT_SKIPPED;
4467 	compact_priority = DEF_COMPACT_PRIORITY;
4468 	cpuset_mems_cookie = read_mems_allowed_begin();
4469 	zonelist_iter_cookie = zonelist_iter_begin();
4470 
4471 	/*
4472 	 * The fast path uses conservative alloc_flags to succeed only until
4473 	 * kswapd needs to be woken up, and to avoid the cost of setting up
4474 	 * alloc_flags precisely. So we do that now.
4475 	 */
4476 	alloc_flags = gfp_to_alloc_flags(gfp_mask, order);
4477 
4478 	/*
4479 	 * We need to recalculate the starting point for the zonelist iterator
4480 	 * because we might have used different nodemask in the fast path, or
4481 	 * there was a cpuset modification and we are retrying - otherwise we
4482 	 * could end up iterating over non-eligible zones endlessly.
4483 	 */
4484 	ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4485 					ac->highest_zoneidx, ac->nodemask);
4486 	if (!zonelist_zone(ac->preferred_zoneref))
4487 		goto nopage;
4488 
4489 	/*
4490 	 * Check for insane configurations where the cpuset doesn't contain
4491 	 * any suitable zone to satisfy the request - e.g. non-movable
4492 	 * GFP_HIGHUSER allocations from MOVABLE nodes only.
4493 	 */
4494 	if (cpusets_insane_config() && (gfp_mask & __GFP_HARDWALL)) {
4495 		struct zoneref *z = first_zones_zonelist(ac->zonelist,
4496 					ac->highest_zoneidx,
4497 					&cpuset_current_mems_allowed);
4498 		if (!zonelist_zone(z))
4499 			goto nopage;
4500 	}
4501 
4502 	if (alloc_flags & ALLOC_KSWAPD)
4503 		wake_all_kswapds(order, gfp_mask, ac);
4504 
4505 	/*
4506 	 * The adjusted alloc_flags might result in immediate success, so try
4507 	 * that first
4508 	 */
4509 	page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4510 	if (page)
4511 		goto got_pg;
4512 
4513 	/*
4514 	 * For costly allocations, try direct compaction first, as it's likely
4515 	 * that we have enough base pages and don't need to reclaim. For non-
4516 	 * movable high-order allocations, do that as well, as compaction will
4517 	 * try prevent permanent fragmentation by migrating from blocks of the
4518 	 * same migratetype.
4519 	 * Don't try this for allocations that are allowed to ignore
4520 	 * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
4521 	 */
4522 	if (can_direct_reclaim && can_compact &&
4523 			(costly_order ||
4524 			   (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
4525 			&& !gfp_pfmemalloc_allowed(gfp_mask)) {
4526 		page = __alloc_pages_direct_compact(gfp_mask, order,
4527 						alloc_flags, ac,
4528 						INIT_COMPACT_PRIORITY,
4529 						&compact_result);
4530 		if (page)
4531 			goto got_pg;
4532 
4533 		/*
4534 		 * Checks for costly allocations with __GFP_NORETRY, which
4535 		 * includes some THP page fault allocations
4536 		 */
4537 		if (costly_order && (gfp_mask & __GFP_NORETRY)) {
4538 			/*
4539 			 * If allocating entire pageblock(s) and compaction
4540 			 * failed because all zones are below low watermarks
4541 			 * or is prohibited because it recently failed at this
4542 			 * order, fail immediately unless the allocator has
4543 			 * requested compaction and reclaim retry.
4544 			 *
4545 			 * Reclaim is
4546 			 *  - potentially very expensive because zones are far
4547 			 *    below their low watermarks or this is part of very
4548 			 *    bursty high order allocations,
4549 			 *  - not guaranteed to help because isolate_freepages()
4550 			 *    may not iterate over freed pages as part of its
4551 			 *    linear scan, and
4552 			 *  - unlikely to make entire pageblocks free on its
4553 			 *    own.
4554 			 */
4555 			if (compact_result == COMPACT_SKIPPED ||
4556 			    compact_result == COMPACT_DEFERRED)
4557 				goto nopage;
4558 
4559 			/*
4560 			 * Looks like reclaim/compaction is worth trying, but
4561 			 * sync compaction could be very expensive, so keep
4562 			 * using async compaction.
4563 			 */
4564 			compact_priority = INIT_COMPACT_PRIORITY;
4565 		}
4566 	}
4567 
4568 retry:
4569 	/* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4570 	if (alloc_flags & ALLOC_KSWAPD)
4571 		wake_all_kswapds(order, gfp_mask, ac);
4572 
4573 	reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
4574 	if (reserve_flags)
4575 		alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, reserve_flags) |
4576 					  (alloc_flags & ALLOC_KSWAPD);
4577 
4578 	/*
4579 	 * Reset the nodemask and zonelist iterators if memory policies can be
4580 	 * ignored. These allocations are high priority and system rather than
4581 	 * user oriented.
4582 	 */
4583 	if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
4584 		ac->nodemask = NULL;
4585 		ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4586 					ac->highest_zoneidx, ac->nodemask);
4587 	}
4588 
4589 	/* Attempt with potentially adjusted zonelist and alloc_flags */
4590 	page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4591 	if (page)
4592 		goto got_pg;
4593 
4594 	/* Caller is not willing to reclaim, we can't balance anything */
4595 	if (!can_direct_reclaim)
4596 		goto nopage;
4597 
4598 	/* Avoid recursion of direct reclaim */
4599 	if (current->flags & PF_MEMALLOC)
4600 		goto nopage;
4601 
4602 	/* Try direct reclaim and then allocating */
4603 	page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
4604 							&did_some_progress);
4605 	if (page)
4606 		goto got_pg;
4607 
4608 	/* Try direct compaction and then allocating */
4609 	page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
4610 					compact_priority, &compact_result);
4611 	if (page)
4612 		goto got_pg;
4613 
4614 	/* Do not loop if specifically requested */
4615 	if (gfp_mask & __GFP_NORETRY)
4616 		goto nopage;
4617 
4618 	/*
4619 	 * Do not retry costly high order allocations unless they are
4620 	 * __GFP_RETRY_MAYFAIL and we can compact
4621 	 */
4622 	if (costly_order && (!can_compact ||
4623 			     !(gfp_mask & __GFP_RETRY_MAYFAIL)))
4624 		goto nopage;
4625 
4626 	if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
4627 				 did_some_progress > 0, &no_progress_loops))
4628 		goto retry;
4629 
4630 	/*
4631 	 * It doesn't make any sense to retry for the compaction if the order-0
4632 	 * reclaim is not able to make any progress because the current
4633 	 * implementation of the compaction depends on the sufficient amount
4634 	 * of free memory (see __compaction_suitable)
4635 	 */
4636 	if (did_some_progress > 0 && can_compact &&
4637 			should_compact_retry(ac, order, alloc_flags,
4638 				compact_result, &compact_priority,
4639 				&compaction_retries))
4640 		goto retry;
4641 
4642 	/* Reclaim/compaction failed to prevent the fallback */
4643 	if (defrag_mode && (alloc_flags & ALLOC_NOFRAGMENT)) {
4644 		alloc_flags &= ~ALLOC_NOFRAGMENT;
4645 		goto retry;
4646 	}
4647 
4648 	/*
4649 	 * Deal with possible cpuset update races or zonelist updates to avoid
4650 	 * a unnecessary OOM kill.
4651 	 */
4652 	if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
4653 	    check_retry_zonelist(zonelist_iter_cookie))
4654 		goto restart;
4655 
4656 	/* Reclaim has failed us, start killing things */
4657 	page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
4658 	if (page)
4659 		goto got_pg;
4660 
4661 	/* Avoid allocations with no watermarks from looping endlessly */
4662 	if (tsk_is_oom_victim(current) &&
4663 	    (alloc_flags & ALLOC_OOM ||
4664 	     (gfp_mask & __GFP_NOMEMALLOC)))
4665 		goto nopage;
4666 
4667 	/* Retry as long as the OOM killer is making progress */
4668 	if (did_some_progress) {
4669 		no_progress_loops = 0;
4670 		goto retry;
4671 	}
4672 
4673 nopage:
4674 	/*
4675 	 * Deal with possible cpuset update races or zonelist updates to avoid
4676 	 * a unnecessary OOM kill.
4677 	 */
4678 	if (check_retry_cpuset(cpuset_mems_cookie, ac) ||
4679 	    check_retry_zonelist(zonelist_iter_cookie))
4680 		goto restart;
4681 
4682 	/*
4683 	 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
4684 	 * we always retry
4685 	 */
4686 	if (unlikely(nofail)) {
4687 		/*
4688 		 * Lacking direct_reclaim we can't do anything to reclaim memory,
4689 		 * we disregard these unreasonable nofail requests and still
4690 		 * return NULL
4691 		 */
4692 		if (!can_direct_reclaim)
4693 			goto fail;
4694 
4695 		/*
4696 		 * Help non-failing allocations by giving some access to memory
4697 		 * reserves normally used for high priority non-blocking
4698 		 * allocations but do not use ALLOC_NO_WATERMARKS because this
4699 		 * could deplete whole memory reserves which would just make
4700 		 * the situation worse.
4701 		 */
4702 		page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_MIN_RESERVE, ac);
4703 		if (page)
4704 			goto got_pg;
4705 
4706 		cond_resched();
4707 		goto retry;
4708 	}
4709 fail:
4710 	warn_alloc(gfp_mask, ac->nodemask,
4711 			"page allocation failure: order:%u", order);
4712 got_pg:
4713 	return page;
4714 }
4715 
4716 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
4717 		int preferred_nid, nodemask_t *nodemask,
4718 		struct alloc_context *ac, gfp_t *alloc_gfp,
4719 		unsigned int *alloc_flags)
4720 {
4721 	ac->highest_zoneidx = gfp_zone(gfp_mask);
4722 	ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
4723 	ac->nodemask = nodemask;
4724 	ac->migratetype = gfp_migratetype(gfp_mask);
4725 
4726 	if (cpusets_enabled()) {
4727 		*alloc_gfp |= __GFP_HARDWALL;
4728 		/*
4729 		 * When we are in the interrupt context, it is irrelevant
4730 		 * to the current task context. It means that any node ok.
4731 		 */
4732 		if (in_task() && !ac->nodemask)
4733 			ac->nodemask = &cpuset_current_mems_allowed;
4734 		else
4735 			*alloc_flags |= ALLOC_CPUSET;
4736 	}
4737 
4738 	might_alloc(gfp_mask);
4739 
4740 	/*
4741 	 * Don't invoke should_fail logic, since it may call
4742 	 * get_random_u32() and printk() which need to spin_lock.
4743 	 */
4744 	if (!(*alloc_flags & ALLOC_TRYLOCK) &&
4745 	    should_fail_alloc_page(gfp_mask, order))
4746 		return false;
4747 
4748 	*alloc_flags = gfp_to_alloc_flags_cma(gfp_mask, *alloc_flags);
4749 
4750 	/* Dirty zone balancing only done in the fast path */
4751 	ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
4752 
4753 	/*
4754 	 * The preferred zone is used for statistics but crucially it is
4755 	 * also used as the starting point for the zonelist iterator. It
4756 	 * may get reset for allocations that ignore memory policies.
4757 	 */
4758 	ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4759 					ac->highest_zoneidx, ac->nodemask);
4760 
4761 	return true;
4762 }
4763 
4764 /*
4765  * __alloc_pages_bulk - Allocate a number of order-0 pages to an array
4766  * @gfp: GFP flags for the allocation
4767  * @preferred_nid: The preferred NUMA node ID to allocate from
4768  * @nodemask: Set of nodes to allocate from, may be NULL
4769  * @nr_pages: The number of pages desired in the array
4770  * @page_array: Array to store the pages
4771  *
4772  * This is a batched version of the page allocator that attempts to
4773  * allocate nr_pages quickly. Pages are added to the page_array.
4774  *
4775  * Note that only NULL elements are populated with pages and nr_pages
4776  * is the maximum number of pages that will be stored in the array.
4777  *
4778  * Returns the number of pages in the array.
4779  */
4780 unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
4781 			nodemask_t *nodemask, int nr_pages,
4782 			struct page **page_array)
4783 {
4784 	struct page *page;
4785 	unsigned long __maybe_unused UP_flags;
4786 	struct zone *zone;
4787 	struct zoneref *z;
4788 	struct per_cpu_pages *pcp;
4789 	struct list_head *pcp_list;
4790 	struct alloc_context ac;
4791 	gfp_t alloc_gfp;
4792 	unsigned int alloc_flags = ALLOC_WMARK_LOW;
4793 	int nr_populated = 0, nr_account = 0;
4794 
4795 	/*
4796 	 * Skip populated array elements to determine if any pages need
4797 	 * to be allocated before disabling IRQs.
4798 	 */
4799 	while (nr_populated < nr_pages && page_array[nr_populated])
4800 		nr_populated++;
4801 
4802 	/* No pages requested? */
4803 	if (unlikely(nr_pages <= 0))
4804 		goto out;
4805 
4806 	/* Already populated array? */
4807 	if (unlikely(nr_pages - nr_populated == 0))
4808 		goto out;
4809 
4810 	/* Bulk allocator does not support memcg accounting. */
4811 	if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT))
4812 		goto failed;
4813 
4814 	/* Use the single page allocator for one page. */
4815 	if (nr_pages - nr_populated == 1)
4816 		goto failed;
4817 
4818 #ifdef CONFIG_PAGE_OWNER
4819 	/*
4820 	 * PAGE_OWNER may recurse into the allocator to allocate space to
4821 	 * save the stack with pagesets.lock held. Releasing/reacquiring
4822 	 * removes much of the performance benefit of bulk allocation so
4823 	 * force the caller to allocate one page at a time as it'll have
4824 	 * similar performance to added complexity to the bulk allocator.
4825 	 */
4826 	if (static_branch_unlikely(&page_owner_inited))
4827 		goto failed;
4828 #endif
4829 
4830 	/* May set ALLOC_NOFRAGMENT, fragmentation will return 1 page. */
4831 	gfp &= gfp_allowed_mask;
4832 	alloc_gfp = gfp;
4833 	if (!prepare_alloc_pages(gfp, 0, preferred_nid, nodemask, &ac, &alloc_gfp, &alloc_flags))
4834 		goto out;
4835 	gfp = alloc_gfp;
4836 
4837 	/* Find an allowed local zone that meets the low watermark. */
4838 	z = ac.preferred_zoneref;
4839 	for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) {
4840 		unsigned long mark;
4841 
4842 		if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) &&
4843 		    !__cpuset_zone_allowed(zone, gfp)) {
4844 			continue;
4845 		}
4846 
4847 		if (nr_online_nodes > 1 && zone != zonelist_zone(ac.preferred_zoneref) &&
4848 		    zone_to_nid(zone) != zonelist_node_idx(ac.preferred_zoneref)) {
4849 			goto failed;
4850 		}
4851 
4852 		cond_accept_memory(zone, 0);
4853 retry_this_zone:
4854 		mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages;
4855 		if (zone_watermark_fast(zone, 0,  mark,
4856 				zonelist_zone_idx(ac.preferred_zoneref),
4857 				alloc_flags, gfp)) {
4858 			break;
4859 		}
4860 
4861 		if (cond_accept_memory(zone, 0))
4862 			goto retry_this_zone;
4863 
4864 		/* Try again if zone has deferred pages */
4865 		if (deferred_pages_enabled()) {
4866 			if (_deferred_grow_zone(zone, 0))
4867 				goto retry_this_zone;
4868 		}
4869 	}
4870 
4871 	/*
4872 	 * If there are no allowed local zones that meets the watermarks then
4873 	 * try to allocate a single page and reclaim if necessary.
4874 	 */
4875 	if (unlikely(!zone))
4876 		goto failed;
4877 
4878 	/* spin_trylock may fail due to a parallel drain or IRQ reentrancy. */
4879 	pcp_trylock_prepare(UP_flags);
4880 	pcp = pcp_spin_trylock(zone->per_cpu_pageset);
4881 	if (!pcp)
4882 		goto failed_irq;
4883 
4884 	/* Attempt the batch allocation */
4885 	pcp_list = &pcp->lists[order_to_pindex(ac.migratetype, 0)];
4886 	while (nr_populated < nr_pages) {
4887 
4888 		/* Skip existing pages */
4889 		if (page_array[nr_populated]) {
4890 			nr_populated++;
4891 			continue;
4892 		}
4893 
4894 		page = __rmqueue_pcplist(zone, 0, ac.migratetype, alloc_flags,
4895 								pcp, pcp_list);
4896 		if (unlikely(!page)) {
4897 			/* Try and allocate at least one page */
4898 			if (!nr_account) {
4899 				pcp_spin_unlock(pcp);
4900 				goto failed_irq;
4901 			}
4902 			break;
4903 		}
4904 		nr_account++;
4905 
4906 		prep_new_page(page, 0, gfp, 0);
4907 		set_page_refcounted(page);
4908 		page_array[nr_populated++] = page;
4909 	}
4910 
4911 	pcp_spin_unlock(pcp);
4912 	pcp_trylock_finish(UP_flags);
4913 
4914 	__count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account);
4915 	zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account);
4916 
4917 out:
4918 	return nr_populated;
4919 
4920 failed_irq:
4921 	pcp_trylock_finish(UP_flags);
4922 
4923 failed:
4924 	page = __alloc_pages_noprof(gfp, 0, preferred_nid, nodemask);
4925 	if (page)
4926 		page_array[nr_populated++] = page;
4927 	goto out;
4928 }
4929 EXPORT_SYMBOL_GPL(alloc_pages_bulk_noprof);
4930 
4931 /*
4932  * This is the 'heart' of the zoned buddy allocator.
4933  */
4934 struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order,
4935 		int preferred_nid, nodemask_t *nodemask)
4936 {
4937 	struct page *page;
4938 	unsigned int alloc_flags = ALLOC_WMARK_LOW;
4939 	gfp_t alloc_gfp; /* The gfp_t that was actually used for allocation */
4940 	struct alloc_context ac = { };
4941 
4942 	/*
4943 	 * There are several places where we assume that the order value is sane
4944 	 * so bail out early if the request is out of bound.
4945 	 */
4946 	if (WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp))
4947 		return NULL;
4948 
4949 	gfp &= gfp_allowed_mask;
4950 	/*
4951 	 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
4952 	 * resp. GFP_NOIO which has to be inherited for all allocation requests
4953 	 * from a particular context which has been marked by
4954 	 * memalloc_no{fs,io}_{save,restore}. And PF_MEMALLOC_PIN which ensures
4955 	 * movable zones are not used during allocation.
4956 	 */
4957 	gfp = current_gfp_context(gfp);
4958 	alloc_gfp = gfp;
4959 	if (!prepare_alloc_pages(gfp, order, preferred_nid, nodemask, &ac,
4960 			&alloc_gfp, &alloc_flags))
4961 		return NULL;
4962 
4963 	/*
4964 	 * Forbid the first pass from falling back to types that fragment
4965 	 * memory until all local zones are considered.
4966 	 */
4967 	alloc_flags |= alloc_flags_nofragment(zonelist_zone(ac.preferred_zoneref), gfp);
4968 
4969 	/* First allocation attempt */
4970 	page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac);
4971 	if (likely(page))
4972 		goto out;
4973 
4974 	alloc_gfp = gfp;
4975 	ac.spread_dirty_pages = false;
4976 
4977 	/*
4978 	 * Restore the original nodemask if it was potentially replaced with
4979 	 * &cpuset_current_mems_allowed to optimize the fast-path attempt.
4980 	 */
4981 	ac.nodemask = nodemask;
4982 
4983 	page = __alloc_pages_slowpath(alloc_gfp, order, &ac);
4984 
4985 out:
4986 	if (memcg_kmem_online() && (gfp & __GFP_ACCOUNT) && page &&
4987 	    unlikely(__memcg_kmem_charge_page(page, gfp, order) != 0)) {
4988 		free_frozen_pages(page, order);
4989 		page = NULL;
4990 	}
4991 
4992 	trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype);
4993 	kmsan_alloc_page(page, order, alloc_gfp);
4994 
4995 	return page;
4996 }
4997 EXPORT_SYMBOL(__alloc_frozen_pages_noprof);
4998 
4999 struct page *__alloc_pages_noprof(gfp_t gfp, unsigned int order,
5000 		int preferred_nid, nodemask_t *nodemask)
5001 {
5002 	struct page *page;
5003 
5004 	page = __alloc_frozen_pages_noprof(gfp, order, preferred_nid, nodemask);
5005 	if (page)
5006 		set_page_refcounted(page);
5007 	return page;
5008 }
5009 EXPORT_SYMBOL(__alloc_pages_noprof);
5010 
5011 struct folio *__folio_alloc_noprof(gfp_t gfp, unsigned int order, int preferred_nid,
5012 		nodemask_t *nodemask)
5013 {
5014 	struct page *page = __alloc_pages_noprof(gfp | __GFP_COMP, order,
5015 					preferred_nid, nodemask);
5016 	return page_rmappable_folio(page);
5017 }
5018 EXPORT_SYMBOL(__folio_alloc_noprof);
5019 
5020 /*
5021  * Common helper functions. Never use with __GFP_HIGHMEM because the returned
5022  * address cannot represent highmem pages. Use alloc_pages and then kmap if
5023  * you need to access high mem.
5024  */
5025 unsigned long get_free_pages_noprof(gfp_t gfp_mask, unsigned int order)
5026 {
5027 	struct page *page;
5028 
5029 	page = alloc_pages_noprof(gfp_mask & ~__GFP_HIGHMEM, order);
5030 	if (!page)
5031 		return 0;
5032 	return (unsigned long) page_address(page);
5033 }
5034 EXPORT_SYMBOL(get_free_pages_noprof);
5035 
5036 unsigned long get_zeroed_page_noprof(gfp_t gfp_mask)
5037 {
5038 	return get_free_pages_noprof(gfp_mask | __GFP_ZERO, 0);
5039 }
5040 EXPORT_SYMBOL(get_zeroed_page_noprof);
5041 
5042 /**
5043  * ___free_pages - Free pages allocated with alloc_pages().
5044  * @page: The page pointer returned from alloc_pages().
5045  * @order: The order of the allocation.
5046  * @fpi_flags: Free Page Internal flags.
5047  *
5048  * This function can free multi-page allocations that are not compound
5049  * pages.  It does not check that the @order passed in matches that of
5050  * the allocation, so it is easy to leak memory.  Freeing more memory
5051  * than was allocated will probably emit a warning.
5052  *
5053  * If the last reference to this page is speculative, it will be released
5054  * by put_page() which only frees the first page of a non-compound
5055  * allocation.  To prevent the remaining pages from being leaked, we free
5056  * the subsequent pages here.  If you want to use the page's reference
5057  * count to decide when to free the allocation, you should allocate a
5058  * compound page, and use put_page() instead of __free_pages().
5059  *
5060  * Context: May be called in interrupt context or while holding a normal
5061  * spinlock, but not in NMI context or while holding a raw spinlock.
5062  */
5063 static void ___free_pages(struct page *page, unsigned int order,
5064 			  fpi_t fpi_flags)
5065 {
5066 	/* get PageHead before we drop reference */
5067 	int head = PageHead(page);
5068 
5069 	if (put_page_testzero(page))
5070 		__free_frozen_pages(page, order, fpi_flags);
5071 	else if (!head) {
5072 		pgalloc_tag_sub_pages(page, (1 << order) - 1);
5073 		while (order-- > 0)
5074 			__free_frozen_pages(page + (1 << order), order,
5075 					    fpi_flags);
5076 	}
5077 }
5078 void __free_pages(struct page *page, unsigned int order)
5079 {
5080 	___free_pages(page, order, FPI_NONE);
5081 }
5082 EXPORT_SYMBOL(__free_pages);
5083 
5084 /*
5085  * Can be called while holding raw_spin_lock or from IRQ and NMI for any
5086  * page type (not only those that came from try_alloc_pages)
5087  */
5088 void free_pages_nolock(struct page *page, unsigned int order)
5089 {
5090 	___free_pages(page, order, FPI_TRYLOCK);
5091 }
5092 
5093 void free_pages(unsigned long addr, unsigned int order)
5094 {
5095 	if (addr != 0) {
5096 		VM_BUG_ON(!virt_addr_valid((void *)addr));
5097 		__free_pages(virt_to_page((void *)addr), order);
5098 	}
5099 }
5100 
5101 EXPORT_SYMBOL(free_pages);
5102 
5103 static void *make_alloc_exact(unsigned long addr, unsigned int order,
5104 		size_t size)
5105 {
5106 	if (addr) {
5107 		unsigned long nr = DIV_ROUND_UP(size, PAGE_SIZE);
5108 		struct page *page = virt_to_page((void *)addr);
5109 		struct page *last = page + nr;
5110 
5111 		split_page_owner(page, order, 0);
5112 		pgalloc_tag_split(page_folio(page), order, 0);
5113 		split_page_memcg(page, order);
5114 		while (page < --last)
5115 			set_page_refcounted(last);
5116 
5117 		last = page + (1UL << order);
5118 		for (page += nr; page < last; page++)
5119 			__free_pages_ok(page, 0, FPI_TO_TAIL);
5120 	}
5121 	return (void *)addr;
5122 }
5123 
5124 /**
5125  * alloc_pages_exact - allocate an exact number physically-contiguous pages.
5126  * @size: the number of bytes to allocate
5127  * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5128  *
5129  * This function is similar to alloc_pages(), except that it allocates the
5130  * minimum number of pages to satisfy the request.  alloc_pages() can only
5131  * allocate memory in power-of-two pages.
5132  *
5133  * This function is also limited by MAX_PAGE_ORDER.
5134  *
5135  * Memory allocated by this function must be released by free_pages_exact().
5136  *
5137  * Return: pointer to the allocated area or %NULL in case of error.
5138  */
5139 void *alloc_pages_exact_noprof(size_t size, gfp_t gfp_mask)
5140 {
5141 	unsigned int order = get_order(size);
5142 	unsigned long addr;
5143 
5144 	if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
5145 		gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
5146 
5147 	addr = get_free_pages_noprof(gfp_mask, order);
5148 	return make_alloc_exact(addr, order, size);
5149 }
5150 EXPORT_SYMBOL(alloc_pages_exact_noprof);
5151 
5152 /**
5153  * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
5154  *			   pages on a node.
5155  * @nid: the preferred node ID where memory should be allocated
5156  * @size: the number of bytes to allocate
5157  * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
5158  *
5159  * Like alloc_pages_exact(), but try to allocate on node nid first before falling
5160  * back.
5161  *
5162  * Return: pointer to the allocated area or %NULL in case of error.
5163  */
5164 void * __meminit alloc_pages_exact_nid_noprof(int nid, size_t size, gfp_t gfp_mask)
5165 {
5166 	unsigned int order = get_order(size);
5167 	struct page *p;
5168 
5169 	if (WARN_ON_ONCE(gfp_mask & (__GFP_COMP | __GFP_HIGHMEM)))
5170 		gfp_mask &= ~(__GFP_COMP | __GFP_HIGHMEM);
5171 
5172 	p = alloc_pages_node_noprof(nid, gfp_mask, order);
5173 	if (!p)
5174 		return NULL;
5175 	return make_alloc_exact((unsigned long)page_address(p), order, size);
5176 }
5177 
5178 /**
5179  * free_pages_exact - release memory allocated via alloc_pages_exact()
5180  * @virt: the value returned by alloc_pages_exact.
5181  * @size: size of allocation, same value as passed to alloc_pages_exact().
5182  *
5183  * Release the memory allocated by a previous call to alloc_pages_exact.
5184  */
5185 void free_pages_exact(void *virt, size_t size)
5186 {
5187 	unsigned long addr = (unsigned long)virt;
5188 	unsigned long end = addr + PAGE_ALIGN(size);
5189 
5190 	while (addr < end) {
5191 		free_page(addr);
5192 		addr += PAGE_SIZE;
5193 	}
5194 }
5195 EXPORT_SYMBOL(free_pages_exact);
5196 
5197 /**
5198  * nr_free_zone_pages - count number of pages beyond high watermark
5199  * @offset: The zone index of the highest zone
5200  *
5201  * nr_free_zone_pages() counts the number of pages which are beyond the
5202  * high watermark within all zones at or below a given zone index.  For each
5203  * zone, the number of pages is calculated as:
5204  *
5205  *     nr_free_zone_pages = managed_pages - high_pages
5206  *
5207  * Return: number of pages beyond high watermark.
5208  */
5209 static unsigned long nr_free_zone_pages(int offset)
5210 {
5211 	struct zoneref *z;
5212 	struct zone *zone;
5213 
5214 	/* Just pick one node, since fallback list is circular */
5215 	unsigned long sum = 0;
5216 
5217 	struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
5218 
5219 	for_each_zone_zonelist(zone, z, zonelist, offset) {
5220 		unsigned long size = zone_managed_pages(zone);
5221 		unsigned long high = high_wmark_pages(zone);
5222 		if (size > high)
5223 			sum += size - high;
5224 	}
5225 
5226 	return sum;
5227 }
5228 
5229 /**
5230  * nr_free_buffer_pages - count number of pages beyond high watermark
5231  *
5232  * nr_free_buffer_pages() counts the number of pages which are beyond the high
5233  * watermark within ZONE_DMA and ZONE_NORMAL.
5234  *
5235  * Return: number of pages beyond high watermark within ZONE_DMA and
5236  * ZONE_NORMAL.
5237  */
5238 unsigned long nr_free_buffer_pages(void)
5239 {
5240 	return nr_free_zone_pages(gfp_zone(GFP_USER));
5241 }
5242 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
5243 
5244 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
5245 {
5246 	zoneref->zone = zone;
5247 	zoneref->zone_idx = zone_idx(zone);
5248 }
5249 
5250 /*
5251  * Builds allocation fallback zone lists.
5252  *
5253  * Add all populated zones of a node to the zonelist.
5254  */
5255 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
5256 {
5257 	struct zone *zone;
5258 	enum zone_type zone_type = MAX_NR_ZONES;
5259 	int nr_zones = 0;
5260 
5261 	do {
5262 		zone_type--;
5263 		zone = pgdat->node_zones + zone_type;
5264 		if (populated_zone(zone)) {
5265 			zoneref_set_zone(zone, &zonerefs[nr_zones++]);
5266 			check_highest_zone(zone_type);
5267 		}
5268 	} while (zone_type);
5269 
5270 	return nr_zones;
5271 }
5272 
5273 #ifdef CONFIG_NUMA
5274 
5275 static int __parse_numa_zonelist_order(char *s)
5276 {
5277 	/*
5278 	 * We used to support different zonelists modes but they turned
5279 	 * out to be just not useful. Let's keep the warning in place
5280 	 * if somebody still use the cmd line parameter so that we do
5281 	 * not fail it silently
5282 	 */
5283 	if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
5284 		pr_warn("Ignoring unsupported numa_zonelist_order value:  %s\n", s);
5285 		return -EINVAL;
5286 	}
5287 	return 0;
5288 }
5289 
5290 static char numa_zonelist_order[] = "Node";
5291 #define NUMA_ZONELIST_ORDER_LEN	16
5292 /*
5293  * sysctl handler for numa_zonelist_order
5294  */
5295 static int numa_zonelist_order_handler(const struct ctl_table *table, int write,
5296 		void *buffer, size_t *length, loff_t *ppos)
5297 {
5298 	if (write)
5299 		return __parse_numa_zonelist_order(buffer);
5300 	return proc_dostring(table, write, buffer, length, ppos);
5301 }
5302 
5303 static int node_load[MAX_NUMNODES];
5304 
5305 /**
5306  * find_next_best_node - find the next node that should appear in a given node's fallback list
5307  * @node: node whose fallback list we're appending
5308  * @used_node_mask: nodemask_t of already used nodes
5309  *
5310  * We use a number of factors to determine which is the next node that should
5311  * appear on a given node's fallback list.  The node should not have appeared
5312  * already in @node's fallback list, and it should be the next closest node
5313  * according to the distance array (which contains arbitrary distance values
5314  * from each node to each node in the system), and should also prefer nodes
5315  * with no CPUs, since presumably they'll have very little allocation pressure
5316  * on them otherwise.
5317  *
5318  * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
5319  */
5320 int find_next_best_node(int node, nodemask_t *used_node_mask)
5321 {
5322 	int n, val;
5323 	int min_val = INT_MAX;
5324 	int best_node = NUMA_NO_NODE;
5325 
5326 	/*
5327 	 * Use the local node if we haven't already, but for memoryless local
5328 	 * node, we should skip it and fall back to other nodes.
5329 	 */
5330 	if (!node_isset(node, *used_node_mask) && node_state(node, N_MEMORY)) {
5331 		node_set(node, *used_node_mask);
5332 		return node;
5333 	}
5334 
5335 	for_each_node_state(n, N_MEMORY) {
5336 
5337 		/* Don't want a node to appear more than once */
5338 		if (node_isset(n, *used_node_mask))
5339 			continue;
5340 
5341 		/* Use the distance array to find the distance */
5342 		val = node_distance(node, n);
5343 
5344 		/* Penalize nodes under us ("prefer the next node") */
5345 		val += (n < node);
5346 
5347 		/* Give preference to headless and unused nodes */
5348 		if (!cpumask_empty(cpumask_of_node(n)))
5349 			val += PENALTY_FOR_NODE_WITH_CPUS;
5350 
5351 		/* Slight preference for less loaded node */
5352 		val *= MAX_NUMNODES;
5353 		val += node_load[n];
5354 
5355 		if (val < min_val) {
5356 			min_val = val;
5357 			best_node = n;
5358 		}
5359 	}
5360 
5361 	if (best_node >= 0)
5362 		node_set(best_node, *used_node_mask);
5363 
5364 	return best_node;
5365 }
5366 
5367 
5368 /*
5369  * Build zonelists ordered by node and zones within node.
5370  * This results in maximum locality--normal zone overflows into local
5371  * DMA zone, if any--but risks exhausting DMA zone.
5372  */
5373 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
5374 		unsigned nr_nodes)
5375 {
5376 	struct zoneref *zonerefs;
5377 	int i;
5378 
5379 	zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5380 
5381 	for (i = 0; i < nr_nodes; i++) {
5382 		int nr_zones;
5383 
5384 		pg_data_t *node = NODE_DATA(node_order[i]);
5385 
5386 		nr_zones = build_zonerefs_node(node, zonerefs);
5387 		zonerefs += nr_zones;
5388 	}
5389 	zonerefs->zone = NULL;
5390 	zonerefs->zone_idx = 0;
5391 }
5392 
5393 /*
5394  * Build __GFP_THISNODE zonelists
5395  */
5396 static void build_thisnode_zonelists(pg_data_t *pgdat)
5397 {
5398 	struct zoneref *zonerefs;
5399 	int nr_zones;
5400 
5401 	zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
5402 	nr_zones = build_zonerefs_node(pgdat, zonerefs);
5403 	zonerefs += nr_zones;
5404 	zonerefs->zone = NULL;
5405 	zonerefs->zone_idx = 0;
5406 }
5407 
5408 static void build_zonelists(pg_data_t *pgdat)
5409 {
5410 	static int node_order[MAX_NUMNODES];
5411 	int node, nr_nodes = 0;
5412 	nodemask_t used_mask = NODE_MASK_NONE;
5413 	int local_node, prev_node;
5414 
5415 	/* NUMA-aware ordering of nodes */
5416 	local_node = pgdat->node_id;
5417 	prev_node = local_node;
5418 
5419 	memset(node_order, 0, sizeof(node_order));
5420 	while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
5421 		/*
5422 		 * We don't want to pressure a particular node.
5423 		 * So adding penalty to the first node in same
5424 		 * distance group to make it round-robin.
5425 		 */
5426 		if (node_distance(local_node, node) !=
5427 		    node_distance(local_node, prev_node))
5428 			node_load[node] += 1;
5429 
5430 		node_order[nr_nodes++] = node;
5431 		prev_node = node;
5432 	}
5433 
5434 	build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
5435 	build_thisnode_zonelists(pgdat);
5436 	pr_info("Fallback order for Node %d: ", local_node);
5437 	for (node = 0; node < nr_nodes; node++)
5438 		pr_cont("%d ", node_order[node]);
5439 	pr_cont("\n");
5440 }
5441 
5442 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5443 /*
5444  * Return node id of node used for "local" allocations.
5445  * I.e., first node id of first zone in arg node's generic zonelist.
5446  * Used for initializing percpu 'numa_mem', which is used primarily
5447  * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
5448  */
5449 int local_memory_node(int node)
5450 {
5451 	struct zoneref *z;
5452 
5453 	z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
5454 				   gfp_zone(GFP_KERNEL),
5455 				   NULL);
5456 	return zonelist_node_idx(z);
5457 }
5458 #endif
5459 
5460 static void setup_min_unmapped_ratio(void);
5461 static void setup_min_slab_ratio(void);
5462 #else	/* CONFIG_NUMA */
5463 
5464 static void build_zonelists(pg_data_t *pgdat)
5465 {
5466 	struct zoneref *zonerefs;
5467 	int nr_zones;
5468 
5469 	zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5470 	nr_zones = build_zonerefs_node(pgdat, zonerefs);
5471 	zonerefs += nr_zones;
5472 
5473 	zonerefs->zone = NULL;
5474 	zonerefs->zone_idx = 0;
5475 }
5476 
5477 #endif	/* CONFIG_NUMA */
5478 
5479 /*
5480  * Boot pageset table. One per cpu which is going to be used for all
5481  * zones and all nodes. The parameters will be set in such a way
5482  * that an item put on a list will immediately be handed over to
5483  * the buddy list. This is safe since pageset manipulation is done
5484  * with interrupts disabled.
5485  *
5486  * The boot_pagesets must be kept even after bootup is complete for
5487  * unused processors and/or zones. They do play a role for bootstrapping
5488  * hotplugged processors.
5489  *
5490  * zoneinfo_show() and maybe other functions do
5491  * not check if the processor is online before following the pageset pointer.
5492  * Other parts of the kernel may not check if the zone is available.
5493  */
5494 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats);
5495 /* These effectively disable the pcplists in the boot pageset completely */
5496 #define BOOT_PAGESET_HIGH	0
5497 #define BOOT_PAGESET_BATCH	1
5498 static DEFINE_PER_CPU(struct per_cpu_pages, boot_pageset);
5499 static DEFINE_PER_CPU(struct per_cpu_zonestat, boot_zonestats);
5500 
5501 static void __build_all_zonelists(void *data)
5502 {
5503 	int nid;
5504 	int __maybe_unused cpu;
5505 	pg_data_t *self = data;
5506 	unsigned long flags;
5507 
5508 	/*
5509 	 * The zonelist_update_seq must be acquired with irqsave because the
5510 	 * reader can be invoked from IRQ with GFP_ATOMIC.
5511 	 */
5512 	write_seqlock_irqsave(&zonelist_update_seq, flags);
5513 	/*
5514 	 * Also disable synchronous printk() to prevent any printk() from
5515 	 * trying to hold port->lock, for
5516 	 * tty_insert_flip_string_and_push_buffer() on other CPU might be
5517 	 * calling kmalloc(GFP_ATOMIC | __GFP_NOWARN) with port->lock held.
5518 	 */
5519 	printk_deferred_enter();
5520 
5521 #ifdef CONFIG_NUMA
5522 	memset(node_load, 0, sizeof(node_load));
5523 #endif
5524 
5525 	/*
5526 	 * This node is hotadded and no memory is yet present.   So just
5527 	 * building zonelists is fine - no need to touch other nodes.
5528 	 */
5529 	if (self && !node_online(self->node_id)) {
5530 		build_zonelists(self);
5531 	} else {
5532 		/*
5533 		 * All possible nodes have pgdat preallocated
5534 		 * in free_area_init
5535 		 */
5536 		for_each_node(nid) {
5537 			pg_data_t *pgdat = NODE_DATA(nid);
5538 
5539 			build_zonelists(pgdat);
5540 		}
5541 
5542 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5543 		/*
5544 		 * We now know the "local memory node" for each node--
5545 		 * i.e., the node of the first zone in the generic zonelist.
5546 		 * Set up numa_mem percpu variable for on-line cpus.  During
5547 		 * boot, only the boot cpu should be on-line;  we'll init the
5548 		 * secondary cpus' numa_mem as they come on-line.  During
5549 		 * node/memory hotplug, we'll fixup all on-line cpus.
5550 		 */
5551 		for_each_online_cpu(cpu)
5552 			set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
5553 #endif
5554 	}
5555 
5556 	printk_deferred_exit();
5557 	write_sequnlock_irqrestore(&zonelist_update_seq, flags);
5558 }
5559 
5560 static noinline void __init
5561 build_all_zonelists_init(void)
5562 {
5563 	int cpu;
5564 
5565 	__build_all_zonelists(NULL);
5566 
5567 	/*
5568 	 * Initialize the boot_pagesets that are going to be used
5569 	 * for bootstrapping processors. The real pagesets for
5570 	 * each zone will be allocated later when the per cpu
5571 	 * allocator is available.
5572 	 *
5573 	 * boot_pagesets are used also for bootstrapping offline
5574 	 * cpus if the system is already booted because the pagesets
5575 	 * are needed to initialize allocators on a specific cpu too.
5576 	 * F.e. the percpu allocator needs the page allocator which
5577 	 * needs the percpu allocator in order to allocate its pagesets
5578 	 * (a chicken-egg dilemma).
5579 	 */
5580 	for_each_possible_cpu(cpu)
5581 		per_cpu_pages_init(&per_cpu(boot_pageset, cpu), &per_cpu(boot_zonestats, cpu));
5582 
5583 	mminit_verify_zonelist();
5584 	cpuset_init_current_mems_allowed();
5585 }
5586 
5587 /*
5588  * unless system_state == SYSTEM_BOOTING.
5589  *
5590  * __ref due to call of __init annotated helper build_all_zonelists_init
5591  * [protected by SYSTEM_BOOTING].
5592  */
5593 void __ref build_all_zonelists(pg_data_t *pgdat)
5594 {
5595 	unsigned long vm_total_pages;
5596 
5597 	if (system_state == SYSTEM_BOOTING) {
5598 		build_all_zonelists_init();
5599 	} else {
5600 		__build_all_zonelists(pgdat);
5601 		/* cpuset refresh routine should be here */
5602 	}
5603 	/* Get the number of free pages beyond high watermark in all zones. */
5604 	vm_total_pages = nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
5605 	/*
5606 	 * Disable grouping by mobility if the number of pages in the
5607 	 * system is too low to allow the mechanism to work. It would be
5608 	 * more accurate, but expensive to check per-zone. This check is
5609 	 * made on memory-hotadd so a system can start with mobility
5610 	 * disabled and enable it later
5611 	 */
5612 	if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
5613 		page_group_by_mobility_disabled = 1;
5614 	else
5615 		page_group_by_mobility_disabled = 0;
5616 
5617 	pr_info("Built %u zonelists, mobility grouping %s.  Total pages: %ld\n",
5618 		nr_online_nodes,
5619 		str_off_on(page_group_by_mobility_disabled),
5620 		vm_total_pages);
5621 #ifdef CONFIG_NUMA
5622 	pr_info("Policy zone: %s\n", zone_names[policy_zone]);
5623 #endif
5624 }
5625 
5626 static int zone_batchsize(struct zone *zone)
5627 {
5628 #ifdef CONFIG_MMU
5629 	int batch;
5630 
5631 	/*
5632 	 * The number of pages to batch allocate is either ~0.1%
5633 	 * of the zone or 1MB, whichever is smaller. The batch
5634 	 * size is striking a balance between allocation latency
5635 	 * and zone lock contention.
5636 	 */
5637 	batch = min(zone_managed_pages(zone) >> 10, SZ_1M / PAGE_SIZE);
5638 	batch /= 4;		/* We effectively *= 4 below */
5639 	if (batch < 1)
5640 		batch = 1;
5641 
5642 	/*
5643 	 * Clamp the batch to a 2^n - 1 value. Having a power
5644 	 * of 2 value was found to be more likely to have
5645 	 * suboptimal cache aliasing properties in some cases.
5646 	 *
5647 	 * For example if 2 tasks are alternately allocating
5648 	 * batches of pages, one task can end up with a lot
5649 	 * of pages of one half of the possible page colors
5650 	 * and the other with pages of the other colors.
5651 	 */
5652 	batch = rounddown_pow_of_two(batch + batch/2) - 1;
5653 
5654 	return batch;
5655 
5656 #else
5657 	/* The deferral and batching of frees should be suppressed under NOMMU
5658 	 * conditions.
5659 	 *
5660 	 * The problem is that NOMMU needs to be able to allocate large chunks
5661 	 * of contiguous memory as there's no hardware page translation to
5662 	 * assemble apparent contiguous memory from discontiguous pages.
5663 	 *
5664 	 * Queueing large contiguous runs of pages for batching, however,
5665 	 * causes the pages to actually be freed in smaller chunks.  As there
5666 	 * can be a significant delay between the individual batches being
5667 	 * recycled, this leads to the once large chunks of space being
5668 	 * fragmented and becoming unavailable for high-order allocations.
5669 	 */
5670 	return 0;
5671 #endif
5672 }
5673 
5674 static int percpu_pagelist_high_fraction;
5675 static int zone_highsize(struct zone *zone, int batch, int cpu_online,
5676 			 int high_fraction)
5677 {
5678 #ifdef CONFIG_MMU
5679 	int high;
5680 	int nr_split_cpus;
5681 	unsigned long total_pages;
5682 
5683 	if (!high_fraction) {
5684 		/*
5685 		 * By default, the high value of the pcp is based on the zone
5686 		 * low watermark so that if they are full then background
5687 		 * reclaim will not be started prematurely.
5688 		 */
5689 		total_pages = low_wmark_pages(zone);
5690 	} else {
5691 		/*
5692 		 * If percpu_pagelist_high_fraction is configured, the high
5693 		 * value is based on a fraction of the managed pages in the
5694 		 * zone.
5695 		 */
5696 		total_pages = zone_managed_pages(zone) / high_fraction;
5697 	}
5698 
5699 	/*
5700 	 * Split the high value across all online CPUs local to the zone. Note
5701 	 * that early in boot that CPUs may not be online yet and that during
5702 	 * CPU hotplug that the cpumask is not yet updated when a CPU is being
5703 	 * onlined. For memory nodes that have no CPUs, split the high value
5704 	 * across all online CPUs to mitigate the risk that reclaim is triggered
5705 	 * prematurely due to pages stored on pcp lists.
5706 	 */
5707 	nr_split_cpus = cpumask_weight(cpumask_of_node(zone_to_nid(zone))) + cpu_online;
5708 	if (!nr_split_cpus)
5709 		nr_split_cpus = num_online_cpus();
5710 	high = total_pages / nr_split_cpus;
5711 
5712 	/*
5713 	 * Ensure high is at least batch*4. The multiple is based on the
5714 	 * historical relationship between high and batch.
5715 	 */
5716 	high = max(high, batch << 2);
5717 
5718 	return high;
5719 #else
5720 	return 0;
5721 #endif
5722 }
5723 
5724 /*
5725  * pcp->high and pcp->batch values are related and generally batch is lower
5726  * than high. They are also related to pcp->count such that count is lower
5727  * than high, and as soon as it reaches high, the pcplist is flushed.
5728  *
5729  * However, guaranteeing these relations at all times would require e.g. write
5730  * barriers here but also careful usage of read barriers at the read side, and
5731  * thus be prone to error and bad for performance. Thus the update only prevents
5732  * store tearing. Any new users of pcp->batch, pcp->high_min and pcp->high_max
5733  * should ensure they can cope with those fields changing asynchronously, and
5734  * fully trust only the pcp->count field on the local CPU with interrupts
5735  * disabled.
5736  *
5737  * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
5738  * outside of boot time (or some other assurance that no concurrent updaters
5739  * exist).
5740  */
5741 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high_min,
5742 			   unsigned long high_max, unsigned long batch)
5743 {
5744 	WRITE_ONCE(pcp->batch, batch);
5745 	WRITE_ONCE(pcp->high_min, high_min);
5746 	WRITE_ONCE(pcp->high_max, high_max);
5747 }
5748 
5749 static void per_cpu_pages_init(struct per_cpu_pages *pcp, struct per_cpu_zonestat *pzstats)
5750 {
5751 	int pindex;
5752 
5753 	memset(pcp, 0, sizeof(*pcp));
5754 	memset(pzstats, 0, sizeof(*pzstats));
5755 
5756 	spin_lock_init(&pcp->lock);
5757 	for (pindex = 0; pindex < NR_PCP_LISTS; pindex++)
5758 		INIT_LIST_HEAD(&pcp->lists[pindex]);
5759 
5760 	/*
5761 	 * Set batch and high values safe for a boot pageset. A true percpu
5762 	 * pageset's initialization will update them subsequently. Here we don't
5763 	 * need to be as careful as pageset_update() as nobody can access the
5764 	 * pageset yet.
5765 	 */
5766 	pcp->high_min = BOOT_PAGESET_HIGH;
5767 	pcp->high_max = BOOT_PAGESET_HIGH;
5768 	pcp->batch = BOOT_PAGESET_BATCH;
5769 	pcp->free_count = 0;
5770 }
5771 
5772 static void __zone_set_pageset_high_and_batch(struct zone *zone, unsigned long high_min,
5773 					      unsigned long high_max, unsigned long batch)
5774 {
5775 	struct per_cpu_pages *pcp;
5776 	int cpu;
5777 
5778 	for_each_possible_cpu(cpu) {
5779 		pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
5780 		pageset_update(pcp, high_min, high_max, batch);
5781 	}
5782 }
5783 
5784 /*
5785  * Calculate and set new high and batch values for all per-cpu pagesets of a
5786  * zone based on the zone's size.
5787  */
5788 static void zone_set_pageset_high_and_batch(struct zone *zone, int cpu_online)
5789 {
5790 	int new_high_min, new_high_max, new_batch;
5791 
5792 	new_batch = max(1, zone_batchsize(zone));
5793 	if (percpu_pagelist_high_fraction) {
5794 		new_high_min = zone_highsize(zone, new_batch, cpu_online,
5795 					     percpu_pagelist_high_fraction);
5796 		/*
5797 		 * PCP high is tuned manually, disable auto-tuning via
5798 		 * setting high_min and high_max to the manual value.
5799 		 */
5800 		new_high_max = new_high_min;
5801 	} else {
5802 		new_high_min = zone_highsize(zone, new_batch, cpu_online, 0);
5803 		new_high_max = zone_highsize(zone, new_batch, cpu_online,
5804 					     MIN_PERCPU_PAGELIST_HIGH_FRACTION);
5805 	}
5806 
5807 	if (zone->pageset_high_min == new_high_min &&
5808 	    zone->pageset_high_max == new_high_max &&
5809 	    zone->pageset_batch == new_batch)
5810 		return;
5811 
5812 	zone->pageset_high_min = new_high_min;
5813 	zone->pageset_high_max = new_high_max;
5814 	zone->pageset_batch = new_batch;
5815 
5816 	__zone_set_pageset_high_and_batch(zone, new_high_min, new_high_max,
5817 					  new_batch);
5818 }
5819 
5820 void __meminit setup_zone_pageset(struct zone *zone)
5821 {
5822 	int cpu;
5823 
5824 	/* Size may be 0 on !SMP && !NUMA */
5825 	if (sizeof(struct per_cpu_zonestat) > 0)
5826 		zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat);
5827 
5828 	zone->per_cpu_pageset = alloc_percpu(struct per_cpu_pages);
5829 	for_each_possible_cpu(cpu) {
5830 		struct per_cpu_pages *pcp;
5831 		struct per_cpu_zonestat *pzstats;
5832 
5833 		pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
5834 		pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
5835 		per_cpu_pages_init(pcp, pzstats);
5836 	}
5837 
5838 	zone_set_pageset_high_and_batch(zone, 0);
5839 }
5840 
5841 /*
5842  * The zone indicated has a new number of managed_pages; batch sizes and percpu
5843  * page high values need to be recalculated.
5844  */
5845 static void zone_pcp_update(struct zone *zone, int cpu_online)
5846 {
5847 	mutex_lock(&pcp_batch_high_lock);
5848 	zone_set_pageset_high_and_batch(zone, cpu_online);
5849 	mutex_unlock(&pcp_batch_high_lock);
5850 }
5851 
5852 static void zone_pcp_update_cacheinfo(struct zone *zone, unsigned int cpu)
5853 {
5854 	struct per_cpu_pages *pcp;
5855 	struct cpu_cacheinfo *cci;
5856 
5857 	pcp = per_cpu_ptr(zone->per_cpu_pageset, cpu);
5858 	cci = get_cpu_cacheinfo(cpu);
5859 	/*
5860 	 * If data cache slice of CPU is large enough, "pcp->batch"
5861 	 * pages can be preserved in PCP before draining PCP for
5862 	 * consecutive high-order pages freeing without allocation.
5863 	 * This can reduce zone lock contention without hurting
5864 	 * cache-hot pages sharing.
5865 	 */
5866 	spin_lock(&pcp->lock);
5867 	if ((cci->per_cpu_data_slice_size >> PAGE_SHIFT) > 3 * pcp->batch)
5868 		pcp->flags |= PCPF_FREE_HIGH_BATCH;
5869 	else
5870 		pcp->flags &= ~PCPF_FREE_HIGH_BATCH;
5871 	spin_unlock(&pcp->lock);
5872 }
5873 
5874 void setup_pcp_cacheinfo(unsigned int cpu)
5875 {
5876 	struct zone *zone;
5877 
5878 	for_each_populated_zone(zone)
5879 		zone_pcp_update_cacheinfo(zone, cpu);
5880 }
5881 
5882 /*
5883  * Allocate per cpu pagesets and initialize them.
5884  * Before this call only boot pagesets were available.
5885  */
5886 void __init setup_per_cpu_pageset(void)
5887 {
5888 	struct pglist_data *pgdat;
5889 	struct zone *zone;
5890 	int __maybe_unused cpu;
5891 
5892 	for_each_populated_zone(zone)
5893 		setup_zone_pageset(zone);
5894 
5895 #ifdef CONFIG_NUMA
5896 	/*
5897 	 * Unpopulated zones continue using the boot pagesets.
5898 	 * The numa stats for these pagesets need to be reset.
5899 	 * Otherwise, they will end up skewing the stats of
5900 	 * the nodes these zones are associated with.
5901 	 */
5902 	for_each_possible_cpu(cpu) {
5903 		struct per_cpu_zonestat *pzstats = &per_cpu(boot_zonestats, cpu);
5904 		memset(pzstats->vm_numa_event, 0,
5905 		       sizeof(pzstats->vm_numa_event));
5906 	}
5907 #endif
5908 
5909 	for_each_online_pgdat(pgdat)
5910 		pgdat->per_cpu_nodestats =
5911 			alloc_percpu(struct per_cpu_nodestat);
5912 }
5913 
5914 __meminit void zone_pcp_init(struct zone *zone)
5915 {
5916 	/*
5917 	 * per cpu subsystem is not up at this point. The following code
5918 	 * relies on the ability of the linker to provide the
5919 	 * offset of a (static) per cpu variable into the per cpu area.
5920 	 */
5921 	zone->per_cpu_pageset = &boot_pageset;
5922 	zone->per_cpu_zonestats = &boot_zonestats;
5923 	zone->pageset_high_min = BOOT_PAGESET_HIGH;
5924 	zone->pageset_high_max = BOOT_PAGESET_HIGH;
5925 	zone->pageset_batch = BOOT_PAGESET_BATCH;
5926 
5927 	if (populated_zone(zone))
5928 		pr_debug("  %s zone: %lu pages, LIFO batch:%u\n", zone->name,
5929 			 zone->present_pages, zone_batchsize(zone));
5930 }
5931 
5932 static void setup_per_zone_lowmem_reserve(void);
5933 
5934 void adjust_managed_page_count(struct page *page, long count)
5935 {
5936 	atomic_long_add(count, &page_zone(page)->managed_pages);
5937 	totalram_pages_add(count);
5938 	setup_per_zone_lowmem_reserve();
5939 }
5940 EXPORT_SYMBOL(adjust_managed_page_count);
5941 
5942 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
5943 {
5944 	void *pos;
5945 	unsigned long pages = 0;
5946 
5947 	start = (void *)PAGE_ALIGN((unsigned long)start);
5948 	end = (void *)((unsigned long)end & PAGE_MASK);
5949 	for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
5950 		struct page *page = virt_to_page(pos);
5951 		void *direct_map_addr;
5952 
5953 		/*
5954 		 * 'direct_map_addr' might be different from 'pos'
5955 		 * because some architectures' virt_to_page()
5956 		 * work with aliases.  Getting the direct map
5957 		 * address ensures that we get a _writeable_
5958 		 * alias for the memset().
5959 		 */
5960 		direct_map_addr = page_address(page);
5961 		/*
5962 		 * Perform a kasan-unchecked memset() since this memory
5963 		 * has not been initialized.
5964 		 */
5965 		direct_map_addr = kasan_reset_tag(direct_map_addr);
5966 		if ((unsigned int)poison <= 0xFF)
5967 			memset(direct_map_addr, poison, PAGE_SIZE);
5968 
5969 		free_reserved_page(page);
5970 	}
5971 
5972 	if (pages && s)
5973 		pr_info("Freeing %s memory: %ldK\n", s, K(pages));
5974 
5975 	return pages;
5976 }
5977 
5978 void free_reserved_page(struct page *page)
5979 {
5980 	clear_page_tag_ref(page);
5981 	ClearPageReserved(page);
5982 	init_page_count(page);
5983 	__free_page(page);
5984 	adjust_managed_page_count(page, 1);
5985 }
5986 EXPORT_SYMBOL(free_reserved_page);
5987 
5988 static int page_alloc_cpu_dead(unsigned int cpu)
5989 {
5990 	struct zone *zone;
5991 
5992 	lru_add_drain_cpu(cpu);
5993 	mlock_drain_remote(cpu);
5994 	drain_pages(cpu);
5995 
5996 	/*
5997 	 * Spill the event counters of the dead processor
5998 	 * into the current processors event counters.
5999 	 * This artificially elevates the count of the current
6000 	 * processor.
6001 	 */
6002 	vm_events_fold_cpu(cpu);
6003 
6004 	/*
6005 	 * Zero the differential counters of the dead processor
6006 	 * so that the vm statistics are consistent.
6007 	 *
6008 	 * This is only okay since the processor is dead and cannot
6009 	 * race with what we are doing.
6010 	 */
6011 	cpu_vm_stats_fold(cpu);
6012 
6013 	for_each_populated_zone(zone)
6014 		zone_pcp_update(zone, 0);
6015 
6016 	return 0;
6017 }
6018 
6019 static int page_alloc_cpu_online(unsigned int cpu)
6020 {
6021 	struct zone *zone;
6022 
6023 	for_each_populated_zone(zone)
6024 		zone_pcp_update(zone, 1);
6025 	return 0;
6026 }
6027 
6028 void __init page_alloc_init_cpuhp(void)
6029 {
6030 	int ret;
6031 
6032 	ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC,
6033 					"mm/page_alloc:pcp",
6034 					page_alloc_cpu_online,
6035 					page_alloc_cpu_dead);
6036 	WARN_ON(ret < 0);
6037 }
6038 
6039 /*
6040  * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
6041  *	or min_free_kbytes changes.
6042  */
6043 static void calculate_totalreserve_pages(void)
6044 {
6045 	struct pglist_data *pgdat;
6046 	unsigned long reserve_pages = 0;
6047 	enum zone_type i, j;
6048 
6049 	for_each_online_pgdat(pgdat) {
6050 
6051 		pgdat->totalreserve_pages = 0;
6052 
6053 		for (i = 0; i < MAX_NR_ZONES; i++) {
6054 			struct zone *zone = pgdat->node_zones + i;
6055 			long max = 0;
6056 			unsigned long managed_pages = zone_managed_pages(zone);
6057 
6058 			/* Find valid and maximum lowmem_reserve in the zone */
6059 			for (j = i; j < MAX_NR_ZONES; j++) {
6060 				if (zone->lowmem_reserve[j] > max)
6061 					max = zone->lowmem_reserve[j];
6062 			}
6063 
6064 			/* we treat the high watermark as reserved pages. */
6065 			max += high_wmark_pages(zone);
6066 
6067 			if (max > managed_pages)
6068 				max = managed_pages;
6069 
6070 			pgdat->totalreserve_pages += max;
6071 
6072 			reserve_pages += max;
6073 		}
6074 	}
6075 	totalreserve_pages = reserve_pages;
6076 	trace_mm_calculate_totalreserve_pages(totalreserve_pages);
6077 }
6078 
6079 /*
6080  * setup_per_zone_lowmem_reserve - called whenever
6081  *	sysctl_lowmem_reserve_ratio changes.  Ensures that each zone
6082  *	has a correct pages reserved value, so an adequate number of
6083  *	pages are left in the zone after a successful __alloc_pages().
6084  */
6085 static void setup_per_zone_lowmem_reserve(void)
6086 {
6087 	struct pglist_data *pgdat;
6088 	enum zone_type i, j;
6089 
6090 	for_each_online_pgdat(pgdat) {
6091 		for (i = 0; i < MAX_NR_ZONES - 1; i++) {
6092 			struct zone *zone = &pgdat->node_zones[i];
6093 			int ratio = sysctl_lowmem_reserve_ratio[i];
6094 			bool clear = !ratio || !zone_managed_pages(zone);
6095 			unsigned long managed_pages = 0;
6096 
6097 			for (j = i + 1; j < MAX_NR_ZONES; j++) {
6098 				struct zone *upper_zone = &pgdat->node_zones[j];
6099 
6100 				managed_pages += zone_managed_pages(upper_zone);
6101 
6102 				if (clear)
6103 					zone->lowmem_reserve[j] = 0;
6104 				else
6105 					zone->lowmem_reserve[j] = managed_pages / ratio;
6106 				trace_mm_setup_per_zone_lowmem_reserve(zone, upper_zone,
6107 								       zone->lowmem_reserve[j]);
6108 			}
6109 		}
6110 	}
6111 
6112 	/* update totalreserve_pages */
6113 	calculate_totalreserve_pages();
6114 }
6115 
6116 static void __setup_per_zone_wmarks(void)
6117 {
6118 	unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
6119 	unsigned long lowmem_pages = 0;
6120 	struct zone *zone;
6121 	unsigned long flags;
6122 
6123 	/* Calculate total number of !ZONE_HIGHMEM and !ZONE_MOVABLE pages */
6124 	for_each_zone(zone) {
6125 		if (!is_highmem(zone) && zone_idx(zone) != ZONE_MOVABLE)
6126 			lowmem_pages += zone_managed_pages(zone);
6127 	}
6128 
6129 	for_each_zone(zone) {
6130 		u64 tmp;
6131 
6132 		spin_lock_irqsave(&zone->lock, flags);
6133 		tmp = (u64)pages_min * zone_managed_pages(zone);
6134 		tmp = div64_ul(tmp, lowmem_pages);
6135 		if (is_highmem(zone) || zone_idx(zone) == ZONE_MOVABLE) {
6136 			/*
6137 			 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
6138 			 * need highmem and movable zones pages, so cap pages_min
6139 			 * to a small  value here.
6140 			 *
6141 			 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
6142 			 * deltas control async page reclaim, and so should
6143 			 * not be capped for highmem and movable zones.
6144 			 */
6145 			unsigned long min_pages;
6146 
6147 			min_pages = zone_managed_pages(zone) / 1024;
6148 			min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
6149 			zone->_watermark[WMARK_MIN] = min_pages;
6150 		} else {
6151 			/*
6152 			 * If it's a lowmem zone, reserve a number of pages
6153 			 * proportionate to the zone's size.
6154 			 */
6155 			zone->_watermark[WMARK_MIN] = tmp;
6156 		}
6157 
6158 		/*
6159 		 * Set the kswapd watermarks distance according to the
6160 		 * scale factor in proportion to available memory, but
6161 		 * ensure a minimum size on small systems.
6162 		 */
6163 		tmp = max_t(u64, tmp >> 2,
6164 			    mult_frac(zone_managed_pages(zone),
6165 				      watermark_scale_factor, 10000));
6166 
6167 		zone->watermark_boost = 0;
6168 		zone->_watermark[WMARK_LOW]  = min_wmark_pages(zone) + tmp;
6169 		zone->_watermark[WMARK_HIGH] = low_wmark_pages(zone) + tmp;
6170 		zone->_watermark[WMARK_PROMO] = high_wmark_pages(zone) + tmp;
6171 		trace_mm_setup_per_zone_wmarks(zone);
6172 
6173 		spin_unlock_irqrestore(&zone->lock, flags);
6174 	}
6175 
6176 	/* update totalreserve_pages */
6177 	calculate_totalreserve_pages();
6178 }
6179 
6180 /**
6181  * setup_per_zone_wmarks - called when min_free_kbytes changes
6182  * or when memory is hot-{added|removed}
6183  *
6184  * Ensures that the watermark[min,low,high] values for each zone are set
6185  * correctly with respect to min_free_kbytes.
6186  */
6187 void setup_per_zone_wmarks(void)
6188 {
6189 	struct zone *zone;
6190 	static DEFINE_SPINLOCK(lock);
6191 
6192 	spin_lock(&lock);
6193 	__setup_per_zone_wmarks();
6194 	spin_unlock(&lock);
6195 
6196 	/*
6197 	 * The watermark size have changed so update the pcpu batch
6198 	 * and high limits or the limits may be inappropriate.
6199 	 */
6200 	for_each_zone(zone)
6201 		zone_pcp_update(zone, 0);
6202 }
6203 
6204 /*
6205  * Initialise min_free_kbytes.
6206  *
6207  * For small machines we want it small (128k min).  For large machines
6208  * we want it large (256MB max).  But it is not linear, because network
6209  * bandwidth does not increase linearly with machine size.  We use
6210  *
6211  *	min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
6212  *	min_free_kbytes = sqrt(lowmem_kbytes * 16)
6213  *
6214  * which yields
6215  *
6216  * 16MB:	512k
6217  * 32MB:	724k
6218  * 64MB:	1024k
6219  * 128MB:	1448k
6220  * 256MB:	2048k
6221  * 512MB:	2896k
6222  * 1024MB:	4096k
6223  * 2048MB:	5792k
6224  * 4096MB:	8192k
6225  * 8192MB:	11584k
6226  * 16384MB:	16384k
6227  */
6228 void calculate_min_free_kbytes(void)
6229 {
6230 	unsigned long lowmem_kbytes;
6231 	int new_min_free_kbytes;
6232 
6233 	lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
6234 	new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
6235 
6236 	if (new_min_free_kbytes > user_min_free_kbytes)
6237 		min_free_kbytes = clamp(new_min_free_kbytes, 128, 262144);
6238 	else
6239 		pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
6240 				new_min_free_kbytes, user_min_free_kbytes);
6241 
6242 }
6243 
6244 int __meminit init_per_zone_wmark_min(void)
6245 {
6246 	calculate_min_free_kbytes();
6247 	setup_per_zone_wmarks();
6248 	refresh_zone_stat_thresholds();
6249 	setup_per_zone_lowmem_reserve();
6250 
6251 #ifdef CONFIG_NUMA
6252 	setup_min_unmapped_ratio();
6253 	setup_min_slab_ratio();
6254 #endif
6255 
6256 	khugepaged_min_free_kbytes_update();
6257 
6258 	return 0;
6259 }
6260 postcore_initcall(init_per_zone_wmark_min)
6261 
6262 /*
6263  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
6264  *	that we can call two helper functions whenever min_free_kbytes
6265  *	changes.
6266  */
6267 static int min_free_kbytes_sysctl_handler(const struct ctl_table *table, int write,
6268 		void *buffer, size_t *length, loff_t *ppos)
6269 {
6270 	int rc;
6271 
6272 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6273 	if (rc)
6274 		return rc;
6275 
6276 	if (write) {
6277 		user_min_free_kbytes = min_free_kbytes;
6278 		setup_per_zone_wmarks();
6279 	}
6280 	return 0;
6281 }
6282 
6283 static int watermark_scale_factor_sysctl_handler(const struct ctl_table *table, int write,
6284 		void *buffer, size_t *length, loff_t *ppos)
6285 {
6286 	int rc;
6287 
6288 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6289 	if (rc)
6290 		return rc;
6291 
6292 	if (write)
6293 		setup_per_zone_wmarks();
6294 
6295 	return 0;
6296 }
6297 
6298 #ifdef CONFIG_NUMA
6299 static void setup_min_unmapped_ratio(void)
6300 {
6301 	pg_data_t *pgdat;
6302 	struct zone *zone;
6303 
6304 	for_each_online_pgdat(pgdat)
6305 		pgdat->min_unmapped_pages = 0;
6306 
6307 	for_each_zone(zone)
6308 		zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
6309 						         sysctl_min_unmapped_ratio) / 100;
6310 }
6311 
6312 
6313 static int sysctl_min_unmapped_ratio_sysctl_handler(const struct ctl_table *table, int write,
6314 		void *buffer, size_t *length, loff_t *ppos)
6315 {
6316 	int rc;
6317 
6318 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6319 	if (rc)
6320 		return rc;
6321 
6322 	setup_min_unmapped_ratio();
6323 
6324 	return 0;
6325 }
6326 
6327 static void setup_min_slab_ratio(void)
6328 {
6329 	pg_data_t *pgdat;
6330 	struct zone *zone;
6331 
6332 	for_each_online_pgdat(pgdat)
6333 		pgdat->min_slab_pages = 0;
6334 
6335 	for_each_zone(zone)
6336 		zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
6337 						     sysctl_min_slab_ratio) / 100;
6338 }
6339 
6340 static int sysctl_min_slab_ratio_sysctl_handler(const struct ctl_table *table, int write,
6341 		void *buffer, size_t *length, loff_t *ppos)
6342 {
6343 	int rc;
6344 
6345 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
6346 	if (rc)
6347 		return rc;
6348 
6349 	setup_min_slab_ratio();
6350 
6351 	return 0;
6352 }
6353 #endif
6354 
6355 /*
6356  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
6357  *	proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
6358  *	whenever sysctl_lowmem_reserve_ratio changes.
6359  *
6360  * The reserve ratio obviously has absolutely no relation with the
6361  * minimum watermarks. The lowmem reserve ratio can only make sense
6362  * if in function of the boot time zone sizes.
6363  */
6364 static int lowmem_reserve_ratio_sysctl_handler(const struct ctl_table *table,
6365 		int write, void *buffer, size_t *length, loff_t *ppos)
6366 {
6367 	int i;
6368 
6369 	proc_dointvec_minmax(table, write, buffer, length, ppos);
6370 
6371 	for (i = 0; i < MAX_NR_ZONES; i++) {
6372 		if (sysctl_lowmem_reserve_ratio[i] < 1)
6373 			sysctl_lowmem_reserve_ratio[i] = 0;
6374 	}
6375 
6376 	setup_per_zone_lowmem_reserve();
6377 	return 0;
6378 }
6379 
6380 /*
6381  * percpu_pagelist_high_fraction - changes the pcp->high for each zone on each
6382  * cpu. It is the fraction of total pages in each zone that a hot per cpu
6383  * pagelist can have before it gets flushed back to buddy allocator.
6384  */
6385 static int percpu_pagelist_high_fraction_sysctl_handler(const struct ctl_table *table,
6386 		int write, void *buffer, size_t *length, loff_t *ppos)
6387 {
6388 	struct zone *zone;
6389 	int old_percpu_pagelist_high_fraction;
6390 	int ret;
6391 
6392 	mutex_lock(&pcp_batch_high_lock);
6393 	old_percpu_pagelist_high_fraction = percpu_pagelist_high_fraction;
6394 
6395 	ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
6396 	if (!write || ret < 0)
6397 		goto out;
6398 
6399 	/* Sanity checking to avoid pcp imbalance */
6400 	if (percpu_pagelist_high_fraction &&
6401 	    percpu_pagelist_high_fraction < MIN_PERCPU_PAGELIST_HIGH_FRACTION) {
6402 		percpu_pagelist_high_fraction = old_percpu_pagelist_high_fraction;
6403 		ret = -EINVAL;
6404 		goto out;
6405 	}
6406 
6407 	/* No change? */
6408 	if (percpu_pagelist_high_fraction == old_percpu_pagelist_high_fraction)
6409 		goto out;
6410 
6411 	for_each_populated_zone(zone)
6412 		zone_set_pageset_high_and_batch(zone, 0);
6413 out:
6414 	mutex_unlock(&pcp_batch_high_lock);
6415 	return ret;
6416 }
6417 
6418 static const struct ctl_table page_alloc_sysctl_table[] = {
6419 	{
6420 		.procname	= "min_free_kbytes",
6421 		.data		= &min_free_kbytes,
6422 		.maxlen		= sizeof(min_free_kbytes),
6423 		.mode		= 0644,
6424 		.proc_handler	= min_free_kbytes_sysctl_handler,
6425 		.extra1		= SYSCTL_ZERO,
6426 	},
6427 	{
6428 		.procname	= "watermark_boost_factor",
6429 		.data		= &watermark_boost_factor,
6430 		.maxlen		= sizeof(watermark_boost_factor),
6431 		.mode		= 0644,
6432 		.proc_handler	= proc_dointvec_minmax,
6433 		.extra1		= SYSCTL_ZERO,
6434 	},
6435 	{
6436 		.procname	= "watermark_scale_factor",
6437 		.data		= &watermark_scale_factor,
6438 		.maxlen		= sizeof(watermark_scale_factor),
6439 		.mode		= 0644,
6440 		.proc_handler	= watermark_scale_factor_sysctl_handler,
6441 		.extra1		= SYSCTL_ONE,
6442 		.extra2		= SYSCTL_THREE_THOUSAND,
6443 	},
6444 	{
6445 		.procname	= "defrag_mode",
6446 		.data		= &defrag_mode,
6447 		.maxlen		= sizeof(defrag_mode),
6448 		.mode		= 0644,
6449 		.proc_handler	= proc_dointvec_minmax,
6450 		.extra1		= SYSCTL_ZERO,
6451 		.extra2		= SYSCTL_ONE,
6452 	},
6453 	{
6454 		.procname	= "percpu_pagelist_high_fraction",
6455 		.data		= &percpu_pagelist_high_fraction,
6456 		.maxlen		= sizeof(percpu_pagelist_high_fraction),
6457 		.mode		= 0644,
6458 		.proc_handler	= percpu_pagelist_high_fraction_sysctl_handler,
6459 		.extra1		= SYSCTL_ZERO,
6460 	},
6461 	{
6462 		.procname	= "lowmem_reserve_ratio",
6463 		.data		= &sysctl_lowmem_reserve_ratio,
6464 		.maxlen		= sizeof(sysctl_lowmem_reserve_ratio),
6465 		.mode		= 0644,
6466 		.proc_handler	= lowmem_reserve_ratio_sysctl_handler,
6467 	},
6468 #ifdef CONFIG_NUMA
6469 	{
6470 		.procname	= "numa_zonelist_order",
6471 		.data		= &numa_zonelist_order,
6472 		.maxlen		= NUMA_ZONELIST_ORDER_LEN,
6473 		.mode		= 0644,
6474 		.proc_handler	= numa_zonelist_order_handler,
6475 	},
6476 	{
6477 		.procname	= "min_unmapped_ratio",
6478 		.data		= &sysctl_min_unmapped_ratio,
6479 		.maxlen		= sizeof(sysctl_min_unmapped_ratio),
6480 		.mode		= 0644,
6481 		.proc_handler	= sysctl_min_unmapped_ratio_sysctl_handler,
6482 		.extra1		= SYSCTL_ZERO,
6483 		.extra2		= SYSCTL_ONE_HUNDRED,
6484 	},
6485 	{
6486 		.procname	= "min_slab_ratio",
6487 		.data		= &sysctl_min_slab_ratio,
6488 		.maxlen		= sizeof(sysctl_min_slab_ratio),
6489 		.mode		= 0644,
6490 		.proc_handler	= sysctl_min_slab_ratio_sysctl_handler,
6491 		.extra1		= SYSCTL_ZERO,
6492 		.extra2		= SYSCTL_ONE_HUNDRED,
6493 	},
6494 #endif
6495 };
6496 
6497 void __init page_alloc_sysctl_init(void)
6498 {
6499 	register_sysctl_init("vm", page_alloc_sysctl_table);
6500 }
6501 
6502 #ifdef CONFIG_CONTIG_ALLOC
6503 /* Usage: See admin-guide/dynamic-debug-howto.rst */
6504 static void alloc_contig_dump_pages(struct list_head *page_list)
6505 {
6506 	DEFINE_DYNAMIC_DEBUG_METADATA(descriptor, "migrate failure");
6507 
6508 	if (DYNAMIC_DEBUG_BRANCH(descriptor)) {
6509 		struct page *page;
6510 
6511 		dump_stack();
6512 		list_for_each_entry(page, page_list, lru)
6513 			dump_page(page, "migration failure");
6514 	}
6515 }
6516 
6517 /*
6518  * [start, end) must belong to a single zone.
6519  * @migratetype: using migratetype to filter the type of migration in
6520  *		trace_mm_alloc_contig_migrate_range_info.
6521  */
6522 static int __alloc_contig_migrate_range(struct compact_control *cc,
6523 		unsigned long start, unsigned long end, int migratetype)
6524 {
6525 	/* This function is based on compact_zone() from compaction.c. */
6526 	unsigned int nr_reclaimed;
6527 	unsigned long pfn = start;
6528 	unsigned int tries = 0;
6529 	int ret = 0;
6530 	struct migration_target_control mtc = {
6531 		.nid = zone_to_nid(cc->zone),
6532 		.gfp_mask = cc->gfp_mask,
6533 		.reason = MR_CONTIG_RANGE,
6534 	};
6535 	struct page *page;
6536 	unsigned long total_mapped = 0;
6537 	unsigned long total_migrated = 0;
6538 	unsigned long total_reclaimed = 0;
6539 
6540 	lru_cache_disable();
6541 
6542 	while (pfn < end || !list_empty(&cc->migratepages)) {
6543 		if (fatal_signal_pending(current)) {
6544 			ret = -EINTR;
6545 			break;
6546 		}
6547 
6548 		if (list_empty(&cc->migratepages)) {
6549 			cc->nr_migratepages = 0;
6550 			ret = isolate_migratepages_range(cc, pfn, end);
6551 			if (ret && ret != -EAGAIN)
6552 				break;
6553 			pfn = cc->migrate_pfn;
6554 			tries = 0;
6555 		} else if (++tries == 5) {
6556 			ret = -EBUSY;
6557 			break;
6558 		}
6559 
6560 		nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
6561 							&cc->migratepages);
6562 		cc->nr_migratepages -= nr_reclaimed;
6563 
6564 		if (trace_mm_alloc_contig_migrate_range_info_enabled()) {
6565 			total_reclaimed += nr_reclaimed;
6566 			list_for_each_entry(page, &cc->migratepages, lru) {
6567 				struct folio *folio = page_folio(page);
6568 
6569 				total_mapped += folio_mapped(folio) *
6570 						folio_nr_pages(folio);
6571 			}
6572 		}
6573 
6574 		ret = migrate_pages(&cc->migratepages, alloc_migration_target,
6575 			NULL, (unsigned long)&mtc, cc->mode, MR_CONTIG_RANGE, NULL);
6576 
6577 		if (trace_mm_alloc_contig_migrate_range_info_enabled() && !ret)
6578 			total_migrated += cc->nr_migratepages;
6579 
6580 		/*
6581 		 * On -ENOMEM, migrate_pages() bails out right away. It is pointless
6582 		 * to retry again over this error, so do the same here.
6583 		 */
6584 		if (ret == -ENOMEM)
6585 			break;
6586 	}
6587 
6588 	lru_cache_enable();
6589 	if (ret < 0) {
6590 		if (!(cc->gfp_mask & __GFP_NOWARN) && ret == -EBUSY)
6591 			alloc_contig_dump_pages(&cc->migratepages);
6592 		putback_movable_pages(&cc->migratepages);
6593 	}
6594 
6595 	trace_mm_alloc_contig_migrate_range_info(start, end, migratetype,
6596 						 total_migrated,
6597 						 total_reclaimed,
6598 						 total_mapped);
6599 	return (ret < 0) ? ret : 0;
6600 }
6601 
6602 static void split_free_pages(struct list_head *list, gfp_t gfp_mask)
6603 {
6604 	int order;
6605 
6606 	for (order = 0; order < NR_PAGE_ORDERS; order++) {
6607 		struct page *page, *next;
6608 		int nr_pages = 1 << order;
6609 
6610 		list_for_each_entry_safe(page, next, &list[order], lru) {
6611 			int i;
6612 
6613 			post_alloc_hook(page, order, gfp_mask);
6614 			set_page_refcounted(page);
6615 			if (!order)
6616 				continue;
6617 
6618 			split_page(page, order);
6619 
6620 			/* Add all subpages to the order-0 head, in sequence. */
6621 			list_del(&page->lru);
6622 			for (i = 0; i < nr_pages; i++)
6623 				list_add_tail(&page[i].lru, &list[0]);
6624 		}
6625 	}
6626 }
6627 
6628 static int __alloc_contig_verify_gfp_mask(gfp_t gfp_mask, gfp_t *gfp_cc_mask)
6629 {
6630 	const gfp_t reclaim_mask = __GFP_IO | __GFP_FS | __GFP_RECLAIM;
6631 	const gfp_t action_mask = __GFP_COMP | __GFP_RETRY_MAYFAIL | __GFP_NOWARN |
6632 				  __GFP_ZERO | __GFP_ZEROTAGS | __GFP_SKIP_ZERO;
6633 	const gfp_t cc_action_mask = __GFP_RETRY_MAYFAIL | __GFP_NOWARN;
6634 
6635 	/*
6636 	 * We are given the range to allocate; node, mobility and placement
6637 	 * hints are irrelevant at this point. We'll simply ignore them.
6638 	 */
6639 	gfp_mask &= ~(GFP_ZONEMASK | __GFP_RECLAIMABLE | __GFP_WRITE |
6640 		      __GFP_HARDWALL | __GFP_THISNODE | __GFP_MOVABLE);
6641 
6642 	/*
6643 	 * We only support most reclaim flags (but not NOFAIL/NORETRY), and
6644 	 * selected action flags.
6645 	 */
6646 	if (gfp_mask & ~(reclaim_mask | action_mask))
6647 		return -EINVAL;
6648 
6649 	/*
6650 	 * Flags to control page compaction/migration/reclaim, to free up our
6651 	 * page range. Migratable pages are movable, __GFP_MOVABLE is implied
6652 	 * for them.
6653 	 *
6654 	 * Traditionally we always had __GFP_RETRY_MAYFAIL set, keep doing that
6655 	 * to not degrade callers.
6656 	 */
6657 	*gfp_cc_mask = (gfp_mask & (reclaim_mask | cc_action_mask)) |
6658 			__GFP_MOVABLE | __GFP_RETRY_MAYFAIL;
6659 	return 0;
6660 }
6661 
6662 /**
6663  * alloc_contig_range() -- tries to allocate given range of pages
6664  * @start:	start PFN to allocate
6665  * @end:	one-past-the-last PFN to allocate
6666  * @migratetype:	migratetype of the underlying pageblocks (either
6667  *			#MIGRATE_MOVABLE or #MIGRATE_CMA).  All pageblocks
6668  *			in range must have the same migratetype and it must
6669  *			be either of the two.
6670  * @gfp_mask:	GFP mask. Node/zone/placement hints are ignored; only some
6671  *		action and reclaim modifiers are supported. Reclaim modifiers
6672  *		control allocation behavior during compaction/migration/reclaim.
6673  *
6674  * The PFN range does not have to be pageblock aligned. The PFN range must
6675  * belong to a single zone.
6676  *
6677  * The first thing this routine does is attempt to MIGRATE_ISOLATE all
6678  * pageblocks in the range.  Once isolated, the pageblocks should not
6679  * be modified by others.
6680  *
6681  * Return: zero on success or negative error code.  On success all
6682  * pages which PFN is in [start, end) are allocated for the caller and
6683  * need to be freed with free_contig_range().
6684  */
6685 int alloc_contig_range_noprof(unsigned long start, unsigned long end,
6686 		       unsigned migratetype, gfp_t gfp_mask)
6687 {
6688 	unsigned long outer_start, outer_end;
6689 	int ret = 0;
6690 
6691 	struct compact_control cc = {
6692 		.nr_migratepages = 0,
6693 		.order = -1,
6694 		.zone = page_zone(pfn_to_page(start)),
6695 		.mode = MIGRATE_SYNC,
6696 		.ignore_skip_hint = true,
6697 		.no_set_skip_hint = true,
6698 		.alloc_contig = true,
6699 	};
6700 	INIT_LIST_HEAD(&cc.migratepages);
6701 
6702 	gfp_mask = current_gfp_context(gfp_mask);
6703 	if (__alloc_contig_verify_gfp_mask(gfp_mask, (gfp_t *)&cc.gfp_mask))
6704 		return -EINVAL;
6705 
6706 	/*
6707 	 * What we do here is we mark all pageblocks in range as
6708 	 * MIGRATE_ISOLATE.  Because pageblock and max order pages may
6709 	 * have different sizes, and due to the way page allocator
6710 	 * work, start_isolate_page_range() has special handlings for this.
6711 	 *
6712 	 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
6713 	 * migrate the pages from an unaligned range (ie. pages that
6714 	 * we are interested in). This will put all the pages in
6715 	 * range back to page allocator as MIGRATE_ISOLATE.
6716 	 *
6717 	 * When this is done, we take the pages in range from page
6718 	 * allocator removing them from the buddy system.  This way
6719 	 * page allocator will never consider using them.
6720 	 *
6721 	 * This lets us mark the pageblocks back as
6722 	 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
6723 	 * aligned range but not in the unaligned, original range are
6724 	 * put back to page allocator so that buddy can use them.
6725 	 */
6726 
6727 	ret = start_isolate_page_range(start, end, migratetype, 0);
6728 	if (ret)
6729 		goto done;
6730 
6731 	drain_all_pages(cc.zone);
6732 
6733 	/*
6734 	 * In case of -EBUSY, we'd like to know which page causes problem.
6735 	 * So, just fall through. test_pages_isolated() has a tracepoint
6736 	 * which will report the busy page.
6737 	 *
6738 	 * It is possible that busy pages could become available before
6739 	 * the call to test_pages_isolated, and the range will actually be
6740 	 * allocated.  So, if we fall through be sure to clear ret so that
6741 	 * -EBUSY is not accidentally used or returned to caller.
6742 	 */
6743 	ret = __alloc_contig_migrate_range(&cc, start, end, migratetype);
6744 	if (ret && ret != -EBUSY)
6745 		goto done;
6746 
6747 	/*
6748 	 * When in-use hugetlb pages are migrated, they may simply be released
6749 	 * back into the free hugepage pool instead of being returned to the
6750 	 * buddy system.  After the migration of in-use huge pages is completed,
6751 	 * we will invoke replace_free_hugepage_folios() to ensure that these
6752 	 * hugepages are properly released to the buddy system.
6753 	 */
6754 	ret = replace_free_hugepage_folios(start, end);
6755 	if (ret)
6756 		goto done;
6757 
6758 	/*
6759 	 * Pages from [start, end) are within a pageblock_nr_pages
6760 	 * aligned blocks that are marked as MIGRATE_ISOLATE.  What's
6761 	 * more, all pages in [start, end) are free in page allocator.
6762 	 * What we are going to do is to allocate all pages from
6763 	 * [start, end) (that is remove them from page allocator).
6764 	 *
6765 	 * The only problem is that pages at the beginning and at the
6766 	 * end of interesting range may be not aligned with pages that
6767 	 * page allocator holds, ie. they can be part of higher order
6768 	 * pages.  Because of this, we reserve the bigger range and
6769 	 * once this is done free the pages we are not interested in.
6770 	 *
6771 	 * We don't have to hold zone->lock here because the pages are
6772 	 * isolated thus they won't get removed from buddy.
6773 	 */
6774 	outer_start = find_large_buddy(start);
6775 
6776 	/* Make sure the range is really isolated. */
6777 	if (test_pages_isolated(outer_start, end, 0)) {
6778 		ret = -EBUSY;
6779 		goto done;
6780 	}
6781 
6782 	/* Grab isolated pages from freelists. */
6783 	outer_end = isolate_freepages_range(&cc, outer_start, end);
6784 	if (!outer_end) {
6785 		ret = -EBUSY;
6786 		goto done;
6787 	}
6788 
6789 	if (!(gfp_mask & __GFP_COMP)) {
6790 		split_free_pages(cc.freepages, gfp_mask);
6791 
6792 		/* Free head and tail (if any) */
6793 		if (start != outer_start)
6794 			free_contig_range(outer_start, start - outer_start);
6795 		if (end != outer_end)
6796 			free_contig_range(end, outer_end - end);
6797 	} else if (start == outer_start && end == outer_end && is_power_of_2(end - start)) {
6798 		struct page *head = pfn_to_page(start);
6799 		int order = ilog2(end - start);
6800 
6801 		check_new_pages(head, order);
6802 		prep_new_page(head, order, gfp_mask, 0);
6803 		set_page_refcounted(head);
6804 	} else {
6805 		ret = -EINVAL;
6806 		WARN(true, "PFN range: requested [%lu, %lu), allocated [%lu, %lu)\n",
6807 		     start, end, outer_start, outer_end);
6808 	}
6809 done:
6810 	undo_isolate_page_range(start, end, migratetype);
6811 	return ret;
6812 }
6813 EXPORT_SYMBOL(alloc_contig_range_noprof);
6814 
6815 static int __alloc_contig_pages(unsigned long start_pfn,
6816 				unsigned long nr_pages, gfp_t gfp_mask)
6817 {
6818 	unsigned long end_pfn = start_pfn + nr_pages;
6819 
6820 	return alloc_contig_range_noprof(start_pfn, end_pfn, MIGRATE_MOVABLE,
6821 				   gfp_mask);
6822 }
6823 
6824 static bool pfn_range_valid_contig(struct zone *z, unsigned long start_pfn,
6825 				   unsigned long nr_pages)
6826 {
6827 	unsigned long i, end_pfn = start_pfn + nr_pages;
6828 	struct page *page;
6829 
6830 	for (i = start_pfn; i < end_pfn; i++) {
6831 		page = pfn_to_online_page(i);
6832 		if (!page)
6833 			return false;
6834 
6835 		if (page_zone(page) != z)
6836 			return false;
6837 
6838 		if (PageReserved(page))
6839 			return false;
6840 
6841 		if (PageHuge(page))
6842 			return false;
6843 	}
6844 	return true;
6845 }
6846 
6847 static bool zone_spans_last_pfn(const struct zone *zone,
6848 				unsigned long start_pfn, unsigned long nr_pages)
6849 {
6850 	unsigned long last_pfn = start_pfn + nr_pages - 1;
6851 
6852 	return zone_spans_pfn(zone, last_pfn);
6853 }
6854 
6855 /**
6856  * alloc_contig_pages() -- tries to find and allocate contiguous range of pages
6857  * @nr_pages:	Number of contiguous pages to allocate
6858  * @gfp_mask:	GFP mask. Node/zone/placement hints limit the search; only some
6859  *		action and reclaim modifiers are supported. Reclaim modifiers
6860  *		control allocation behavior during compaction/migration/reclaim.
6861  * @nid:	Target node
6862  * @nodemask:	Mask for other possible nodes
6863  *
6864  * This routine is a wrapper around alloc_contig_range(). It scans over zones
6865  * on an applicable zonelist to find a contiguous pfn range which can then be
6866  * tried for allocation with alloc_contig_range(). This routine is intended
6867  * for allocation requests which can not be fulfilled with the buddy allocator.
6868  *
6869  * The allocated memory is always aligned to a page boundary. If nr_pages is a
6870  * power of two, then allocated range is also guaranteed to be aligned to same
6871  * nr_pages (e.g. 1GB request would be aligned to 1GB).
6872  *
6873  * Allocated pages can be freed with free_contig_range() or by manually calling
6874  * __free_page() on each allocated page.
6875  *
6876  * Return: pointer to contiguous pages on success, or NULL if not successful.
6877  */
6878 struct page *alloc_contig_pages_noprof(unsigned long nr_pages, gfp_t gfp_mask,
6879 				 int nid, nodemask_t *nodemask)
6880 {
6881 	unsigned long ret, pfn, flags;
6882 	struct zonelist *zonelist;
6883 	struct zone *zone;
6884 	struct zoneref *z;
6885 
6886 	zonelist = node_zonelist(nid, gfp_mask);
6887 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
6888 					gfp_zone(gfp_mask), nodemask) {
6889 		spin_lock_irqsave(&zone->lock, flags);
6890 
6891 		pfn = ALIGN(zone->zone_start_pfn, nr_pages);
6892 		while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
6893 			if (pfn_range_valid_contig(zone, pfn, nr_pages)) {
6894 				/*
6895 				 * We release the zone lock here because
6896 				 * alloc_contig_range() will also lock the zone
6897 				 * at some point. If there's an allocation
6898 				 * spinning on this lock, it may win the race
6899 				 * and cause alloc_contig_range() to fail...
6900 				 */
6901 				spin_unlock_irqrestore(&zone->lock, flags);
6902 				ret = __alloc_contig_pages(pfn, nr_pages,
6903 							gfp_mask);
6904 				if (!ret)
6905 					return pfn_to_page(pfn);
6906 				spin_lock_irqsave(&zone->lock, flags);
6907 			}
6908 			pfn += nr_pages;
6909 		}
6910 		spin_unlock_irqrestore(&zone->lock, flags);
6911 	}
6912 	return NULL;
6913 }
6914 #endif /* CONFIG_CONTIG_ALLOC */
6915 
6916 void free_contig_range(unsigned long pfn, unsigned long nr_pages)
6917 {
6918 	unsigned long count = 0;
6919 	struct folio *folio = pfn_folio(pfn);
6920 
6921 	if (folio_test_large(folio)) {
6922 		int expected = folio_nr_pages(folio);
6923 
6924 		if (nr_pages == expected)
6925 			folio_put(folio);
6926 		else
6927 			WARN(true, "PFN %lu: nr_pages %lu != expected %d\n",
6928 			     pfn, nr_pages, expected);
6929 		return;
6930 	}
6931 
6932 	for (; nr_pages--; pfn++) {
6933 		struct page *page = pfn_to_page(pfn);
6934 
6935 		count += page_count(page) != 1;
6936 		__free_page(page);
6937 	}
6938 	WARN(count != 0, "%lu pages are still in use!\n", count);
6939 }
6940 EXPORT_SYMBOL(free_contig_range);
6941 
6942 /*
6943  * Effectively disable pcplists for the zone by setting the high limit to 0
6944  * and draining all cpus. A concurrent page freeing on another CPU that's about
6945  * to put the page on pcplist will either finish before the drain and the page
6946  * will be drained, or observe the new high limit and skip the pcplist.
6947  *
6948  * Must be paired with a call to zone_pcp_enable().
6949  */
6950 void zone_pcp_disable(struct zone *zone)
6951 {
6952 	mutex_lock(&pcp_batch_high_lock);
6953 	__zone_set_pageset_high_and_batch(zone, 0, 0, 1);
6954 	__drain_all_pages(zone, true);
6955 }
6956 
6957 void zone_pcp_enable(struct zone *zone)
6958 {
6959 	__zone_set_pageset_high_and_batch(zone, zone->pageset_high_min,
6960 		zone->pageset_high_max, zone->pageset_batch);
6961 	mutex_unlock(&pcp_batch_high_lock);
6962 }
6963 
6964 void zone_pcp_reset(struct zone *zone)
6965 {
6966 	int cpu;
6967 	struct per_cpu_zonestat *pzstats;
6968 
6969 	if (zone->per_cpu_pageset != &boot_pageset) {
6970 		for_each_online_cpu(cpu) {
6971 			pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
6972 			drain_zonestat(zone, pzstats);
6973 		}
6974 		free_percpu(zone->per_cpu_pageset);
6975 		zone->per_cpu_pageset = &boot_pageset;
6976 		if (zone->per_cpu_zonestats != &boot_zonestats) {
6977 			free_percpu(zone->per_cpu_zonestats);
6978 			zone->per_cpu_zonestats = &boot_zonestats;
6979 		}
6980 	}
6981 }
6982 
6983 #ifdef CONFIG_MEMORY_HOTREMOVE
6984 /*
6985  * All pages in the range must be in a single zone, must not contain holes,
6986  * must span full sections, and must be isolated before calling this function.
6987  *
6988  * Returns the number of managed (non-PageOffline()) pages in the range: the
6989  * number of pages for which memory offlining code must adjust managed page
6990  * counters using adjust_managed_page_count().
6991  */
6992 unsigned long __offline_isolated_pages(unsigned long start_pfn,
6993 		unsigned long end_pfn)
6994 {
6995 	unsigned long already_offline = 0, flags;
6996 	unsigned long pfn = start_pfn;
6997 	struct page *page;
6998 	struct zone *zone;
6999 	unsigned int order;
7000 
7001 	offline_mem_sections(pfn, end_pfn);
7002 	zone = page_zone(pfn_to_page(pfn));
7003 	spin_lock_irqsave(&zone->lock, flags);
7004 	while (pfn < end_pfn) {
7005 		page = pfn_to_page(pfn);
7006 		/*
7007 		 * The HWPoisoned page may be not in buddy system, and
7008 		 * page_count() is not 0.
7009 		 */
7010 		if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
7011 			pfn++;
7012 			continue;
7013 		}
7014 		/*
7015 		 * At this point all remaining PageOffline() pages have a
7016 		 * reference count of 0 and can simply be skipped.
7017 		 */
7018 		if (PageOffline(page)) {
7019 			BUG_ON(page_count(page));
7020 			BUG_ON(PageBuddy(page));
7021 			already_offline++;
7022 			pfn++;
7023 			continue;
7024 		}
7025 
7026 		BUG_ON(page_count(page));
7027 		BUG_ON(!PageBuddy(page));
7028 		VM_WARN_ON(get_pageblock_migratetype(page) != MIGRATE_ISOLATE);
7029 		order = buddy_order(page);
7030 		del_page_from_free_list(page, zone, order, MIGRATE_ISOLATE);
7031 		pfn += (1 << order);
7032 	}
7033 	spin_unlock_irqrestore(&zone->lock, flags);
7034 
7035 	return end_pfn - start_pfn - already_offline;
7036 }
7037 #endif
7038 
7039 /*
7040  * This function returns a stable result only if called under zone lock.
7041  */
7042 bool is_free_buddy_page(const struct page *page)
7043 {
7044 	unsigned long pfn = page_to_pfn(page);
7045 	unsigned int order;
7046 
7047 	for (order = 0; order < NR_PAGE_ORDERS; order++) {
7048 		const struct page *head = page - (pfn & ((1 << order) - 1));
7049 
7050 		if (PageBuddy(head) &&
7051 		    buddy_order_unsafe(head) >= order)
7052 			break;
7053 	}
7054 
7055 	return order <= MAX_PAGE_ORDER;
7056 }
7057 EXPORT_SYMBOL(is_free_buddy_page);
7058 
7059 #ifdef CONFIG_MEMORY_FAILURE
7060 static inline void add_to_free_list(struct page *page, struct zone *zone,
7061 				    unsigned int order, int migratetype,
7062 				    bool tail)
7063 {
7064 	__add_to_free_list(page, zone, order, migratetype, tail);
7065 	account_freepages(zone, 1 << order, migratetype);
7066 }
7067 
7068 /*
7069  * Break down a higher-order page in sub-pages, and keep our target out of
7070  * buddy allocator.
7071  */
7072 static void break_down_buddy_pages(struct zone *zone, struct page *page,
7073 				   struct page *target, int low, int high,
7074 				   int migratetype)
7075 {
7076 	unsigned long size = 1 << high;
7077 	struct page *current_buddy;
7078 
7079 	while (high > low) {
7080 		high--;
7081 		size >>= 1;
7082 
7083 		if (target >= &page[size]) {
7084 			current_buddy = page;
7085 			page = page + size;
7086 		} else {
7087 			current_buddy = page + size;
7088 		}
7089 
7090 		if (set_page_guard(zone, current_buddy, high))
7091 			continue;
7092 
7093 		add_to_free_list(current_buddy, zone, high, migratetype, false);
7094 		set_buddy_order(current_buddy, high);
7095 	}
7096 }
7097 
7098 /*
7099  * Take a page that will be marked as poisoned off the buddy allocator.
7100  */
7101 bool take_page_off_buddy(struct page *page)
7102 {
7103 	struct zone *zone = page_zone(page);
7104 	unsigned long pfn = page_to_pfn(page);
7105 	unsigned long flags;
7106 	unsigned int order;
7107 	bool ret = false;
7108 
7109 	spin_lock_irqsave(&zone->lock, flags);
7110 	for (order = 0; order < NR_PAGE_ORDERS; order++) {
7111 		struct page *page_head = page - (pfn & ((1 << order) - 1));
7112 		int page_order = buddy_order(page_head);
7113 
7114 		if (PageBuddy(page_head) && page_order >= order) {
7115 			unsigned long pfn_head = page_to_pfn(page_head);
7116 			int migratetype = get_pfnblock_migratetype(page_head,
7117 								   pfn_head);
7118 
7119 			del_page_from_free_list(page_head, zone, page_order,
7120 						migratetype);
7121 			break_down_buddy_pages(zone, page_head, page, 0,
7122 						page_order, migratetype);
7123 			SetPageHWPoisonTakenOff(page);
7124 			ret = true;
7125 			break;
7126 		}
7127 		if (page_count(page_head) > 0)
7128 			break;
7129 	}
7130 	spin_unlock_irqrestore(&zone->lock, flags);
7131 	return ret;
7132 }
7133 
7134 /*
7135  * Cancel takeoff done by take_page_off_buddy().
7136  */
7137 bool put_page_back_buddy(struct page *page)
7138 {
7139 	struct zone *zone = page_zone(page);
7140 	unsigned long flags;
7141 	bool ret = false;
7142 
7143 	spin_lock_irqsave(&zone->lock, flags);
7144 	if (put_page_testzero(page)) {
7145 		unsigned long pfn = page_to_pfn(page);
7146 		int migratetype = get_pfnblock_migratetype(page, pfn);
7147 
7148 		ClearPageHWPoisonTakenOff(page);
7149 		__free_one_page(page, pfn, zone, 0, migratetype, FPI_NONE);
7150 		if (TestClearPageHWPoison(page)) {
7151 			ret = true;
7152 		}
7153 	}
7154 	spin_unlock_irqrestore(&zone->lock, flags);
7155 
7156 	return ret;
7157 }
7158 #endif
7159 
7160 #ifdef CONFIG_ZONE_DMA
7161 bool has_managed_dma(void)
7162 {
7163 	struct pglist_data *pgdat;
7164 
7165 	for_each_online_pgdat(pgdat) {
7166 		struct zone *zone = &pgdat->node_zones[ZONE_DMA];
7167 
7168 		if (managed_zone(zone))
7169 			return true;
7170 	}
7171 	return false;
7172 }
7173 #endif /* CONFIG_ZONE_DMA */
7174 
7175 #ifdef CONFIG_UNACCEPTED_MEMORY
7176 
7177 /* Counts number of zones with unaccepted pages. */
7178 static DEFINE_STATIC_KEY_FALSE(zones_with_unaccepted_pages);
7179 
7180 static bool lazy_accept = true;
7181 
7182 void unaccepted_cleanup_work(struct work_struct *work)
7183 {
7184 	static_branch_dec(&zones_with_unaccepted_pages);
7185 }
7186 
7187 static int __init accept_memory_parse(char *p)
7188 {
7189 	if (!strcmp(p, "lazy")) {
7190 		lazy_accept = true;
7191 		return 0;
7192 	} else if (!strcmp(p, "eager")) {
7193 		lazy_accept = false;
7194 		return 0;
7195 	} else {
7196 		return -EINVAL;
7197 	}
7198 }
7199 early_param("accept_memory", accept_memory_parse);
7200 
7201 static bool page_contains_unaccepted(struct page *page, unsigned int order)
7202 {
7203 	phys_addr_t start = page_to_phys(page);
7204 
7205 	return range_contains_unaccepted_memory(start, PAGE_SIZE << order);
7206 }
7207 
7208 static void __accept_page(struct zone *zone, unsigned long *flags,
7209 			  struct page *page)
7210 {
7211 	bool last;
7212 
7213 	list_del(&page->lru);
7214 	last = list_empty(&zone->unaccepted_pages);
7215 
7216 	account_freepages(zone, -MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE);
7217 	__mod_zone_page_state(zone, NR_UNACCEPTED, -MAX_ORDER_NR_PAGES);
7218 	__ClearPageUnaccepted(page);
7219 	spin_unlock_irqrestore(&zone->lock, *flags);
7220 
7221 	accept_memory(page_to_phys(page), PAGE_SIZE << MAX_PAGE_ORDER);
7222 
7223 	__free_pages_ok(page, MAX_PAGE_ORDER, FPI_TO_TAIL);
7224 
7225 	if (last) {
7226 		/*
7227 		 * There are two corner cases:
7228 		 *
7229 		 * - If allocation occurs during the CPU bring up,
7230 		 *   static_branch_dec() cannot be used directly as
7231 		 *   it causes a deadlock on cpu_hotplug_lock.
7232 		 *
7233 		 *   Instead, use schedule_work() to prevent deadlock.
7234 		 *
7235 		 * - If allocation occurs before workqueues are initialized,
7236 		 *   static_branch_dec() should be called directly.
7237 		 *
7238 		 *   Workqueues are initialized before CPU bring up, so this
7239 		 *   will not conflict with the first scenario.
7240 		 */
7241 		if (system_wq)
7242 			schedule_work(&zone->unaccepted_cleanup);
7243 		else
7244 			unaccepted_cleanup_work(&zone->unaccepted_cleanup);
7245 	}
7246 }
7247 
7248 void accept_page(struct page *page)
7249 {
7250 	struct zone *zone = page_zone(page);
7251 	unsigned long flags;
7252 
7253 	spin_lock_irqsave(&zone->lock, flags);
7254 	if (!PageUnaccepted(page)) {
7255 		spin_unlock_irqrestore(&zone->lock, flags);
7256 		return;
7257 	}
7258 
7259 	/* Unlocks zone->lock */
7260 	__accept_page(zone, &flags, page);
7261 }
7262 
7263 static bool try_to_accept_memory_one(struct zone *zone)
7264 {
7265 	unsigned long flags;
7266 	struct page *page;
7267 
7268 	spin_lock_irqsave(&zone->lock, flags);
7269 	page = list_first_entry_or_null(&zone->unaccepted_pages,
7270 					struct page, lru);
7271 	if (!page) {
7272 		spin_unlock_irqrestore(&zone->lock, flags);
7273 		return false;
7274 	}
7275 
7276 	/* Unlocks zone->lock */
7277 	__accept_page(zone, &flags, page);
7278 
7279 	return true;
7280 }
7281 
7282 static inline bool has_unaccepted_memory(void)
7283 {
7284 	return static_branch_unlikely(&zones_with_unaccepted_pages);
7285 }
7286 
7287 static bool cond_accept_memory(struct zone *zone, unsigned int order)
7288 {
7289 	long to_accept, wmark;
7290 	bool ret = false;
7291 
7292 	if (!has_unaccepted_memory())
7293 		return false;
7294 
7295 	if (list_empty(&zone->unaccepted_pages))
7296 		return false;
7297 
7298 	wmark = promo_wmark_pages(zone);
7299 
7300 	/*
7301 	 * Watermarks have not been initialized yet.
7302 	 *
7303 	 * Accepting one MAX_ORDER page to ensure progress.
7304 	 */
7305 	if (!wmark)
7306 		return try_to_accept_memory_one(zone);
7307 
7308 	/* How much to accept to get to promo watermark? */
7309 	to_accept = wmark -
7310 		    (zone_page_state(zone, NR_FREE_PAGES) -
7311 		    __zone_watermark_unusable_free(zone, order, 0) -
7312 		    zone_page_state(zone, NR_UNACCEPTED));
7313 
7314 	while (to_accept > 0) {
7315 		if (!try_to_accept_memory_one(zone))
7316 			break;
7317 		ret = true;
7318 		to_accept -= MAX_ORDER_NR_PAGES;
7319 	}
7320 
7321 	return ret;
7322 }
7323 
7324 static bool __free_unaccepted(struct page *page)
7325 {
7326 	struct zone *zone = page_zone(page);
7327 	unsigned long flags;
7328 	bool first = false;
7329 
7330 	if (!lazy_accept)
7331 		return false;
7332 
7333 	spin_lock_irqsave(&zone->lock, flags);
7334 	first = list_empty(&zone->unaccepted_pages);
7335 	list_add_tail(&page->lru, &zone->unaccepted_pages);
7336 	account_freepages(zone, MAX_ORDER_NR_PAGES, MIGRATE_MOVABLE);
7337 	__mod_zone_page_state(zone, NR_UNACCEPTED, MAX_ORDER_NR_PAGES);
7338 	__SetPageUnaccepted(page);
7339 	spin_unlock_irqrestore(&zone->lock, flags);
7340 
7341 	if (first)
7342 		static_branch_inc(&zones_with_unaccepted_pages);
7343 
7344 	return true;
7345 }
7346 
7347 #else
7348 
7349 static bool page_contains_unaccepted(struct page *page, unsigned int order)
7350 {
7351 	return false;
7352 }
7353 
7354 static bool cond_accept_memory(struct zone *zone, unsigned int order)
7355 {
7356 	return false;
7357 }
7358 
7359 static bool __free_unaccepted(struct page *page)
7360 {
7361 	BUILD_BUG();
7362 	return false;
7363 }
7364 
7365 #endif /* CONFIG_UNACCEPTED_MEMORY */
7366 
7367 /**
7368  * try_alloc_pages - opportunistic reentrant allocation from any context
7369  * @nid: node to allocate from
7370  * @order: allocation order size
7371  *
7372  * Allocates pages of a given order from the given node. This is safe to
7373  * call from any context (from atomic, NMI, and also reentrant
7374  * allocator -> tracepoint -> try_alloc_pages_noprof).
7375  * Allocation is best effort and to be expected to fail easily so nobody should
7376  * rely on the success. Failures are not reported via warn_alloc().
7377  * See always fail conditions below.
7378  *
7379  * Return: allocated page or NULL on failure.
7380  */
7381 struct page *try_alloc_pages_noprof(int nid, unsigned int order)
7382 {
7383 	/*
7384 	 * Do not specify __GFP_DIRECT_RECLAIM, since direct claim is not allowed.
7385 	 * Do not specify __GFP_KSWAPD_RECLAIM either, since wake up of kswapd
7386 	 * is not safe in arbitrary context.
7387 	 *
7388 	 * These two are the conditions for gfpflags_allow_spinning() being true.
7389 	 *
7390 	 * Specify __GFP_NOWARN since failing try_alloc_pages() is not a reason
7391 	 * to warn. Also warn would trigger printk() which is unsafe from
7392 	 * various contexts. We cannot use printk_deferred_enter() to mitigate,
7393 	 * since the running context is unknown.
7394 	 *
7395 	 * Specify __GFP_ZERO to make sure that call to kmsan_alloc_page() below
7396 	 * is safe in any context. Also zeroing the page is mandatory for
7397 	 * BPF use cases.
7398 	 *
7399 	 * Though __GFP_NOMEMALLOC is not checked in the code path below,
7400 	 * specify it here to highlight that try_alloc_pages()
7401 	 * doesn't want to deplete reserves.
7402 	 */
7403 	gfp_t alloc_gfp = __GFP_NOWARN | __GFP_ZERO | __GFP_NOMEMALLOC
7404 			| __GFP_ACCOUNT;
7405 	unsigned int alloc_flags = ALLOC_TRYLOCK;
7406 	struct alloc_context ac = { };
7407 	struct page *page;
7408 
7409 	/*
7410 	 * In PREEMPT_RT spin_trylock() will call raw_spin_lock() which is
7411 	 * unsafe in NMI. If spin_trylock() is called from hard IRQ the current
7412 	 * task may be waiting for one rt_spin_lock, but rt_spin_trylock() will
7413 	 * mark the task as the owner of another rt_spin_lock which will
7414 	 * confuse PI logic, so return immediately if called form hard IRQ or
7415 	 * NMI.
7416 	 *
7417 	 * Note, irqs_disabled() case is ok. This function can be called
7418 	 * from raw_spin_lock_irqsave region.
7419 	 */
7420 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && (in_nmi() || in_hardirq()))
7421 		return NULL;
7422 	if (!pcp_allowed_order(order))
7423 		return NULL;
7424 
7425 #ifdef CONFIG_UNACCEPTED_MEMORY
7426 	/* Bailout, since try_to_accept_memory_one() needs to take a lock */
7427 	if (has_unaccepted_memory())
7428 		return NULL;
7429 #endif
7430 	/* Bailout, since _deferred_grow_zone() needs to take a lock */
7431 	if (deferred_pages_enabled())
7432 		return NULL;
7433 
7434 	if (nid == NUMA_NO_NODE)
7435 		nid = numa_node_id();
7436 
7437 	prepare_alloc_pages(alloc_gfp, order, nid, NULL, &ac,
7438 			    &alloc_gfp, &alloc_flags);
7439 
7440 	/*
7441 	 * Best effort allocation from percpu free list.
7442 	 * If it's empty attempt to spin_trylock zone->lock.
7443 	 */
7444 	page = get_page_from_freelist(alloc_gfp, order, alloc_flags, &ac);
7445 
7446 	/* Unlike regular alloc_pages() there is no __alloc_pages_slowpath(). */
7447 
7448 	if (page)
7449 		set_page_refcounted(page);
7450 
7451 	if (memcg_kmem_online() && page &&
7452 	    unlikely(__memcg_kmem_charge_page(page, alloc_gfp, order) != 0)) {
7453 		free_pages_nolock(page, order);
7454 		page = NULL;
7455 	}
7456 	trace_mm_page_alloc(page, order, alloc_gfp, ac.migratetype);
7457 	kmsan_alloc_page(page, order, alloc_gfp);
7458 	return page;
7459 }
7460