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