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