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