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