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