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