• 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/swap.h>
22 #include <linux/interrupt.h>
23 #include <linux/pagemap.h>
24 #include <linux/jiffies.h>
25 #include <linux/memblock.h>
26 #include <linux/compiler.h>
27 #include <linux/kernel.h>
28 #include <linux/kasan.h>
29 #include <linux/module.h>
30 #include <linux/suspend.h>
31 #include <linux/pagevec.h>
32 #include <linux/blkdev.h>
33 #include <linux/slab.h>
34 #include <linux/ratelimit.h>
35 #include <linux/oom.h>
36 #include <linux/topology.h>
37 #include <linux/sysctl.h>
38 #include <linux/cpu.h>
39 #include <linux/cpuset.h>
40 #include <linux/memory_hotplug.h>
41 #include <linux/nodemask.h>
42 #include <linux/vmalloc.h>
43 #include <linux/vmstat.h>
44 #include <linux/mempolicy.h>
45 #include <linux/memremap.h>
46 #include <linux/stop_machine.h>
47 #include <linux/random.h>
48 #include <linux/sort.h>
49 #include <linux/pfn.h>
50 #include <linux/backing-dev.h>
51 #include <linux/fault-inject.h>
52 #include <linux/page-isolation.h>
53 #include <linux/debugobjects.h>
54 #include <linux/kmemleak.h>
55 #include <linux/compaction.h>
56 #include <trace/events/kmem.h>
57 #include <trace/events/oom.h>
58 #include <linux/prefetch.h>
59 #include <linux/mm_inline.h>
60 #include <linux/migrate.h>
61 #include <linux/hugetlb.h>
62 #include <linux/sched/rt.h>
63 #include <linux/sched/mm.h>
64 #include <linux/page_owner.h>
65 #include <linux/kthread.h>
66 #include <linux/memcontrol.h>
67 #include <linux/ftrace.h>
68 #include <linux/lockdep.h>
69 #include <linux/nmi.h>
70 #include <linux/psi.h>
71 
72 #include <asm/sections.h>
73 #include <asm/tlbflush.h>
74 #include <asm/div64.h>
75 #include "internal.h"
76 #include "shuffle.h"
77 
78 /* prevent >1 _updater_ of zone percpu pageset ->high and ->batch fields */
79 static DEFINE_MUTEX(pcp_batch_high_lock);
80 #define MIN_PERCPU_PAGELIST_FRACTION	(8)
81 
82 #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID
83 DEFINE_PER_CPU(int, numa_node);
84 EXPORT_PER_CPU_SYMBOL(numa_node);
85 #endif
86 
87 DEFINE_STATIC_KEY_TRUE(vm_numa_stat_key);
88 
89 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
90 /*
91  * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
92  * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
93  * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem()
94  * defined in <linux/topology.h>.
95  */
96 DEFINE_PER_CPU(int, _numa_mem_);		/* Kernel "local memory" node */
97 EXPORT_PER_CPU_SYMBOL(_numa_mem_);
98 int _node_numa_mem_[MAX_NUMNODES];
99 #endif
100 
101 /* work_structs for global per-cpu drains */
102 struct pcpu_drain {
103 	struct zone *zone;
104 	struct work_struct work;
105 };
106 DEFINE_MUTEX(pcpu_drain_mutex);
107 DEFINE_PER_CPU(struct pcpu_drain, pcpu_drain);
108 
109 #ifdef CONFIG_GCC_PLUGIN_LATENT_ENTROPY
110 volatile unsigned long latent_entropy __latent_entropy;
111 EXPORT_SYMBOL(latent_entropy);
112 #endif
113 
114 /*
115  * Array of node states.
116  */
117 nodemask_t node_states[NR_NODE_STATES] __read_mostly = {
118 	[N_POSSIBLE] = NODE_MASK_ALL,
119 	[N_ONLINE] = { { [0] = 1UL } },
120 #ifndef CONFIG_NUMA
121 	[N_NORMAL_MEMORY] = { { [0] = 1UL } },
122 #ifdef CONFIG_HIGHMEM
123 	[N_HIGH_MEMORY] = { { [0] = 1UL } },
124 #endif
125 	[N_MEMORY] = { { [0] = 1UL } },
126 	[N_CPU] = { { [0] = 1UL } },
127 #endif	/* NUMA */
128 };
129 EXPORT_SYMBOL(node_states);
130 
131 atomic_long_t _totalram_pages __read_mostly;
132 EXPORT_SYMBOL(_totalram_pages);
133 unsigned long totalreserve_pages __read_mostly;
134 unsigned long totalcma_pages __read_mostly;
135 
136 int percpu_pagelist_fraction;
137 gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK;
138 #ifdef CONFIG_INIT_ON_ALLOC_DEFAULT_ON
139 DEFINE_STATIC_KEY_TRUE(init_on_alloc);
140 #else
141 DEFINE_STATIC_KEY_FALSE(init_on_alloc);
142 #endif
143 EXPORT_SYMBOL(init_on_alloc);
144 
145 #ifdef CONFIG_INIT_ON_FREE_DEFAULT_ON
146 DEFINE_STATIC_KEY_TRUE(init_on_free);
147 #else
148 DEFINE_STATIC_KEY_FALSE(init_on_free);
149 #endif
150 EXPORT_SYMBOL(init_on_free);
151 
early_init_on_alloc(char * buf)152 static int __init early_init_on_alloc(char *buf)
153 {
154 	int ret;
155 	bool bool_result;
156 
157 	if (!buf)
158 		return -EINVAL;
159 	ret = kstrtobool(buf, &bool_result);
160 	if (bool_result && page_poisoning_enabled())
161 		pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, will take precedence over init_on_alloc\n");
162 	if (bool_result)
163 		static_branch_enable(&init_on_alloc);
164 	else
165 		static_branch_disable(&init_on_alloc);
166 	return ret;
167 }
168 early_param("init_on_alloc", early_init_on_alloc);
169 
early_init_on_free(char * buf)170 static int __init early_init_on_free(char *buf)
171 {
172 	int ret;
173 	bool bool_result;
174 
175 	if (!buf)
176 		return -EINVAL;
177 	ret = kstrtobool(buf, &bool_result);
178 	if (bool_result && page_poisoning_enabled())
179 		pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, will take precedence over init_on_free\n");
180 	if (bool_result)
181 		static_branch_enable(&init_on_free);
182 	else
183 		static_branch_disable(&init_on_free);
184 	return ret;
185 }
186 early_param("init_on_free", early_init_on_free);
187 
188 /*
189  * A cached value of the page's pageblock's migratetype, used when the page is
190  * put on a pcplist. Used to avoid the pageblock migratetype lookup when
191  * freeing from pcplists in most cases, at the cost of possibly becoming stale.
192  * Also the migratetype set in the page does not necessarily match the pcplist
193  * index, e.g. page might have MIGRATE_CMA set but be on a pcplist with any
194  * other index - this ensures that it will be put on the correct CMA freelist.
195  */
get_pcppage_migratetype(struct page * page)196 static inline int get_pcppage_migratetype(struct page *page)
197 {
198 	return page->index;
199 }
200 
set_pcppage_migratetype(struct page * page,int migratetype)201 static inline void set_pcppage_migratetype(struct page *page, int migratetype)
202 {
203 	page->index = migratetype;
204 }
205 
206 #ifdef CONFIG_PM_SLEEP
207 /*
208  * The following functions are used by the suspend/hibernate code to temporarily
209  * change gfp_allowed_mask in order to avoid using I/O during memory allocations
210  * while devices are suspended.  To avoid races with the suspend/hibernate code,
211  * they should always be called with system_transition_mutex held
212  * (gfp_allowed_mask also should only be modified with system_transition_mutex
213  * held, unless the suspend/hibernate code is guaranteed not to run in parallel
214  * with that modification).
215  */
216 
217 static gfp_t saved_gfp_mask;
218 
pm_restore_gfp_mask(void)219 void pm_restore_gfp_mask(void)
220 {
221 	WARN_ON(!mutex_is_locked(&system_transition_mutex));
222 	if (saved_gfp_mask) {
223 		gfp_allowed_mask = saved_gfp_mask;
224 		saved_gfp_mask = 0;
225 	}
226 }
227 
pm_restrict_gfp_mask(void)228 void pm_restrict_gfp_mask(void)
229 {
230 	WARN_ON(!mutex_is_locked(&system_transition_mutex));
231 	WARN_ON(saved_gfp_mask);
232 	saved_gfp_mask = gfp_allowed_mask;
233 	gfp_allowed_mask &= ~(__GFP_IO | __GFP_FS);
234 }
235 
pm_suspended_storage(void)236 bool pm_suspended_storage(void)
237 {
238 	if ((gfp_allowed_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
239 		return false;
240 	return true;
241 }
242 #endif /* CONFIG_PM_SLEEP */
243 
244 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
245 unsigned int pageblock_order __read_mostly;
246 #endif
247 
248 static void __free_pages_ok(struct page *page, unsigned int order);
249 
250 /*
251  * results with 256, 32 in the lowmem_reserve sysctl:
252  *	1G machine -> (16M dma, 800M-16M normal, 1G-800M high)
253  *	1G machine -> (16M dma, 784M normal, 224M high)
254  *	NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA
255  *	HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL
256  *	HIGHMEM allocation will leave (224M+784M)/256 of ram reserved in ZONE_DMA
257  *
258  * TBD: should special case ZONE_DMA32 machines here - in those we normally
259  * don't need any ZONE_NORMAL reservation
260  */
261 int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES] = {
262 #ifdef CONFIG_ZONE_DMA
263 	[ZONE_DMA] = 256,
264 #endif
265 #ifdef CONFIG_ZONE_DMA32
266 	[ZONE_DMA32] = 256,
267 #endif
268 	[ZONE_NORMAL] = 32,
269 #ifdef CONFIG_HIGHMEM
270 	[ZONE_HIGHMEM] = 0,
271 #endif
272 	[ZONE_MOVABLE] = 0,
273 };
274 
275 static char * const zone_names[MAX_NR_ZONES] = {
276 #ifdef CONFIG_ZONE_DMA
277 	 "DMA",
278 #endif
279 #ifdef CONFIG_ZONE_DMA32
280 	 "DMA32",
281 #endif
282 	 "Normal",
283 #ifdef CONFIG_HIGHMEM
284 	 "HighMem",
285 #endif
286 	 "Movable",
287 #ifdef CONFIG_ZONE_DEVICE
288 	 "Device",
289 #endif
290 };
291 
292 const char * const migratetype_names[MIGRATE_TYPES] = {
293 	"Unmovable",
294 	"Movable",
295 	"Reclaimable",
296 	"HighAtomic",
297 #ifdef CONFIG_CMA
298 	"CMA",
299 #endif
300 #ifdef CONFIG_MEMORY_ISOLATION
301 	"Isolate",
302 #endif
303 };
304 
305 compound_page_dtor * const compound_page_dtors[] = {
306 	NULL,
307 	free_compound_page,
308 #ifdef CONFIG_HUGETLB_PAGE
309 	free_huge_page,
310 #endif
311 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
312 	free_transhuge_page,
313 #endif
314 };
315 
316 /*
317  * Try to keep at least this much lowmem free.  Do not allow normal
318  * allocations below this point, only high priority ones. Automatically
319  * tuned according to the amount of memory in the system.
320  */
321 int min_free_kbytes = 1024;
322 int user_min_free_kbytes = -1;
323 #ifdef CONFIG_DISCONTIGMEM
324 /*
325  * DiscontigMem defines memory ranges as separate pg_data_t even if the ranges
326  * are not on separate NUMA nodes. Functionally this works but with
327  * watermark_boost_factor, it can reclaim prematurely as the ranges can be
328  * quite small. By default, do not boost watermarks on discontigmem as in
329  * many cases very high-order allocations like THP are likely to be
330  * unsupported and the premature reclaim offsets the advantage of long-term
331  * fragmentation avoidance.
332  */
333 int watermark_boost_factor __read_mostly;
334 #else
335 int watermark_boost_factor __read_mostly = 15000;
336 #endif
337 int watermark_scale_factor = 10;
338 
339 /*
340  * Extra memory for the system to try freeing. Used to temporarily
341  * free memory, to make space for new workloads. Anyone can allocate
342  * down to the min watermarks controlled by min_free_kbytes above.
343  */
344 int extra_free_kbytes = 0;
345 
346 static unsigned long nr_kernel_pages __initdata;
347 static unsigned long nr_all_pages __initdata;
348 static unsigned long dma_reserve __initdata;
349 
350 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
351 static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata;
352 static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata;
353 static unsigned long required_kernelcore __initdata;
354 static unsigned long required_kernelcore_percent __initdata;
355 static unsigned long required_movablecore __initdata;
356 static unsigned long required_movablecore_percent __initdata;
357 static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata;
358 static bool mirrored_kernelcore __meminitdata;
359 
360 /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */
361 int movable_zone;
362 EXPORT_SYMBOL(movable_zone);
363 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
364 
365 #if MAX_NUMNODES > 1
366 unsigned int nr_node_ids __read_mostly = MAX_NUMNODES;
367 unsigned int nr_online_nodes __read_mostly = 1;
368 EXPORT_SYMBOL(nr_node_ids);
369 EXPORT_SYMBOL(nr_online_nodes);
370 #endif
371 
372 int page_group_by_mobility_disabled __read_mostly;
373 
374 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
375 /*
376  * During boot we initialize deferred pages on-demand, as needed, but once
377  * page_alloc_init_late() has finished, the deferred pages are all initialized,
378  * and we can permanently disable that path.
379  */
380 static DEFINE_STATIC_KEY_TRUE(deferred_pages);
381 
382 /*
383  * Calling kasan_free_pages() only after deferred memory initialization
384  * has completed. Poisoning pages during deferred memory init will greatly
385  * lengthen the process and cause problem in large memory systems as the
386  * deferred pages initialization is done with interrupt disabled.
387  *
388  * Assuming that there will be no reference to those newly initialized
389  * pages before they are ever allocated, this should have no effect on
390  * KASAN memory tracking as the poison will be properly inserted at page
391  * allocation time. The only corner case is when pages are allocated by
392  * on-demand allocation and then freed again before the deferred pages
393  * initialization is done, but this is not likely to happen.
394  */
kasan_free_nondeferred_pages(struct page * page,int order)395 static inline void kasan_free_nondeferred_pages(struct page *page, int order)
396 {
397 	if (!static_branch_unlikely(&deferred_pages))
398 		kasan_free_pages(page, order);
399 }
400 
401 /* Returns true if the struct page for the pfn is uninitialised */
early_page_uninitialised(unsigned long pfn)402 static inline bool __meminit early_page_uninitialised(unsigned long pfn)
403 {
404 	int nid = early_pfn_to_nid(pfn);
405 
406 	if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
407 		return true;
408 
409 	return false;
410 }
411 
412 /*
413  * Returns true when the remaining initialisation should be deferred until
414  * later in the boot cycle when it can be parallelised.
415  */
416 static bool __meminit
defer_init(int nid,unsigned long pfn,unsigned long end_pfn)417 defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
418 {
419 	static unsigned long prev_end_pfn, nr_initialised;
420 
421 	/*
422 	 * prev_end_pfn static that contains the end of previous zone
423 	 * No need to protect because called very early in boot before smp_init.
424 	 */
425 	if (prev_end_pfn != end_pfn) {
426 		prev_end_pfn = end_pfn;
427 		nr_initialised = 0;
428 	}
429 
430 	/* Always populate low zones for address-constrained allocations */
431 	if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
432 		return false;
433 
434 	/*
435 	 * We start only with one section of pages, more pages are added as
436 	 * needed until the rest of deferred pages are initialized.
437 	 */
438 	nr_initialised++;
439 	if ((nr_initialised > PAGES_PER_SECTION) &&
440 	    (pfn & (PAGES_PER_SECTION - 1)) == 0) {
441 		NODE_DATA(nid)->first_deferred_pfn = pfn;
442 		return true;
443 	}
444 	return false;
445 }
446 #else
447 #define kasan_free_nondeferred_pages(p, o)	kasan_free_pages(p, o)
448 
early_page_uninitialised(unsigned long pfn)449 static inline bool early_page_uninitialised(unsigned long pfn)
450 {
451 	return false;
452 }
453 
defer_init(int nid,unsigned long pfn,unsigned long end_pfn)454 static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
455 {
456 	return false;
457 }
458 #endif
459 
460 /* Return a pointer to the bitmap storing bits affecting a block of pages */
get_pageblock_bitmap(struct page * page,unsigned long pfn)461 static inline unsigned long *get_pageblock_bitmap(struct page *page,
462 							unsigned long pfn)
463 {
464 #ifdef CONFIG_SPARSEMEM
465 	return section_to_usemap(__pfn_to_section(pfn));
466 #else
467 	return page_zone(page)->pageblock_flags;
468 #endif /* CONFIG_SPARSEMEM */
469 }
470 
pfn_to_bitidx(struct page * page,unsigned long pfn)471 static inline int pfn_to_bitidx(struct page *page, unsigned long pfn)
472 {
473 #ifdef CONFIG_SPARSEMEM
474 	pfn &= (PAGES_PER_SECTION-1);
475 	return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
476 #else
477 	pfn = pfn - round_down(page_zone(page)->zone_start_pfn, pageblock_nr_pages);
478 	return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS;
479 #endif /* CONFIG_SPARSEMEM */
480 }
481 
482 /**
483  * get_pfnblock_flags_mask - Return the requested group of flags for the pageblock_nr_pages block of pages
484  * @page: The page within the block of interest
485  * @pfn: The target page frame number
486  * @end_bitidx: The last bit of interest to retrieve
487  * @mask: mask of bits that the caller is interested in
488  *
489  * Return: pageblock_bits flags
490  */
__get_pfnblock_flags_mask(struct page * page,unsigned long pfn,unsigned long end_bitidx,unsigned long mask)491 static __always_inline unsigned long __get_pfnblock_flags_mask(struct page *page,
492 					unsigned long pfn,
493 					unsigned long end_bitidx,
494 					unsigned long mask)
495 {
496 	unsigned long *bitmap;
497 	unsigned long bitidx, word_bitidx;
498 	unsigned long word;
499 
500 	bitmap = get_pageblock_bitmap(page, pfn);
501 	bitidx = pfn_to_bitidx(page, pfn);
502 	word_bitidx = bitidx / BITS_PER_LONG;
503 	bitidx &= (BITS_PER_LONG-1);
504 
505 	word = bitmap[word_bitidx];
506 	bitidx += end_bitidx;
507 	return (word >> (BITS_PER_LONG - bitidx - 1)) & mask;
508 }
509 
get_pfnblock_flags_mask(struct page * page,unsigned long pfn,unsigned long end_bitidx,unsigned long mask)510 unsigned long get_pfnblock_flags_mask(struct page *page, unsigned long pfn,
511 					unsigned long end_bitidx,
512 					unsigned long mask)
513 {
514 	return __get_pfnblock_flags_mask(page, pfn, end_bitidx, mask);
515 }
516 
get_pfnblock_migratetype(struct page * page,unsigned long pfn)517 static __always_inline int get_pfnblock_migratetype(struct page *page, unsigned long pfn)
518 {
519 	return __get_pfnblock_flags_mask(page, pfn, PB_migrate_end, MIGRATETYPE_MASK);
520 }
521 
522 /**
523  * set_pfnblock_flags_mask - Set the requested group of flags for a pageblock_nr_pages block of pages
524  * @page: The page within the block of interest
525  * @flags: The flags to set
526  * @pfn: The target page frame number
527  * @end_bitidx: The last bit of interest
528  * @mask: mask of bits that the caller is interested in
529  */
set_pfnblock_flags_mask(struct page * page,unsigned long flags,unsigned long pfn,unsigned long end_bitidx,unsigned long mask)530 void set_pfnblock_flags_mask(struct page *page, unsigned long flags,
531 					unsigned long pfn,
532 					unsigned long end_bitidx,
533 					unsigned long mask)
534 {
535 	unsigned long *bitmap;
536 	unsigned long bitidx, word_bitidx;
537 	unsigned long old_word, word;
538 
539 	BUILD_BUG_ON(NR_PAGEBLOCK_BITS != 4);
540 	BUILD_BUG_ON(MIGRATE_TYPES > (1 << PB_migratetype_bits));
541 
542 	bitmap = get_pageblock_bitmap(page, pfn);
543 	bitidx = pfn_to_bitidx(page, pfn);
544 	word_bitidx = bitidx / BITS_PER_LONG;
545 	bitidx &= (BITS_PER_LONG-1);
546 
547 	VM_BUG_ON_PAGE(!zone_spans_pfn(page_zone(page), pfn), page);
548 
549 	bitidx += end_bitidx;
550 	mask <<= (BITS_PER_LONG - bitidx - 1);
551 	flags <<= (BITS_PER_LONG - bitidx - 1);
552 
553 	word = READ_ONCE(bitmap[word_bitidx]);
554 	for (;;) {
555 		old_word = cmpxchg(&bitmap[word_bitidx], word, (word & ~mask) | flags);
556 		if (word == old_word)
557 			break;
558 		word = old_word;
559 	}
560 }
561 
set_pageblock_migratetype(struct page * page,int migratetype)562 void set_pageblock_migratetype(struct page *page, int migratetype)
563 {
564 	if (unlikely(page_group_by_mobility_disabled &&
565 		     migratetype < MIGRATE_PCPTYPES))
566 		migratetype = MIGRATE_UNMOVABLE;
567 
568 	set_pageblock_flags_group(page, (unsigned long)migratetype,
569 					PB_migrate, PB_migrate_end);
570 }
571 
572 #ifdef CONFIG_DEBUG_VM
page_outside_zone_boundaries(struct zone * zone,struct page * page)573 static int page_outside_zone_boundaries(struct zone *zone, struct page *page)
574 {
575 	int ret = 0;
576 	unsigned seq;
577 	unsigned long pfn = page_to_pfn(page);
578 	unsigned long sp, start_pfn;
579 
580 	do {
581 		seq = zone_span_seqbegin(zone);
582 		start_pfn = zone->zone_start_pfn;
583 		sp = zone->spanned_pages;
584 		if (!zone_spans_pfn(zone, pfn))
585 			ret = 1;
586 	} while (zone_span_seqretry(zone, seq));
587 
588 	if (ret)
589 		pr_err("page 0x%lx outside node %d zone %s [ 0x%lx - 0x%lx ]\n",
590 			pfn, zone_to_nid(zone), zone->name,
591 			start_pfn, start_pfn + sp);
592 
593 	return ret;
594 }
595 
page_is_consistent(struct zone * zone,struct page * page)596 static int page_is_consistent(struct zone *zone, struct page *page)
597 {
598 	if (!pfn_valid_within(page_to_pfn(page)))
599 		return 0;
600 	if (zone != page_zone(page))
601 		return 0;
602 
603 	return 1;
604 }
605 /*
606  * Temporary debugging check for pages not lying within a given zone.
607  */
bad_range(struct zone * zone,struct page * page)608 static int __maybe_unused bad_range(struct zone *zone, struct page *page)
609 {
610 	if (page_outside_zone_boundaries(zone, page))
611 		return 1;
612 	if (!page_is_consistent(zone, page))
613 		return 1;
614 
615 	return 0;
616 }
617 #else
bad_range(struct zone * zone,struct page * page)618 static inline int __maybe_unused bad_range(struct zone *zone, struct page *page)
619 {
620 	return 0;
621 }
622 #endif
623 
bad_page(struct page * page,const char * reason,unsigned long bad_flags)624 static void bad_page(struct page *page, const char *reason,
625 		unsigned long bad_flags)
626 {
627 	static unsigned long resume;
628 	static unsigned long nr_shown;
629 	static unsigned long nr_unshown;
630 
631 	/*
632 	 * Allow a burst of 60 reports, then keep quiet for that minute;
633 	 * or allow a steady drip of one report per second.
634 	 */
635 	if (nr_shown == 60) {
636 		if (time_before(jiffies, resume)) {
637 			nr_unshown++;
638 			goto out;
639 		}
640 		if (nr_unshown) {
641 			pr_alert(
642 			      "BUG: Bad page state: %lu messages suppressed\n",
643 				nr_unshown);
644 			nr_unshown = 0;
645 		}
646 		nr_shown = 0;
647 	}
648 	if (nr_shown++ == 0)
649 		resume = jiffies + 60 * HZ;
650 
651 	pr_alert("BUG: Bad page state in process %s  pfn:%05lx\n",
652 		current->comm, page_to_pfn(page));
653 	__dump_page(page, reason);
654 	bad_flags &= page->flags;
655 	if (bad_flags)
656 		pr_alert("bad because of flags: %#lx(%pGp)\n",
657 						bad_flags, &bad_flags);
658 	dump_page_owner(page);
659 
660 	print_modules();
661 	dump_stack();
662 out:
663 	/* Leave bad fields for debug, except PageBuddy could make trouble */
664 	page_mapcount_reset(page); /* remove PageBuddy */
665 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
666 }
667 
668 /*
669  * Higher-order pages are called "compound pages".  They are structured thusly:
670  *
671  * The first PAGE_SIZE page is called the "head page" and have PG_head set.
672  *
673  * The remaining PAGE_SIZE pages are called "tail pages". PageTail() is encoded
674  * in bit 0 of page->compound_head. The rest of bits is pointer to head page.
675  *
676  * The first tail page's ->compound_dtor holds the offset in array of compound
677  * page destructors. See compound_page_dtors.
678  *
679  * The first tail page's ->compound_order holds the order of allocation.
680  * This usage means that zero-order pages may not be compound.
681  */
682 
free_compound_page(struct page * page)683 void free_compound_page(struct page *page)
684 {
685 	mem_cgroup_uncharge(page);
686 	__free_pages_ok(page, compound_order(page));
687 }
688 
prep_compound_page(struct page * page,unsigned int order)689 void prep_compound_page(struct page *page, unsigned int order)
690 {
691 	int i;
692 	int nr_pages = 1 << order;
693 
694 	set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
695 	set_compound_order(page, order);
696 	__SetPageHead(page);
697 	for (i = 1; i < nr_pages; i++) {
698 		struct page *p = page + i;
699 		set_page_count(p, 0);
700 		p->mapping = TAIL_MAPPING;
701 		set_compound_head(p, page);
702 	}
703 	atomic_set(compound_mapcount_ptr(page), -1);
704 }
705 
706 #ifdef CONFIG_DEBUG_PAGEALLOC
707 unsigned int _debug_guardpage_minorder;
708 
709 bool _debug_pagealloc_enabled_early __read_mostly
710 			= IS_ENABLED(CONFIG_DEBUG_PAGEALLOC_ENABLE_DEFAULT);
711 EXPORT_SYMBOL(_debug_pagealloc_enabled_early);
712 DEFINE_STATIC_KEY_FALSE(_debug_pagealloc_enabled);
713 EXPORT_SYMBOL(_debug_pagealloc_enabled);
714 
715 DEFINE_STATIC_KEY_FALSE(_debug_guardpage_enabled);
716 
early_debug_pagealloc(char * buf)717 static int __init early_debug_pagealloc(char *buf)
718 {
719 	return kstrtobool(buf, &_debug_pagealloc_enabled_early);
720 }
721 early_param("debug_pagealloc", early_debug_pagealloc);
722 
init_debug_pagealloc(void)723 void init_debug_pagealloc(void)
724 {
725 	if (!debug_pagealloc_enabled())
726 		return;
727 
728 	static_branch_enable(&_debug_pagealloc_enabled);
729 
730 	if (!debug_guardpage_minorder())
731 		return;
732 
733 	static_branch_enable(&_debug_guardpage_enabled);
734 }
735 
debug_guardpage_minorder_setup(char * buf)736 static int __init debug_guardpage_minorder_setup(char *buf)
737 {
738 	unsigned long res;
739 
740 	if (kstrtoul(buf, 10, &res) < 0 ||  res > MAX_ORDER / 2) {
741 		pr_err("Bad debug_guardpage_minorder value\n");
742 		return 0;
743 	}
744 	_debug_guardpage_minorder = res;
745 	pr_info("Setting debug_guardpage_minorder to %lu\n", res);
746 	return 0;
747 }
748 early_param("debug_guardpage_minorder", debug_guardpage_minorder_setup);
749 
set_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)750 static inline bool set_page_guard(struct zone *zone, struct page *page,
751 				unsigned int order, int migratetype)
752 {
753 	if (!debug_guardpage_enabled())
754 		return false;
755 
756 	if (order >= debug_guardpage_minorder())
757 		return false;
758 
759 	__SetPageGuard(page);
760 	INIT_LIST_HEAD(&page->lru);
761 	set_page_private(page, order);
762 	/* Guard pages are not available for any usage */
763 	__mod_zone_freepage_state(zone, -(1 << order), migratetype);
764 
765 	return true;
766 }
767 
clear_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)768 static inline void clear_page_guard(struct zone *zone, struct page *page,
769 				unsigned int order, int migratetype)
770 {
771 	if (!debug_guardpage_enabled())
772 		return;
773 
774 	__ClearPageGuard(page);
775 
776 	set_page_private(page, 0);
777 	if (!is_migrate_isolate(migratetype))
778 		__mod_zone_freepage_state(zone, (1 << order), migratetype);
779 }
780 #else
set_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)781 static inline bool set_page_guard(struct zone *zone, struct page *page,
782 			unsigned int order, int migratetype) { return false; }
clear_page_guard(struct zone * zone,struct page * page,unsigned int order,int migratetype)783 static inline void clear_page_guard(struct zone *zone, struct page *page,
784 				unsigned int order, int migratetype) {}
785 #endif
786 
set_page_order(struct page * page,unsigned int order)787 static inline void set_page_order(struct page *page, unsigned int order)
788 {
789 	set_page_private(page, order);
790 	__SetPageBuddy(page);
791 }
792 
793 /*
794  * This function checks whether a page is free && is the buddy
795  * we can coalesce a page and its buddy if
796  * (a) the buddy is not in a hole (check before calling!) &&
797  * (b) the buddy is in the buddy system &&
798  * (c) a page and its buddy have the same order &&
799  * (d) a page and its buddy are in the same zone.
800  *
801  * For recording whether a page is in the buddy system, we set PageBuddy.
802  * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
803  *
804  * For recording page's order, we use page_private(page).
805  */
page_is_buddy(struct page * page,struct page * buddy,unsigned int order)806 static inline int page_is_buddy(struct page *page, struct page *buddy,
807 							unsigned int order)
808 {
809 	if (page_is_guard(buddy) && page_order(buddy) == order) {
810 		if (page_zone_id(page) != page_zone_id(buddy))
811 			return 0;
812 
813 		VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
814 
815 		return 1;
816 	}
817 
818 	if (PageBuddy(buddy) && page_order(buddy) == order) {
819 		/*
820 		 * zone check is done late to avoid uselessly
821 		 * calculating zone/node ids for pages that could
822 		 * never merge.
823 		 */
824 		if (page_zone_id(page) != page_zone_id(buddy))
825 			return 0;
826 
827 		VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
828 
829 		return 1;
830 	}
831 	return 0;
832 }
833 
834 #ifdef CONFIG_COMPACTION
task_capc(struct zone * zone)835 static inline struct capture_control *task_capc(struct zone *zone)
836 {
837 	struct capture_control *capc = current->capture_control;
838 
839 	return capc &&
840 		!(current->flags & PF_KTHREAD) &&
841 		!capc->page &&
842 		capc->cc->zone == zone &&
843 		capc->cc->direct_compaction ? capc : NULL;
844 }
845 
846 static inline bool
compaction_capture(struct capture_control * capc,struct page * page,int order,int migratetype)847 compaction_capture(struct capture_control *capc, struct page *page,
848 		   int order, int migratetype)
849 {
850 	if (!capc || order != capc->cc->order)
851 		return false;
852 
853 	/* Do not accidentally pollute CMA or isolated regions*/
854 	if (is_migrate_cma(migratetype) ||
855 	    is_migrate_isolate(migratetype))
856 		return false;
857 
858 	/*
859 	 * Do not let lower order allocations polluate a movable pageblock.
860 	 * This might let an unmovable request use a reclaimable pageblock
861 	 * and vice-versa but no more than normal fallback logic which can
862 	 * have trouble finding a high-order free page.
863 	 */
864 	if (order < pageblock_order && migratetype == MIGRATE_MOVABLE)
865 		return false;
866 
867 	capc->page = page;
868 	return true;
869 }
870 
871 #else
task_capc(struct zone * zone)872 static inline struct capture_control *task_capc(struct zone *zone)
873 {
874 	return NULL;
875 }
876 
877 static inline bool
compaction_capture(struct capture_control * capc,struct page * page,int order,int migratetype)878 compaction_capture(struct capture_control *capc, struct page *page,
879 		   int order, int migratetype)
880 {
881 	return false;
882 }
883 #endif /* CONFIG_COMPACTION */
884 
885 /*
886  * Freeing function for a buddy system allocator.
887  *
888  * The concept of a buddy system is to maintain direct-mapped table
889  * (containing bit values) for memory blocks of various "orders".
890  * The bottom level table contains the map for the smallest allocatable
891  * units of memory (here, pages), and each level above it describes
892  * pairs of units from the levels below, hence, "buddies".
893  * At a high level, all that happens here is marking the table entry
894  * at the bottom level available, and propagating the changes upward
895  * as necessary, plus some accounting needed to play nicely with other
896  * parts of the VM system.
897  * At each level, we keep a list of pages, which are heads of continuous
898  * free pages of length of (1 << order) and marked with PageBuddy.
899  * Page's order is recorded in page_private(page) field.
900  * So when we are allocating or freeing one, we can derive the state of the
901  * other.  That is, if we allocate a small block, and both were
902  * free, the remainder of the region must be split into blocks.
903  * If a block is freed, and its buddy is also free, then this
904  * triggers coalescing into a block of larger size.
905  *
906  * -- nyc
907  */
908 
__free_one_page(struct page * page,unsigned long pfn,struct zone * zone,unsigned int order,int migratetype)909 static inline void __free_one_page(struct page *page,
910 		unsigned long pfn,
911 		struct zone *zone, unsigned int order,
912 		int migratetype)
913 {
914 	unsigned long combined_pfn;
915 	unsigned long uninitialized_var(buddy_pfn);
916 	struct page *buddy;
917 	unsigned int max_order;
918 	struct capture_control *capc = task_capc(zone);
919 
920 	max_order = min_t(unsigned int, MAX_ORDER, pageblock_order + 1);
921 
922 	VM_BUG_ON(!zone_is_initialized(zone));
923 	VM_BUG_ON_PAGE(page->flags & PAGE_FLAGS_CHECK_AT_PREP, page);
924 
925 	VM_BUG_ON(migratetype == -1);
926 	if (likely(!is_migrate_isolate(migratetype)))
927 		__mod_zone_freepage_state(zone, 1 << order, migratetype);
928 
929 	VM_BUG_ON_PAGE(pfn & ((1 << order) - 1), page);
930 	VM_BUG_ON_PAGE(bad_range(zone, page), page);
931 
932 continue_merging:
933 	while (order < max_order - 1) {
934 		if (compaction_capture(capc, page, order, migratetype)) {
935 			__mod_zone_freepage_state(zone, -(1 << order),
936 								migratetype);
937 			return;
938 		}
939 		buddy_pfn = __find_buddy_pfn(pfn, order);
940 		buddy = page + (buddy_pfn - pfn);
941 
942 		if (!pfn_valid_within(buddy_pfn))
943 			goto done_merging;
944 		if (!page_is_buddy(page, buddy, order))
945 			goto done_merging;
946 		/*
947 		 * Our buddy is free or it is CONFIG_DEBUG_PAGEALLOC guard page,
948 		 * merge with it and move up one order.
949 		 */
950 		if (page_is_guard(buddy))
951 			clear_page_guard(zone, buddy, order, migratetype);
952 		else
953 			del_page_from_free_area(buddy, &zone->free_area[order]);
954 		combined_pfn = buddy_pfn & pfn;
955 		page = page + (combined_pfn - pfn);
956 		pfn = combined_pfn;
957 		order++;
958 	}
959 	if (max_order < MAX_ORDER) {
960 		/* If we are here, it means order is >= pageblock_order.
961 		 * We want to prevent merge between freepages on isolate
962 		 * pageblock and normal pageblock. Without this, pageblock
963 		 * isolation could cause incorrect freepage or CMA accounting.
964 		 *
965 		 * We don't want to hit this code for the more frequent
966 		 * low-order merging.
967 		 */
968 		if (unlikely(has_isolate_pageblock(zone))) {
969 			int buddy_mt;
970 
971 			buddy_pfn = __find_buddy_pfn(pfn, order);
972 			buddy = page + (buddy_pfn - pfn);
973 			buddy_mt = get_pageblock_migratetype(buddy);
974 
975 			if (migratetype != buddy_mt
976 					&& (is_migrate_isolate(migratetype) ||
977 						is_migrate_isolate(buddy_mt)))
978 				goto done_merging;
979 		}
980 		max_order++;
981 		goto continue_merging;
982 	}
983 
984 done_merging:
985 	set_page_order(page, order);
986 
987 	/*
988 	 * If this is not the largest possible page, check if the buddy
989 	 * of the next-highest order is free. If it is, it's possible
990 	 * that pages are being freed that will coalesce soon. In case,
991 	 * that is happening, add the free page to the tail of the list
992 	 * so it's less likely to be used soon and more likely to be merged
993 	 * as a higher order page
994 	 */
995 	if ((order < MAX_ORDER-2) && pfn_valid_within(buddy_pfn)
996 			&& !is_shuffle_order(order)) {
997 		struct page *higher_page, *higher_buddy;
998 		combined_pfn = buddy_pfn & pfn;
999 		higher_page = page + (combined_pfn - pfn);
1000 		buddy_pfn = __find_buddy_pfn(combined_pfn, order + 1);
1001 		higher_buddy = higher_page + (buddy_pfn - combined_pfn);
1002 		if (pfn_valid_within(buddy_pfn) &&
1003 		    page_is_buddy(higher_page, higher_buddy, order + 1)) {
1004 			add_to_free_area_tail(page, &zone->free_area[order],
1005 					      migratetype);
1006 			return;
1007 		}
1008 	}
1009 
1010 	if (is_shuffle_order(order))
1011 		add_to_free_area_random(page, &zone->free_area[order],
1012 				migratetype);
1013 	else
1014 		add_to_free_area(page, &zone->free_area[order], migratetype);
1015 
1016 }
1017 
1018 /*
1019  * A bad page could be due to a number of fields. Instead of multiple branches,
1020  * try and check multiple fields with one check. The caller must do a detailed
1021  * check if necessary.
1022  */
page_expected_state(struct page * page,unsigned long check_flags)1023 static inline bool page_expected_state(struct page *page,
1024 					unsigned long check_flags)
1025 {
1026 	if (unlikely(atomic_read(&page->_mapcount) != -1))
1027 		return false;
1028 
1029 	if (unlikely((unsigned long)page->mapping |
1030 			page_ref_count(page) |
1031 #ifdef CONFIG_MEMCG
1032 			(unsigned long)page->mem_cgroup |
1033 #endif
1034 			(page->flags & check_flags)))
1035 		return false;
1036 
1037 	return true;
1038 }
1039 
free_pages_check_bad(struct page * page)1040 static void free_pages_check_bad(struct page *page)
1041 {
1042 	const char *bad_reason;
1043 	unsigned long bad_flags;
1044 
1045 	bad_reason = NULL;
1046 	bad_flags = 0;
1047 
1048 	if (unlikely(atomic_read(&page->_mapcount) != -1))
1049 		bad_reason = "nonzero mapcount";
1050 	if (unlikely(page->mapping != NULL))
1051 		bad_reason = "non-NULL mapping";
1052 	if (unlikely(page_ref_count(page) != 0))
1053 		bad_reason = "nonzero _refcount";
1054 	if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_FREE)) {
1055 		bad_reason = "PAGE_FLAGS_CHECK_AT_FREE flag(s) set";
1056 		bad_flags = PAGE_FLAGS_CHECK_AT_FREE;
1057 	}
1058 #ifdef CONFIG_MEMCG
1059 	if (unlikely(page->mem_cgroup))
1060 		bad_reason = "page still charged to cgroup";
1061 #endif
1062 	bad_page(page, bad_reason, bad_flags);
1063 }
1064 
free_pages_check(struct page * page)1065 static inline int free_pages_check(struct page *page)
1066 {
1067 	if (likely(page_expected_state(page, PAGE_FLAGS_CHECK_AT_FREE)))
1068 		return 0;
1069 
1070 	/* Something has gone sideways, find it */
1071 	free_pages_check_bad(page);
1072 	return 1;
1073 }
1074 
free_tail_pages_check(struct page * head_page,struct page * page)1075 static int free_tail_pages_check(struct page *head_page, struct page *page)
1076 {
1077 	int ret = 1;
1078 
1079 	/*
1080 	 * We rely page->lru.next never has bit 0 set, unless the page
1081 	 * is PageTail(). Let's make sure that's true even for poisoned ->lru.
1082 	 */
1083 	BUILD_BUG_ON((unsigned long)LIST_POISON1 & 1);
1084 
1085 	if (!IS_ENABLED(CONFIG_DEBUG_VM)) {
1086 		ret = 0;
1087 		goto out;
1088 	}
1089 	switch (page - head_page) {
1090 	case 1:
1091 		/* the first tail page: ->mapping may be compound_mapcount() */
1092 		if (unlikely(compound_mapcount(page))) {
1093 			bad_page(page, "nonzero compound_mapcount", 0);
1094 			goto out;
1095 		}
1096 		break;
1097 	case 2:
1098 		/*
1099 		 * the second tail page: ->mapping is
1100 		 * deferred_list.next -- ignore value.
1101 		 */
1102 		break;
1103 	default:
1104 		if (page->mapping != TAIL_MAPPING) {
1105 			bad_page(page, "corrupted mapping in tail page", 0);
1106 			goto out;
1107 		}
1108 		break;
1109 	}
1110 	if (unlikely(!PageTail(page))) {
1111 		bad_page(page, "PageTail not set", 0);
1112 		goto out;
1113 	}
1114 	if (unlikely(compound_head(page) != head_page)) {
1115 		bad_page(page, "compound_head not consistent", 0);
1116 		goto out;
1117 	}
1118 	ret = 0;
1119 out:
1120 	page->mapping = NULL;
1121 	clear_compound_head(page);
1122 	return ret;
1123 }
1124 
kernel_init_free_pages(struct page * page,int numpages)1125 static void kernel_init_free_pages(struct page *page, int numpages)
1126 {
1127 	int i;
1128 
1129 	for (i = 0; i < numpages; i++)
1130 		clear_highpage(page + i);
1131 }
1132 
free_pages_prepare(struct page * page,unsigned int order,bool check_free)1133 static __always_inline bool free_pages_prepare(struct page *page,
1134 					unsigned int order, bool check_free)
1135 {
1136 	int bad = 0;
1137 
1138 	VM_BUG_ON_PAGE(PageTail(page), page);
1139 
1140 	trace_mm_page_free(page, order);
1141 
1142 	/*
1143 	 * Check tail pages before head page information is cleared to
1144 	 * avoid checking PageCompound for order-0 pages.
1145 	 */
1146 	if (unlikely(order)) {
1147 		bool compound = PageCompound(page);
1148 		int i;
1149 
1150 		VM_BUG_ON_PAGE(compound && compound_order(page) != order, page);
1151 
1152 		if (compound)
1153 			ClearPageDoubleMap(page);
1154 		for (i = 1; i < (1 << order); i++) {
1155 			if (compound)
1156 				bad += free_tail_pages_check(page, page + i);
1157 			if (unlikely(free_pages_check(page + i))) {
1158 				bad++;
1159 				continue;
1160 			}
1161 			(page + i)->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1162 		}
1163 	}
1164 	if (PageMappingFlags(page))
1165 		page->mapping = NULL;
1166 	if (memcg_kmem_enabled() && PageKmemcg(page))
1167 		__memcg_kmem_uncharge(page, order);
1168 	if (check_free)
1169 		bad += free_pages_check(page);
1170 	if (bad)
1171 		return false;
1172 
1173 	page_cpupid_reset_last(page);
1174 	page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP;
1175 	reset_page_owner(page, order);
1176 
1177 	if (!PageHighMem(page)) {
1178 		debug_check_no_locks_freed(page_address(page),
1179 					   PAGE_SIZE << order);
1180 		debug_check_no_obj_freed(page_address(page),
1181 					   PAGE_SIZE << order);
1182 	}
1183 	if (want_init_on_free())
1184 		kernel_init_free_pages(page, 1 << order);
1185 
1186 	kernel_poison_pages(page, 1 << order, 0);
1187 	/*
1188 	 * arch_free_page() can make the page's contents inaccessible.  s390
1189 	 * does this.  So nothing which can access the page's contents should
1190 	 * happen after this.
1191 	 */
1192 	arch_free_page(page, order);
1193 
1194 	if (debug_pagealloc_enabled_static())
1195 		kernel_map_pages(page, 1 << order, 0);
1196 
1197 	kasan_free_nondeferred_pages(page, order);
1198 
1199 	return true;
1200 }
1201 
1202 #ifdef CONFIG_DEBUG_VM
1203 /*
1204  * With DEBUG_VM enabled, order-0 pages are checked immediately when being freed
1205  * to pcp lists. With debug_pagealloc also enabled, they are also rechecked when
1206  * moved from pcp lists to free lists.
1207  */
free_pcp_prepare(struct page * page)1208 static bool free_pcp_prepare(struct page *page)
1209 {
1210 	return free_pages_prepare(page, 0, true);
1211 }
1212 
bulkfree_pcp_prepare(struct page * page)1213 static bool bulkfree_pcp_prepare(struct page *page)
1214 {
1215 	if (debug_pagealloc_enabled_static())
1216 		return free_pages_check(page);
1217 	else
1218 		return false;
1219 }
1220 #else
1221 /*
1222  * With DEBUG_VM disabled, order-0 pages being freed are checked only when
1223  * moving from pcp lists to free list in order to reduce overhead. With
1224  * debug_pagealloc enabled, they are checked also immediately when being freed
1225  * to the pcp lists.
1226  */
free_pcp_prepare(struct page * page)1227 static bool free_pcp_prepare(struct page *page)
1228 {
1229 	if (debug_pagealloc_enabled_static())
1230 		return free_pages_prepare(page, 0, true);
1231 	else
1232 		return free_pages_prepare(page, 0, false);
1233 }
1234 
bulkfree_pcp_prepare(struct page * page)1235 static bool bulkfree_pcp_prepare(struct page *page)
1236 {
1237 	return free_pages_check(page);
1238 }
1239 #endif /* CONFIG_DEBUG_VM */
1240 
prefetch_buddy(struct page * page)1241 static inline void prefetch_buddy(struct page *page)
1242 {
1243 	unsigned long pfn = page_to_pfn(page);
1244 	unsigned long buddy_pfn = __find_buddy_pfn(pfn, 0);
1245 	struct page *buddy = page + (buddy_pfn - pfn);
1246 
1247 	prefetch(buddy);
1248 }
1249 
1250 /*
1251  * Frees a number of pages from the PCP lists
1252  * Assumes all pages on list are in same zone, and of same order.
1253  * count is the number of pages to free.
1254  *
1255  * If the zone was previously in an "all pages pinned" state then look to
1256  * see if this freeing clears that state.
1257  *
1258  * And clear the zone's pages_scanned counter, to hold off the "all pages are
1259  * pinned" detection logic.
1260  */
free_pcppages_bulk(struct zone * zone,int count,struct per_cpu_pages * pcp)1261 static void free_pcppages_bulk(struct zone *zone, int count,
1262 					struct per_cpu_pages *pcp)
1263 {
1264 	int migratetype = 0;
1265 	int batch_free = 0;
1266 	int prefetch_nr = 0;
1267 	bool isolated_pageblocks;
1268 	struct page *page, *tmp;
1269 	LIST_HEAD(head);
1270 
1271 	while (count) {
1272 		struct list_head *list;
1273 
1274 		/*
1275 		 * Remove pages from lists in a round-robin fashion. A
1276 		 * batch_free count is maintained that is incremented when an
1277 		 * empty list is encountered.  This is so more pages are freed
1278 		 * off fuller lists instead of spinning excessively around empty
1279 		 * lists
1280 		 */
1281 		do {
1282 			batch_free++;
1283 			if (++migratetype == MIGRATE_PCPTYPES)
1284 				migratetype = 0;
1285 			list = &pcp->lists[migratetype];
1286 		} while (list_empty(list));
1287 
1288 		/* This is the only non-empty list. Free them all. */
1289 		if (batch_free == MIGRATE_PCPTYPES)
1290 			batch_free = count;
1291 
1292 		do {
1293 			page = list_last_entry(list, struct page, lru);
1294 			/* must delete to avoid corrupting pcp list */
1295 			list_del(&page->lru);
1296 			pcp->count--;
1297 
1298 			if (bulkfree_pcp_prepare(page))
1299 				continue;
1300 
1301 			list_add_tail(&page->lru, &head);
1302 
1303 			/*
1304 			 * We are going to put the page back to the global
1305 			 * pool, prefetch its buddy to speed up later access
1306 			 * under zone->lock. It is believed the overhead of
1307 			 * an additional test and calculating buddy_pfn here
1308 			 * can be offset by reduced memory latency later. To
1309 			 * avoid excessive prefetching due to large count, only
1310 			 * prefetch buddy for the first pcp->batch nr of pages.
1311 			 */
1312 			if (prefetch_nr++ < pcp->batch)
1313 				prefetch_buddy(page);
1314 		} while (--count && --batch_free && !list_empty(list));
1315 	}
1316 
1317 	spin_lock(&zone->lock);
1318 	isolated_pageblocks = has_isolate_pageblock(zone);
1319 
1320 	/*
1321 	 * Use safe version since after __free_one_page(),
1322 	 * page->lru.next will not point to original list.
1323 	 */
1324 	list_for_each_entry_safe(page, tmp, &head, lru) {
1325 		int mt = get_pcppage_migratetype(page);
1326 		/* MIGRATE_ISOLATE page should not go to pcplists */
1327 		VM_BUG_ON_PAGE(is_migrate_isolate(mt), page);
1328 		/* Pageblock could have been isolated meanwhile */
1329 		if (unlikely(isolated_pageblocks))
1330 			mt = get_pageblock_migratetype(page);
1331 
1332 		__free_one_page(page, page_to_pfn(page), zone, 0, mt);
1333 		trace_mm_page_pcpu_drain(page, 0, mt);
1334 	}
1335 	spin_unlock(&zone->lock);
1336 }
1337 
free_one_page(struct zone * zone,struct page * page,unsigned long pfn,unsigned int order,int migratetype)1338 static void free_one_page(struct zone *zone,
1339 				struct page *page, unsigned long pfn,
1340 				unsigned int order,
1341 				int migratetype)
1342 {
1343 	spin_lock(&zone->lock);
1344 	if (unlikely(has_isolate_pageblock(zone) ||
1345 		is_migrate_isolate(migratetype))) {
1346 		migratetype = get_pfnblock_migratetype(page, pfn);
1347 	}
1348 	__free_one_page(page, pfn, zone, order, migratetype);
1349 	spin_unlock(&zone->lock);
1350 }
1351 
__init_single_page(struct page * page,unsigned long pfn,unsigned long zone,int nid)1352 static void __meminit __init_single_page(struct page *page, unsigned long pfn,
1353 				unsigned long zone, int nid)
1354 {
1355 	mm_zero_struct_page(page);
1356 	set_page_links(page, zone, nid, pfn);
1357 	init_page_count(page);
1358 	page_mapcount_reset(page);
1359 	page_cpupid_reset_last(page);
1360 	page_kasan_tag_reset(page);
1361 
1362 	INIT_LIST_HEAD(&page->lru);
1363 #ifdef WANT_PAGE_VIRTUAL
1364 	/* The shift won't overflow because ZONE_NORMAL is below 4G. */
1365 	if (!is_highmem_idx(zone))
1366 		set_page_address(page, __va(pfn << PAGE_SHIFT));
1367 #endif
1368 }
1369 
1370 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
init_reserved_page(unsigned long pfn)1371 static void __meminit init_reserved_page(unsigned long pfn)
1372 {
1373 	pg_data_t *pgdat;
1374 	int nid, zid;
1375 
1376 	if (!early_page_uninitialised(pfn))
1377 		return;
1378 
1379 	nid = early_pfn_to_nid(pfn);
1380 	pgdat = NODE_DATA(nid);
1381 
1382 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1383 		struct zone *zone = &pgdat->node_zones[zid];
1384 
1385 		if (pfn >= zone->zone_start_pfn && pfn < zone_end_pfn(zone))
1386 			break;
1387 	}
1388 	__init_single_page(pfn_to_page(pfn), pfn, zid, nid);
1389 }
1390 #else
init_reserved_page(unsigned long pfn)1391 static inline void init_reserved_page(unsigned long pfn)
1392 {
1393 }
1394 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1395 
1396 /*
1397  * Initialised pages do not have PageReserved set. This function is
1398  * called for each range allocated by the bootmem allocator and
1399  * marks the pages PageReserved. The remaining valid pages are later
1400  * sent to the buddy page allocator.
1401  */
reserve_bootmem_region(phys_addr_t start,phys_addr_t end)1402 void __meminit reserve_bootmem_region(phys_addr_t start, phys_addr_t end)
1403 {
1404 	unsigned long start_pfn = PFN_DOWN(start);
1405 	unsigned long end_pfn = PFN_UP(end);
1406 
1407 	for (; start_pfn < end_pfn; start_pfn++) {
1408 		if (pfn_valid(start_pfn)) {
1409 			struct page *page = pfn_to_page(start_pfn);
1410 
1411 			init_reserved_page(start_pfn);
1412 
1413 			/* Avoid false-positive PageTail() */
1414 			INIT_LIST_HEAD(&page->lru);
1415 
1416 			/*
1417 			 * no need for atomic set_bit because the struct
1418 			 * page is not visible yet so nobody should
1419 			 * access it yet.
1420 			 */
1421 			__SetPageReserved(page);
1422 		}
1423 	}
1424 }
1425 
__free_pages_ok(struct page * page,unsigned int order)1426 static void __free_pages_ok(struct page *page, unsigned int order)
1427 {
1428 	unsigned long flags;
1429 	int migratetype;
1430 	unsigned long pfn = page_to_pfn(page);
1431 
1432 	if (!free_pages_prepare(page, order, true))
1433 		return;
1434 
1435 	migratetype = get_pfnblock_migratetype(page, pfn);
1436 	local_irq_save(flags);
1437 	__count_vm_events(PGFREE, 1 << order);
1438 	free_one_page(page_zone(page), page, pfn, order, migratetype);
1439 	local_irq_restore(flags);
1440 }
1441 
__free_pages_core(struct page * page,unsigned int order)1442 void __free_pages_core(struct page *page, unsigned int order)
1443 {
1444 	unsigned int nr_pages = 1 << order;
1445 	struct page *p = page;
1446 	unsigned int loop;
1447 
1448 	prefetchw(p);
1449 	for (loop = 0; loop < (nr_pages - 1); loop++, p++) {
1450 		prefetchw(p + 1);
1451 		__ClearPageReserved(p);
1452 		set_page_count(p, 0);
1453 	}
1454 	__ClearPageReserved(p);
1455 	set_page_count(p, 0);
1456 
1457 	atomic_long_add(nr_pages, &page_zone(page)->managed_pages);
1458 	set_page_refcounted(page);
1459 	__free_pages(page, order);
1460 }
1461 
1462 #if defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) || \
1463 	defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
1464 
1465 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
1466 
early_pfn_to_nid(unsigned long pfn)1467 int __meminit early_pfn_to_nid(unsigned long pfn)
1468 {
1469 	static DEFINE_SPINLOCK(early_pfn_lock);
1470 	int nid;
1471 
1472 	spin_lock(&early_pfn_lock);
1473 	nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1474 	if (nid < 0)
1475 		nid = first_online_node;
1476 	spin_unlock(&early_pfn_lock);
1477 
1478 	return nid;
1479 }
1480 #endif
1481 
1482 #ifdef CONFIG_NODES_SPAN_OTHER_NODES
1483 /* Only safe to use early in boot when initialisation is single-threaded */
early_pfn_in_nid(unsigned long pfn,int node)1484 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1485 {
1486 	int nid;
1487 
1488 	nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
1489 	if (nid >= 0 && nid != node)
1490 		return false;
1491 	return true;
1492 }
1493 
1494 #else
early_pfn_in_nid(unsigned long pfn,int node)1495 static inline bool __meminit early_pfn_in_nid(unsigned long pfn, int node)
1496 {
1497 	return true;
1498 }
1499 #endif
1500 
1501 
memblock_free_pages(struct page * page,unsigned long pfn,unsigned int order)1502 void __init memblock_free_pages(struct page *page, unsigned long pfn,
1503 							unsigned int order)
1504 {
1505 	if (early_page_uninitialised(pfn))
1506 		return;
1507 	__free_pages_core(page, order);
1508 }
1509 
1510 /*
1511  * Check that the whole (or subset of) a pageblock given by the interval of
1512  * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
1513  * with the migration of free compaction scanner. The scanners then need to
1514  * use only pfn_valid_within() check for arches that allow holes within
1515  * pageblocks.
1516  *
1517  * Return struct page pointer of start_pfn, or NULL if checks were not passed.
1518  *
1519  * It's possible on some configurations to have a setup like node0 node1 node0
1520  * i.e. it's possible that all pages within a zones range of pages do not
1521  * belong to a single zone. We assume that a border between node0 and node1
1522  * can occur within a single pageblock, but not a node0 node1 node0
1523  * interleaving within a single pageblock. It is therefore sufficient to check
1524  * the first and last page of a pageblock and avoid checking each individual
1525  * page in a pageblock.
1526  */
__pageblock_pfn_to_page(unsigned long start_pfn,unsigned long end_pfn,struct zone * zone)1527 struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
1528 				     unsigned long end_pfn, struct zone *zone)
1529 {
1530 	struct page *start_page;
1531 	struct page *end_page;
1532 
1533 	/* end_pfn is one past the range we are checking */
1534 	end_pfn--;
1535 
1536 	if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
1537 		return NULL;
1538 
1539 	start_page = pfn_to_online_page(start_pfn);
1540 	if (!start_page)
1541 		return NULL;
1542 
1543 	if (page_zone(start_page) != zone)
1544 		return NULL;
1545 
1546 	end_page = pfn_to_page(end_pfn);
1547 
1548 	/* This gives a shorter code than deriving page_zone(end_page) */
1549 	if (page_zone_id(start_page) != page_zone_id(end_page))
1550 		return NULL;
1551 
1552 	return start_page;
1553 }
1554 
set_zone_contiguous(struct zone * zone)1555 void set_zone_contiguous(struct zone *zone)
1556 {
1557 	unsigned long block_start_pfn = zone->zone_start_pfn;
1558 	unsigned long block_end_pfn;
1559 
1560 	block_end_pfn = ALIGN(block_start_pfn + 1, pageblock_nr_pages);
1561 	for (; block_start_pfn < zone_end_pfn(zone);
1562 			block_start_pfn = block_end_pfn,
1563 			 block_end_pfn += pageblock_nr_pages) {
1564 
1565 		block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
1566 
1567 		if (!__pageblock_pfn_to_page(block_start_pfn,
1568 					     block_end_pfn, zone))
1569 			return;
1570 	}
1571 
1572 	/* We confirm that there is no hole */
1573 	zone->contiguous = true;
1574 }
1575 
clear_zone_contiguous(struct zone * zone)1576 void clear_zone_contiguous(struct zone *zone)
1577 {
1578 	zone->contiguous = false;
1579 }
1580 
1581 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
deferred_free_range(unsigned long pfn,unsigned long nr_pages)1582 static void __init deferred_free_range(unsigned long pfn,
1583 				       unsigned long nr_pages)
1584 {
1585 	struct page *page;
1586 	unsigned long i;
1587 
1588 	if (!nr_pages)
1589 		return;
1590 
1591 	page = pfn_to_page(pfn);
1592 
1593 	/* Free a large naturally-aligned chunk if possible */
1594 	if (nr_pages == pageblock_nr_pages &&
1595 	    (pfn & (pageblock_nr_pages - 1)) == 0) {
1596 		set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1597 		__free_pages_core(page, pageblock_order);
1598 		return;
1599 	}
1600 
1601 	for (i = 0; i < nr_pages; i++, page++, pfn++) {
1602 		if ((pfn & (pageblock_nr_pages - 1)) == 0)
1603 			set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1604 		__free_pages_core(page, 0);
1605 	}
1606 }
1607 
1608 /* Completion tracking for deferred_init_memmap() threads */
1609 static atomic_t pgdat_init_n_undone __initdata;
1610 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1611 
pgdat_init_report_one_done(void)1612 static inline void __init pgdat_init_report_one_done(void)
1613 {
1614 	if (atomic_dec_and_test(&pgdat_init_n_undone))
1615 		complete(&pgdat_init_all_done_comp);
1616 }
1617 
1618 /*
1619  * Returns true if page needs to be initialized or freed to buddy allocator.
1620  *
1621  * First we check if pfn is valid on architectures where it is possible to have
1622  * holes within pageblock_nr_pages. On systems where it is not possible, this
1623  * function is optimized out.
1624  *
1625  * Then, we check if a current large page is valid by only checking the validity
1626  * of the head pfn.
1627  */
deferred_pfn_valid(unsigned long pfn)1628 static inline bool __init deferred_pfn_valid(unsigned long pfn)
1629 {
1630 	if (!pfn_valid_within(pfn))
1631 		return false;
1632 	if (!(pfn & (pageblock_nr_pages - 1)) && !pfn_valid(pfn))
1633 		return false;
1634 	return true;
1635 }
1636 
1637 /*
1638  * Free pages to buddy allocator. Try to free aligned pages in
1639  * pageblock_nr_pages sizes.
1640  */
deferred_free_pages(unsigned long pfn,unsigned long end_pfn)1641 static void __init deferred_free_pages(unsigned long pfn,
1642 				       unsigned long end_pfn)
1643 {
1644 	unsigned long nr_pgmask = pageblock_nr_pages - 1;
1645 	unsigned long nr_free = 0;
1646 
1647 	for (; pfn < end_pfn; pfn++) {
1648 		if (!deferred_pfn_valid(pfn)) {
1649 			deferred_free_range(pfn - nr_free, nr_free);
1650 			nr_free = 0;
1651 		} else if (!(pfn & nr_pgmask)) {
1652 			deferred_free_range(pfn - nr_free, nr_free);
1653 			nr_free = 1;
1654 			touch_nmi_watchdog();
1655 		} else {
1656 			nr_free++;
1657 		}
1658 	}
1659 	/* Free the last block of pages to allocator */
1660 	deferred_free_range(pfn - nr_free, nr_free);
1661 }
1662 
1663 /*
1664  * Initialize struct pages.  We minimize pfn page lookups and scheduler checks
1665  * by performing it only once every pageblock_nr_pages.
1666  * Return number of pages initialized.
1667  */
deferred_init_pages(struct zone * zone,unsigned long pfn,unsigned long end_pfn)1668 static unsigned long  __init deferred_init_pages(struct zone *zone,
1669 						 unsigned long pfn,
1670 						 unsigned long end_pfn)
1671 {
1672 	unsigned long nr_pgmask = pageblock_nr_pages - 1;
1673 	int nid = zone_to_nid(zone);
1674 	unsigned long nr_pages = 0;
1675 	int zid = zone_idx(zone);
1676 	struct page *page = NULL;
1677 
1678 	for (; pfn < end_pfn; pfn++) {
1679 		if (!deferred_pfn_valid(pfn)) {
1680 			page = NULL;
1681 			continue;
1682 		} else if (!page || !(pfn & nr_pgmask)) {
1683 			page = pfn_to_page(pfn);
1684 			touch_nmi_watchdog();
1685 		} else {
1686 			page++;
1687 		}
1688 		__init_single_page(page, pfn, zid, nid);
1689 		nr_pages++;
1690 	}
1691 	return (nr_pages);
1692 }
1693 
1694 /*
1695  * This function is meant to pre-load the iterator for the zone init.
1696  * Specifically it walks through the ranges until we are caught up to the
1697  * first_init_pfn value and exits there. If we never encounter the value we
1698  * return false indicating there are no valid ranges left.
1699  */
1700 static bool __init
deferred_init_mem_pfn_range_in_zone(u64 * i,struct zone * zone,unsigned long * spfn,unsigned long * epfn,unsigned long first_init_pfn)1701 deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone,
1702 				    unsigned long *spfn, unsigned long *epfn,
1703 				    unsigned long first_init_pfn)
1704 {
1705 	u64 j;
1706 
1707 	/*
1708 	 * Start out by walking through the ranges in this zone that have
1709 	 * already been initialized. We don't need to do anything with them
1710 	 * so we just need to flush them out of the system.
1711 	 */
1712 	for_each_free_mem_pfn_range_in_zone(j, zone, spfn, epfn) {
1713 		if (*epfn <= first_init_pfn)
1714 			continue;
1715 		if (*spfn < first_init_pfn)
1716 			*spfn = first_init_pfn;
1717 		*i = j;
1718 		return true;
1719 	}
1720 
1721 	return false;
1722 }
1723 
1724 /*
1725  * Initialize and free pages. We do it in two loops: first we initialize
1726  * struct page, then free to buddy allocator, because while we are
1727  * freeing pages we can access pages that are ahead (computing buddy
1728  * page in __free_one_page()).
1729  *
1730  * In order to try and keep some memory in the cache we have the loop
1731  * broken along max page order boundaries. This way we will not cause
1732  * any issues with the buddy page computation.
1733  */
1734 static unsigned long __init
deferred_init_maxorder(u64 * i,struct zone * zone,unsigned long * start_pfn,unsigned long * end_pfn)1735 deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn,
1736 		       unsigned long *end_pfn)
1737 {
1738 	unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES);
1739 	unsigned long spfn = *start_pfn, epfn = *end_pfn;
1740 	unsigned long nr_pages = 0;
1741 	u64 j = *i;
1742 
1743 	/* First we loop through and initialize the page values */
1744 	for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) {
1745 		unsigned long t;
1746 
1747 		if (mo_pfn <= *start_pfn)
1748 			break;
1749 
1750 		t = min(mo_pfn, *end_pfn);
1751 		nr_pages += deferred_init_pages(zone, *start_pfn, t);
1752 
1753 		if (mo_pfn < *end_pfn) {
1754 			*start_pfn = mo_pfn;
1755 			break;
1756 		}
1757 	}
1758 
1759 	/* Reset values and now loop through freeing pages as needed */
1760 	swap(j, *i);
1761 
1762 	for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) {
1763 		unsigned long t;
1764 
1765 		if (mo_pfn <= spfn)
1766 			break;
1767 
1768 		t = min(mo_pfn, epfn);
1769 		deferred_free_pages(spfn, t);
1770 
1771 		if (mo_pfn <= epfn)
1772 			break;
1773 	}
1774 
1775 	return nr_pages;
1776 }
1777 
1778 /* Initialise remaining memory on a node */
deferred_init_memmap(void * data)1779 static int __init deferred_init_memmap(void *data)
1780 {
1781 	pg_data_t *pgdat = data;
1782 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1783 	unsigned long spfn = 0, epfn = 0, nr_pages = 0;
1784 	unsigned long first_init_pfn, flags;
1785 	unsigned long start = jiffies;
1786 	struct zone *zone;
1787 	int zid;
1788 	u64 i;
1789 
1790 	/* Bind memory initialisation thread to a local node if possible */
1791 	if (!cpumask_empty(cpumask))
1792 		set_cpus_allowed_ptr(current, cpumask);
1793 
1794 	pgdat_resize_lock(pgdat, &flags);
1795 	first_init_pfn = pgdat->first_deferred_pfn;
1796 	if (first_init_pfn == ULONG_MAX) {
1797 		pgdat_resize_unlock(pgdat, &flags);
1798 		pgdat_init_report_one_done();
1799 		return 0;
1800 	}
1801 
1802 	/* Sanity check boundaries */
1803 	BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
1804 	BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
1805 	pgdat->first_deferred_pfn = ULONG_MAX;
1806 
1807 	/* Only the highest zone is deferred so find it */
1808 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1809 		zone = pgdat->node_zones + zid;
1810 		if (first_init_pfn < zone_end_pfn(zone))
1811 			break;
1812 	}
1813 
1814 	/* If the zone is empty somebody else may have cleared out the zone */
1815 	if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
1816 						 first_init_pfn))
1817 		goto zone_empty;
1818 
1819 	/*
1820 	 * Initialize and free pages in MAX_ORDER sized increments so
1821 	 * that we can avoid introducing any issues with the buddy
1822 	 * allocator.
1823 	 */
1824 	while (spfn < epfn)
1825 		nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
1826 zone_empty:
1827 	pgdat_resize_unlock(pgdat, &flags);
1828 
1829 	/* Sanity check that the next zone really is unpopulated */
1830 	WARN_ON(++zid < MAX_NR_ZONES && populated_zone(++zone));
1831 
1832 	pr_info("node %d initialised, %lu pages in %ums\n",
1833 		pgdat->node_id,	nr_pages, jiffies_to_msecs(jiffies - start));
1834 
1835 	pgdat_init_report_one_done();
1836 	return 0;
1837 }
1838 
1839 /*
1840  * If this zone has deferred pages, try to grow it by initializing enough
1841  * deferred pages to satisfy the allocation specified by order, rounded up to
1842  * the nearest PAGES_PER_SECTION boundary.  So we're adding memory in increments
1843  * of SECTION_SIZE bytes by initializing struct pages in increments of
1844  * PAGES_PER_SECTION * sizeof(struct page) bytes.
1845  *
1846  * Return true when zone was grown, otherwise return false. We return true even
1847  * when we grow less than requested, to let the caller decide if there are
1848  * enough pages to satisfy the allocation.
1849  *
1850  * Note: We use noinline because this function is needed only during boot, and
1851  * it is called from a __ref function _deferred_grow_zone. This way we are
1852  * making sure that it is not inlined into permanent text section.
1853  */
1854 static noinline bool __init
deferred_grow_zone(struct zone * zone,unsigned int order)1855 deferred_grow_zone(struct zone *zone, unsigned int order)
1856 {
1857 	unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
1858 	pg_data_t *pgdat = zone->zone_pgdat;
1859 	unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
1860 	unsigned long spfn, epfn, flags;
1861 	unsigned long nr_pages = 0;
1862 	u64 i;
1863 
1864 	/* Only the last zone may have deferred pages */
1865 	if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
1866 		return false;
1867 
1868 	pgdat_resize_lock(pgdat, &flags);
1869 
1870 	/*
1871 	 * If deferred pages have been initialized while we were waiting for
1872 	 * the lock, return true, as the zone was grown.  The caller will retry
1873 	 * this zone.  We won't return to this function since the caller also
1874 	 * has this static branch.
1875 	 */
1876 	if (!static_branch_unlikely(&deferred_pages)) {
1877 		pgdat_resize_unlock(pgdat, &flags);
1878 		return true;
1879 	}
1880 
1881 	/*
1882 	 * If someone grew this zone while we were waiting for spinlock, return
1883 	 * true, as there might be enough pages already.
1884 	 */
1885 	if (first_deferred_pfn != pgdat->first_deferred_pfn) {
1886 		pgdat_resize_unlock(pgdat, &flags);
1887 		return true;
1888 	}
1889 
1890 	/* If the zone is empty somebody else may have cleared out the zone */
1891 	if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
1892 						 first_deferred_pfn)) {
1893 		pgdat->first_deferred_pfn = ULONG_MAX;
1894 		pgdat_resize_unlock(pgdat, &flags);
1895 		/* Retry only once. */
1896 		return first_deferred_pfn != ULONG_MAX;
1897 	}
1898 
1899 	/*
1900 	 * Initialize and free pages in MAX_ORDER sized increments so
1901 	 * that we can avoid introducing any issues with the buddy
1902 	 * allocator.
1903 	 */
1904 	while (spfn < epfn) {
1905 		/* update our first deferred PFN for this section */
1906 		first_deferred_pfn = spfn;
1907 
1908 		nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
1909 
1910 		/* We should only stop along section boundaries */
1911 		if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION)
1912 			continue;
1913 
1914 		/* If our quota has been met we can stop here */
1915 		if (nr_pages >= nr_pages_needed)
1916 			break;
1917 	}
1918 
1919 	pgdat->first_deferred_pfn = spfn;
1920 	pgdat_resize_unlock(pgdat, &flags);
1921 
1922 	return nr_pages > 0;
1923 }
1924 
1925 /*
1926  * deferred_grow_zone() is __init, but it is called from
1927  * get_page_from_freelist() during early boot until deferred_pages permanently
1928  * disables this call. This is why we have refdata wrapper to avoid warning,
1929  * and to ensure that the function body gets unloaded.
1930  */
1931 static bool __ref
_deferred_grow_zone(struct zone * zone,unsigned int order)1932 _deferred_grow_zone(struct zone *zone, unsigned int order)
1933 {
1934 	return deferred_grow_zone(zone, order);
1935 }
1936 
1937 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
1938 
page_alloc_init_late(void)1939 void __init page_alloc_init_late(void)
1940 {
1941 	struct zone *zone;
1942 	int nid;
1943 
1944 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1945 
1946 	/* There will be num_node_state(N_MEMORY) threads */
1947 	atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
1948 	for_each_node_state(nid, N_MEMORY) {
1949 		kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
1950 	}
1951 
1952 	/* Block until all are initialised */
1953 	wait_for_completion(&pgdat_init_all_done_comp);
1954 
1955 	/*
1956 	 * The number of managed pages has changed due to the initialisation
1957 	 * so the pcpu batch and high limits needs to be updated or the limits
1958 	 * will be artificially small.
1959 	 */
1960 	for_each_populated_zone(zone)
1961 		zone_pcp_update(zone);
1962 
1963 	/*
1964 	 * We initialized the rest of the deferred pages.  Permanently disable
1965 	 * on-demand struct page initialization.
1966 	 */
1967 	static_branch_disable(&deferred_pages);
1968 
1969 	/* Reinit limits that are based on free pages after the kernel is up */
1970 	files_maxfiles_init();
1971 #endif
1972 
1973 	/* Discard memblock private memory */
1974 	memblock_discard();
1975 
1976 	for_each_node_state(nid, N_MEMORY)
1977 		shuffle_free_memory(NODE_DATA(nid));
1978 
1979 	for_each_populated_zone(zone)
1980 		set_zone_contiguous(zone);
1981 }
1982 
1983 #ifdef CONFIG_CMA
1984 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
init_cma_reserved_pageblock(struct page * page)1985 void __init init_cma_reserved_pageblock(struct page *page)
1986 {
1987 	unsigned i = pageblock_nr_pages;
1988 	struct page *p = page;
1989 
1990 	do {
1991 		__ClearPageReserved(p);
1992 		set_page_count(p, 0);
1993 	} while (++p, --i);
1994 
1995 	set_pageblock_migratetype(page, MIGRATE_CMA);
1996 
1997 	if (pageblock_order >= MAX_ORDER) {
1998 		i = pageblock_nr_pages;
1999 		p = page;
2000 		do {
2001 			set_page_refcounted(p);
2002 			__free_pages(p, MAX_ORDER - 1);
2003 			p += MAX_ORDER_NR_PAGES;
2004 		} while (i -= MAX_ORDER_NR_PAGES);
2005 	} else {
2006 		set_page_refcounted(page);
2007 		__free_pages(page, pageblock_order);
2008 	}
2009 
2010 	adjust_managed_page_count(page, pageblock_nr_pages);
2011 }
2012 #endif
2013 
2014 /*
2015  * The order of subdivision here is critical for the IO subsystem.
2016  * Please do not alter this order without good reasons and regression
2017  * testing. Specifically, as large blocks of memory are subdivided,
2018  * the order in which smaller blocks are delivered depends on the order
2019  * they're subdivided in this function. This is the primary factor
2020  * influencing the order in which pages are delivered to the IO
2021  * subsystem according to empirical testing, and this is also justified
2022  * by considering the behavior of a buddy system containing a single
2023  * large block of memory acted on by a series of small allocations.
2024  * This behavior is a critical factor in sglist merging's success.
2025  *
2026  * -- nyc
2027  */
expand(struct zone * zone,struct page * page,int low,int high,struct free_area * area,int migratetype)2028 static inline void expand(struct zone *zone, struct page *page,
2029 	int low, int high, struct free_area *area,
2030 	int migratetype)
2031 {
2032 	unsigned long size = 1 << high;
2033 
2034 	while (high > low) {
2035 		area--;
2036 		high--;
2037 		size >>= 1;
2038 		VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
2039 
2040 		/*
2041 		 * Mark as guard pages (or page), that will allow to
2042 		 * merge back to allocator when buddy will be freed.
2043 		 * Corresponding page table entries will not be touched,
2044 		 * pages will stay not present in virtual address space
2045 		 */
2046 		if (set_page_guard(zone, &page[size], high, migratetype))
2047 			continue;
2048 
2049 		add_to_free_area(&page[size], area, migratetype);
2050 		set_page_order(&page[size], high);
2051 	}
2052 }
2053 
check_new_page_bad(struct page * page)2054 static void check_new_page_bad(struct page *page)
2055 {
2056 	const char *bad_reason = NULL;
2057 	unsigned long bad_flags = 0;
2058 
2059 	if (unlikely(atomic_read(&page->_mapcount) != -1))
2060 		bad_reason = "nonzero mapcount";
2061 	if (unlikely(page->mapping != NULL))
2062 		bad_reason = "non-NULL mapping";
2063 	if (unlikely(page_ref_count(page) != 0))
2064 		bad_reason = "nonzero _refcount";
2065 	if (unlikely(page->flags & __PG_HWPOISON)) {
2066 		bad_reason = "HWPoisoned (hardware-corrupted)";
2067 		bad_flags = __PG_HWPOISON;
2068 		/* Don't complain about hwpoisoned pages */
2069 		page_mapcount_reset(page); /* remove PageBuddy */
2070 		return;
2071 	}
2072 	if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
2073 		bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
2074 		bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
2075 	}
2076 #ifdef CONFIG_MEMCG
2077 	if (unlikely(page->mem_cgroup))
2078 		bad_reason = "page still charged to cgroup";
2079 #endif
2080 	bad_page(page, bad_reason, bad_flags);
2081 }
2082 
2083 /*
2084  * This page is about to be returned from the page allocator
2085  */
check_new_page(struct page * page)2086 static inline int check_new_page(struct page *page)
2087 {
2088 	if (likely(page_expected_state(page,
2089 				PAGE_FLAGS_CHECK_AT_PREP|__PG_HWPOISON)))
2090 		return 0;
2091 
2092 	check_new_page_bad(page);
2093 	return 1;
2094 }
2095 
free_pages_prezeroed(void)2096 static inline bool free_pages_prezeroed(void)
2097 {
2098 	return (IS_ENABLED(CONFIG_PAGE_POISONING_ZERO) &&
2099 		page_poisoning_enabled()) || want_init_on_free();
2100 }
2101 
2102 #ifdef CONFIG_DEBUG_VM
2103 /*
2104  * With DEBUG_VM enabled, order-0 pages are checked for expected state when
2105  * being allocated from pcp lists. With debug_pagealloc also enabled, they are
2106  * also checked when pcp lists are refilled from the free lists.
2107  */
check_pcp_refill(struct page * page)2108 static inline bool check_pcp_refill(struct page *page)
2109 {
2110 	if (debug_pagealloc_enabled_static())
2111 		return check_new_page(page);
2112 	else
2113 		return false;
2114 }
2115 
check_new_pcp(struct page * page)2116 static inline bool check_new_pcp(struct page *page)
2117 {
2118 	return check_new_page(page);
2119 }
2120 #else
2121 /*
2122  * With DEBUG_VM disabled, free order-0 pages are checked for expected state
2123  * when pcp lists are being refilled from the free lists. With debug_pagealloc
2124  * enabled, they are also checked when being allocated from the pcp lists.
2125  */
check_pcp_refill(struct page * page)2126 static inline bool check_pcp_refill(struct page *page)
2127 {
2128 	return check_new_page(page);
2129 }
check_new_pcp(struct page * page)2130 static inline bool check_new_pcp(struct page *page)
2131 {
2132 	if (debug_pagealloc_enabled_static())
2133 		return check_new_page(page);
2134 	else
2135 		return false;
2136 }
2137 #endif /* CONFIG_DEBUG_VM */
2138 
check_new_pages(struct page * page,unsigned int order)2139 static bool check_new_pages(struct page *page, unsigned int order)
2140 {
2141 	int i;
2142 	for (i = 0; i < (1 << order); i++) {
2143 		struct page *p = page + i;
2144 
2145 		if (unlikely(check_new_page(p)))
2146 			return true;
2147 	}
2148 
2149 	return false;
2150 }
2151 
post_alloc_hook(struct page * page,unsigned int order,gfp_t gfp_flags)2152 inline void post_alloc_hook(struct page *page, unsigned int order,
2153 				gfp_t gfp_flags)
2154 {
2155 	set_page_private(page, 0);
2156 	set_page_refcounted(page);
2157 
2158 	arch_alloc_page(page, order);
2159 	if (debug_pagealloc_enabled_static())
2160 		kernel_map_pages(page, 1 << order, 1);
2161 	kasan_alloc_pages(page, order);
2162 	kernel_poison_pages(page, 1 << order, 1);
2163 	set_page_owner(page, order, gfp_flags);
2164 }
2165 
prep_new_page(struct page * page,unsigned int order,gfp_t gfp_flags,unsigned int alloc_flags)2166 static void prep_new_page(struct page *page, unsigned int order, gfp_t gfp_flags,
2167 							unsigned int alloc_flags)
2168 {
2169 	post_alloc_hook(page, order, gfp_flags);
2170 
2171 	if (!free_pages_prezeroed() && want_init_on_alloc(gfp_flags))
2172 		kernel_init_free_pages(page, 1 << order);
2173 
2174 	if (order && (gfp_flags & __GFP_COMP))
2175 		prep_compound_page(page, order);
2176 
2177 	/*
2178 	 * page is set pfmemalloc when ALLOC_NO_WATERMARKS was necessary to
2179 	 * allocate the page. The expectation is that the caller is taking
2180 	 * steps that will free more memory. The caller should avoid the page
2181 	 * being used for !PFMEMALLOC purposes.
2182 	 */
2183 	if (alloc_flags & ALLOC_NO_WATERMARKS)
2184 		set_page_pfmemalloc(page);
2185 	else
2186 		clear_page_pfmemalloc(page);
2187 }
2188 
2189 /*
2190  * Go through the free lists for the given migratetype and remove
2191  * the smallest available page from the freelists
2192  */
2193 static __always_inline
__rmqueue_smallest(struct zone * zone,unsigned int order,int migratetype)2194 struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
2195 						int migratetype)
2196 {
2197 	unsigned int current_order;
2198 	struct free_area *area;
2199 	struct page *page;
2200 
2201 	/* Find a page of the appropriate size in the preferred list */
2202 	for (current_order = order; current_order < MAX_ORDER; ++current_order) {
2203 		area = &(zone->free_area[current_order]);
2204 		page = get_page_from_free_area(area, migratetype);
2205 		if (!page)
2206 			continue;
2207 		del_page_from_free_area(page, area);
2208 		expand(zone, page, order, current_order, area, migratetype);
2209 		set_pcppage_migratetype(page, migratetype);
2210 		return page;
2211 	}
2212 
2213 	return NULL;
2214 }
2215 
2216 
2217 /*
2218  * This array describes the order lists are fallen back to when
2219  * the free lists for the desirable migrate type are depleted
2220  */
2221 static int fallbacks[MIGRATE_TYPES][4] = {
2222 	[MIGRATE_UNMOVABLE]   = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE,   MIGRATE_TYPES },
2223 	[MIGRATE_MOVABLE]     = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_TYPES },
2224 	[MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE,   MIGRATE_MOVABLE,   MIGRATE_TYPES },
2225 #ifdef CONFIG_CMA
2226 	[MIGRATE_CMA]         = { MIGRATE_TYPES }, /* Never used */
2227 #endif
2228 #ifdef CONFIG_MEMORY_ISOLATION
2229 	[MIGRATE_ISOLATE]     = { MIGRATE_TYPES }, /* Never used */
2230 #endif
2231 };
2232 
2233 #ifdef CONFIG_CMA
__rmqueue_cma_fallback(struct zone * zone,unsigned int order)2234 static __always_inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2235 					unsigned int order)
2236 {
2237 	return __rmqueue_smallest(zone, order, MIGRATE_CMA);
2238 }
2239 #else
__rmqueue_cma_fallback(struct zone * zone,unsigned int order)2240 static inline struct page *__rmqueue_cma_fallback(struct zone *zone,
2241 					unsigned int order) { return NULL; }
2242 #endif
2243 
2244 /*
2245  * Move the free pages in a range to the free lists of the requested type.
2246  * Note that start_page and end_pages are not aligned on a pageblock
2247  * boundary. If alignment is required, use move_freepages_block()
2248  */
move_freepages(struct zone * zone,struct page * start_page,struct page * end_page,int migratetype,int * num_movable)2249 static int move_freepages(struct zone *zone,
2250 			  struct page *start_page, struct page *end_page,
2251 			  int migratetype, int *num_movable)
2252 {
2253 	struct page *page;
2254 	unsigned int order;
2255 	int pages_moved = 0;
2256 
2257 	for (page = start_page; page <= end_page;) {
2258 		if (!pfn_valid_within(page_to_pfn(page))) {
2259 			page++;
2260 			continue;
2261 		}
2262 
2263 		if (!PageBuddy(page)) {
2264 			/*
2265 			 * We assume that pages that could be isolated for
2266 			 * migration are movable. But we don't actually try
2267 			 * isolating, as that would be expensive.
2268 			 */
2269 			if (num_movable &&
2270 					(PageLRU(page) || __PageMovable(page)))
2271 				(*num_movable)++;
2272 
2273 			page++;
2274 			continue;
2275 		}
2276 
2277 		/* Make sure we are not inadvertently changing nodes */
2278 		VM_BUG_ON_PAGE(page_to_nid(page) != zone_to_nid(zone), page);
2279 		VM_BUG_ON_PAGE(page_zone(page) != zone, page);
2280 
2281 		order = page_order(page);
2282 		move_to_free_area(page, &zone->free_area[order], migratetype);
2283 		page += 1 << order;
2284 		pages_moved += 1 << order;
2285 	}
2286 
2287 	return pages_moved;
2288 }
2289 
move_freepages_block(struct zone * zone,struct page * page,int migratetype,int * num_movable)2290 int move_freepages_block(struct zone *zone, struct page *page,
2291 				int migratetype, int *num_movable)
2292 {
2293 	unsigned long start_pfn, end_pfn;
2294 	struct page *start_page, *end_page;
2295 
2296 	if (num_movable)
2297 		*num_movable = 0;
2298 
2299 	start_pfn = page_to_pfn(page);
2300 	start_pfn = start_pfn & ~(pageblock_nr_pages-1);
2301 	start_page = pfn_to_page(start_pfn);
2302 	end_page = start_page + pageblock_nr_pages - 1;
2303 	end_pfn = start_pfn + pageblock_nr_pages - 1;
2304 
2305 	/* Do not cross zone boundaries */
2306 	if (!zone_spans_pfn(zone, start_pfn))
2307 		start_page = page;
2308 	if (!zone_spans_pfn(zone, end_pfn))
2309 		return 0;
2310 
2311 	return move_freepages(zone, start_page, end_page, migratetype,
2312 								num_movable);
2313 }
2314 
change_pageblock_range(struct page * pageblock_page,int start_order,int migratetype)2315 static void change_pageblock_range(struct page *pageblock_page,
2316 					int start_order, int migratetype)
2317 {
2318 	int nr_pageblocks = 1 << (start_order - pageblock_order);
2319 
2320 	while (nr_pageblocks--) {
2321 		set_pageblock_migratetype(pageblock_page, migratetype);
2322 		pageblock_page += pageblock_nr_pages;
2323 	}
2324 }
2325 
2326 /*
2327  * When we are falling back to another migratetype during allocation, try to
2328  * steal extra free pages from the same pageblocks to satisfy further
2329  * allocations, instead of polluting multiple pageblocks.
2330  *
2331  * If we are stealing a relatively large buddy page, it is likely there will
2332  * be more free pages in the pageblock, so try to steal them all. For
2333  * reclaimable and unmovable allocations, we steal regardless of page size,
2334  * as fragmentation caused by those allocations polluting movable pageblocks
2335  * is worse than movable allocations stealing from unmovable and reclaimable
2336  * pageblocks.
2337  */
can_steal_fallback(unsigned int order,int start_mt)2338 static bool can_steal_fallback(unsigned int order, int start_mt)
2339 {
2340 	/*
2341 	 * Leaving this order check is intended, although there is
2342 	 * relaxed order check in next check. The reason is that
2343 	 * we can actually steal whole pageblock if this condition met,
2344 	 * but, below check doesn't guarantee it and that is just heuristic
2345 	 * so could be changed anytime.
2346 	 */
2347 	if (order >= pageblock_order)
2348 		return true;
2349 
2350 	if (order >= pageblock_order / 2 ||
2351 		start_mt == MIGRATE_RECLAIMABLE ||
2352 		start_mt == MIGRATE_UNMOVABLE ||
2353 		page_group_by_mobility_disabled)
2354 		return true;
2355 
2356 	return false;
2357 }
2358 
boost_watermark(struct zone * zone)2359 static inline void boost_watermark(struct zone *zone)
2360 {
2361 	unsigned long max_boost;
2362 
2363 	if (!watermark_boost_factor)
2364 		return;
2365 
2366 	max_boost = mult_frac(zone->_watermark[WMARK_HIGH],
2367 			watermark_boost_factor, 10000);
2368 
2369 	/*
2370 	 * high watermark may be uninitialised if fragmentation occurs
2371 	 * very early in boot so do not boost. We do not fall
2372 	 * through and boost by pageblock_nr_pages as failing
2373 	 * allocations that early means that reclaim is not going
2374 	 * to help and it may even be impossible to reclaim the
2375 	 * boosted watermark resulting in a hang.
2376 	 */
2377 	if (!max_boost)
2378 		return;
2379 
2380 	max_boost = max(pageblock_nr_pages, max_boost);
2381 
2382 	zone->watermark_boost = min(zone->watermark_boost + pageblock_nr_pages,
2383 		max_boost);
2384 }
2385 
2386 /*
2387  * This function implements actual steal behaviour. If order is large enough,
2388  * we can steal whole pageblock. If not, we first move freepages in this
2389  * pageblock to our migratetype and determine how many already-allocated pages
2390  * are there in the pageblock with a compatible migratetype. If at least half
2391  * of pages are free or compatible, we can change migratetype of the pageblock
2392  * itself, so pages freed in the future will be put on the correct free list.
2393  */
steal_suitable_fallback(struct zone * zone,struct page * page,unsigned int alloc_flags,int start_type,bool whole_block)2394 static void steal_suitable_fallback(struct zone *zone, struct page *page,
2395 		unsigned int alloc_flags, int start_type, bool whole_block)
2396 {
2397 	unsigned int current_order = page_order(page);
2398 	struct free_area *area;
2399 	int free_pages, movable_pages, alike_pages;
2400 	int old_block_type;
2401 
2402 	old_block_type = get_pageblock_migratetype(page);
2403 
2404 	/*
2405 	 * This can happen due to races and we want to prevent broken
2406 	 * highatomic accounting.
2407 	 */
2408 	if (is_migrate_highatomic(old_block_type))
2409 		goto single_page;
2410 
2411 	/* Take ownership for orders >= pageblock_order */
2412 	if (current_order >= pageblock_order) {
2413 		change_pageblock_range(page, current_order, start_type);
2414 		goto single_page;
2415 	}
2416 
2417 	/*
2418 	 * Boost watermarks to increase reclaim pressure to reduce the
2419 	 * likelihood of future fallbacks. Wake kswapd now as the node
2420 	 * may be balanced overall and kswapd will not wake naturally.
2421 	 */
2422 	boost_watermark(zone);
2423 	if (alloc_flags & ALLOC_KSWAPD)
2424 		set_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
2425 
2426 	/* We are not allowed to try stealing from the whole block */
2427 	if (!whole_block)
2428 		goto single_page;
2429 
2430 	free_pages = move_freepages_block(zone, page, start_type,
2431 						&movable_pages);
2432 	/*
2433 	 * Determine how many pages are compatible with our allocation.
2434 	 * For movable allocation, it's the number of movable pages which
2435 	 * we just obtained. For other types it's a bit more tricky.
2436 	 */
2437 	if (start_type == MIGRATE_MOVABLE) {
2438 		alike_pages = movable_pages;
2439 	} else {
2440 		/*
2441 		 * If we are falling back a RECLAIMABLE or UNMOVABLE allocation
2442 		 * to MOVABLE pageblock, consider all non-movable pages as
2443 		 * compatible. If it's UNMOVABLE falling back to RECLAIMABLE or
2444 		 * vice versa, be conservative since we can't distinguish the
2445 		 * exact migratetype of non-movable pages.
2446 		 */
2447 		if (old_block_type == MIGRATE_MOVABLE)
2448 			alike_pages = pageblock_nr_pages
2449 						- (free_pages + movable_pages);
2450 		else
2451 			alike_pages = 0;
2452 	}
2453 
2454 	/* moving whole block can fail due to zone boundary conditions */
2455 	if (!free_pages)
2456 		goto single_page;
2457 
2458 	/*
2459 	 * If a sufficient number of pages in the block are either free or of
2460 	 * comparable migratability as our allocation, claim the whole block.
2461 	 */
2462 	if (free_pages + alike_pages >= (1 << (pageblock_order-1)) ||
2463 			page_group_by_mobility_disabled)
2464 		set_pageblock_migratetype(page, start_type);
2465 
2466 	return;
2467 
2468 single_page:
2469 	area = &zone->free_area[current_order];
2470 	move_to_free_area(page, area, start_type);
2471 }
2472 
2473 /*
2474  * Check whether there is a suitable fallback freepage with requested order.
2475  * If only_stealable is true, this function returns fallback_mt only if
2476  * we can steal other freepages all together. This would help to reduce
2477  * fragmentation due to mixed migratetype pages in one pageblock.
2478  */
find_suitable_fallback(struct free_area * area,unsigned int order,int migratetype,bool only_stealable,bool * can_steal)2479 int find_suitable_fallback(struct free_area *area, unsigned int order,
2480 			int migratetype, bool only_stealable, bool *can_steal)
2481 {
2482 	int i;
2483 	int fallback_mt;
2484 
2485 	if (area->nr_free == 0)
2486 		return -1;
2487 
2488 	*can_steal = false;
2489 	for (i = 0;; i++) {
2490 		fallback_mt = fallbacks[migratetype][i];
2491 		if (fallback_mt == MIGRATE_TYPES)
2492 			break;
2493 
2494 		if (free_area_empty(area, fallback_mt))
2495 			continue;
2496 
2497 		if (can_steal_fallback(order, migratetype))
2498 			*can_steal = true;
2499 
2500 		if (!only_stealable)
2501 			return fallback_mt;
2502 
2503 		if (*can_steal)
2504 			return fallback_mt;
2505 	}
2506 
2507 	return -1;
2508 }
2509 
2510 /*
2511  * Reserve a pageblock for exclusive use of high-order atomic allocations if
2512  * there are no empty page blocks that contain a page with a suitable order
2513  */
reserve_highatomic_pageblock(struct page * page,struct zone * zone,unsigned int alloc_order)2514 static void reserve_highatomic_pageblock(struct page *page, struct zone *zone,
2515 				unsigned int alloc_order)
2516 {
2517 	int mt;
2518 	unsigned long max_managed, flags;
2519 
2520 	/*
2521 	 * Limit the number reserved to 1 pageblock or roughly 1% of a zone.
2522 	 * Check is race-prone but harmless.
2523 	 */
2524 	max_managed = (zone_managed_pages(zone) / 100) + pageblock_nr_pages;
2525 	if (zone->nr_reserved_highatomic >= max_managed)
2526 		return;
2527 
2528 	spin_lock_irqsave(&zone->lock, flags);
2529 
2530 	/* Recheck the nr_reserved_highatomic limit under the lock */
2531 	if (zone->nr_reserved_highatomic >= max_managed)
2532 		goto out_unlock;
2533 
2534 	/* Yoink! */
2535 	mt = get_pageblock_migratetype(page);
2536 	if (!is_migrate_highatomic(mt) && !is_migrate_isolate(mt)
2537 	    && !is_migrate_cma(mt)) {
2538 		zone->nr_reserved_highatomic += pageblock_nr_pages;
2539 		set_pageblock_migratetype(page, MIGRATE_HIGHATOMIC);
2540 		move_freepages_block(zone, page, MIGRATE_HIGHATOMIC, NULL);
2541 	}
2542 
2543 out_unlock:
2544 	spin_unlock_irqrestore(&zone->lock, flags);
2545 }
2546 
2547 /*
2548  * Used when an allocation is about to fail under memory pressure. This
2549  * potentially hurts the reliability of high-order allocations when under
2550  * intense memory pressure but failed atomic allocations should be easier
2551  * to recover from than an OOM.
2552  *
2553  * If @force is true, try to unreserve a pageblock even though highatomic
2554  * pageblock is exhausted.
2555  */
unreserve_highatomic_pageblock(const struct alloc_context * ac,bool force)2556 static bool unreserve_highatomic_pageblock(const struct alloc_context *ac,
2557 						bool force)
2558 {
2559 	struct zonelist *zonelist = ac->zonelist;
2560 	unsigned long flags;
2561 	struct zoneref *z;
2562 	struct zone *zone;
2563 	struct page *page;
2564 	int order;
2565 	bool ret;
2566 
2567 	for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
2568 								ac->nodemask) {
2569 		/*
2570 		 * Preserve at least one pageblock unless memory pressure
2571 		 * is really high.
2572 		 */
2573 		if (!force && zone->nr_reserved_highatomic <=
2574 					pageblock_nr_pages)
2575 			continue;
2576 
2577 		spin_lock_irqsave(&zone->lock, flags);
2578 		for (order = 0; order < MAX_ORDER; order++) {
2579 			struct free_area *area = &(zone->free_area[order]);
2580 
2581 			page = get_page_from_free_area(area, MIGRATE_HIGHATOMIC);
2582 			if (!page)
2583 				continue;
2584 
2585 			/*
2586 			 * In page freeing path, migratetype change is racy so
2587 			 * we can counter several free pages in a pageblock
2588 			 * in this loop althoug we changed the pageblock type
2589 			 * from highatomic to ac->migratetype. So we should
2590 			 * adjust the count once.
2591 			 */
2592 			if (is_migrate_highatomic_page(page)) {
2593 				/*
2594 				 * It should never happen but changes to
2595 				 * locking could inadvertently allow a per-cpu
2596 				 * drain to add pages to MIGRATE_HIGHATOMIC
2597 				 * while unreserving so be safe and watch for
2598 				 * underflows.
2599 				 */
2600 				zone->nr_reserved_highatomic -= min(
2601 						pageblock_nr_pages,
2602 						zone->nr_reserved_highatomic);
2603 			}
2604 
2605 			/*
2606 			 * Convert to ac->migratetype and avoid the normal
2607 			 * pageblock stealing heuristics. Minimally, the caller
2608 			 * is doing the work and needs the pages. More
2609 			 * importantly, if the block was always converted to
2610 			 * MIGRATE_UNMOVABLE or another type then the number
2611 			 * of pageblocks that cannot be completely freed
2612 			 * may increase.
2613 			 */
2614 			set_pageblock_migratetype(page, ac->migratetype);
2615 			ret = move_freepages_block(zone, page, ac->migratetype,
2616 									NULL);
2617 			if (ret) {
2618 				spin_unlock_irqrestore(&zone->lock, flags);
2619 				return ret;
2620 			}
2621 		}
2622 		spin_unlock_irqrestore(&zone->lock, flags);
2623 	}
2624 
2625 	return false;
2626 }
2627 
2628 /*
2629  * Try finding a free buddy page on the fallback list and put it on the free
2630  * list of requested migratetype, possibly along with other pages from the same
2631  * block, depending on fragmentation avoidance heuristics. Returns true if
2632  * fallback was found so that __rmqueue_smallest() can grab it.
2633  *
2634  * The use of signed ints for order and current_order is a deliberate
2635  * deviation from the rest of this file, to make the for loop
2636  * condition simpler.
2637  */
2638 static __always_inline bool
__rmqueue_fallback(struct zone * zone,int order,int start_migratetype,unsigned int alloc_flags)2639 __rmqueue_fallback(struct zone *zone, int order, int start_migratetype,
2640 						unsigned int alloc_flags)
2641 {
2642 	struct free_area *area;
2643 	int current_order;
2644 	int min_order = order;
2645 	struct page *page;
2646 	int fallback_mt;
2647 	bool can_steal;
2648 
2649 	/*
2650 	 * Do not steal pages from freelists belonging to other pageblocks
2651 	 * i.e. orders < pageblock_order. If there are no local zones free,
2652 	 * the zonelists will be reiterated without ALLOC_NOFRAGMENT.
2653 	 */
2654 	if (alloc_flags & ALLOC_NOFRAGMENT)
2655 		min_order = pageblock_order;
2656 
2657 	/*
2658 	 * Find the largest available free page in the other list. This roughly
2659 	 * approximates finding the pageblock with the most free pages, which
2660 	 * would be too costly to do exactly.
2661 	 */
2662 	for (current_order = MAX_ORDER - 1; current_order >= min_order;
2663 				--current_order) {
2664 		area = &(zone->free_area[current_order]);
2665 		fallback_mt = find_suitable_fallback(area, current_order,
2666 				start_migratetype, false, &can_steal);
2667 		if (fallback_mt == -1)
2668 			continue;
2669 
2670 		/*
2671 		 * We cannot steal all free pages from the pageblock and the
2672 		 * requested migratetype is movable. In that case it's better to
2673 		 * steal and split the smallest available page instead of the
2674 		 * largest available page, because even if the next movable
2675 		 * allocation falls back into a different pageblock than this
2676 		 * one, it won't cause permanent fragmentation.
2677 		 */
2678 		if (!can_steal && start_migratetype == MIGRATE_MOVABLE
2679 					&& current_order > order)
2680 			goto find_smallest;
2681 
2682 		goto do_steal;
2683 	}
2684 
2685 	return false;
2686 
2687 find_smallest:
2688 	for (current_order = order; current_order < MAX_ORDER;
2689 							current_order++) {
2690 		area = &(zone->free_area[current_order]);
2691 		fallback_mt = find_suitable_fallback(area, current_order,
2692 				start_migratetype, false, &can_steal);
2693 		if (fallback_mt != -1)
2694 			break;
2695 	}
2696 
2697 	/*
2698 	 * This should not happen - we already found a suitable fallback
2699 	 * when looking for the largest page.
2700 	 */
2701 	VM_BUG_ON(current_order == MAX_ORDER);
2702 
2703 do_steal:
2704 	page = get_page_from_free_area(area, fallback_mt);
2705 
2706 	steal_suitable_fallback(zone, page, alloc_flags, start_migratetype,
2707 								can_steal);
2708 
2709 	trace_mm_page_alloc_extfrag(page, order, current_order,
2710 		start_migratetype, fallback_mt);
2711 
2712 	return true;
2713 
2714 }
2715 
2716 /*
2717  * Do the hard work of removing an element from the buddy allocator.
2718  * Call me with the zone->lock already held.
2719  */
2720 static __always_inline struct page *
__rmqueue(struct zone * zone,unsigned int order,int migratetype,unsigned int alloc_flags)2721 __rmqueue(struct zone *zone, unsigned int order, int migratetype,
2722 						unsigned int alloc_flags)
2723 {
2724 	struct page *page;
2725 
2726 retry:
2727 	page = __rmqueue_smallest(zone, order, migratetype);
2728 	if (unlikely(!page)) {
2729 		if (migratetype == MIGRATE_MOVABLE)
2730 			page = __rmqueue_cma_fallback(zone, order);
2731 
2732 		if (!page && __rmqueue_fallback(zone, order, migratetype,
2733 								alloc_flags))
2734 			goto retry;
2735 	}
2736 
2737 	trace_mm_page_alloc_zone_locked(page, order, migratetype);
2738 	return page;
2739 }
2740 
2741 /*
2742  * Obtain a specified number of elements from the buddy allocator, all under
2743  * a single hold of the lock, for efficiency.  Add them to the supplied list.
2744  * Returns the number of new pages which were placed at *list.
2745  */
rmqueue_bulk(struct zone * zone,unsigned int order,unsigned long count,struct list_head * list,int migratetype,unsigned int alloc_flags)2746 static int rmqueue_bulk(struct zone *zone, unsigned int order,
2747 			unsigned long count, struct list_head *list,
2748 			int migratetype, unsigned int alloc_flags)
2749 {
2750 	int i, alloced = 0;
2751 
2752 	spin_lock(&zone->lock);
2753 	for (i = 0; i < count; ++i) {
2754 		struct page *page = __rmqueue(zone, order, migratetype,
2755 								alloc_flags);
2756 		if (unlikely(page == NULL))
2757 			break;
2758 
2759 		if (unlikely(check_pcp_refill(page)))
2760 			continue;
2761 
2762 		/*
2763 		 * Split buddy pages returned by expand() are received here in
2764 		 * physical page order. The page is added to the tail of
2765 		 * caller's list. From the callers perspective, the linked list
2766 		 * is ordered by page number under some conditions. This is
2767 		 * useful for IO devices that can forward direction from the
2768 		 * head, thus also in the physical page order. This is useful
2769 		 * for IO devices that can merge IO requests if the physical
2770 		 * pages are ordered properly.
2771 		 */
2772 		list_add_tail(&page->lru, list);
2773 		alloced++;
2774 		if (is_migrate_cma(get_pcppage_migratetype(page)))
2775 			__mod_zone_page_state(zone, NR_FREE_CMA_PAGES,
2776 					      -(1 << order));
2777 	}
2778 
2779 	/*
2780 	 * i pages were removed from the buddy list even if some leak due
2781 	 * to check_pcp_refill failing so adjust NR_FREE_PAGES based
2782 	 * on i. Do not confuse with 'alloced' which is the number of
2783 	 * pages added to the pcp list.
2784 	 */
2785 	__mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order));
2786 	spin_unlock(&zone->lock);
2787 	return alloced;
2788 }
2789 
2790 #ifdef CONFIG_NUMA
2791 /*
2792  * Called from the vmstat counter updater to drain pagesets of this
2793  * currently executing processor on remote nodes after they have
2794  * expired.
2795  *
2796  * Note that this function must be called with the thread pinned to
2797  * a single processor.
2798  */
drain_zone_pages(struct zone * zone,struct per_cpu_pages * pcp)2799 void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp)
2800 {
2801 	unsigned long flags;
2802 	int to_drain, batch;
2803 
2804 	local_irq_save(flags);
2805 	batch = READ_ONCE(pcp->batch);
2806 	to_drain = min(pcp->count, batch);
2807 	if (to_drain > 0)
2808 		free_pcppages_bulk(zone, to_drain, pcp);
2809 	local_irq_restore(flags);
2810 }
2811 #endif
2812 
2813 /*
2814  * Drain pcplists of the indicated processor and zone.
2815  *
2816  * The processor must either be the current processor and the
2817  * thread pinned to the current processor or a processor that
2818  * is not online.
2819  */
drain_pages_zone(unsigned int cpu,struct zone * zone)2820 static void drain_pages_zone(unsigned int cpu, struct zone *zone)
2821 {
2822 	unsigned long flags;
2823 	struct per_cpu_pageset *pset;
2824 	struct per_cpu_pages *pcp;
2825 
2826 	local_irq_save(flags);
2827 	pset = per_cpu_ptr(zone->pageset, cpu);
2828 
2829 	pcp = &pset->pcp;
2830 	if (pcp->count)
2831 		free_pcppages_bulk(zone, pcp->count, pcp);
2832 	local_irq_restore(flags);
2833 }
2834 
2835 /*
2836  * Drain pcplists of all zones on the indicated processor.
2837  *
2838  * The processor must either be the current processor and the
2839  * thread pinned to the current processor or a processor that
2840  * is not online.
2841  */
drain_pages(unsigned int cpu)2842 static void drain_pages(unsigned int cpu)
2843 {
2844 	struct zone *zone;
2845 
2846 	for_each_populated_zone(zone) {
2847 		drain_pages_zone(cpu, zone);
2848 	}
2849 }
2850 
2851 /*
2852  * Spill all of this CPU's per-cpu pages back into the buddy allocator.
2853  *
2854  * The CPU has to be pinned. When zone parameter is non-NULL, spill just
2855  * the single zone's pages.
2856  */
drain_local_pages(struct zone * zone)2857 void drain_local_pages(struct zone *zone)
2858 {
2859 	int cpu = smp_processor_id();
2860 
2861 	if (zone)
2862 		drain_pages_zone(cpu, zone);
2863 	else
2864 		drain_pages(cpu);
2865 }
2866 
drain_local_pages_wq(struct work_struct * work)2867 static void drain_local_pages_wq(struct work_struct *work)
2868 {
2869 	struct pcpu_drain *drain;
2870 
2871 	drain = container_of(work, struct pcpu_drain, work);
2872 
2873 	/*
2874 	 * drain_all_pages doesn't use proper cpu hotplug protection so
2875 	 * we can race with cpu offline when the WQ can move this from
2876 	 * a cpu pinned worker to an unbound one. We can operate on a different
2877 	 * cpu which is allright but we also have to make sure to not move to
2878 	 * a different one.
2879 	 */
2880 	preempt_disable();
2881 	drain_local_pages(drain->zone);
2882 	preempt_enable();
2883 }
2884 
2885 /*
2886  * Spill all the per-cpu pages from all CPUs back into the buddy allocator.
2887  *
2888  * When zone parameter is non-NULL, spill just the single zone's pages.
2889  *
2890  * Note that this can be extremely slow as the draining happens in a workqueue.
2891  */
drain_all_pages(struct zone * zone)2892 void drain_all_pages(struct zone *zone)
2893 {
2894 	int cpu;
2895 
2896 	/*
2897 	 * Allocate in the BSS so we wont require allocation in
2898 	 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
2899 	 */
2900 	static cpumask_t cpus_with_pcps;
2901 
2902 	/*
2903 	 * Make sure nobody triggers this path before mm_percpu_wq is fully
2904 	 * initialized.
2905 	 */
2906 	if (WARN_ON_ONCE(!mm_percpu_wq))
2907 		return;
2908 
2909 	/*
2910 	 * Do not drain if one is already in progress unless it's specific to
2911 	 * a zone. Such callers are primarily CMA and memory hotplug and need
2912 	 * the drain to be complete when the call returns.
2913 	 */
2914 	if (unlikely(!mutex_trylock(&pcpu_drain_mutex))) {
2915 		if (!zone)
2916 			return;
2917 		mutex_lock(&pcpu_drain_mutex);
2918 	}
2919 
2920 	/*
2921 	 * We don't care about racing with CPU hotplug event
2922 	 * as offline notification will cause the notified
2923 	 * cpu to drain that CPU pcps and on_each_cpu_mask
2924 	 * disables preemption as part of its processing
2925 	 */
2926 	for_each_online_cpu(cpu) {
2927 		struct per_cpu_pageset *pcp;
2928 		struct zone *z;
2929 		bool has_pcps = false;
2930 
2931 		if (zone) {
2932 			pcp = per_cpu_ptr(zone->pageset, cpu);
2933 			if (pcp->pcp.count)
2934 				has_pcps = true;
2935 		} else {
2936 			for_each_populated_zone(z) {
2937 				pcp = per_cpu_ptr(z->pageset, cpu);
2938 				if (pcp->pcp.count) {
2939 					has_pcps = true;
2940 					break;
2941 				}
2942 			}
2943 		}
2944 
2945 		if (has_pcps)
2946 			cpumask_set_cpu(cpu, &cpus_with_pcps);
2947 		else
2948 			cpumask_clear_cpu(cpu, &cpus_with_pcps);
2949 	}
2950 
2951 	for_each_cpu(cpu, &cpus_with_pcps) {
2952 		struct pcpu_drain *drain = per_cpu_ptr(&pcpu_drain, cpu);
2953 
2954 		drain->zone = zone;
2955 		INIT_WORK(&drain->work, drain_local_pages_wq);
2956 		queue_work_on(cpu, mm_percpu_wq, &drain->work);
2957 	}
2958 	for_each_cpu(cpu, &cpus_with_pcps)
2959 		flush_work(&per_cpu_ptr(&pcpu_drain, cpu)->work);
2960 
2961 	mutex_unlock(&pcpu_drain_mutex);
2962 }
2963 
2964 #ifdef CONFIG_HIBERNATION
2965 
2966 /*
2967  * Touch the watchdog for every WD_PAGE_COUNT pages.
2968  */
2969 #define WD_PAGE_COUNT	(128*1024)
2970 
mark_free_pages(struct zone * zone)2971 void mark_free_pages(struct zone *zone)
2972 {
2973 	unsigned long pfn, max_zone_pfn, page_count = WD_PAGE_COUNT;
2974 	unsigned long flags;
2975 	unsigned int order, t;
2976 	struct page *page;
2977 
2978 	if (zone_is_empty(zone))
2979 		return;
2980 
2981 	spin_lock_irqsave(&zone->lock, flags);
2982 
2983 	max_zone_pfn = zone_end_pfn(zone);
2984 	for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
2985 		if (pfn_valid(pfn)) {
2986 			page = pfn_to_page(pfn);
2987 
2988 			if (!--page_count) {
2989 				touch_nmi_watchdog();
2990 				page_count = WD_PAGE_COUNT;
2991 			}
2992 
2993 			if (page_zone(page) != zone)
2994 				continue;
2995 
2996 			if (!swsusp_page_is_forbidden(page))
2997 				swsusp_unset_page_free(page);
2998 		}
2999 
3000 	for_each_migratetype_order(order, t) {
3001 		list_for_each_entry(page,
3002 				&zone->free_area[order].free_list[t], lru) {
3003 			unsigned long i;
3004 
3005 			pfn = page_to_pfn(page);
3006 			for (i = 0; i < (1UL << order); i++) {
3007 				if (!--page_count) {
3008 					touch_nmi_watchdog();
3009 					page_count = WD_PAGE_COUNT;
3010 				}
3011 				swsusp_set_page_free(pfn_to_page(pfn + i));
3012 			}
3013 		}
3014 	}
3015 	spin_unlock_irqrestore(&zone->lock, flags);
3016 }
3017 #endif /* CONFIG_PM */
3018 
free_unref_page_prepare(struct page * page,unsigned long pfn)3019 static bool free_unref_page_prepare(struct page *page, unsigned long pfn)
3020 {
3021 	int migratetype;
3022 
3023 	if (!free_pcp_prepare(page))
3024 		return false;
3025 
3026 	migratetype = get_pfnblock_migratetype(page, pfn);
3027 	set_pcppage_migratetype(page, migratetype);
3028 	return true;
3029 }
3030 
free_unref_page_commit(struct page * page,unsigned long pfn)3031 static void free_unref_page_commit(struct page *page, unsigned long pfn)
3032 {
3033 	struct zone *zone = page_zone(page);
3034 	struct per_cpu_pages *pcp;
3035 	int migratetype;
3036 
3037 	migratetype = get_pcppage_migratetype(page);
3038 	__count_vm_event(PGFREE);
3039 
3040 	/*
3041 	 * We only track unmovable, reclaimable and movable on pcp lists.
3042 	 * Free ISOLATE pages back to the allocator because they are being
3043 	 * offlined but treat HIGHATOMIC as movable pages so we can get those
3044 	 * areas back if necessary. Otherwise, we may have to free
3045 	 * excessively into the page allocator
3046 	 */
3047 	if (migratetype >= MIGRATE_PCPTYPES) {
3048 		if (unlikely(is_migrate_isolate(migratetype))) {
3049 			free_one_page(zone, page, pfn, 0, migratetype);
3050 			return;
3051 		}
3052 		migratetype = MIGRATE_MOVABLE;
3053 	}
3054 
3055 	pcp = &this_cpu_ptr(zone->pageset)->pcp;
3056 	list_add(&page->lru, &pcp->lists[migratetype]);
3057 	pcp->count++;
3058 	if (pcp->count >= pcp->high) {
3059 		unsigned long batch = READ_ONCE(pcp->batch);
3060 		free_pcppages_bulk(zone, batch, pcp);
3061 	}
3062 }
3063 
3064 /*
3065  * Free a 0-order page
3066  */
free_unref_page(struct page * page)3067 void free_unref_page(struct page *page)
3068 {
3069 	unsigned long flags;
3070 	unsigned long pfn = page_to_pfn(page);
3071 
3072 	if (!free_unref_page_prepare(page, pfn))
3073 		return;
3074 
3075 	local_irq_save(flags);
3076 	free_unref_page_commit(page, pfn);
3077 	local_irq_restore(flags);
3078 }
3079 
3080 /*
3081  * Free a list of 0-order pages
3082  */
free_unref_page_list(struct list_head * list)3083 void free_unref_page_list(struct list_head *list)
3084 {
3085 	struct page *page, *next;
3086 	unsigned long flags, pfn;
3087 	int batch_count = 0;
3088 
3089 	/* Prepare pages for freeing */
3090 	list_for_each_entry_safe(page, next, list, lru) {
3091 		pfn = page_to_pfn(page);
3092 		if (!free_unref_page_prepare(page, pfn))
3093 			list_del(&page->lru);
3094 		set_page_private(page, pfn);
3095 	}
3096 
3097 	local_irq_save(flags);
3098 	list_for_each_entry_safe(page, next, list, lru) {
3099 		unsigned long pfn = page_private(page);
3100 
3101 		set_page_private(page, 0);
3102 		trace_mm_page_free_batched(page);
3103 		free_unref_page_commit(page, pfn);
3104 
3105 		/*
3106 		 * Guard against excessive IRQ disabled times when we get
3107 		 * a large list of pages to free.
3108 		 */
3109 		if (++batch_count == SWAP_CLUSTER_MAX) {
3110 			local_irq_restore(flags);
3111 			batch_count = 0;
3112 			local_irq_save(flags);
3113 		}
3114 	}
3115 	local_irq_restore(flags);
3116 }
3117 
3118 /*
3119  * split_page takes a non-compound higher-order page, and splits it into
3120  * n (1<<order) sub-pages: page[0..n]
3121  * Each sub-page must be freed individually.
3122  *
3123  * Note: this is probably too low level an operation for use in drivers.
3124  * Please consult with lkml before using this in your driver.
3125  */
split_page(struct page * page,unsigned int order)3126 void split_page(struct page *page, unsigned int order)
3127 {
3128 	int i;
3129 
3130 	VM_BUG_ON_PAGE(PageCompound(page), page);
3131 	VM_BUG_ON_PAGE(!page_count(page), page);
3132 
3133 	for (i = 1; i < (1 << order); i++)
3134 		set_page_refcounted(page + i);
3135 	split_page_owner(page, order);
3136 }
3137 EXPORT_SYMBOL_GPL(split_page);
3138 
__isolate_free_page(struct page * page,unsigned int order)3139 int __isolate_free_page(struct page *page, unsigned int order)
3140 {
3141 	struct free_area *area = &page_zone(page)->free_area[order];
3142 	unsigned long watermark;
3143 	struct zone *zone;
3144 	int mt;
3145 
3146 	BUG_ON(!PageBuddy(page));
3147 
3148 	zone = page_zone(page);
3149 	mt = get_pageblock_migratetype(page);
3150 
3151 	if (!is_migrate_isolate(mt)) {
3152 		/*
3153 		 * Obey watermarks as if the page was being allocated. We can
3154 		 * emulate a high-order watermark check with a raised order-0
3155 		 * watermark, because we already know our high-order page
3156 		 * exists.
3157 		 */
3158 		watermark = zone->_watermark[WMARK_MIN] + (1UL << order);
3159 		if (!zone_watermark_ok(zone, 0, watermark, 0, ALLOC_CMA))
3160 			return 0;
3161 
3162 		__mod_zone_freepage_state(zone, -(1UL << order), mt);
3163 	}
3164 
3165 	/* Remove page from free list */
3166 
3167 	del_page_from_free_area(page, area);
3168 
3169 	/*
3170 	 * Set the pageblock if the isolated page is at least half of a
3171 	 * pageblock
3172 	 */
3173 	if (order >= pageblock_order - 1) {
3174 		struct page *endpage = page + (1 << order) - 1;
3175 		for (; page < endpage; page += pageblock_nr_pages) {
3176 			int mt = get_pageblock_migratetype(page);
3177 			if (!is_migrate_isolate(mt) && !is_migrate_cma(mt)
3178 			    && !is_migrate_highatomic(mt))
3179 				set_pageblock_migratetype(page,
3180 							  MIGRATE_MOVABLE);
3181 		}
3182 	}
3183 
3184 
3185 	return 1UL << order;
3186 }
3187 
3188 /*
3189  * Update NUMA hit/miss statistics
3190  *
3191  * Must be called with interrupts disabled.
3192  */
zone_statistics(struct zone * preferred_zone,struct zone * z)3193 static inline void zone_statistics(struct zone *preferred_zone, struct zone *z)
3194 {
3195 #ifdef CONFIG_NUMA
3196 	enum numa_stat_item local_stat = NUMA_LOCAL;
3197 
3198 	/* skip numa counters update if numa stats is disabled */
3199 	if (!static_branch_likely(&vm_numa_stat_key))
3200 		return;
3201 
3202 	if (zone_to_nid(z) != numa_node_id())
3203 		local_stat = NUMA_OTHER;
3204 
3205 	if (zone_to_nid(z) == zone_to_nid(preferred_zone))
3206 		__inc_numa_state(z, NUMA_HIT);
3207 	else {
3208 		__inc_numa_state(z, NUMA_MISS);
3209 		__inc_numa_state(preferred_zone, NUMA_FOREIGN);
3210 	}
3211 	__inc_numa_state(z, local_stat);
3212 #endif
3213 }
3214 
3215 /* Remove page from the per-cpu list, caller must protect the list */
__rmqueue_pcplist(struct zone * zone,int migratetype,unsigned int alloc_flags,struct per_cpu_pages * pcp,struct list_head * list)3216 static struct page *__rmqueue_pcplist(struct zone *zone, int migratetype,
3217 			unsigned int alloc_flags,
3218 			struct per_cpu_pages *pcp,
3219 			struct list_head *list)
3220 {
3221 	struct page *page;
3222 
3223 	do {
3224 		if (list_empty(list)) {
3225 			pcp->count += rmqueue_bulk(zone, 0,
3226 					pcp->batch, list,
3227 					migratetype, alloc_flags);
3228 			if (unlikely(list_empty(list)))
3229 				return NULL;
3230 		}
3231 
3232 		page = list_first_entry(list, struct page, lru);
3233 		list_del(&page->lru);
3234 		pcp->count--;
3235 	} while (check_new_pcp(page));
3236 
3237 	return page;
3238 }
3239 
3240 /* Lock and remove page from the per-cpu list */
rmqueue_pcplist(struct zone * preferred_zone,struct zone * zone,gfp_t gfp_flags,int migratetype,unsigned int alloc_flags)3241 static struct page *rmqueue_pcplist(struct zone *preferred_zone,
3242 			struct zone *zone, gfp_t gfp_flags,
3243 			int migratetype, unsigned int alloc_flags)
3244 {
3245 	struct per_cpu_pages *pcp;
3246 	struct list_head *list;
3247 	struct page *page;
3248 	unsigned long flags;
3249 
3250 	local_irq_save(flags);
3251 	pcp = &this_cpu_ptr(zone->pageset)->pcp;
3252 	list = &pcp->lists[migratetype];
3253 	page = __rmqueue_pcplist(zone,  migratetype, alloc_flags, pcp, list);
3254 	if (page) {
3255 		__count_zid_vm_events(PGALLOC, page_zonenum(page), 1);
3256 		zone_statistics(preferred_zone, zone);
3257 	}
3258 	local_irq_restore(flags);
3259 	return page;
3260 }
3261 
3262 /*
3263  * Allocate a page from the given zone. Use pcplists for order-0 allocations.
3264  */
3265 static inline
rmqueue(struct zone * preferred_zone,struct zone * zone,unsigned int order,gfp_t gfp_flags,unsigned int alloc_flags,int migratetype)3266 struct page *rmqueue(struct zone *preferred_zone,
3267 			struct zone *zone, unsigned int order,
3268 			gfp_t gfp_flags, unsigned int alloc_flags,
3269 			int migratetype)
3270 {
3271 	unsigned long flags;
3272 	struct page *page;
3273 
3274 	if (likely(order == 0)) {
3275 		page = rmqueue_pcplist(preferred_zone, zone, gfp_flags,
3276 					migratetype, alloc_flags);
3277 		goto out;
3278 	}
3279 
3280 	/*
3281 	 * We most definitely don't want callers attempting to
3282 	 * allocate greater than order-1 page units with __GFP_NOFAIL.
3283 	 */
3284 	WARN_ON_ONCE((gfp_flags & __GFP_NOFAIL) && (order > 1));
3285 	spin_lock_irqsave(&zone->lock, flags);
3286 
3287 	do {
3288 		page = NULL;
3289 		if (alloc_flags & ALLOC_HARDER) {
3290 			page = __rmqueue_smallest(zone, order, MIGRATE_HIGHATOMIC);
3291 			if (page)
3292 				trace_mm_page_alloc_zone_locked(page, order, migratetype);
3293 		}
3294 		if (!page)
3295 			page = __rmqueue(zone, order, migratetype, alloc_flags);
3296 	} while (page && check_new_pages(page, order));
3297 	spin_unlock(&zone->lock);
3298 	if (!page)
3299 		goto failed;
3300 	__mod_zone_freepage_state(zone, -(1 << order),
3301 				  get_pcppage_migratetype(page));
3302 
3303 	__count_zid_vm_events(PGALLOC, page_zonenum(page), 1 << order);
3304 	zone_statistics(preferred_zone, zone);
3305 	local_irq_restore(flags);
3306 
3307 out:
3308 	/* Separate test+clear to avoid unnecessary atomics */
3309 	if (test_bit(ZONE_BOOSTED_WATERMARK, &zone->flags)) {
3310 		clear_bit(ZONE_BOOSTED_WATERMARK, &zone->flags);
3311 		wakeup_kswapd(zone, 0, 0, zone_idx(zone));
3312 	}
3313 
3314 	VM_BUG_ON_PAGE(page && bad_range(zone, page), page);
3315 	return page;
3316 
3317 failed:
3318 	local_irq_restore(flags);
3319 	return NULL;
3320 }
3321 
3322 #ifdef CONFIG_FAIL_PAGE_ALLOC
3323 
3324 static struct {
3325 	struct fault_attr attr;
3326 
3327 	bool ignore_gfp_highmem;
3328 	bool ignore_gfp_reclaim;
3329 	u32 min_order;
3330 } fail_page_alloc = {
3331 	.attr = FAULT_ATTR_INITIALIZER,
3332 	.ignore_gfp_reclaim = true,
3333 	.ignore_gfp_highmem = true,
3334 	.min_order = 1,
3335 };
3336 
setup_fail_page_alloc(char * str)3337 static int __init setup_fail_page_alloc(char *str)
3338 {
3339 	return setup_fault_attr(&fail_page_alloc.attr, str);
3340 }
3341 __setup("fail_page_alloc=", setup_fail_page_alloc);
3342 
__should_fail_alloc_page(gfp_t gfp_mask,unsigned int order)3343 static bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3344 {
3345 	if (order < fail_page_alloc.min_order)
3346 		return false;
3347 	if (gfp_mask & __GFP_NOFAIL)
3348 		return false;
3349 	if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM))
3350 		return false;
3351 	if (fail_page_alloc.ignore_gfp_reclaim &&
3352 			(gfp_mask & __GFP_DIRECT_RECLAIM))
3353 		return false;
3354 
3355 	return should_fail(&fail_page_alloc.attr, 1 << order);
3356 }
3357 
3358 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3359 
fail_page_alloc_debugfs(void)3360 static int __init fail_page_alloc_debugfs(void)
3361 {
3362 	umode_t mode = S_IFREG | 0600;
3363 	struct dentry *dir;
3364 
3365 	dir = fault_create_debugfs_attr("fail_page_alloc", NULL,
3366 					&fail_page_alloc.attr);
3367 
3368 	debugfs_create_bool("ignore-gfp-wait", mode, dir,
3369 			    &fail_page_alloc.ignore_gfp_reclaim);
3370 	debugfs_create_bool("ignore-gfp-highmem", mode, dir,
3371 			    &fail_page_alloc.ignore_gfp_highmem);
3372 	debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order);
3373 
3374 	return 0;
3375 }
3376 
3377 late_initcall(fail_page_alloc_debugfs);
3378 
3379 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3380 
3381 #else /* CONFIG_FAIL_PAGE_ALLOC */
3382 
__should_fail_alloc_page(gfp_t gfp_mask,unsigned int order)3383 static inline bool __should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3384 {
3385 	return false;
3386 }
3387 
3388 #endif /* CONFIG_FAIL_PAGE_ALLOC */
3389 
should_fail_alloc_page(gfp_t gfp_mask,unsigned int order)3390 static noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
3391 {
3392 	return __should_fail_alloc_page(gfp_mask, order);
3393 }
3394 ALLOW_ERROR_INJECTION(should_fail_alloc_page, TRUE);
3395 
3396 /*
3397  * Return true if free base pages are above 'mark'. For high-order checks it
3398  * will return true of the order-0 watermark is reached and there is at least
3399  * one free page of a suitable size. Checking now avoids taking the zone lock
3400  * to check in the allocation paths if no pages are free.
3401  */
__zone_watermark_ok(struct zone * z,unsigned int order,unsigned long mark,int classzone_idx,unsigned int alloc_flags,long free_pages)3402 bool __zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3403 			 int classzone_idx, unsigned int alloc_flags,
3404 			 long free_pages)
3405 {
3406 	long min = mark;
3407 	int o;
3408 	const bool alloc_harder = (alloc_flags & (ALLOC_HARDER|ALLOC_OOM));
3409 
3410 	/* free_pages may go negative - that's OK */
3411 	free_pages -= (1 << order) - 1;
3412 
3413 	if (alloc_flags & ALLOC_HIGH)
3414 		min -= min / 2;
3415 
3416 	/*
3417 	 * If the caller does not have rights to ALLOC_HARDER then subtract
3418 	 * the high-atomic reserves. This will over-estimate the size of the
3419 	 * atomic reserve but it avoids a search.
3420 	 */
3421 	if (likely(!alloc_harder)) {
3422 		free_pages -= z->nr_reserved_highatomic;
3423 	} else {
3424 		/*
3425 		 * OOM victims can try even harder than normal ALLOC_HARDER
3426 		 * users on the grounds that it's definitely going to be in
3427 		 * the exit path shortly and free memory. Any allocation it
3428 		 * makes during the free path will be small and short-lived.
3429 		 */
3430 		if (alloc_flags & ALLOC_OOM)
3431 			min -= min / 2;
3432 		else
3433 			min -= min / 4;
3434 	}
3435 
3436 
3437 #ifdef CONFIG_CMA
3438 	/* If allocation can't use CMA areas don't use free CMA pages */
3439 	if (!(alloc_flags & ALLOC_CMA))
3440 		free_pages -= zone_page_state(z, NR_FREE_CMA_PAGES);
3441 #endif
3442 
3443 	/*
3444 	 * Check watermarks for an order-0 allocation request. If these
3445 	 * are not met, then a high-order request also cannot go ahead
3446 	 * even if a suitable page happened to be free.
3447 	 */
3448 	if (free_pages <= min + z->lowmem_reserve[classzone_idx])
3449 		return false;
3450 
3451 	/* If this is an order-0 request then the watermark is fine */
3452 	if (!order)
3453 		return true;
3454 
3455 	/* For a high-order request, check at least one suitable page is free */
3456 	for (o = order; o < MAX_ORDER; o++) {
3457 		struct free_area *area = &z->free_area[o];
3458 		int mt;
3459 
3460 		if (!area->nr_free)
3461 			continue;
3462 
3463 		for (mt = 0; mt < MIGRATE_PCPTYPES; mt++) {
3464 			if (!free_area_empty(area, mt))
3465 				return true;
3466 		}
3467 
3468 #ifdef CONFIG_CMA
3469 		if ((alloc_flags & ALLOC_CMA) &&
3470 		    !free_area_empty(area, MIGRATE_CMA)) {
3471 			return true;
3472 		}
3473 #endif
3474 		if (alloc_harder &&
3475 			!list_empty(&area->free_list[MIGRATE_HIGHATOMIC]))
3476 			return true;
3477 	}
3478 	return false;
3479 }
3480 
zone_watermark_ok(struct zone * z,unsigned int order,unsigned long mark,int classzone_idx,unsigned int alloc_flags)3481 bool zone_watermark_ok(struct zone *z, unsigned int order, unsigned long mark,
3482 		      int classzone_idx, unsigned int alloc_flags)
3483 {
3484 	return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3485 					zone_page_state(z, NR_FREE_PAGES));
3486 }
3487 
zone_watermark_fast(struct zone * z,unsigned int order,unsigned long mark,int classzone_idx,unsigned int alloc_flags)3488 static inline bool zone_watermark_fast(struct zone *z, unsigned int order,
3489 		unsigned long mark, int classzone_idx, unsigned int alloc_flags)
3490 {
3491 	long free_pages = zone_page_state(z, NR_FREE_PAGES);
3492 	long cma_pages = 0;
3493 
3494 #ifdef CONFIG_CMA
3495 	/* If allocation can't use CMA areas don't use free CMA pages */
3496 	if (!(alloc_flags & ALLOC_CMA))
3497 		cma_pages = zone_page_state(z, NR_FREE_CMA_PAGES);
3498 #endif
3499 
3500 	/*
3501 	 * Fast check for order-0 only. If this fails then the reserves
3502 	 * need to be calculated. There is a corner case where the check
3503 	 * passes but only the high-order atomic reserve are free. If
3504 	 * the caller is !atomic then it'll uselessly search the free
3505 	 * list. That corner case is then slower but it is harmless.
3506 	 */
3507 	if (!order && (free_pages - cma_pages) > mark + z->lowmem_reserve[classzone_idx])
3508 		return true;
3509 
3510 	return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags,
3511 					free_pages);
3512 }
3513 
zone_watermark_ok_safe(struct zone * z,unsigned int order,unsigned long mark,int classzone_idx)3514 bool zone_watermark_ok_safe(struct zone *z, unsigned int order,
3515 			unsigned long mark, int classzone_idx)
3516 {
3517 	long free_pages = zone_page_state(z, NR_FREE_PAGES);
3518 
3519 	if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark)
3520 		free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES);
3521 
3522 	return __zone_watermark_ok(z, order, mark, classzone_idx, 0,
3523 								free_pages);
3524 }
3525 
3526 #ifdef CONFIG_NUMA
zone_allows_reclaim(struct zone * local_zone,struct zone * zone)3527 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3528 {
3529 	return node_distance(zone_to_nid(local_zone), zone_to_nid(zone)) <=
3530 				node_reclaim_distance;
3531 }
3532 #else	/* CONFIG_NUMA */
zone_allows_reclaim(struct zone * local_zone,struct zone * zone)3533 static bool zone_allows_reclaim(struct zone *local_zone, struct zone *zone)
3534 {
3535 	return true;
3536 }
3537 #endif	/* CONFIG_NUMA */
3538 
3539 /*
3540  * The restriction on ZONE_DMA32 as being a suitable zone to use to avoid
3541  * fragmentation is subtle. If the preferred zone was HIGHMEM then
3542  * premature use of a lower zone may cause lowmem pressure problems that
3543  * are worse than fragmentation. If the next zone is ZONE_DMA then it is
3544  * probably too small. It only makes sense to spread allocations to avoid
3545  * fragmentation between the Normal and DMA32 zones.
3546  */
3547 static inline unsigned int
alloc_flags_nofragment(struct zone * zone,gfp_t gfp_mask)3548 alloc_flags_nofragment(struct zone *zone, gfp_t gfp_mask)
3549 {
3550 	unsigned int alloc_flags = 0;
3551 
3552 	if (gfp_mask & __GFP_KSWAPD_RECLAIM)
3553 		alloc_flags |= ALLOC_KSWAPD;
3554 
3555 #ifdef CONFIG_ZONE_DMA32
3556 	if (!zone)
3557 		return alloc_flags;
3558 
3559 	if (zone_idx(zone) != ZONE_NORMAL)
3560 		return alloc_flags;
3561 
3562 	/*
3563 	 * If ZONE_DMA32 exists, assume it is the one after ZONE_NORMAL and
3564 	 * the pointer is within zone->zone_pgdat->node_zones[]. Also assume
3565 	 * on UMA that if Normal is populated then so is DMA32.
3566 	 */
3567 	BUILD_BUG_ON(ZONE_NORMAL - ZONE_DMA32 != 1);
3568 	if (nr_online_nodes > 1 && !populated_zone(--zone))
3569 		return alloc_flags;
3570 
3571 	alloc_flags |= ALLOC_NOFRAGMENT;
3572 #endif /* CONFIG_ZONE_DMA32 */
3573 	return alloc_flags;
3574 }
3575 
3576 /*
3577  * get_page_from_freelist goes through the zonelist trying to allocate
3578  * a page.
3579  */
3580 static struct page *
get_page_from_freelist(gfp_t gfp_mask,unsigned int order,int alloc_flags,const struct alloc_context * ac)3581 get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
3582 						const struct alloc_context *ac)
3583 {
3584 	struct zoneref *z;
3585 	struct zone *zone;
3586 	struct pglist_data *last_pgdat_dirty_limit = NULL;
3587 	bool no_fallback;
3588 
3589 retry:
3590 	/*
3591 	 * Scan zonelist, looking for a zone with enough free.
3592 	 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
3593 	 */
3594 	no_fallback = alloc_flags & ALLOC_NOFRAGMENT;
3595 	z = ac->preferred_zoneref;
3596 	for_next_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
3597 								ac->nodemask) {
3598 		struct page *page;
3599 		unsigned long mark;
3600 
3601 		if (cpusets_enabled() &&
3602 			(alloc_flags & ALLOC_CPUSET) &&
3603 			!__cpuset_zone_allowed(zone, gfp_mask))
3604 				continue;
3605 		/*
3606 		 * When allocating a page cache page for writing, we
3607 		 * want to get it from a node that is within its dirty
3608 		 * limit, such that no single node holds more than its
3609 		 * proportional share of globally allowed dirty pages.
3610 		 * The dirty limits take into account the node's
3611 		 * lowmem reserves and high watermark so that kswapd
3612 		 * should be able to balance it without having to
3613 		 * write pages from its LRU list.
3614 		 *
3615 		 * XXX: For now, allow allocations to potentially
3616 		 * exceed the per-node dirty limit in the slowpath
3617 		 * (spread_dirty_pages unset) before going into reclaim,
3618 		 * which is important when on a NUMA setup the allowed
3619 		 * nodes are together not big enough to reach the
3620 		 * global limit.  The proper fix for these situations
3621 		 * will require awareness of nodes in the
3622 		 * dirty-throttling and the flusher threads.
3623 		 */
3624 		if (ac->spread_dirty_pages) {
3625 			if (last_pgdat_dirty_limit == zone->zone_pgdat)
3626 				continue;
3627 
3628 			if (!node_dirty_ok(zone->zone_pgdat)) {
3629 				last_pgdat_dirty_limit = zone->zone_pgdat;
3630 				continue;
3631 			}
3632 		}
3633 
3634 		if (no_fallback && nr_online_nodes > 1 &&
3635 		    zone != ac->preferred_zoneref->zone) {
3636 			int local_nid;
3637 
3638 			/*
3639 			 * If moving to a remote node, retry but allow
3640 			 * fragmenting fallbacks. Locality is more important
3641 			 * than fragmentation avoidance.
3642 			 */
3643 			local_nid = zone_to_nid(ac->preferred_zoneref->zone);
3644 			if (zone_to_nid(zone) != local_nid) {
3645 				alloc_flags &= ~ALLOC_NOFRAGMENT;
3646 				goto retry;
3647 			}
3648 		}
3649 
3650 		mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
3651 		if (!zone_watermark_fast(zone, order, mark,
3652 				       ac_classzone_idx(ac), alloc_flags)) {
3653 			int ret;
3654 
3655 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3656 			/*
3657 			 * Watermark failed for this zone, but see if we can
3658 			 * grow this zone if it contains deferred pages.
3659 			 */
3660 			if (static_branch_unlikely(&deferred_pages)) {
3661 				if (_deferred_grow_zone(zone, order))
3662 					goto try_this_zone;
3663 			}
3664 #endif
3665 			/* Checked here to keep the fast path fast */
3666 			BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK);
3667 			if (alloc_flags & ALLOC_NO_WATERMARKS)
3668 				goto try_this_zone;
3669 
3670 			if (node_reclaim_mode == 0 ||
3671 			    !zone_allows_reclaim(ac->preferred_zoneref->zone, zone))
3672 				continue;
3673 
3674 			ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
3675 			switch (ret) {
3676 			case NODE_RECLAIM_NOSCAN:
3677 				/* did not scan */
3678 				continue;
3679 			case NODE_RECLAIM_FULL:
3680 				/* scanned but unreclaimable */
3681 				continue;
3682 			default:
3683 				/* did we reclaim enough */
3684 				if (zone_watermark_ok(zone, order, mark,
3685 						ac_classzone_idx(ac), alloc_flags))
3686 					goto try_this_zone;
3687 
3688 				continue;
3689 			}
3690 		}
3691 
3692 try_this_zone:
3693 		page = rmqueue(ac->preferred_zoneref->zone, zone, order,
3694 				gfp_mask, alloc_flags, ac->migratetype);
3695 		if (page) {
3696 			prep_new_page(page, order, gfp_mask, alloc_flags);
3697 
3698 			/*
3699 			 * If this is a high-order atomic allocation then check
3700 			 * if the pageblock should be reserved for the future
3701 			 */
3702 			if (unlikely(order && (alloc_flags & ALLOC_HARDER)))
3703 				reserve_highatomic_pageblock(page, zone, order);
3704 
3705 			return page;
3706 		} else {
3707 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
3708 			/* Try again if zone has deferred pages */
3709 			if (static_branch_unlikely(&deferred_pages)) {
3710 				if (_deferred_grow_zone(zone, order))
3711 					goto try_this_zone;
3712 			}
3713 #endif
3714 		}
3715 	}
3716 
3717 	/*
3718 	 * It's possible on a UMA machine to get through all zones that are
3719 	 * fragmented. If avoiding fragmentation, reset and try again.
3720 	 */
3721 	if (no_fallback) {
3722 		alloc_flags &= ~ALLOC_NOFRAGMENT;
3723 		goto retry;
3724 	}
3725 
3726 	return NULL;
3727 }
3728 
warn_alloc_show_mem(gfp_t gfp_mask,nodemask_t * nodemask)3729 static void warn_alloc_show_mem(gfp_t gfp_mask, nodemask_t *nodemask)
3730 {
3731 	unsigned int filter = SHOW_MEM_FILTER_NODES;
3732 
3733 	/*
3734 	 * This documents exceptions given to allocations in certain
3735 	 * contexts that are allowed to allocate outside current's set
3736 	 * of allowed nodes.
3737 	 */
3738 	if (!(gfp_mask & __GFP_NOMEMALLOC))
3739 		if (tsk_is_oom_victim(current) ||
3740 		    (current->flags & (PF_MEMALLOC | PF_EXITING)))
3741 			filter &= ~SHOW_MEM_FILTER_NODES;
3742 	if (in_interrupt() || !(gfp_mask & __GFP_DIRECT_RECLAIM))
3743 		filter &= ~SHOW_MEM_FILTER_NODES;
3744 
3745 	show_mem(filter, nodemask);
3746 }
3747 
warn_alloc(gfp_t gfp_mask,nodemask_t * nodemask,const char * fmt,...)3748 void warn_alloc(gfp_t gfp_mask, nodemask_t *nodemask, const char *fmt, ...)
3749 {
3750 	struct va_format vaf;
3751 	va_list args;
3752 	static DEFINE_RATELIMIT_STATE(nopage_rs, 10*HZ, 1);
3753 
3754 	if ((gfp_mask & __GFP_NOWARN) || !__ratelimit(&nopage_rs))
3755 		return;
3756 
3757 	va_start(args, fmt);
3758 	vaf.fmt = fmt;
3759 	vaf.va = &args;
3760 	pr_warn("%s: %pV, mode:%#x(%pGg), nodemask=%*pbl",
3761 			current->comm, &vaf, gfp_mask, &gfp_mask,
3762 			nodemask_pr_args(nodemask));
3763 	va_end(args);
3764 
3765 	cpuset_print_current_mems_allowed();
3766 	pr_cont("\n");
3767 	dump_stack();
3768 	warn_alloc_show_mem(gfp_mask, nodemask);
3769 }
3770 
3771 static inline struct page *
__alloc_pages_cpuset_fallback(gfp_t gfp_mask,unsigned int order,unsigned int alloc_flags,const struct alloc_context * ac)3772 __alloc_pages_cpuset_fallback(gfp_t gfp_mask, unsigned int order,
3773 			      unsigned int alloc_flags,
3774 			      const struct alloc_context *ac)
3775 {
3776 	struct page *page;
3777 
3778 	page = get_page_from_freelist(gfp_mask, order,
3779 			alloc_flags|ALLOC_CPUSET, ac);
3780 	/*
3781 	 * fallback to ignore cpuset restriction if our nodes
3782 	 * are depleted
3783 	 */
3784 	if (!page)
3785 		page = get_page_from_freelist(gfp_mask, order,
3786 				alloc_flags, ac);
3787 
3788 	return page;
3789 }
3790 
3791 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)3792 __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order,
3793 	const struct alloc_context *ac, unsigned long *did_some_progress)
3794 {
3795 	struct oom_control oc = {
3796 		.zonelist = ac->zonelist,
3797 		.nodemask = ac->nodemask,
3798 		.memcg = NULL,
3799 		.gfp_mask = gfp_mask,
3800 		.order = order,
3801 	};
3802 	struct page *page;
3803 
3804 	*did_some_progress = 0;
3805 
3806 	/*
3807 	 * Acquire the oom lock.  If that fails, somebody else is
3808 	 * making progress for us.
3809 	 */
3810 	if (!mutex_trylock(&oom_lock)) {
3811 		*did_some_progress = 1;
3812 		schedule_timeout_uninterruptible(1);
3813 		return NULL;
3814 	}
3815 
3816 	/*
3817 	 * Go through the zonelist yet one more time, keep very high watermark
3818 	 * here, this is only to catch a parallel oom killing, we must fail if
3819 	 * we're still under heavy pressure. But make sure that this reclaim
3820 	 * attempt shall not depend on __GFP_DIRECT_RECLAIM && !__GFP_NORETRY
3821 	 * allocation which will never fail due to oom_lock already held.
3822 	 */
3823 	page = get_page_from_freelist((gfp_mask | __GFP_HARDWALL) &
3824 				      ~__GFP_DIRECT_RECLAIM, order,
3825 				      ALLOC_WMARK_HIGH|ALLOC_CPUSET, ac);
3826 	if (page)
3827 		goto out;
3828 
3829 	/* Coredumps can quickly deplete all memory reserves */
3830 	if (current->flags & PF_DUMPCORE)
3831 		goto out;
3832 	/* The OOM killer will not help higher order allocs */
3833 	if (order > PAGE_ALLOC_COSTLY_ORDER)
3834 		goto out;
3835 	/*
3836 	 * We have already exhausted all our reclaim opportunities without any
3837 	 * success so it is time to admit defeat. We will skip the OOM killer
3838 	 * because it is very likely that the caller has a more reasonable
3839 	 * fallback than shooting a random task.
3840 	 */
3841 	if (gfp_mask & __GFP_RETRY_MAYFAIL)
3842 		goto out;
3843 	/* The OOM killer does not needlessly kill tasks for lowmem */
3844 	if (ac->high_zoneidx < ZONE_NORMAL)
3845 		goto out;
3846 	if (pm_suspended_storage())
3847 		goto out;
3848 	/*
3849 	 * XXX: GFP_NOFS allocations should rather fail than rely on
3850 	 * other request to make a forward progress.
3851 	 * We are in an unfortunate situation where out_of_memory cannot
3852 	 * do much for this context but let's try it to at least get
3853 	 * access to memory reserved if the current task is killed (see
3854 	 * out_of_memory). Once filesystems are ready to handle allocation
3855 	 * failures more gracefully we should just bail out here.
3856 	 */
3857 
3858 	/* The OOM killer may not free memory on a specific node */
3859 	if (gfp_mask & __GFP_THISNODE)
3860 		goto out;
3861 
3862 	/* Exhausted what can be done so it's blame time */
3863 	if (out_of_memory(&oc) || WARN_ON_ONCE(gfp_mask & __GFP_NOFAIL)) {
3864 		*did_some_progress = 1;
3865 
3866 		/*
3867 		 * Help non-failing allocations by giving them access to memory
3868 		 * reserves
3869 		 */
3870 		if (gfp_mask & __GFP_NOFAIL)
3871 			page = __alloc_pages_cpuset_fallback(gfp_mask, order,
3872 					ALLOC_NO_WATERMARKS, ac);
3873 	}
3874 out:
3875 	mutex_unlock(&oom_lock);
3876 	return page;
3877 }
3878 
3879 /*
3880  * Maximum number of compaction retries wit a progress before OOM
3881  * killer is consider as the only way to move forward.
3882  */
3883 #define MAX_COMPACT_RETRIES 16
3884 
3885 #ifdef CONFIG_COMPACTION
3886 /* Try memory compaction for high-order allocations before reclaim */
3887 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)3888 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
3889 		unsigned int alloc_flags, const struct alloc_context *ac,
3890 		enum compact_priority prio, enum compact_result *compact_result)
3891 {
3892 	struct page *page = NULL;
3893 	unsigned long pflags;
3894 	unsigned int noreclaim_flag;
3895 
3896 	if (!order)
3897 		return NULL;
3898 
3899 	psi_memstall_enter(&pflags);
3900 	noreclaim_flag = memalloc_noreclaim_save();
3901 
3902 	*compact_result = try_to_compact_pages(gfp_mask, order, alloc_flags, ac,
3903 								prio, &page);
3904 
3905 	memalloc_noreclaim_restore(noreclaim_flag);
3906 	psi_memstall_leave(&pflags);
3907 
3908 	/*
3909 	 * At least in one zone compaction wasn't deferred or skipped, so let's
3910 	 * count a compaction stall
3911 	 */
3912 	count_vm_event(COMPACTSTALL);
3913 
3914 	/* Prep a captured page if available */
3915 	if (page)
3916 		prep_new_page(page, order, gfp_mask, alloc_flags);
3917 
3918 	/* Try get a page from the freelist if available */
3919 	if (!page)
3920 		page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
3921 
3922 	if (page) {
3923 		struct zone *zone = page_zone(page);
3924 
3925 		zone->compact_blockskip_flush = false;
3926 		compaction_defer_reset(zone, order, true);
3927 		count_vm_event(COMPACTSUCCESS);
3928 		return page;
3929 	}
3930 
3931 	/*
3932 	 * It's bad if compaction run occurs and fails. The most likely reason
3933 	 * is that pages exist, but not enough to satisfy watermarks.
3934 	 */
3935 	count_vm_event(COMPACTFAIL);
3936 
3937 	cond_resched();
3938 
3939 	return NULL;
3940 }
3941 
3942 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)3943 should_compact_retry(struct alloc_context *ac, int order, int alloc_flags,
3944 		     enum compact_result compact_result,
3945 		     enum compact_priority *compact_priority,
3946 		     int *compaction_retries)
3947 {
3948 	int max_retries = MAX_COMPACT_RETRIES;
3949 	int min_priority;
3950 	bool ret = false;
3951 	int retries = *compaction_retries;
3952 	enum compact_priority priority = *compact_priority;
3953 
3954 	if (!order)
3955 		return false;
3956 
3957 	if (compaction_made_progress(compact_result))
3958 		(*compaction_retries)++;
3959 
3960 	/*
3961 	 * compaction considers all the zone as desperately out of memory
3962 	 * so it doesn't really make much sense to retry except when the
3963 	 * failure could be caused by insufficient priority
3964 	 */
3965 	if (compaction_failed(compact_result))
3966 		goto check_priority;
3967 
3968 	/*
3969 	 * compaction was skipped because there are not enough order-0 pages
3970 	 * to work with, so we retry only if it looks like reclaim can help.
3971 	 */
3972 	if (compaction_needs_reclaim(compact_result)) {
3973 		ret = compaction_zonelist_suitable(ac, order, alloc_flags);
3974 		goto out;
3975 	}
3976 
3977 	/*
3978 	 * make sure the compaction wasn't deferred or didn't bail out early
3979 	 * due to locks contention before we declare that we should give up.
3980 	 * But the next retry should use a higher priority if allowed, so
3981 	 * we don't just keep bailing out endlessly.
3982 	 */
3983 	if (compaction_withdrawn(compact_result)) {
3984 		goto check_priority;
3985 	}
3986 
3987 	/*
3988 	 * !costly requests are much more important than __GFP_RETRY_MAYFAIL
3989 	 * costly ones because they are de facto nofail and invoke OOM
3990 	 * killer to move on while costly can fail and users are ready
3991 	 * to cope with that. 1/4 retries is rather arbitrary but we
3992 	 * would need much more detailed feedback from compaction to
3993 	 * make a better decision.
3994 	 */
3995 	if (order > PAGE_ALLOC_COSTLY_ORDER)
3996 		max_retries /= 4;
3997 	if (*compaction_retries <= max_retries) {
3998 		ret = true;
3999 		goto out;
4000 	}
4001 
4002 	/*
4003 	 * Make sure there are attempts at the highest priority if we exhausted
4004 	 * all retries or failed at the lower priorities.
4005 	 */
4006 check_priority:
4007 	min_priority = (order > PAGE_ALLOC_COSTLY_ORDER) ?
4008 			MIN_COMPACT_COSTLY_PRIORITY : MIN_COMPACT_PRIORITY;
4009 
4010 	if (*compact_priority > min_priority) {
4011 		(*compact_priority)--;
4012 		*compaction_retries = 0;
4013 		ret = true;
4014 	}
4015 out:
4016 	trace_compact_retry(order, priority, compact_result, retries, max_retries, ret);
4017 	return ret;
4018 }
4019 #else
4020 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)4021 __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order,
4022 		unsigned int alloc_flags, const struct alloc_context *ac,
4023 		enum compact_priority prio, enum compact_result *compact_result)
4024 {
4025 	*compact_result = COMPACT_SKIPPED;
4026 	return NULL;
4027 }
4028 
4029 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)4030 should_compact_retry(struct alloc_context *ac, unsigned int order, int alloc_flags,
4031 		     enum compact_result compact_result,
4032 		     enum compact_priority *compact_priority,
4033 		     int *compaction_retries)
4034 {
4035 	struct zone *zone;
4036 	struct zoneref *z;
4037 
4038 	if (!order || order > PAGE_ALLOC_COSTLY_ORDER)
4039 		return false;
4040 
4041 	/*
4042 	 * There are setups with compaction disabled which would prefer to loop
4043 	 * inside the allocator rather than hit the oom killer prematurely.
4044 	 * Let's give them a good hope and keep retrying while the order-0
4045 	 * watermarks are OK.
4046 	 */
4047 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
4048 					ac->nodemask) {
4049 		if (zone_watermark_ok(zone, 0, min_wmark_pages(zone),
4050 					ac_classzone_idx(ac), alloc_flags))
4051 			return true;
4052 	}
4053 	return false;
4054 }
4055 #endif /* CONFIG_COMPACTION */
4056 
4057 #ifdef CONFIG_LOCKDEP
4058 static struct lockdep_map __fs_reclaim_map =
4059 	STATIC_LOCKDEP_MAP_INIT("fs_reclaim", &__fs_reclaim_map);
4060 
__need_fs_reclaim(gfp_t gfp_mask)4061 static bool __need_fs_reclaim(gfp_t gfp_mask)
4062 {
4063 	gfp_mask = current_gfp_context(gfp_mask);
4064 
4065 	/* no reclaim without waiting on it */
4066 	if (!(gfp_mask & __GFP_DIRECT_RECLAIM))
4067 		return false;
4068 
4069 	/* this guy won't enter reclaim */
4070 	if (current->flags & PF_MEMALLOC)
4071 		return false;
4072 
4073 	/* We're only interested __GFP_FS allocations for now */
4074 	if (!(gfp_mask & __GFP_FS))
4075 		return false;
4076 
4077 	if (gfp_mask & __GFP_NOLOCKDEP)
4078 		return false;
4079 
4080 	return true;
4081 }
4082 
__fs_reclaim_acquire(void)4083 void __fs_reclaim_acquire(void)
4084 {
4085 	lock_map_acquire(&__fs_reclaim_map);
4086 }
4087 
__fs_reclaim_release(void)4088 void __fs_reclaim_release(void)
4089 {
4090 	lock_map_release(&__fs_reclaim_map);
4091 }
4092 
fs_reclaim_acquire(gfp_t gfp_mask)4093 void fs_reclaim_acquire(gfp_t gfp_mask)
4094 {
4095 	if (__need_fs_reclaim(gfp_mask))
4096 		__fs_reclaim_acquire();
4097 }
4098 EXPORT_SYMBOL_GPL(fs_reclaim_acquire);
4099 
fs_reclaim_release(gfp_t gfp_mask)4100 void fs_reclaim_release(gfp_t gfp_mask)
4101 {
4102 	if (__need_fs_reclaim(gfp_mask))
4103 		__fs_reclaim_release();
4104 }
4105 EXPORT_SYMBOL_GPL(fs_reclaim_release);
4106 #endif
4107 
4108 /* Perform direct synchronous page reclaim */
4109 static int
__perform_reclaim(gfp_t gfp_mask,unsigned int order,const struct alloc_context * ac)4110 __perform_reclaim(gfp_t gfp_mask, unsigned int order,
4111 					const struct alloc_context *ac)
4112 {
4113 	int progress;
4114 	unsigned int noreclaim_flag;
4115 	unsigned long pflags;
4116 
4117 	cond_resched();
4118 
4119 	/* We now go into synchronous reclaim */
4120 	cpuset_memory_pressure_bump();
4121 	psi_memstall_enter(&pflags);
4122 	fs_reclaim_acquire(gfp_mask);
4123 	noreclaim_flag = memalloc_noreclaim_save();
4124 
4125 	progress = try_to_free_pages(ac->zonelist, order, gfp_mask,
4126 								ac->nodemask);
4127 
4128 	memalloc_noreclaim_restore(noreclaim_flag);
4129 	fs_reclaim_release(gfp_mask);
4130 	psi_memstall_leave(&pflags);
4131 
4132 	cond_resched();
4133 
4134 	return progress;
4135 }
4136 
4137 /* The really slow allocator path where we enter direct reclaim */
4138 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)4139 __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
4140 		unsigned int alloc_flags, const struct alloc_context *ac,
4141 		unsigned long *did_some_progress)
4142 {
4143 	struct page *page = NULL;
4144 	bool drained = false;
4145 
4146 	*did_some_progress = __perform_reclaim(gfp_mask, order, ac);
4147 	if (unlikely(!(*did_some_progress)))
4148 		return NULL;
4149 
4150 retry:
4151 	page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4152 
4153 	/*
4154 	 * If an allocation failed after direct reclaim, it could be because
4155 	 * pages are pinned on the per-cpu lists or in high alloc reserves.
4156 	 * Shrink them them and try again
4157 	 */
4158 	if (!page && !drained) {
4159 		unreserve_highatomic_pageblock(ac, false);
4160 		drain_all_pages(NULL);
4161 		drained = true;
4162 		goto retry;
4163 	}
4164 
4165 	return page;
4166 }
4167 
wake_all_kswapds(unsigned int order,gfp_t gfp_mask,const struct alloc_context * ac)4168 static void wake_all_kswapds(unsigned int order, gfp_t gfp_mask,
4169 			     const struct alloc_context *ac)
4170 {
4171 	struct zoneref *z;
4172 	struct zone *zone;
4173 	pg_data_t *last_pgdat = NULL;
4174 	enum zone_type high_zoneidx = ac->high_zoneidx;
4175 
4176 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, high_zoneidx,
4177 					ac->nodemask) {
4178 		if (last_pgdat != zone->zone_pgdat)
4179 			wakeup_kswapd(zone, gfp_mask, order, high_zoneidx);
4180 		last_pgdat = zone->zone_pgdat;
4181 	}
4182 }
4183 
4184 static inline unsigned int
gfp_to_alloc_flags(gfp_t gfp_mask)4185 gfp_to_alloc_flags(gfp_t gfp_mask)
4186 {
4187 	unsigned int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET;
4188 
4189 	/* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */
4190 	BUILD_BUG_ON(__GFP_HIGH != (__force gfp_t) ALLOC_HIGH);
4191 
4192 	/*
4193 	 * The caller may dip into page reserves a bit more if the caller
4194 	 * cannot run direct reclaim, or if the caller has realtime scheduling
4195 	 * policy or is asking for __GFP_HIGH memory.  GFP_ATOMIC requests will
4196 	 * set both ALLOC_HARDER (__GFP_ATOMIC) and ALLOC_HIGH (__GFP_HIGH).
4197 	 */
4198 	alloc_flags |= (__force int) (gfp_mask & __GFP_HIGH);
4199 
4200 	if (gfp_mask & __GFP_ATOMIC) {
4201 		/*
4202 		 * Not worth trying to allocate harder for __GFP_NOMEMALLOC even
4203 		 * if it can't schedule.
4204 		 */
4205 		if (!(gfp_mask & __GFP_NOMEMALLOC))
4206 			alloc_flags |= ALLOC_HARDER;
4207 		/*
4208 		 * Ignore cpuset mems for GFP_ATOMIC rather than fail, see the
4209 		 * comment for __cpuset_node_allowed().
4210 		 */
4211 		alloc_flags &= ~ALLOC_CPUSET;
4212 	} else if (unlikely(rt_task(current)) && !in_interrupt())
4213 		alloc_flags |= ALLOC_HARDER;
4214 
4215 	if (gfp_mask & __GFP_KSWAPD_RECLAIM)
4216 		alloc_flags |= ALLOC_KSWAPD;
4217 
4218 #ifdef CONFIG_CMA
4219 	if (gfpflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
4220 		alloc_flags |= ALLOC_CMA;
4221 #endif
4222 	return alloc_flags;
4223 }
4224 
oom_reserves_allowed(struct task_struct * tsk)4225 static bool oom_reserves_allowed(struct task_struct *tsk)
4226 {
4227 	if (!tsk_is_oom_victim(tsk))
4228 		return false;
4229 
4230 	/*
4231 	 * !MMU doesn't have oom reaper so give access to memory reserves
4232 	 * only to the thread with TIF_MEMDIE set
4233 	 */
4234 	if (!IS_ENABLED(CONFIG_MMU) && !test_thread_flag(TIF_MEMDIE))
4235 		return false;
4236 
4237 	return true;
4238 }
4239 
4240 /*
4241  * Distinguish requests which really need access to full memory
4242  * reserves from oom victims which can live with a portion of it
4243  */
__gfp_pfmemalloc_flags(gfp_t gfp_mask)4244 static inline int __gfp_pfmemalloc_flags(gfp_t gfp_mask)
4245 {
4246 	if (unlikely(gfp_mask & __GFP_NOMEMALLOC))
4247 		return 0;
4248 	if (gfp_mask & __GFP_MEMALLOC)
4249 		return ALLOC_NO_WATERMARKS;
4250 	if (in_serving_softirq() && (current->flags & PF_MEMALLOC))
4251 		return ALLOC_NO_WATERMARKS;
4252 	if (!in_interrupt()) {
4253 		if (current->flags & PF_MEMALLOC)
4254 			return ALLOC_NO_WATERMARKS;
4255 		else if (oom_reserves_allowed(current))
4256 			return ALLOC_OOM;
4257 	}
4258 
4259 	return 0;
4260 }
4261 
gfp_pfmemalloc_allowed(gfp_t gfp_mask)4262 bool gfp_pfmemalloc_allowed(gfp_t gfp_mask)
4263 {
4264 	return !!__gfp_pfmemalloc_flags(gfp_mask);
4265 }
4266 
4267 /*
4268  * Checks whether it makes sense to retry the reclaim to make a forward progress
4269  * for the given allocation request.
4270  *
4271  * We give up when we either have tried MAX_RECLAIM_RETRIES in a row
4272  * without success, or when we couldn't even meet the watermark if we
4273  * reclaimed all remaining pages on the LRU lists.
4274  *
4275  * Returns true if a retry is viable or false to enter the oom path.
4276  */
4277 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)4278 should_reclaim_retry(gfp_t gfp_mask, unsigned order,
4279 		     struct alloc_context *ac, int alloc_flags,
4280 		     bool did_some_progress, int *no_progress_loops)
4281 {
4282 	struct zone *zone;
4283 	struct zoneref *z;
4284 	bool ret = false;
4285 
4286 	/*
4287 	 * Costly allocations might have made a progress but this doesn't mean
4288 	 * their order will become available due to high fragmentation so
4289 	 * always increment the no progress counter for them
4290 	 */
4291 	if (did_some_progress && order <= PAGE_ALLOC_COSTLY_ORDER)
4292 		*no_progress_loops = 0;
4293 	else
4294 		(*no_progress_loops)++;
4295 
4296 	/*
4297 	 * Make sure we converge to OOM if we cannot make any progress
4298 	 * several times in the row.
4299 	 */
4300 	if (*no_progress_loops > MAX_RECLAIM_RETRIES) {
4301 		/* Before OOM, exhaust highatomic_reserve */
4302 		return unreserve_highatomic_pageblock(ac, true);
4303 	}
4304 
4305 	/*
4306 	 * Keep reclaiming pages while there is a chance this will lead
4307 	 * somewhere.  If none of the target zones can satisfy our allocation
4308 	 * request even if all reclaimable pages are considered then we are
4309 	 * screwed and have to go OOM.
4310 	 */
4311 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
4312 					ac->nodemask) {
4313 		unsigned long available;
4314 		unsigned long reclaimable;
4315 		unsigned long min_wmark = min_wmark_pages(zone);
4316 		bool wmark;
4317 
4318 		available = reclaimable = zone_reclaimable_pages(zone);
4319 		available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
4320 
4321 		/*
4322 		 * Would the allocation succeed if we reclaimed all
4323 		 * reclaimable pages?
4324 		 */
4325 		wmark = __zone_watermark_ok(zone, order, min_wmark,
4326 				ac_classzone_idx(ac), alloc_flags, available);
4327 		trace_reclaim_retry_zone(z, order, reclaimable,
4328 				available, min_wmark, *no_progress_loops, wmark);
4329 		if (wmark) {
4330 			/*
4331 			 * If we didn't make any progress and have a lot of
4332 			 * dirty + writeback pages then we should wait for
4333 			 * an IO to complete to slow down the reclaim and
4334 			 * prevent from pre mature OOM
4335 			 */
4336 			if (!did_some_progress) {
4337 				unsigned long write_pending;
4338 
4339 				write_pending = zone_page_state_snapshot(zone,
4340 							NR_ZONE_WRITE_PENDING);
4341 
4342 				if (2 * write_pending > reclaimable) {
4343 					congestion_wait(BLK_RW_ASYNC, HZ/10);
4344 					return true;
4345 				}
4346 			}
4347 
4348 			ret = true;
4349 			goto out;
4350 		}
4351 	}
4352 
4353 out:
4354 	/*
4355 	 * Memory allocation/reclaim might be called from a WQ context and the
4356 	 * current implementation of the WQ concurrency control doesn't
4357 	 * recognize that a particular WQ is congested if the worker thread is
4358 	 * looping without ever sleeping. Therefore we have to do a short sleep
4359 	 * here rather than calling cond_resched().
4360 	 */
4361 	if (current->flags & PF_WQ_WORKER)
4362 		schedule_timeout_uninterruptible(1);
4363 	else
4364 		cond_resched();
4365 	return ret;
4366 }
4367 
4368 static inline bool
check_retry_cpuset(int cpuset_mems_cookie,struct alloc_context * ac)4369 check_retry_cpuset(int cpuset_mems_cookie, struct alloc_context *ac)
4370 {
4371 	/*
4372 	 * It's possible that cpuset's mems_allowed and the nodemask from
4373 	 * mempolicy don't intersect. This should be normally dealt with by
4374 	 * policy_nodemask(), but it's possible to race with cpuset update in
4375 	 * such a way the check therein was true, and then it became false
4376 	 * before we got our cpuset_mems_cookie here.
4377 	 * This assumes that for all allocations, ac->nodemask can come only
4378 	 * from MPOL_BIND mempolicy (whose documented semantics is to be ignored
4379 	 * when it does not intersect with the cpuset restrictions) or the
4380 	 * caller can deal with a violated nodemask.
4381 	 */
4382 	if (cpusets_enabled() && ac->nodemask &&
4383 			!cpuset_nodemask_valid_mems_allowed(ac->nodemask)) {
4384 		ac->nodemask = NULL;
4385 		return true;
4386 	}
4387 
4388 	/*
4389 	 * When updating a task's mems_allowed or mempolicy nodemask, it is
4390 	 * possible to race with parallel threads in such a way that our
4391 	 * allocation can fail while the mask is being updated. If we are about
4392 	 * to fail, check if the cpuset changed during allocation and if so,
4393 	 * retry.
4394 	 */
4395 	if (read_mems_allowed_retry(cpuset_mems_cookie))
4396 		return true;
4397 
4398 	return false;
4399 }
4400 
4401 static inline struct page *
__alloc_pages_slowpath(gfp_t gfp_mask,unsigned int order,struct alloc_context * ac)4402 __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order,
4403 						struct alloc_context *ac)
4404 {
4405 	bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM;
4406 	const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER;
4407 	struct page *page = NULL;
4408 	unsigned int alloc_flags;
4409 	unsigned long did_some_progress;
4410 	enum compact_priority compact_priority;
4411 	enum compact_result compact_result;
4412 	int compaction_retries;
4413 	int no_progress_loops;
4414 	unsigned int cpuset_mems_cookie;
4415 	int reserve_flags;
4416 
4417 	/*
4418 	 * We also sanity check to catch abuse of atomic reserves being used by
4419 	 * callers that are not in atomic context.
4420 	 */
4421 	if (WARN_ON_ONCE((gfp_mask & (__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)) ==
4422 				(__GFP_ATOMIC|__GFP_DIRECT_RECLAIM)))
4423 		gfp_mask &= ~__GFP_ATOMIC;
4424 
4425 retry_cpuset:
4426 	compaction_retries = 0;
4427 	no_progress_loops = 0;
4428 	compact_priority = DEF_COMPACT_PRIORITY;
4429 	cpuset_mems_cookie = read_mems_allowed_begin();
4430 
4431 	/*
4432 	 * The fast path uses conservative alloc_flags to succeed only until
4433 	 * kswapd needs to be woken up, and to avoid the cost of setting up
4434 	 * alloc_flags precisely. So we do that now.
4435 	 */
4436 	alloc_flags = gfp_to_alloc_flags(gfp_mask);
4437 
4438 	/*
4439 	 * We need to recalculate the starting point for the zonelist iterator
4440 	 * because we might have used different nodemask in the fast path, or
4441 	 * there was a cpuset modification and we are retrying - otherwise we
4442 	 * could end up iterating over non-eligible zones endlessly.
4443 	 */
4444 	ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4445 					ac->high_zoneidx, ac->nodemask);
4446 	if (!ac->preferred_zoneref->zone)
4447 		goto nopage;
4448 
4449 	if (alloc_flags & ALLOC_KSWAPD)
4450 		wake_all_kswapds(order, gfp_mask, ac);
4451 
4452 	/*
4453 	 * The adjusted alloc_flags might result in immediate success, so try
4454 	 * that first
4455 	 */
4456 	page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4457 	if (page)
4458 		goto got_pg;
4459 
4460 	/*
4461 	 * For costly allocations, try direct compaction first, as it's likely
4462 	 * that we have enough base pages and don't need to reclaim. For non-
4463 	 * movable high-order allocations, do that as well, as compaction will
4464 	 * try prevent permanent fragmentation by migrating from blocks of the
4465 	 * same migratetype.
4466 	 * Don't try this for allocations that are allowed to ignore
4467 	 * watermarks, as the ALLOC_NO_WATERMARKS attempt didn't yet happen.
4468 	 */
4469 	if (can_direct_reclaim &&
4470 			(costly_order ||
4471 			   (order > 0 && ac->migratetype != MIGRATE_MOVABLE))
4472 			&& !gfp_pfmemalloc_allowed(gfp_mask)) {
4473 		page = __alloc_pages_direct_compact(gfp_mask, order,
4474 						alloc_flags, ac,
4475 						INIT_COMPACT_PRIORITY,
4476 						&compact_result);
4477 		if (page)
4478 			goto got_pg;
4479 
4480 		 if (order >= pageblock_order && (gfp_mask & __GFP_IO) &&
4481 		     !(gfp_mask & __GFP_RETRY_MAYFAIL)) {
4482 			/*
4483 			 * If allocating entire pageblock(s) and compaction
4484 			 * failed because all zones are below low watermarks
4485 			 * or is prohibited because it recently failed at this
4486 			 * order, fail immediately unless the allocator has
4487 			 * requested compaction and reclaim retry.
4488 			 *
4489 			 * Reclaim is
4490 			 *  - potentially very expensive because zones are far
4491 			 *    below their low watermarks or this is part of very
4492 			 *    bursty high order allocations,
4493 			 *  - not guaranteed to help because isolate_freepages()
4494 			 *    may not iterate over freed pages as part of its
4495 			 *    linear scan, and
4496 			 *  - unlikely to make entire pageblocks free on its
4497 			 *    own.
4498 			 */
4499 			if (compact_result == COMPACT_SKIPPED ||
4500 			    compact_result == COMPACT_DEFERRED)
4501 				goto nopage;
4502 		}
4503 
4504 		/*
4505 		 * Checks for costly allocations with __GFP_NORETRY, which
4506 		 * includes THP page fault allocations
4507 		 */
4508 		if (costly_order && (gfp_mask & __GFP_NORETRY)) {
4509 			/*
4510 			 * If compaction is deferred for high-order allocations,
4511 			 * it is because sync compaction recently failed. If
4512 			 * this is the case and the caller requested a THP
4513 			 * allocation, we do not want to heavily disrupt the
4514 			 * system, so we fail the allocation instead of entering
4515 			 * direct reclaim.
4516 			 */
4517 			if (compact_result == COMPACT_DEFERRED)
4518 				goto nopage;
4519 
4520 			/*
4521 			 * Looks like reclaim/compaction is worth trying, but
4522 			 * sync compaction could be very expensive, so keep
4523 			 * using async compaction.
4524 			 */
4525 			compact_priority = INIT_COMPACT_PRIORITY;
4526 		}
4527 	}
4528 
4529 retry:
4530 	/* Ensure kswapd doesn't accidentally go to sleep as long as we loop */
4531 	if (alloc_flags & ALLOC_KSWAPD)
4532 		wake_all_kswapds(order, gfp_mask, ac);
4533 
4534 	reserve_flags = __gfp_pfmemalloc_flags(gfp_mask);
4535 	if (reserve_flags)
4536 		alloc_flags = reserve_flags;
4537 
4538 	/*
4539 	 * Reset the nodemask and zonelist iterators if memory policies can be
4540 	 * ignored. These allocations are high priority and system rather than
4541 	 * user oriented.
4542 	 */
4543 	if (!(alloc_flags & ALLOC_CPUSET) || reserve_flags) {
4544 		ac->nodemask = NULL;
4545 		ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4546 					ac->high_zoneidx, ac->nodemask);
4547 	}
4548 
4549 	/* Attempt with potentially adjusted zonelist and alloc_flags */
4550 	page = get_page_from_freelist(gfp_mask, order, alloc_flags, ac);
4551 	if (page)
4552 		goto got_pg;
4553 
4554 	/* Caller is not willing to reclaim, we can't balance anything */
4555 	if (!can_direct_reclaim)
4556 		goto nopage;
4557 
4558 	/* Avoid recursion of direct reclaim */
4559 	if (current->flags & PF_MEMALLOC)
4560 		goto nopage;
4561 
4562 	/* Try direct reclaim and then allocating */
4563 	page = __alloc_pages_direct_reclaim(gfp_mask, order, alloc_flags, ac,
4564 							&did_some_progress);
4565 	if (page)
4566 		goto got_pg;
4567 
4568 	/* Try direct compaction and then allocating */
4569 	page = __alloc_pages_direct_compact(gfp_mask, order, alloc_flags, ac,
4570 					compact_priority, &compact_result);
4571 	if (page)
4572 		goto got_pg;
4573 
4574 	/* Do not loop if specifically requested */
4575 	if (gfp_mask & __GFP_NORETRY)
4576 		goto nopage;
4577 
4578 	/*
4579 	 * Do not retry costly high order allocations unless they are
4580 	 * __GFP_RETRY_MAYFAIL
4581 	 */
4582 	if (costly_order && !(gfp_mask & __GFP_RETRY_MAYFAIL))
4583 		goto nopage;
4584 
4585 	if (should_reclaim_retry(gfp_mask, order, ac, alloc_flags,
4586 				 did_some_progress > 0, &no_progress_loops))
4587 		goto retry;
4588 
4589 	/*
4590 	 * It doesn't make any sense to retry for the compaction if the order-0
4591 	 * reclaim is not able to make any progress because the current
4592 	 * implementation of the compaction depends on the sufficient amount
4593 	 * of free memory (see __compaction_suitable)
4594 	 */
4595 	if (did_some_progress > 0 &&
4596 			should_compact_retry(ac, order, alloc_flags,
4597 				compact_result, &compact_priority,
4598 				&compaction_retries))
4599 		goto retry;
4600 
4601 
4602 	/* Deal with possible cpuset update races before we start OOM killing */
4603 	if (check_retry_cpuset(cpuset_mems_cookie, ac))
4604 		goto retry_cpuset;
4605 
4606 	/* Reclaim has failed us, start killing things */
4607 	page = __alloc_pages_may_oom(gfp_mask, order, ac, &did_some_progress);
4608 	if (page)
4609 		goto got_pg;
4610 
4611 	/* Avoid allocations with no watermarks from looping endlessly */
4612 	if (tsk_is_oom_victim(current) &&
4613 	    (alloc_flags == ALLOC_OOM ||
4614 	     (gfp_mask & __GFP_NOMEMALLOC)))
4615 		goto nopage;
4616 
4617 	/* Retry as long as the OOM killer is making progress */
4618 	if (did_some_progress) {
4619 		no_progress_loops = 0;
4620 		goto retry;
4621 	}
4622 
4623 nopage:
4624 	/* Deal with possible cpuset update races before we fail */
4625 	if (check_retry_cpuset(cpuset_mems_cookie, ac))
4626 		goto retry_cpuset;
4627 
4628 	/*
4629 	 * Make sure that __GFP_NOFAIL request doesn't leak out and make sure
4630 	 * we always retry
4631 	 */
4632 	if (gfp_mask & __GFP_NOFAIL) {
4633 		/*
4634 		 * All existing users of the __GFP_NOFAIL are blockable, so warn
4635 		 * of any new users that actually require GFP_NOWAIT
4636 		 */
4637 		if (WARN_ON_ONCE(!can_direct_reclaim))
4638 			goto fail;
4639 
4640 		/*
4641 		 * PF_MEMALLOC request from this context is rather bizarre
4642 		 * because we cannot reclaim anything and only can loop waiting
4643 		 * for somebody to do a work for us
4644 		 */
4645 		WARN_ON_ONCE(current->flags & PF_MEMALLOC);
4646 
4647 		/*
4648 		 * non failing costly orders are a hard requirement which we
4649 		 * are not prepared for much so let's warn about these users
4650 		 * so that we can identify them and convert them to something
4651 		 * else.
4652 		 */
4653 		WARN_ON_ONCE(order > PAGE_ALLOC_COSTLY_ORDER);
4654 
4655 		/*
4656 		 * Help non-failing allocations by giving them access to memory
4657 		 * reserves but do not use ALLOC_NO_WATERMARKS because this
4658 		 * could deplete whole memory reserves which would just make
4659 		 * the situation worse
4660 		 */
4661 		page = __alloc_pages_cpuset_fallback(gfp_mask, order, ALLOC_HARDER, ac);
4662 		if (page)
4663 			goto got_pg;
4664 
4665 		cond_resched();
4666 		goto retry;
4667 	}
4668 fail:
4669 	warn_alloc(gfp_mask, ac->nodemask,
4670 			"page allocation failure: order:%u", order);
4671 got_pg:
4672 	return page;
4673 }
4674 
prepare_alloc_pages(gfp_t gfp_mask,unsigned int order,int preferred_nid,nodemask_t * nodemask,struct alloc_context * ac,gfp_t * alloc_mask,unsigned int * alloc_flags)4675 static inline bool prepare_alloc_pages(gfp_t gfp_mask, unsigned int order,
4676 		int preferred_nid, nodemask_t *nodemask,
4677 		struct alloc_context *ac, gfp_t *alloc_mask,
4678 		unsigned int *alloc_flags)
4679 {
4680 	ac->high_zoneidx = gfp_zone(gfp_mask);
4681 	ac->zonelist = node_zonelist(preferred_nid, gfp_mask);
4682 	ac->nodemask = nodemask;
4683 	ac->migratetype = gfpflags_to_migratetype(gfp_mask);
4684 
4685 	if (cpusets_enabled()) {
4686 		*alloc_mask |= __GFP_HARDWALL;
4687 		if (!ac->nodemask)
4688 			ac->nodemask = &cpuset_current_mems_allowed;
4689 		else
4690 			*alloc_flags |= ALLOC_CPUSET;
4691 	}
4692 
4693 	fs_reclaim_acquire(gfp_mask);
4694 	fs_reclaim_release(gfp_mask);
4695 
4696 	might_sleep_if(gfp_mask & __GFP_DIRECT_RECLAIM);
4697 
4698 	if (should_fail_alloc_page(gfp_mask, order))
4699 		return false;
4700 
4701 	if (IS_ENABLED(CONFIG_CMA) && ac->migratetype == MIGRATE_MOVABLE)
4702 		*alloc_flags |= ALLOC_CMA;
4703 
4704 	return true;
4705 }
4706 
4707 /* Determine whether to spread dirty pages and what the first usable zone */
finalise_ac(gfp_t gfp_mask,struct alloc_context * ac)4708 static inline void finalise_ac(gfp_t gfp_mask, struct alloc_context *ac)
4709 {
4710 	/* Dirty zone balancing only done in the fast path */
4711 	ac->spread_dirty_pages = (gfp_mask & __GFP_WRITE);
4712 
4713 	/*
4714 	 * The preferred zone is used for statistics but crucially it is
4715 	 * also used as the starting point for the zonelist iterator. It
4716 	 * may get reset for allocations that ignore memory policies.
4717 	 */
4718 	ac->preferred_zoneref = first_zones_zonelist(ac->zonelist,
4719 					ac->high_zoneidx, ac->nodemask);
4720 }
4721 
4722 /*
4723  * This is the 'heart' of the zoned buddy allocator.
4724  */
4725 struct page *
__alloc_pages_nodemask(gfp_t gfp_mask,unsigned int order,int preferred_nid,nodemask_t * nodemask)4726 __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order, int preferred_nid,
4727 							nodemask_t *nodemask)
4728 {
4729 	struct page *page;
4730 	unsigned int alloc_flags = ALLOC_WMARK_LOW;
4731 	gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
4732 	struct alloc_context ac = { };
4733 
4734 	/*
4735 	 * There are several places where we assume that the order value is sane
4736 	 * so bail out early if the request is out of bound.
4737 	 */
4738 	if (unlikely(order >= MAX_ORDER)) {
4739 		WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN));
4740 		return NULL;
4741 	}
4742 
4743 	gfp_mask &= gfp_allowed_mask;
4744 	alloc_mask = gfp_mask;
4745 	if (!prepare_alloc_pages(gfp_mask, order, preferred_nid, nodemask, &ac, &alloc_mask, &alloc_flags))
4746 		return NULL;
4747 
4748 	finalise_ac(gfp_mask, &ac);
4749 
4750 	/*
4751 	 * Forbid the first pass from falling back to types that fragment
4752 	 * memory until all local zones are considered.
4753 	 */
4754 	alloc_flags |= alloc_flags_nofragment(ac.preferred_zoneref->zone, gfp_mask);
4755 
4756 	/* First allocation attempt */
4757 	page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
4758 	if (likely(page))
4759 		goto out;
4760 
4761 	/*
4762 	 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
4763 	 * resp. GFP_NOIO which has to be inherited for all allocation requests
4764 	 * from a particular context which has been marked by
4765 	 * memalloc_no{fs,io}_{save,restore}.
4766 	 */
4767 	alloc_mask = current_gfp_context(gfp_mask);
4768 	ac.spread_dirty_pages = false;
4769 
4770 	/*
4771 	 * Restore the original nodemask if it was potentially replaced with
4772 	 * &cpuset_current_mems_allowed to optimize the fast-path attempt.
4773 	 */
4774 	if (unlikely(ac.nodemask != nodemask))
4775 		ac.nodemask = nodemask;
4776 
4777 	page = __alloc_pages_slowpath(alloc_mask, order, &ac);
4778 
4779 out:
4780 	if (memcg_kmem_enabled() && (gfp_mask & __GFP_ACCOUNT) && page &&
4781 	    unlikely(__memcg_kmem_charge(page, gfp_mask, order) != 0)) {
4782 		__free_pages(page, order);
4783 		page = NULL;
4784 	}
4785 
4786 	trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);
4787 
4788 	return page;
4789 }
4790 EXPORT_SYMBOL(__alloc_pages_nodemask);
4791 
4792 /*
4793  * Common helper functions. Never use with __GFP_HIGHMEM because the returned
4794  * address cannot represent highmem pages. Use alloc_pages and then kmap if
4795  * you need to access high mem.
4796  */
__get_free_pages(gfp_t gfp_mask,unsigned int order)4797 unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order)
4798 {
4799 	struct page *page;
4800 
4801 	page = alloc_pages(gfp_mask & ~__GFP_HIGHMEM, order);
4802 	if (!page)
4803 		return 0;
4804 	return (unsigned long) page_address(page);
4805 }
4806 EXPORT_SYMBOL(__get_free_pages);
4807 
get_zeroed_page(gfp_t gfp_mask)4808 unsigned long get_zeroed_page(gfp_t gfp_mask)
4809 {
4810 	return __get_free_pages(gfp_mask | __GFP_ZERO, 0);
4811 }
4812 EXPORT_SYMBOL(get_zeroed_page);
4813 
free_the_page(struct page * page,unsigned int order)4814 static inline void free_the_page(struct page *page, unsigned int order)
4815 {
4816 	if (order == 0)		/* Via pcp? */
4817 		free_unref_page(page);
4818 	else
4819 		__free_pages_ok(page, order);
4820 }
4821 
__free_pages(struct page * page,unsigned int order)4822 void __free_pages(struct page *page, unsigned int order)
4823 {
4824 	if (put_page_testzero(page))
4825 		free_the_page(page, order);
4826 }
4827 EXPORT_SYMBOL(__free_pages);
4828 
free_pages(unsigned long addr,unsigned int order)4829 void free_pages(unsigned long addr, unsigned int order)
4830 {
4831 	if (addr != 0) {
4832 		VM_BUG_ON(!virt_addr_valid((void *)addr));
4833 		__free_pages(virt_to_page((void *)addr), order);
4834 	}
4835 }
4836 
4837 EXPORT_SYMBOL(free_pages);
4838 
4839 /*
4840  * Page Fragment:
4841  *  An arbitrary-length arbitrary-offset area of memory which resides
4842  *  within a 0 or higher order page.  Multiple fragments within that page
4843  *  are individually refcounted, in the page's reference counter.
4844  *
4845  * The page_frag functions below provide a simple allocation framework for
4846  * page fragments.  This is used by the network stack and network device
4847  * drivers to provide a backing region of memory for use as either an
4848  * sk_buff->head, or to be used in the "frags" portion of skb_shared_info.
4849  */
__page_frag_cache_refill(struct page_frag_cache * nc,gfp_t gfp_mask)4850 static struct page *__page_frag_cache_refill(struct page_frag_cache *nc,
4851 					     gfp_t gfp_mask)
4852 {
4853 	struct page *page = NULL;
4854 	gfp_t gfp = gfp_mask;
4855 
4856 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4857 	gfp_mask |= __GFP_COMP | __GFP_NOWARN | __GFP_NORETRY |
4858 		    __GFP_NOMEMALLOC;
4859 	page = alloc_pages_node(NUMA_NO_NODE, gfp_mask,
4860 				PAGE_FRAG_CACHE_MAX_ORDER);
4861 	nc->size = page ? PAGE_FRAG_CACHE_MAX_SIZE : PAGE_SIZE;
4862 #endif
4863 	if (unlikely(!page))
4864 		page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
4865 
4866 	nc->va = page ? page_address(page) : NULL;
4867 
4868 	return page;
4869 }
4870 
__page_frag_cache_drain(struct page * page,unsigned int count)4871 void __page_frag_cache_drain(struct page *page, unsigned int count)
4872 {
4873 	VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
4874 
4875 	if (page_ref_sub_and_test(page, count))
4876 		free_the_page(page, compound_order(page));
4877 }
4878 EXPORT_SYMBOL(__page_frag_cache_drain);
4879 
page_frag_alloc(struct page_frag_cache * nc,unsigned int fragsz,gfp_t gfp_mask)4880 void *page_frag_alloc(struct page_frag_cache *nc,
4881 		      unsigned int fragsz, gfp_t gfp_mask)
4882 {
4883 	unsigned int size = PAGE_SIZE;
4884 	struct page *page;
4885 	int offset;
4886 
4887 	if (unlikely(!nc->va)) {
4888 refill:
4889 		page = __page_frag_cache_refill(nc, gfp_mask);
4890 		if (!page)
4891 			return NULL;
4892 
4893 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4894 		/* if size can vary use size else just use PAGE_SIZE */
4895 		size = nc->size;
4896 #endif
4897 		/* Even if we own the page, we do not use atomic_set().
4898 		 * This would break get_page_unless_zero() users.
4899 		 */
4900 		page_ref_add(page, PAGE_FRAG_CACHE_MAX_SIZE);
4901 
4902 		/* reset page count bias and offset to start of new frag */
4903 		nc->pfmemalloc = page_is_pfmemalloc(page);
4904 		nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
4905 		nc->offset = size;
4906 	}
4907 
4908 	offset = nc->offset - fragsz;
4909 	if (unlikely(offset < 0)) {
4910 		page = virt_to_page(nc->va);
4911 
4912 		if (!page_ref_sub_and_test(page, nc->pagecnt_bias))
4913 			goto refill;
4914 
4915 #if (PAGE_SIZE < PAGE_FRAG_CACHE_MAX_SIZE)
4916 		/* if size can vary use size else just use PAGE_SIZE */
4917 		size = nc->size;
4918 #endif
4919 		/* OK, page count is 0, we can safely set it */
4920 		set_page_count(page, PAGE_FRAG_CACHE_MAX_SIZE + 1);
4921 
4922 		/* reset page count bias and offset to start of new frag */
4923 		nc->pagecnt_bias = PAGE_FRAG_CACHE_MAX_SIZE + 1;
4924 		offset = size - fragsz;
4925 	}
4926 
4927 	nc->pagecnt_bias--;
4928 	nc->offset = offset;
4929 
4930 	return nc->va + offset;
4931 }
4932 EXPORT_SYMBOL(page_frag_alloc);
4933 
4934 /*
4935  * Frees a page fragment allocated out of either a compound or order 0 page.
4936  */
page_frag_free(void * addr)4937 void page_frag_free(void *addr)
4938 {
4939 	struct page *page = virt_to_head_page(addr);
4940 
4941 	if (unlikely(put_page_testzero(page)))
4942 		free_the_page(page, compound_order(page));
4943 }
4944 EXPORT_SYMBOL(page_frag_free);
4945 
make_alloc_exact(unsigned long addr,unsigned int order,size_t size)4946 static void *make_alloc_exact(unsigned long addr, unsigned int order,
4947 		size_t size)
4948 {
4949 	if (addr) {
4950 		unsigned long alloc_end = addr + (PAGE_SIZE << order);
4951 		unsigned long used = addr + PAGE_ALIGN(size);
4952 
4953 		split_page(virt_to_page((void *)addr), order);
4954 		while (used < alloc_end) {
4955 			free_page(used);
4956 			used += PAGE_SIZE;
4957 		}
4958 	}
4959 	return (void *)addr;
4960 }
4961 
4962 /**
4963  * alloc_pages_exact - allocate an exact number physically-contiguous pages.
4964  * @size: the number of bytes to allocate
4965  * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
4966  *
4967  * This function is similar to alloc_pages(), except that it allocates the
4968  * minimum number of pages to satisfy the request.  alloc_pages() can only
4969  * allocate memory in power-of-two pages.
4970  *
4971  * This function is also limited by MAX_ORDER.
4972  *
4973  * Memory allocated by this function must be released by free_pages_exact().
4974  *
4975  * Return: pointer to the allocated area or %NULL in case of error.
4976  */
alloc_pages_exact(size_t size,gfp_t gfp_mask)4977 void *alloc_pages_exact(size_t size, gfp_t gfp_mask)
4978 {
4979 	unsigned int order = get_order(size);
4980 	unsigned long addr;
4981 
4982 	if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
4983 		gfp_mask &= ~__GFP_COMP;
4984 
4985 	addr = __get_free_pages(gfp_mask, order);
4986 	return make_alloc_exact(addr, order, size);
4987 }
4988 EXPORT_SYMBOL(alloc_pages_exact);
4989 
4990 /**
4991  * alloc_pages_exact_nid - allocate an exact number of physically-contiguous
4992  *			   pages on a node.
4993  * @nid: the preferred node ID where memory should be allocated
4994  * @size: the number of bytes to allocate
4995  * @gfp_mask: GFP flags for the allocation, must not contain __GFP_COMP
4996  *
4997  * Like alloc_pages_exact(), but try to allocate on node nid first before falling
4998  * back.
4999  *
5000  * Return: pointer to the allocated area or %NULL in case of error.
5001  */
alloc_pages_exact_nid(int nid,size_t size,gfp_t gfp_mask)5002 void * __meminit alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
5003 {
5004 	unsigned int order = get_order(size);
5005 	struct page *p;
5006 
5007 	if (WARN_ON_ONCE(gfp_mask & __GFP_COMP))
5008 		gfp_mask &= ~__GFP_COMP;
5009 
5010 	p = alloc_pages_node(nid, gfp_mask, order);
5011 	if (!p)
5012 		return NULL;
5013 	return make_alloc_exact((unsigned long)page_address(p), order, size);
5014 }
5015 
5016 /**
5017  * free_pages_exact - release memory allocated via alloc_pages_exact()
5018  * @virt: the value returned by alloc_pages_exact.
5019  * @size: size of allocation, same value as passed to alloc_pages_exact().
5020  *
5021  * Release the memory allocated by a previous call to alloc_pages_exact.
5022  */
free_pages_exact(void * virt,size_t size)5023 void free_pages_exact(void *virt, size_t size)
5024 {
5025 	unsigned long addr = (unsigned long)virt;
5026 	unsigned long end = addr + PAGE_ALIGN(size);
5027 
5028 	while (addr < end) {
5029 		free_page(addr);
5030 		addr += PAGE_SIZE;
5031 	}
5032 }
5033 EXPORT_SYMBOL(free_pages_exact);
5034 
5035 /**
5036  * nr_free_zone_pages - count number of pages beyond high watermark
5037  * @offset: The zone index of the highest zone
5038  *
5039  * nr_free_zone_pages() counts the number of pages which are beyond the
5040  * high watermark within all zones at or below a given zone index.  For each
5041  * zone, the number of pages is calculated as:
5042  *
5043  *     nr_free_zone_pages = managed_pages - high_pages
5044  *
5045  * Return: number of pages beyond high watermark.
5046  */
nr_free_zone_pages(int offset)5047 static unsigned long nr_free_zone_pages(int offset)
5048 {
5049 	struct zoneref *z;
5050 	struct zone *zone;
5051 
5052 	/* Just pick one node, since fallback list is circular */
5053 	unsigned long sum = 0;
5054 
5055 	struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL);
5056 
5057 	for_each_zone_zonelist(zone, z, zonelist, offset) {
5058 		unsigned long size = zone_managed_pages(zone);
5059 		unsigned long high = high_wmark_pages(zone);
5060 		if (size > high)
5061 			sum += size - high;
5062 	}
5063 
5064 	return sum;
5065 }
5066 
5067 /**
5068  * nr_free_buffer_pages - count number of pages beyond high watermark
5069  *
5070  * nr_free_buffer_pages() counts the number of pages which are beyond the high
5071  * watermark within ZONE_DMA and ZONE_NORMAL.
5072  *
5073  * Return: number of pages beyond high watermark within ZONE_DMA and
5074  * ZONE_NORMAL.
5075  */
nr_free_buffer_pages(void)5076 unsigned long nr_free_buffer_pages(void)
5077 {
5078 	return nr_free_zone_pages(gfp_zone(GFP_USER));
5079 }
5080 EXPORT_SYMBOL_GPL(nr_free_buffer_pages);
5081 
5082 /**
5083  * nr_free_pagecache_pages - count number of pages beyond high watermark
5084  *
5085  * nr_free_pagecache_pages() counts the number of pages which are beyond the
5086  * high watermark within all zones.
5087  *
5088  * Return: number of pages beyond high watermark within all zones.
5089  */
nr_free_pagecache_pages(void)5090 unsigned long nr_free_pagecache_pages(void)
5091 {
5092 	return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE));
5093 }
5094 
show_node(struct zone * zone)5095 static inline void show_node(struct zone *zone)
5096 {
5097 	if (IS_ENABLED(CONFIG_NUMA))
5098 		printk("Node %d ", zone_to_nid(zone));
5099 }
5100 
si_mem_available(void)5101 long si_mem_available(void)
5102 {
5103 	long available;
5104 	unsigned long pagecache;
5105 	unsigned long wmark_low = 0;
5106 	unsigned long pages[NR_LRU_LISTS];
5107 	unsigned long reclaimable;
5108 	struct zone *zone;
5109 	int lru;
5110 
5111 	for (lru = LRU_BASE; lru < NR_LRU_LISTS; lru++)
5112 		pages[lru] = global_node_page_state(NR_LRU_BASE + lru);
5113 
5114 	for_each_zone(zone)
5115 		wmark_low += low_wmark_pages(zone);
5116 
5117 	/*
5118 	 * Estimate the amount of memory available for userspace allocations,
5119 	 * without causing swapping.
5120 	 */
5121 	available = global_zone_page_state(NR_FREE_PAGES) - totalreserve_pages;
5122 
5123 	/*
5124 	 * Not all the page cache can be freed, otherwise the system will
5125 	 * start swapping. Assume at least half of the page cache, or the
5126 	 * low watermark worth of cache, needs to stay.
5127 	 */
5128 	pagecache = pages[LRU_ACTIVE_FILE] + pages[LRU_INACTIVE_FILE];
5129 	pagecache -= min(pagecache / 2, wmark_low);
5130 	available += pagecache;
5131 
5132 	/*
5133 	 * Part of the reclaimable slab and other kernel memory consists of
5134 	 * items that are in use, and cannot be freed. Cap this estimate at the
5135 	 * low watermark.
5136 	 */
5137 	reclaimable = global_node_page_state(NR_SLAB_RECLAIMABLE) +
5138 			global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE);
5139 	available += reclaimable - min(reclaimable / 2, wmark_low);
5140 
5141 	if (available < 0)
5142 		available = 0;
5143 	return available;
5144 }
5145 EXPORT_SYMBOL_GPL(si_mem_available);
5146 
si_meminfo(struct sysinfo * val)5147 void si_meminfo(struct sysinfo *val)
5148 {
5149 	val->totalram = totalram_pages();
5150 	val->sharedram = global_node_page_state(NR_SHMEM);
5151 	val->freeram = global_zone_page_state(NR_FREE_PAGES);
5152 	val->bufferram = nr_blockdev_pages();
5153 	val->totalhigh = totalhigh_pages();
5154 	val->freehigh = nr_free_highpages();
5155 	val->mem_unit = PAGE_SIZE;
5156 }
5157 
5158 EXPORT_SYMBOL(si_meminfo);
5159 
5160 #ifdef CONFIG_NUMA
si_meminfo_node(struct sysinfo * val,int nid)5161 void si_meminfo_node(struct sysinfo *val, int nid)
5162 {
5163 	int zone_type;		/* needs to be signed */
5164 	unsigned long managed_pages = 0;
5165 	unsigned long managed_highpages = 0;
5166 	unsigned long free_highpages = 0;
5167 	pg_data_t *pgdat = NODE_DATA(nid);
5168 
5169 	for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++)
5170 		managed_pages += zone_managed_pages(&pgdat->node_zones[zone_type]);
5171 	val->totalram = managed_pages;
5172 	val->sharedram = node_page_state(pgdat, NR_SHMEM);
5173 	val->freeram = sum_zone_node_page_state(nid, NR_FREE_PAGES);
5174 #ifdef CONFIG_HIGHMEM
5175 	for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) {
5176 		struct zone *zone = &pgdat->node_zones[zone_type];
5177 
5178 		if (is_highmem(zone)) {
5179 			managed_highpages += zone_managed_pages(zone);
5180 			free_highpages += zone_page_state(zone, NR_FREE_PAGES);
5181 		}
5182 	}
5183 	val->totalhigh = managed_highpages;
5184 	val->freehigh = free_highpages;
5185 #else
5186 	val->totalhigh = managed_highpages;
5187 	val->freehigh = free_highpages;
5188 #endif
5189 	val->mem_unit = PAGE_SIZE;
5190 }
5191 #endif
5192 
5193 /*
5194  * Determine whether the node should be displayed or not, depending on whether
5195  * SHOW_MEM_FILTER_NODES was passed to show_free_areas().
5196  */
show_mem_node_skip(unsigned int flags,int nid,nodemask_t * nodemask)5197 static bool show_mem_node_skip(unsigned int flags, int nid, nodemask_t *nodemask)
5198 {
5199 	if (!(flags & SHOW_MEM_FILTER_NODES))
5200 		return false;
5201 
5202 	/*
5203 	 * no node mask - aka implicit memory numa policy. Do not bother with
5204 	 * the synchronization - read_mems_allowed_begin - because we do not
5205 	 * have to be precise here.
5206 	 */
5207 	if (!nodemask)
5208 		nodemask = &cpuset_current_mems_allowed;
5209 
5210 	return !node_isset(nid, *nodemask);
5211 }
5212 
5213 #define K(x) ((x) << (PAGE_SHIFT-10))
5214 
show_migration_types(unsigned char type)5215 static void show_migration_types(unsigned char type)
5216 {
5217 	static const char types[MIGRATE_TYPES] = {
5218 		[MIGRATE_UNMOVABLE]	= 'U',
5219 		[MIGRATE_MOVABLE]	= 'M',
5220 		[MIGRATE_RECLAIMABLE]	= 'E',
5221 		[MIGRATE_HIGHATOMIC]	= 'H',
5222 #ifdef CONFIG_CMA
5223 		[MIGRATE_CMA]		= 'C',
5224 #endif
5225 #ifdef CONFIG_MEMORY_ISOLATION
5226 		[MIGRATE_ISOLATE]	= 'I',
5227 #endif
5228 	};
5229 	char tmp[MIGRATE_TYPES + 1];
5230 	char *p = tmp;
5231 	int i;
5232 
5233 	for (i = 0; i < MIGRATE_TYPES; i++) {
5234 		if (type & (1 << i))
5235 			*p++ = types[i];
5236 	}
5237 
5238 	*p = '\0';
5239 	printk(KERN_CONT "(%s) ", tmp);
5240 }
5241 
5242 /*
5243  * Show free area list (used inside shift_scroll-lock stuff)
5244  * We also calculate the percentage fragmentation. We do this by counting the
5245  * memory on each free list with the exception of the first item on the list.
5246  *
5247  * Bits in @filter:
5248  * SHOW_MEM_FILTER_NODES: suppress nodes that are not allowed by current's
5249  *   cpuset.
5250  */
show_free_areas(unsigned int filter,nodemask_t * nodemask)5251 void show_free_areas(unsigned int filter, nodemask_t *nodemask)
5252 {
5253 	unsigned long free_pcp = 0;
5254 	int cpu;
5255 	struct zone *zone;
5256 	pg_data_t *pgdat;
5257 
5258 	for_each_populated_zone(zone) {
5259 		if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5260 			continue;
5261 
5262 		for_each_online_cpu(cpu)
5263 			free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5264 	}
5265 
5266 	printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n"
5267 		" active_file:%lu inactive_file:%lu isolated_file:%lu\n"
5268 		" unevictable:%lu dirty:%lu writeback:%lu unstable:%lu\n"
5269 		" slab_reclaimable:%lu slab_unreclaimable:%lu\n"
5270 		" mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n"
5271 		" free:%lu free_pcp:%lu free_cma:%lu\n",
5272 		global_node_page_state(NR_ACTIVE_ANON),
5273 		global_node_page_state(NR_INACTIVE_ANON),
5274 		global_node_page_state(NR_ISOLATED_ANON),
5275 		global_node_page_state(NR_ACTIVE_FILE),
5276 		global_node_page_state(NR_INACTIVE_FILE),
5277 		global_node_page_state(NR_ISOLATED_FILE),
5278 		global_node_page_state(NR_UNEVICTABLE),
5279 		global_node_page_state(NR_FILE_DIRTY),
5280 		global_node_page_state(NR_WRITEBACK),
5281 		global_node_page_state(NR_UNSTABLE_NFS),
5282 		global_node_page_state(NR_SLAB_RECLAIMABLE),
5283 		global_node_page_state(NR_SLAB_UNRECLAIMABLE),
5284 		global_node_page_state(NR_FILE_MAPPED),
5285 		global_node_page_state(NR_SHMEM),
5286 		global_zone_page_state(NR_PAGETABLE),
5287 		global_zone_page_state(NR_BOUNCE),
5288 		global_zone_page_state(NR_FREE_PAGES),
5289 		free_pcp,
5290 		global_zone_page_state(NR_FREE_CMA_PAGES));
5291 
5292 	for_each_online_pgdat(pgdat) {
5293 		if (show_mem_node_skip(filter, pgdat->node_id, nodemask))
5294 			continue;
5295 
5296 		printk("Node %d"
5297 			" active_anon:%lukB"
5298 			" inactive_anon:%lukB"
5299 			" active_file:%lukB"
5300 			" inactive_file:%lukB"
5301 			" unevictable:%lukB"
5302 			" isolated(anon):%lukB"
5303 			" isolated(file):%lukB"
5304 			" mapped:%lukB"
5305 			" dirty:%lukB"
5306 			" writeback:%lukB"
5307 			" shmem:%lukB"
5308 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5309 			" shmem_thp: %lukB"
5310 			" shmem_pmdmapped: %lukB"
5311 			" anon_thp: %lukB"
5312 #endif
5313 			" writeback_tmp:%lukB"
5314 			" unstable:%lukB"
5315 			" all_unreclaimable? %s"
5316 			"\n",
5317 			pgdat->node_id,
5318 			K(node_page_state(pgdat, NR_ACTIVE_ANON)),
5319 			K(node_page_state(pgdat, NR_INACTIVE_ANON)),
5320 			K(node_page_state(pgdat, NR_ACTIVE_FILE)),
5321 			K(node_page_state(pgdat, NR_INACTIVE_FILE)),
5322 			K(node_page_state(pgdat, NR_UNEVICTABLE)),
5323 			K(node_page_state(pgdat, NR_ISOLATED_ANON)),
5324 			K(node_page_state(pgdat, NR_ISOLATED_FILE)),
5325 			K(node_page_state(pgdat, NR_FILE_MAPPED)),
5326 			K(node_page_state(pgdat, NR_FILE_DIRTY)),
5327 			K(node_page_state(pgdat, NR_WRITEBACK)),
5328 			K(node_page_state(pgdat, NR_SHMEM)),
5329 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5330 			K(node_page_state(pgdat, NR_SHMEM_THPS) * HPAGE_PMD_NR),
5331 			K(node_page_state(pgdat, NR_SHMEM_PMDMAPPED)
5332 					* HPAGE_PMD_NR),
5333 			K(node_page_state(pgdat, NR_ANON_THPS) * HPAGE_PMD_NR),
5334 #endif
5335 			K(node_page_state(pgdat, NR_WRITEBACK_TEMP)),
5336 			K(node_page_state(pgdat, NR_UNSTABLE_NFS)),
5337 			pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ?
5338 				"yes" : "no");
5339 	}
5340 
5341 	for_each_populated_zone(zone) {
5342 		int i;
5343 
5344 		if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5345 			continue;
5346 
5347 		free_pcp = 0;
5348 		for_each_online_cpu(cpu)
5349 			free_pcp += per_cpu_ptr(zone->pageset, cpu)->pcp.count;
5350 
5351 		show_node(zone);
5352 		printk(KERN_CONT
5353 			"%s"
5354 			" free:%lukB"
5355 			" min:%lukB"
5356 			" low:%lukB"
5357 			" high:%lukB"
5358 			" active_anon:%lukB"
5359 			" inactive_anon:%lukB"
5360 			" active_file:%lukB"
5361 			" inactive_file:%lukB"
5362 			" unevictable:%lukB"
5363 			" writepending:%lukB"
5364 			" present:%lukB"
5365 			" managed:%lukB"
5366 			" mlocked:%lukB"
5367 			" kernel_stack:%lukB"
5368 #ifdef CONFIG_SHADOW_CALL_STACK
5369 			" shadow_call_stack:%lukB"
5370 #endif
5371 			" pagetables:%lukB"
5372 			" bounce:%lukB"
5373 			" free_pcp:%lukB"
5374 			" local_pcp:%ukB"
5375 			" free_cma:%lukB"
5376 			"\n",
5377 			zone->name,
5378 			K(zone_page_state(zone, NR_FREE_PAGES)),
5379 			K(min_wmark_pages(zone)),
5380 			K(low_wmark_pages(zone)),
5381 			K(high_wmark_pages(zone)),
5382 			K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON)),
5383 			K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON)),
5384 			K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE)),
5385 			K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE)),
5386 			K(zone_page_state(zone, NR_ZONE_UNEVICTABLE)),
5387 			K(zone_page_state(zone, NR_ZONE_WRITE_PENDING)),
5388 			K(zone->present_pages),
5389 			K(zone_managed_pages(zone)),
5390 			K(zone_page_state(zone, NR_MLOCK)),
5391 			zone_page_state(zone, NR_KERNEL_STACK_KB),
5392 #ifdef CONFIG_SHADOW_CALL_STACK
5393 			zone_page_state(zone, NR_KERNEL_SCS_BYTES) / 1024,
5394 #endif
5395 			K(zone_page_state(zone, NR_PAGETABLE)),
5396 			K(zone_page_state(zone, NR_BOUNCE)),
5397 			K(free_pcp),
5398 			K(this_cpu_read(zone->pageset->pcp.count)),
5399 			K(zone_page_state(zone, NR_FREE_CMA_PAGES)));
5400 		printk("lowmem_reserve[]:");
5401 		for (i = 0; i < MAX_NR_ZONES; i++)
5402 			printk(KERN_CONT " %ld", zone->lowmem_reserve[i]);
5403 		printk(KERN_CONT "\n");
5404 	}
5405 
5406 	for_each_populated_zone(zone) {
5407 		unsigned int order;
5408 		unsigned long nr[MAX_ORDER], flags, total = 0;
5409 		unsigned char types[MAX_ORDER];
5410 
5411 		if (show_mem_node_skip(filter, zone_to_nid(zone), nodemask))
5412 			continue;
5413 		show_node(zone);
5414 		printk(KERN_CONT "%s: ", zone->name);
5415 
5416 		spin_lock_irqsave(&zone->lock, flags);
5417 		for (order = 0; order < MAX_ORDER; order++) {
5418 			struct free_area *area = &zone->free_area[order];
5419 			int type;
5420 
5421 			nr[order] = area->nr_free;
5422 			total += nr[order] << order;
5423 
5424 			types[order] = 0;
5425 			for (type = 0; type < MIGRATE_TYPES; type++) {
5426 				if (!free_area_empty(area, type))
5427 					types[order] |= 1 << type;
5428 			}
5429 		}
5430 		spin_unlock_irqrestore(&zone->lock, flags);
5431 		for (order = 0; order < MAX_ORDER; order++) {
5432 			printk(KERN_CONT "%lu*%lukB ",
5433 			       nr[order], K(1UL) << order);
5434 			if (nr[order])
5435 				show_migration_types(types[order]);
5436 		}
5437 		printk(KERN_CONT "= %lukB\n", K(total));
5438 	}
5439 
5440 	hugetlb_show_meminfo();
5441 
5442 	printk("%ld total pagecache pages\n", global_node_page_state(NR_FILE_PAGES));
5443 
5444 	show_swap_cache_info();
5445 }
5446 
zoneref_set_zone(struct zone * zone,struct zoneref * zoneref)5447 static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref)
5448 {
5449 	zoneref->zone = zone;
5450 	zoneref->zone_idx = zone_idx(zone);
5451 }
5452 
5453 /*
5454  * Builds allocation fallback zone lists.
5455  *
5456  * Add all populated zones of a node to the zonelist.
5457  */
build_zonerefs_node(pg_data_t * pgdat,struct zoneref * zonerefs)5458 static int build_zonerefs_node(pg_data_t *pgdat, struct zoneref *zonerefs)
5459 {
5460 	struct zone *zone;
5461 	enum zone_type zone_type = MAX_NR_ZONES;
5462 	int nr_zones = 0;
5463 
5464 	do {
5465 		zone_type--;
5466 		zone = pgdat->node_zones + zone_type;
5467 		if (managed_zone(zone)) {
5468 			zoneref_set_zone(zone, &zonerefs[nr_zones++]);
5469 			check_highest_zone(zone_type);
5470 		}
5471 	} while (zone_type);
5472 
5473 	return nr_zones;
5474 }
5475 
5476 #ifdef CONFIG_NUMA
5477 
__parse_numa_zonelist_order(char * s)5478 static int __parse_numa_zonelist_order(char *s)
5479 {
5480 	/*
5481 	 * We used to support different zonlists modes but they turned
5482 	 * out to be just not useful. Let's keep the warning in place
5483 	 * if somebody still use the cmd line parameter so that we do
5484 	 * not fail it silently
5485 	 */
5486 	if (!(*s == 'd' || *s == 'D' || *s == 'n' || *s == 'N')) {
5487 		pr_warn("Ignoring unsupported numa_zonelist_order value:  %s\n", s);
5488 		return -EINVAL;
5489 	}
5490 	return 0;
5491 }
5492 
setup_numa_zonelist_order(char * s)5493 static __init int setup_numa_zonelist_order(char *s)
5494 {
5495 	if (!s)
5496 		return 0;
5497 
5498 	return __parse_numa_zonelist_order(s);
5499 }
5500 early_param("numa_zonelist_order", setup_numa_zonelist_order);
5501 
5502 char numa_zonelist_order[] = "Node";
5503 
5504 /*
5505  * sysctl handler for numa_zonelist_order
5506  */
numa_zonelist_order_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)5507 int numa_zonelist_order_handler(struct ctl_table *table, int write,
5508 		void __user *buffer, size_t *length,
5509 		loff_t *ppos)
5510 {
5511 	char *str;
5512 	int ret;
5513 
5514 	if (!write)
5515 		return proc_dostring(table, write, buffer, length, ppos);
5516 	str = memdup_user_nul(buffer, 16);
5517 	if (IS_ERR(str))
5518 		return PTR_ERR(str);
5519 
5520 	ret = __parse_numa_zonelist_order(str);
5521 	kfree(str);
5522 	return ret;
5523 }
5524 
5525 
5526 #define MAX_NODE_LOAD (nr_online_nodes)
5527 static int node_load[MAX_NUMNODES];
5528 
5529 /**
5530  * find_next_best_node - find the next node that should appear in a given node's fallback list
5531  * @node: node whose fallback list we're appending
5532  * @used_node_mask: nodemask_t of already used nodes
5533  *
5534  * We use a number of factors to determine which is the next node that should
5535  * appear on a given node's fallback list.  The node should not have appeared
5536  * already in @node's fallback list, and it should be the next closest node
5537  * according to the distance array (which contains arbitrary distance values
5538  * from each node to each node in the system), and should also prefer nodes
5539  * with no CPUs, since presumably they'll have very little allocation pressure
5540  * on them otherwise.
5541  *
5542  * Return: node id of the found node or %NUMA_NO_NODE if no node is found.
5543  */
find_next_best_node(int node,nodemask_t * used_node_mask)5544 static int find_next_best_node(int node, nodemask_t *used_node_mask)
5545 {
5546 	int n, val;
5547 	int min_val = INT_MAX;
5548 	int best_node = NUMA_NO_NODE;
5549 	const struct cpumask *tmp = cpumask_of_node(0);
5550 
5551 	/* Use the local node if we haven't already */
5552 	if (!node_isset(node, *used_node_mask)) {
5553 		node_set(node, *used_node_mask);
5554 		return node;
5555 	}
5556 
5557 	for_each_node_state(n, N_MEMORY) {
5558 
5559 		/* Don't want a node to appear more than once */
5560 		if (node_isset(n, *used_node_mask))
5561 			continue;
5562 
5563 		/* Use the distance array to find the distance */
5564 		val = node_distance(node, n);
5565 
5566 		/* Penalize nodes under us ("prefer the next node") */
5567 		val += (n < node);
5568 
5569 		/* Give preference to headless and unused nodes */
5570 		tmp = cpumask_of_node(n);
5571 		if (!cpumask_empty(tmp))
5572 			val += PENALTY_FOR_NODE_WITH_CPUS;
5573 
5574 		/* Slight preference for less loaded node */
5575 		val *= (MAX_NODE_LOAD*MAX_NUMNODES);
5576 		val += node_load[n];
5577 
5578 		if (val < min_val) {
5579 			min_val = val;
5580 			best_node = n;
5581 		}
5582 	}
5583 
5584 	if (best_node >= 0)
5585 		node_set(best_node, *used_node_mask);
5586 
5587 	return best_node;
5588 }
5589 
5590 
5591 /*
5592  * Build zonelists ordered by node and zones within node.
5593  * This results in maximum locality--normal zone overflows into local
5594  * DMA zone, if any--but risks exhausting DMA zone.
5595  */
build_zonelists_in_node_order(pg_data_t * pgdat,int * node_order,unsigned nr_nodes)5596 static void build_zonelists_in_node_order(pg_data_t *pgdat, int *node_order,
5597 		unsigned nr_nodes)
5598 {
5599 	struct zoneref *zonerefs;
5600 	int i;
5601 
5602 	zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5603 
5604 	for (i = 0; i < nr_nodes; i++) {
5605 		int nr_zones;
5606 
5607 		pg_data_t *node = NODE_DATA(node_order[i]);
5608 
5609 		nr_zones = build_zonerefs_node(node, zonerefs);
5610 		zonerefs += nr_zones;
5611 	}
5612 	zonerefs->zone = NULL;
5613 	zonerefs->zone_idx = 0;
5614 }
5615 
5616 /*
5617  * Build gfp_thisnode zonelists
5618  */
build_thisnode_zonelists(pg_data_t * pgdat)5619 static void build_thisnode_zonelists(pg_data_t *pgdat)
5620 {
5621 	struct zoneref *zonerefs;
5622 	int nr_zones;
5623 
5624 	zonerefs = pgdat->node_zonelists[ZONELIST_NOFALLBACK]._zonerefs;
5625 	nr_zones = build_zonerefs_node(pgdat, zonerefs);
5626 	zonerefs += nr_zones;
5627 	zonerefs->zone = NULL;
5628 	zonerefs->zone_idx = 0;
5629 }
5630 
5631 /*
5632  * Build zonelists ordered by zone and nodes within zones.
5633  * This results in conserving DMA zone[s] until all Normal memory is
5634  * exhausted, but results in overflowing to remote node while memory
5635  * may still exist in local DMA zone.
5636  */
5637 
build_zonelists(pg_data_t * pgdat)5638 static void build_zonelists(pg_data_t *pgdat)
5639 {
5640 	static int node_order[MAX_NUMNODES];
5641 	int node, load, nr_nodes = 0;
5642 	nodemask_t used_mask;
5643 	int local_node, prev_node;
5644 
5645 	/* NUMA-aware ordering of nodes */
5646 	local_node = pgdat->node_id;
5647 	load = nr_online_nodes;
5648 	prev_node = local_node;
5649 	nodes_clear(used_mask);
5650 
5651 	memset(node_order, 0, sizeof(node_order));
5652 	while ((node = find_next_best_node(local_node, &used_mask)) >= 0) {
5653 		/*
5654 		 * We don't want to pressure a particular node.
5655 		 * So adding penalty to the first node in same
5656 		 * distance group to make it round-robin.
5657 		 */
5658 		if (node_distance(local_node, node) !=
5659 		    node_distance(local_node, prev_node))
5660 			node_load[node] = load;
5661 
5662 		node_order[nr_nodes++] = node;
5663 		prev_node = node;
5664 		load--;
5665 	}
5666 
5667 	build_zonelists_in_node_order(pgdat, node_order, nr_nodes);
5668 	build_thisnode_zonelists(pgdat);
5669 }
5670 
5671 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5672 /*
5673  * Return node id of node used for "local" allocations.
5674  * I.e., first node id of first zone in arg node's generic zonelist.
5675  * Used for initializing percpu 'numa_mem', which is used primarily
5676  * for kernel allocations, so use GFP_KERNEL flags to locate zonelist.
5677  */
local_memory_node(int node)5678 int local_memory_node(int node)
5679 {
5680 	struct zoneref *z;
5681 
5682 	z = first_zones_zonelist(node_zonelist(node, GFP_KERNEL),
5683 				   gfp_zone(GFP_KERNEL),
5684 				   NULL);
5685 	return zone_to_nid(z->zone);
5686 }
5687 #endif
5688 
5689 static void setup_min_unmapped_ratio(void);
5690 static void setup_min_slab_ratio(void);
5691 #else	/* CONFIG_NUMA */
5692 
build_zonelists(pg_data_t * pgdat)5693 static void build_zonelists(pg_data_t *pgdat)
5694 {
5695 	int node, local_node;
5696 	struct zoneref *zonerefs;
5697 	int nr_zones;
5698 
5699 	local_node = pgdat->node_id;
5700 
5701 	zonerefs = pgdat->node_zonelists[ZONELIST_FALLBACK]._zonerefs;
5702 	nr_zones = build_zonerefs_node(pgdat, zonerefs);
5703 	zonerefs += nr_zones;
5704 
5705 	/*
5706 	 * Now we build the zonelist so that it contains the zones
5707 	 * of all the other nodes.
5708 	 * We don't want to pressure a particular node, so when
5709 	 * building the zones for node N, we make sure that the
5710 	 * zones coming right after the local ones are those from
5711 	 * node N+1 (modulo N)
5712 	 */
5713 	for (node = local_node + 1; node < MAX_NUMNODES; node++) {
5714 		if (!node_online(node))
5715 			continue;
5716 		nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
5717 		zonerefs += nr_zones;
5718 	}
5719 	for (node = 0; node < local_node; node++) {
5720 		if (!node_online(node))
5721 			continue;
5722 		nr_zones = build_zonerefs_node(NODE_DATA(node), zonerefs);
5723 		zonerefs += nr_zones;
5724 	}
5725 
5726 	zonerefs->zone = NULL;
5727 	zonerefs->zone_idx = 0;
5728 }
5729 
5730 #endif	/* CONFIG_NUMA */
5731 
5732 /*
5733  * Boot pageset table. One per cpu which is going to be used for all
5734  * zones and all nodes. The parameters will be set in such a way
5735  * that an item put on a list will immediately be handed over to
5736  * the buddy list. This is safe since pageset manipulation is done
5737  * with interrupts disabled.
5738  *
5739  * The boot_pagesets must be kept even after bootup is complete for
5740  * unused processors and/or zones. They do play a role for bootstrapping
5741  * hotplugged processors.
5742  *
5743  * zoneinfo_show() and maybe other functions do
5744  * not check if the processor is online before following the pageset pointer.
5745  * Other parts of the kernel may not check if the zone is available.
5746  */
5747 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch);
5748 static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset);
5749 static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
5750 
__build_all_zonelists(void * data)5751 static void __build_all_zonelists(void *data)
5752 {
5753 	int nid;
5754 	int __maybe_unused cpu;
5755 	pg_data_t *self = data;
5756 	static DEFINE_SPINLOCK(lock);
5757 
5758 	spin_lock(&lock);
5759 
5760 #ifdef CONFIG_NUMA
5761 	memset(node_load, 0, sizeof(node_load));
5762 #endif
5763 
5764 	/*
5765 	 * This node is hotadded and no memory is yet present.   So just
5766 	 * building zonelists is fine - no need to touch other nodes.
5767 	 */
5768 	if (self && !node_online(self->node_id)) {
5769 		build_zonelists(self);
5770 	} else {
5771 		for_each_online_node(nid) {
5772 			pg_data_t *pgdat = NODE_DATA(nid);
5773 
5774 			build_zonelists(pgdat);
5775 		}
5776 
5777 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
5778 		/*
5779 		 * We now know the "local memory node" for each node--
5780 		 * i.e., the node of the first zone in the generic zonelist.
5781 		 * Set up numa_mem percpu variable for on-line cpus.  During
5782 		 * boot, only the boot cpu should be on-line;  we'll init the
5783 		 * secondary cpus' numa_mem as they come on-line.  During
5784 		 * node/memory hotplug, we'll fixup all on-line cpus.
5785 		 */
5786 		for_each_online_cpu(cpu)
5787 			set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu)));
5788 #endif
5789 	}
5790 
5791 	spin_unlock(&lock);
5792 }
5793 
5794 static noinline void __init
build_all_zonelists_init(void)5795 build_all_zonelists_init(void)
5796 {
5797 	int cpu;
5798 
5799 	__build_all_zonelists(NULL);
5800 
5801 	/*
5802 	 * Initialize the boot_pagesets that are going to be used
5803 	 * for bootstrapping processors. The real pagesets for
5804 	 * each zone will be allocated later when the per cpu
5805 	 * allocator is available.
5806 	 *
5807 	 * boot_pagesets are used also for bootstrapping offline
5808 	 * cpus if the system is already booted because the pagesets
5809 	 * are needed to initialize allocators on a specific cpu too.
5810 	 * F.e. the percpu allocator needs the page allocator which
5811 	 * needs the percpu allocator in order to allocate its pagesets
5812 	 * (a chicken-egg dilemma).
5813 	 */
5814 	for_each_possible_cpu(cpu)
5815 		setup_pageset(&per_cpu(boot_pageset, cpu), 0);
5816 
5817 	mminit_verify_zonelist();
5818 	cpuset_init_current_mems_allowed();
5819 }
5820 
5821 /*
5822  * unless system_state == SYSTEM_BOOTING.
5823  *
5824  * __ref due to call of __init annotated helper build_all_zonelists_init
5825  * [protected by SYSTEM_BOOTING].
5826  */
build_all_zonelists(pg_data_t * pgdat)5827 void __ref build_all_zonelists(pg_data_t *pgdat)
5828 {
5829 	if (system_state == SYSTEM_BOOTING) {
5830 		build_all_zonelists_init();
5831 	} else {
5832 		__build_all_zonelists(pgdat);
5833 		/* cpuset refresh routine should be here */
5834 	}
5835 	vm_total_pages = nr_free_pagecache_pages();
5836 	/*
5837 	 * Disable grouping by mobility if the number of pages in the
5838 	 * system is too low to allow the mechanism to work. It would be
5839 	 * more accurate, but expensive to check per-zone. This check is
5840 	 * made on memory-hotadd so a system can start with mobility
5841 	 * disabled and enable it later
5842 	 */
5843 	if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES))
5844 		page_group_by_mobility_disabled = 1;
5845 	else
5846 		page_group_by_mobility_disabled = 0;
5847 
5848 	pr_info("Built %u zonelists, mobility grouping %s.  Total pages: %ld\n",
5849 		nr_online_nodes,
5850 		page_group_by_mobility_disabled ? "off" : "on",
5851 		vm_total_pages);
5852 #ifdef CONFIG_NUMA
5853 	pr_info("Policy zone: %s\n", zone_names[policy_zone]);
5854 #endif
5855 }
5856 
5857 /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
5858 static bool __meminit
overlap_memmap_init(unsigned long zone,unsigned long * pfn)5859 overlap_memmap_init(unsigned long zone, unsigned long *pfn)
5860 {
5861 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
5862 	static struct memblock_region *r;
5863 
5864 	if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
5865 		if (!r || *pfn >= memblock_region_memory_end_pfn(r)) {
5866 			for_each_memblock(memory, r) {
5867 				if (*pfn < memblock_region_memory_end_pfn(r))
5868 					break;
5869 			}
5870 		}
5871 		if (*pfn >= memblock_region_memory_base_pfn(r) &&
5872 		    memblock_is_mirror(r)) {
5873 			*pfn = memblock_region_memory_end_pfn(r);
5874 			return true;
5875 		}
5876 	}
5877 #endif
5878 	return false;
5879 }
5880 
5881 /*
5882  * Initially all pages are reserved - free ones are freed
5883  * up by memblock_free_all() once the early boot process is
5884  * done. Non-atomic initialization, single-pass.
5885  */
memmap_init_zone(unsigned long size,int nid,unsigned long zone,unsigned long start_pfn,enum memmap_context context,struct vmem_altmap * altmap)5886 void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone,
5887 		unsigned long start_pfn, enum memmap_context context,
5888 		struct vmem_altmap *altmap)
5889 {
5890 	unsigned long pfn, end_pfn = start_pfn + size;
5891 	struct page *page;
5892 
5893 	if (highest_memmap_pfn < end_pfn - 1)
5894 		highest_memmap_pfn = end_pfn - 1;
5895 
5896 #ifdef CONFIG_ZONE_DEVICE
5897 	/*
5898 	 * Honor reservation requested by the driver for this ZONE_DEVICE
5899 	 * memory. We limit the total number of pages to initialize to just
5900 	 * those that might contain the memory mapping. We will defer the
5901 	 * ZONE_DEVICE page initialization until after we have released
5902 	 * the hotplug lock.
5903 	 */
5904 	if (zone == ZONE_DEVICE) {
5905 		if (!altmap)
5906 			return;
5907 
5908 		if (start_pfn == altmap->base_pfn)
5909 			start_pfn += altmap->reserve;
5910 		end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
5911 	}
5912 #endif
5913 
5914 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
5915 		/*
5916 		 * There can be holes in boot-time mem_map[]s handed to this
5917 		 * function.  They do not exist on hotplugged memory.
5918 		 */
5919 		if (context == MEMMAP_EARLY) {
5920 			if (!early_pfn_valid(pfn))
5921 				continue;
5922 			if (!early_pfn_in_nid(pfn, nid))
5923 				continue;
5924 			if (overlap_memmap_init(zone, &pfn))
5925 				continue;
5926 			if (defer_init(nid, pfn, end_pfn))
5927 				break;
5928 		}
5929 
5930 		page = pfn_to_page(pfn);
5931 		__init_single_page(page, pfn, zone, nid);
5932 		if (context == MEMMAP_HOTPLUG)
5933 			__SetPageReserved(page);
5934 
5935 		/*
5936 		 * Mark the block movable so that blocks are reserved for
5937 		 * movable at startup. This will force kernel allocations
5938 		 * to reserve their blocks rather than leaking throughout
5939 		 * the address space during boot when many long-lived
5940 		 * kernel allocations are made.
5941 		 *
5942 		 * bitmap is created for zone's valid pfn range. but memmap
5943 		 * can be created for invalid pages (for alignment)
5944 		 * check here not to call set_pageblock_migratetype() against
5945 		 * pfn out of zone.
5946 		 */
5947 		if (!(pfn & (pageblock_nr_pages - 1))) {
5948 			set_pageblock_migratetype(page, MIGRATE_MOVABLE);
5949 			cond_resched();
5950 		}
5951 	}
5952 }
5953 
5954 #ifdef CONFIG_ZONE_DEVICE
memmap_init_zone_device(struct zone * zone,unsigned long start_pfn,unsigned long size,struct dev_pagemap * pgmap)5955 void __ref memmap_init_zone_device(struct zone *zone,
5956 				   unsigned long start_pfn,
5957 				   unsigned long size,
5958 				   struct dev_pagemap *pgmap)
5959 {
5960 	unsigned long pfn, end_pfn = start_pfn + size;
5961 	struct pglist_data *pgdat = zone->zone_pgdat;
5962 	struct vmem_altmap *altmap = pgmap_altmap(pgmap);
5963 	unsigned long zone_idx = zone_idx(zone);
5964 	unsigned long start = jiffies;
5965 	int nid = pgdat->node_id;
5966 
5967 	if (WARN_ON_ONCE(!pgmap || zone_idx(zone) != ZONE_DEVICE))
5968 		return;
5969 
5970 	/*
5971 	 * The call to memmap_init_zone should have already taken care
5972 	 * of the pages reserved for the memmap, so we can just jump to
5973 	 * the end of that region and start processing the device pages.
5974 	 */
5975 	if (altmap) {
5976 		start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
5977 		size = end_pfn - start_pfn;
5978 	}
5979 
5980 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
5981 		struct page *page = pfn_to_page(pfn);
5982 
5983 		__init_single_page(page, pfn, zone_idx, nid);
5984 
5985 		/*
5986 		 * Mark page reserved as it will need to wait for onlining
5987 		 * phase for it to be fully associated with a zone.
5988 		 *
5989 		 * We can use the non-atomic __set_bit operation for setting
5990 		 * the flag as we are still initializing the pages.
5991 		 */
5992 		__SetPageReserved(page);
5993 
5994 		/*
5995 		 * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer
5996 		 * and zone_device_data.  It is a bug if a ZONE_DEVICE page is
5997 		 * ever freed or placed on a driver-private list.
5998 		 */
5999 		page->pgmap = pgmap;
6000 		page->zone_device_data = NULL;
6001 
6002 		/*
6003 		 * Mark the block movable so that blocks are reserved for
6004 		 * movable at startup. This will force kernel allocations
6005 		 * to reserve their blocks rather than leaking throughout
6006 		 * the address space during boot when many long-lived
6007 		 * kernel allocations are made.
6008 		 *
6009 		 * bitmap is created for zone's valid pfn range. but memmap
6010 		 * can be created for invalid pages (for alignment)
6011 		 * check here not to call set_pageblock_migratetype() against
6012 		 * pfn out of zone.
6013 		 *
6014 		 * Please note that MEMMAP_HOTPLUG path doesn't clear memmap
6015 		 * because this is done early in section_activate()
6016 		 */
6017 		if (!(pfn & (pageblock_nr_pages - 1))) {
6018 			set_pageblock_migratetype(page, MIGRATE_MOVABLE);
6019 			cond_resched();
6020 		}
6021 	}
6022 
6023 	pr_info("%s initialised %lu pages in %ums\n", __func__,
6024 		size, jiffies_to_msecs(jiffies - start));
6025 }
6026 
6027 #endif
zone_init_free_lists(struct zone * zone)6028 static void __meminit zone_init_free_lists(struct zone *zone)
6029 {
6030 	unsigned int order, t;
6031 	for_each_migratetype_order(order, t) {
6032 		INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
6033 		zone->free_area[order].nr_free = 0;
6034 	}
6035 }
6036 
memmap_init(unsigned long size,int nid,unsigned long zone,unsigned long start_pfn)6037 void __meminit __weak memmap_init(unsigned long size, int nid,
6038 				  unsigned long zone, unsigned long start_pfn)
6039 {
6040 	memmap_init_zone(size, nid, zone, start_pfn, MEMMAP_EARLY, NULL);
6041 }
6042 
zone_batchsize(struct zone * zone)6043 static int zone_batchsize(struct zone *zone)
6044 {
6045 #ifdef CONFIG_MMU
6046 	int batch;
6047 
6048 	/*
6049 	 * The per-cpu-pages pools are set to around 1000th of the
6050 	 * size of the zone.
6051 	 */
6052 	batch = zone_managed_pages(zone) / 1024;
6053 	/* But no more than a meg. */
6054 	if (batch * PAGE_SIZE > 1024 * 1024)
6055 		batch = (1024 * 1024) / PAGE_SIZE;
6056 	batch /= 4;		/* We effectively *= 4 below */
6057 	if (batch < 1)
6058 		batch = 1;
6059 
6060 	/*
6061 	 * Clamp the batch to a 2^n - 1 value. Having a power
6062 	 * of 2 value was found to be more likely to have
6063 	 * suboptimal cache aliasing properties in some cases.
6064 	 *
6065 	 * For example if 2 tasks are alternately allocating
6066 	 * batches of pages, one task can end up with a lot
6067 	 * of pages of one half of the possible page colors
6068 	 * and the other with pages of the other colors.
6069 	 */
6070 	batch = rounddown_pow_of_two(batch + batch/2) - 1;
6071 
6072 	return batch;
6073 
6074 #else
6075 	/* The deferral and batching of frees should be suppressed under NOMMU
6076 	 * conditions.
6077 	 *
6078 	 * The problem is that NOMMU needs to be able to allocate large chunks
6079 	 * of contiguous memory as there's no hardware page translation to
6080 	 * assemble apparent contiguous memory from discontiguous pages.
6081 	 *
6082 	 * Queueing large contiguous runs of pages for batching, however,
6083 	 * causes the pages to actually be freed in smaller chunks.  As there
6084 	 * can be a significant delay between the individual batches being
6085 	 * recycled, this leads to the once large chunks of space being
6086 	 * fragmented and becoming unavailable for high-order allocations.
6087 	 */
6088 	return 0;
6089 #endif
6090 }
6091 
6092 /*
6093  * pcp->high and pcp->batch values are related and dependent on one another:
6094  * ->batch must never be higher then ->high.
6095  * The following function updates them in a safe manner without read side
6096  * locking.
6097  *
6098  * Any new users of pcp->batch and pcp->high should ensure they can cope with
6099  * those fields changing asynchronously (acording the the above rule).
6100  *
6101  * mutex_is_locked(&pcp_batch_high_lock) required when calling this function
6102  * outside of boot time (or some other assurance that no concurrent updaters
6103  * exist).
6104  */
pageset_update(struct per_cpu_pages * pcp,unsigned long high,unsigned long batch)6105 static void pageset_update(struct per_cpu_pages *pcp, unsigned long high,
6106 		unsigned long batch)
6107 {
6108        /* start with a fail safe value for batch */
6109 	pcp->batch = 1;
6110 	smp_wmb();
6111 
6112        /* Update high, then batch, in order */
6113 	pcp->high = high;
6114 	smp_wmb();
6115 
6116 	pcp->batch = batch;
6117 }
6118 
6119 /* a companion to pageset_set_high() */
pageset_set_batch(struct per_cpu_pageset * p,unsigned long batch)6120 static void pageset_set_batch(struct per_cpu_pageset *p, unsigned long batch)
6121 {
6122 	pageset_update(&p->pcp, 6 * batch, max(1UL, 1 * batch));
6123 }
6124 
pageset_init(struct per_cpu_pageset * p)6125 static void pageset_init(struct per_cpu_pageset *p)
6126 {
6127 	struct per_cpu_pages *pcp;
6128 	int migratetype;
6129 
6130 	memset(p, 0, sizeof(*p));
6131 
6132 	pcp = &p->pcp;
6133 	for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++)
6134 		INIT_LIST_HEAD(&pcp->lists[migratetype]);
6135 }
6136 
setup_pageset(struct per_cpu_pageset * p,unsigned long batch)6137 static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch)
6138 {
6139 	pageset_init(p);
6140 	pageset_set_batch(p, batch);
6141 }
6142 
6143 /*
6144  * pageset_set_high() sets the high water mark for hot per_cpu_pagelist
6145  * to the value high for the pageset p.
6146  */
pageset_set_high(struct per_cpu_pageset * p,unsigned long high)6147 static void pageset_set_high(struct per_cpu_pageset *p,
6148 				unsigned long high)
6149 {
6150 	unsigned long batch = max(1UL, high / 4);
6151 	if ((high / 4) > (PAGE_SHIFT * 8))
6152 		batch = PAGE_SHIFT * 8;
6153 
6154 	pageset_update(&p->pcp, high, batch);
6155 }
6156 
pageset_set_high_and_batch(struct zone * zone,struct per_cpu_pageset * pcp)6157 static void pageset_set_high_and_batch(struct zone *zone,
6158 				       struct per_cpu_pageset *pcp)
6159 {
6160 	if (percpu_pagelist_fraction)
6161 		pageset_set_high(pcp,
6162 			(zone_managed_pages(zone) /
6163 				percpu_pagelist_fraction));
6164 	else
6165 		pageset_set_batch(pcp, zone_batchsize(zone));
6166 }
6167 
zone_pageset_init(struct zone * zone,int cpu)6168 static void __meminit zone_pageset_init(struct zone *zone, int cpu)
6169 {
6170 	struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu);
6171 
6172 	pageset_init(pcp);
6173 	pageset_set_high_and_batch(zone, pcp);
6174 }
6175 
setup_zone_pageset(struct zone * zone)6176 void __meminit setup_zone_pageset(struct zone *zone)
6177 {
6178 	int cpu;
6179 	zone->pageset = alloc_percpu(struct per_cpu_pageset);
6180 	for_each_possible_cpu(cpu)
6181 		zone_pageset_init(zone, cpu);
6182 }
6183 
6184 /*
6185  * Allocate per cpu pagesets and initialize them.
6186  * Before this call only boot pagesets were available.
6187  */
setup_per_cpu_pageset(void)6188 void __init setup_per_cpu_pageset(void)
6189 {
6190 	struct pglist_data *pgdat;
6191 	struct zone *zone;
6192 
6193 	for_each_populated_zone(zone)
6194 		setup_zone_pageset(zone);
6195 
6196 	for_each_online_pgdat(pgdat)
6197 		pgdat->per_cpu_nodestats =
6198 			alloc_percpu(struct per_cpu_nodestat);
6199 }
6200 
zone_pcp_init(struct zone * zone)6201 static __meminit void zone_pcp_init(struct zone *zone)
6202 {
6203 	/*
6204 	 * per cpu subsystem is not up at this point. The following code
6205 	 * relies on the ability of the linker to provide the
6206 	 * offset of a (static) per cpu variable into the per cpu area.
6207 	 */
6208 	zone->pageset = &boot_pageset;
6209 
6210 	if (populated_zone(zone))
6211 		printk(KERN_DEBUG "  %s zone: %lu pages, LIFO batch:%u\n",
6212 			zone->name, zone->present_pages,
6213 					 zone_batchsize(zone));
6214 }
6215 
init_currently_empty_zone(struct zone * zone,unsigned long zone_start_pfn,unsigned long size)6216 void __meminit init_currently_empty_zone(struct zone *zone,
6217 					unsigned long zone_start_pfn,
6218 					unsigned long size)
6219 {
6220 	struct pglist_data *pgdat = zone->zone_pgdat;
6221 	int zone_idx = zone_idx(zone) + 1;
6222 
6223 	if (zone_idx > pgdat->nr_zones)
6224 		pgdat->nr_zones = zone_idx;
6225 
6226 	zone->zone_start_pfn = zone_start_pfn;
6227 
6228 	mminit_dprintk(MMINIT_TRACE, "memmap_init",
6229 			"Initialising map node %d zone %lu pfns %lu -> %lu\n",
6230 			pgdat->node_id,
6231 			(unsigned long)zone_idx(zone),
6232 			zone_start_pfn, (zone_start_pfn + size));
6233 
6234 	zone_init_free_lists(zone);
6235 	zone->initialized = 1;
6236 }
6237 
6238 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6239 #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID
6240 
6241 /*
6242  * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
6243  */
__early_pfn_to_nid(unsigned long pfn,struct mminit_pfnnid_cache * state)6244 int __meminit __early_pfn_to_nid(unsigned long pfn,
6245 					struct mminit_pfnnid_cache *state)
6246 {
6247 	unsigned long start_pfn, end_pfn;
6248 	int nid;
6249 
6250 	if (state->last_start <= pfn && pfn < state->last_end)
6251 		return state->last_nid;
6252 
6253 	nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
6254 	if (nid != NUMA_NO_NODE) {
6255 		state->last_start = start_pfn;
6256 		state->last_end = end_pfn;
6257 		state->last_nid = nid;
6258 	}
6259 
6260 	return nid;
6261 }
6262 #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */
6263 
6264 /**
6265  * free_bootmem_with_active_regions - Call memblock_free_early_nid for each active range
6266  * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed.
6267  * @max_low_pfn: The highest PFN that will be passed to memblock_free_early_nid
6268  *
6269  * If an architecture guarantees that all ranges registered contain no holes
6270  * and may be freed, this this function may be used instead of calling
6271  * memblock_free_early_nid() manually.
6272  */
free_bootmem_with_active_regions(int nid,unsigned long max_low_pfn)6273 void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn)
6274 {
6275 	unsigned long start_pfn, end_pfn;
6276 	int i, this_nid;
6277 
6278 	for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid) {
6279 		start_pfn = min(start_pfn, max_low_pfn);
6280 		end_pfn = min(end_pfn, max_low_pfn);
6281 
6282 		if (start_pfn < end_pfn)
6283 			memblock_free_early_nid(PFN_PHYS(start_pfn),
6284 					(end_pfn - start_pfn) << PAGE_SHIFT,
6285 					this_nid);
6286 	}
6287 }
6288 
6289 /**
6290  * sparse_memory_present_with_active_regions - Call memory_present for each active range
6291  * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used.
6292  *
6293  * If an architecture guarantees that all ranges registered contain no holes and may
6294  * be freed, this function may be used instead of calling memory_present() manually.
6295  */
sparse_memory_present_with_active_regions(int nid)6296 void __init sparse_memory_present_with_active_regions(int nid)
6297 {
6298 	unsigned long start_pfn, end_pfn;
6299 	int i, this_nid;
6300 
6301 	for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, &this_nid)
6302 		memory_present(this_nid, start_pfn, end_pfn);
6303 }
6304 
6305 /**
6306  * get_pfn_range_for_nid - Return the start and end page frames for a node
6307  * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
6308  * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
6309  * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
6310  *
6311  * It returns the start and end page frame of a node based on information
6312  * provided by memblock_set_node(). If called for a node
6313  * with no available memory, a warning is printed and the start and end
6314  * PFNs will be 0.
6315  */
get_pfn_range_for_nid(unsigned int nid,unsigned long * start_pfn,unsigned long * end_pfn)6316 void __init get_pfn_range_for_nid(unsigned int nid,
6317 			unsigned long *start_pfn, unsigned long *end_pfn)
6318 {
6319 	unsigned long this_start_pfn, this_end_pfn;
6320 	int i;
6321 
6322 	*start_pfn = -1UL;
6323 	*end_pfn = 0;
6324 
6325 	for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
6326 		*start_pfn = min(*start_pfn, this_start_pfn);
6327 		*end_pfn = max(*end_pfn, this_end_pfn);
6328 	}
6329 
6330 	if (*start_pfn == -1UL)
6331 		*start_pfn = 0;
6332 }
6333 
6334 /*
6335  * This finds a zone that can be used for ZONE_MOVABLE pages. The
6336  * assumption is made that zones within a node are ordered in monotonic
6337  * increasing memory addresses so that the "highest" populated zone is used
6338  */
find_usable_zone_for_movable(void)6339 static void __init find_usable_zone_for_movable(void)
6340 {
6341 	int zone_index;
6342 	for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
6343 		if (zone_index == ZONE_MOVABLE)
6344 			continue;
6345 
6346 		if (arch_zone_highest_possible_pfn[zone_index] >
6347 				arch_zone_lowest_possible_pfn[zone_index])
6348 			break;
6349 	}
6350 
6351 	VM_BUG_ON(zone_index == -1);
6352 	movable_zone = zone_index;
6353 }
6354 
6355 /*
6356  * The zone ranges provided by the architecture do not include ZONE_MOVABLE
6357  * because it is sized independent of architecture. Unlike the other zones,
6358  * the starting point for ZONE_MOVABLE is not fixed. It may be different
6359  * in each node depending on the size of each node and how evenly kernelcore
6360  * is distributed. This helper function adjusts the zone ranges
6361  * provided by the architecture for a given node by using the end of the
6362  * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
6363  * zones within a node are in order of monotonic increases memory addresses
6364  */
adjust_zone_range_for_zone_movable(int nid,unsigned long zone_type,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * zone_start_pfn,unsigned long * zone_end_pfn)6365 static void __init adjust_zone_range_for_zone_movable(int nid,
6366 					unsigned long zone_type,
6367 					unsigned long node_start_pfn,
6368 					unsigned long node_end_pfn,
6369 					unsigned long *zone_start_pfn,
6370 					unsigned long *zone_end_pfn)
6371 {
6372 	/* Only adjust if ZONE_MOVABLE is on this node */
6373 	if (zone_movable_pfn[nid]) {
6374 		/* Size ZONE_MOVABLE */
6375 		if (zone_type == ZONE_MOVABLE) {
6376 			*zone_start_pfn = zone_movable_pfn[nid];
6377 			*zone_end_pfn = min(node_end_pfn,
6378 				arch_zone_highest_possible_pfn[movable_zone]);
6379 
6380 		/* Adjust for ZONE_MOVABLE starting within this range */
6381 		} else if (!mirrored_kernelcore &&
6382 			*zone_start_pfn < zone_movable_pfn[nid] &&
6383 			*zone_end_pfn > zone_movable_pfn[nid]) {
6384 			*zone_end_pfn = zone_movable_pfn[nid];
6385 
6386 		/* Check if this whole range is within ZONE_MOVABLE */
6387 		} else if (*zone_start_pfn >= zone_movable_pfn[nid])
6388 			*zone_start_pfn = *zone_end_pfn;
6389 	}
6390 }
6391 
6392 /*
6393  * Return the number of pages a zone spans in a node, including holes
6394  * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
6395  */
zone_spanned_pages_in_node(int nid,unsigned long zone_type,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * zone_start_pfn,unsigned long * zone_end_pfn,unsigned long * ignored)6396 static unsigned long __init zone_spanned_pages_in_node(int nid,
6397 					unsigned long zone_type,
6398 					unsigned long node_start_pfn,
6399 					unsigned long node_end_pfn,
6400 					unsigned long *zone_start_pfn,
6401 					unsigned long *zone_end_pfn,
6402 					unsigned long *ignored)
6403 {
6404 	unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
6405 	unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
6406 	/* When hotadd a new node from cpu_up(), the node should be empty */
6407 	if (!node_start_pfn && !node_end_pfn)
6408 		return 0;
6409 
6410 	/* Get the start and end of the zone */
6411 	*zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
6412 	*zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
6413 	adjust_zone_range_for_zone_movable(nid, zone_type,
6414 				node_start_pfn, node_end_pfn,
6415 				zone_start_pfn, zone_end_pfn);
6416 
6417 	/* Check that this node has pages within the zone's required range */
6418 	if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
6419 		return 0;
6420 
6421 	/* Move the zone boundaries inside the node if necessary */
6422 	*zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
6423 	*zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
6424 
6425 	/* Return the spanned pages */
6426 	return *zone_end_pfn - *zone_start_pfn;
6427 }
6428 
6429 /*
6430  * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
6431  * then all holes in the requested range will be accounted for.
6432  */
__absent_pages_in_range(int nid,unsigned long range_start_pfn,unsigned long range_end_pfn)6433 unsigned long __init __absent_pages_in_range(int nid,
6434 				unsigned long range_start_pfn,
6435 				unsigned long range_end_pfn)
6436 {
6437 	unsigned long nr_absent = range_end_pfn - range_start_pfn;
6438 	unsigned long start_pfn, end_pfn;
6439 	int i;
6440 
6441 	for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
6442 		start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
6443 		end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
6444 		nr_absent -= end_pfn - start_pfn;
6445 	}
6446 	return nr_absent;
6447 }
6448 
6449 /**
6450  * absent_pages_in_range - Return number of page frames in holes within a range
6451  * @start_pfn: The start PFN to start searching for holes
6452  * @end_pfn: The end PFN to stop searching for holes
6453  *
6454  * Return: the number of pages frames in memory holes within a range.
6455  */
absent_pages_in_range(unsigned long start_pfn,unsigned long end_pfn)6456 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
6457 							unsigned long end_pfn)
6458 {
6459 	return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
6460 }
6461 
6462 /* Return the number of page frames in holes in a zone on a node */
zone_absent_pages_in_node(int nid,unsigned long zone_type,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * ignored)6463 static unsigned long __init zone_absent_pages_in_node(int nid,
6464 					unsigned long zone_type,
6465 					unsigned long node_start_pfn,
6466 					unsigned long node_end_pfn,
6467 					unsigned long *ignored)
6468 {
6469 	unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
6470 	unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
6471 	unsigned long zone_start_pfn, zone_end_pfn;
6472 	unsigned long nr_absent;
6473 
6474 	/* When hotadd a new node from cpu_up(), the node should be empty */
6475 	if (!node_start_pfn && !node_end_pfn)
6476 		return 0;
6477 
6478 	zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
6479 	zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
6480 
6481 	adjust_zone_range_for_zone_movable(nid, zone_type,
6482 			node_start_pfn, node_end_pfn,
6483 			&zone_start_pfn, &zone_end_pfn);
6484 	nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
6485 
6486 	/*
6487 	 * ZONE_MOVABLE handling.
6488 	 * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
6489 	 * and vice versa.
6490 	 */
6491 	if (mirrored_kernelcore && zone_movable_pfn[nid]) {
6492 		unsigned long start_pfn, end_pfn;
6493 		struct memblock_region *r;
6494 
6495 		for_each_memblock(memory, r) {
6496 			start_pfn = clamp(memblock_region_memory_base_pfn(r),
6497 					  zone_start_pfn, zone_end_pfn);
6498 			end_pfn = clamp(memblock_region_memory_end_pfn(r),
6499 					zone_start_pfn, zone_end_pfn);
6500 
6501 			if (zone_type == ZONE_MOVABLE &&
6502 			    memblock_is_mirror(r))
6503 				nr_absent += end_pfn - start_pfn;
6504 
6505 			if (zone_type == ZONE_NORMAL &&
6506 			    !memblock_is_mirror(r))
6507 				nr_absent += end_pfn - start_pfn;
6508 		}
6509 	}
6510 
6511 	return nr_absent;
6512 }
6513 
6514 #else /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
zone_spanned_pages_in_node(int nid,unsigned long zone_type,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * zone_start_pfn,unsigned long * zone_end_pfn,unsigned long * zones_size)6515 static inline unsigned long __init zone_spanned_pages_in_node(int nid,
6516 					unsigned long zone_type,
6517 					unsigned long node_start_pfn,
6518 					unsigned long node_end_pfn,
6519 					unsigned long *zone_start_pfn,
6520 					unsigned long *zone_end_pfn,
6521 					unsigned long *zones_size)
6522 {
6523 	unsigned int zone;
6524 
6525 	*zone_start_pfn = node_start_pfn;
6526 	for (zone = 0; zone < zone_type; zone++)
6527 		*zone_start_pfn += zones_size[zone];
6528 
6529 	*zone_end_pfn = *zone_start_pfn + zones_size[zone_type];
6530 
6531 	return zones_size[zone_type];
6532 }
6533 
zone_absent_pages_in_node(int nid,unsigned long zone_type,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * zholes_size)6534 static inline unsigned long __init zone_absent_pages_in_node(int nid,
6535 						unsigned long zone_type,
6536 						unsigned long node_start_pfn,
6537 						unsigned long node_end_pfn,
6538 						unsigned long *zholes_size)
6539 {
6540 	if (!zholes_size)
6541 		return 0;
6542 
6543 	return zholes_size[zone_type];
6544 }
6545 
6546 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6547 
calculate_node_totalpages(struct pglist_data * pgdat,unsigned long node_start_pfn,unsigned long node_end_pfn,unsigned long * zones_size,unsigned long * zholes_size)6548 static void __init calculate_node_totalpages(struct pglist_data *pgdat,
6549 						unsigned long node_start_pfn,
6550 						unsigned long node_end_pfn,
6551 						unsigned long *zones_size,
6552 						unsigned long *zholes_size)
6553 {
6554 	unsigned long realtotalpages = 0, totalpages = 0;
6555 	enum zone_type i;
6556 
6557 	for (i = 0; i < MAX_NR_ZONES; i++) {
6558 		struct zone *zone = pgdat->node_zones + i;
6559 		unsigned long zone_start_pfn, zone_end_pfn;
6560 		unsigned long size, real_size;
6561 
6562 		size = zone_spanned_pages_in_node(pgdat->node_id, i,
6563 						  node_start_pfn,
6564 						  node_end_pfn,
6565 						  &zone_start_pfn,
6566 						  &zone_end_pfn,
6567 						  zones_size);
6568 		real_size = size - zone_absent_pages_in_node(pgdat->node_id, i,
6569 						  node_start_pfn, node_end_pfn,
6570 						  zholes_size);
6571 		if (size)
6572 			zone->zone_start_pfn = zone_start_pfn;
6573 		else
6574 			zone->zone_start_pfn = 0;
6575 		zone->spanned_pages = size;
6576 		zone->present_pages = real_size;
6577 
6578 		totalpages += size;
6579 		realtotalpages += real_size;
6580 	}
6581 
6582 	pgdat->node_spanned_pages = totalpages;
6583 	pgdat->node_present_pages = realtotalpages;
6584 	printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id,
6585 							realtotalpages);
6586 }
6587 
6588 #ifndef CONFIG_SPARSEMEM
6589 /*
6590  * Calculate the size of the zone->blockflags rounded to an unsigned long
6591  * Start by making sure zonesize is a multiple of pageblock_order by rounding
6592  * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
6593  * round what is now in bits to nearest long in bits, then return it in
6594  * bytes.
6595  */
usemap_size(unsigned long zone_start_pfn,unsigned long zonesize)6596 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
6597 {
6598 	unsigned long usemapsize;
6599 
6600 	zonesize += zone_start_pfn & (pageblock_nr_pages-1);
6601 	usemapsize = roundup(zonesize, pageblock_nr_pages);
6602 	usemapsize = usemapsize >> pageblock_order;
6603 	usemapsize *= NR_PAGEBLOCK_BITS;
6604 	usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long));
6605 
6606 	return usemapsize / 8;
6607 }
6608 
setup_usemap(struct pglist_data * pgdat,struct zone * zone,unsigned long zone_start_pfn,unsigned long zonesize)6609 static void __ref setup_usemap(struct pglist_data *pgdat,
6610 				struct zone *zone,
6611 				unsigned long zone_start_pfn,
6612 				unsigned long zonesize)
6613 {
6614 	unsigned long usemapsize = usemap_size(zone_start_pfn, zonesize);
6615 	zone->pageblock_flags = NULL;
6616 	if (usemapsize) {
6617 		zone->pageblock_flags =
6618 			memblock_alloc_node(usemapsize, SMP_CACHE_BYTES,
6619 					    pgdat->node_id);
6620 		if (!zone->pageblock_flags)
6621 			panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n",
6622 			      usemapsize, zone->name, pgdat->node_id);
6623 	}
6624 }
6625 #else
setup_usemap(struct pglist_data * pgdat,struct zone * zone,unsigned long zone_start_pfn,unsigned long zonesize)6626 static inline void setup_usemap(struct pglist_data *pgdat, struct zone *zone,
6627 				unsigned long zone_start_pfn, unsigned long zonesize) {}
6628 #endif /* CONFIG_SPARSEMEM */
6629 
6630 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
6631 
6632 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
set_pageblock_order(void)6633 void __init set_pageblock_order(void)
6634 {
6635 	unsigned int order;
6636 
6637 	/* Check that pageblock_nr_pages has not already been setup */
6638 	if (pageblock_order)
6639 		return;
6640 
6641 	if (HPAGE_SHIFT > PAGE_SHIFT)
6642 		order = HUGETLB_PAGE_ORDER;
6643 	else
6644 		order = MAX_ORDER - 1;
6645 
6646 	/*
6647 	 * Assume the largest contiguous order of interest is a huge page.
6648 	 * This value may be variable depending on boot parameters on IA64 and
6649 	 * powerpc.
6650 	 */
6651 	pageblock_order = order;
6652 }
6653 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6654 
6655 /*
6656  * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
6657  * is unused as pageblock_order is set at compile-time. See
6658  * include/linux/pageblock-flags.h for the values of pageblock_order based on
6659  * the kernel config
6660  */
set_pageblock_order(void)6661 void __init set_pageblock_order(void)
6662 {
6663 }
6664 
6665 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
6666 
calc_memmap_size(unsigned long spanned_pages,unsigned long present_pages)6667 static unsigned long __init calc_memmap_size(unsigned long spanned_pages,
6668 						unsigned long present_pages)
6669 {
6670 	unsigned long pages = spanned_pages;
6671 
6672 	/*
6673 	 * Provide a more accurate estimation if there are holes within
6674 	 * the zone and SPARSEMEM is in use. If there are holes within the
6675 	 * zone, each populated memory region may cost us one or two extra
6676 	 * memmap pages due to alignment because memmap pages for each
6677 	 * populated regions may not be naturally aligned on page boundary.
6678 	 * So the (present_pages >> 4) heuristic is a tradeoff for that.
6679 	 */
6680 	if (spanned_pages > present_pages + (present_pages >> 4) &&
6681 	    IS_ENABLED(CONFIG_SPARSEMEM))
6682 		pages = present_pages;
6683 
6684 	return PAGE_ALIGN(pages * sizeof(struct page)) >> PAGE_SHIFT;
6685 }
6686 
6687 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
pgdat_init_split_queue(struct pglist_data * pgdat)6688 static void pgdat_init_split_queue(struct pglist_data *pgdat)
6689 {
6690 	struct deferred_split *ds_queue = &pgdat->deferred_split_queue;
6691 
6692 	spin_lock_init(&ds_queue->split_queue_lock);
6693 	INIT_LIST_HEAD(&ds_queue->split_queue);
6694 	ds_queue->split_queue_len = 0;
6695 }
6696 #else
pgdat_init_split_queue(struct pglist_data * pgdat)6697 static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
6698 #endif
6699 
6700 #ifdef CONFIG_COMPACTION
pgdat_init_kcompactd(struct pglist_data * pgdat)6701 static void pgdat_init_kcompactd(struct pglist_data *pgdat)
6702 {
6703 	init_waitqueue_head(&pgdat->kcompactd_wait);
6704 }
6705 #else
pgdat_init_kcompactd(struct pglist_data * pgdat)6706 static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
6707 #endif
6708 
pgdat_init_internals(struct pglist_data * pgdat)6709 static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
6710 {
6711 	pgdat_resize_init(pgdat);
6712 
6713 	pgdat_init_split_queue(pgdat);
6714 	pgdat_init_kcompactd(pgdat);
6715 
6716 	init_waitqueue_head(&pgdat->kswapd_wait);
6717 	init_waitqueue_head(&pgdat->pfmemalloc_wait);
6718 
6719 	pgdat_page_ext_init(pgdat);
6720 	spin_lock_init(&pgdat->lru_lock);
6721 	lruvec_init(node_lruvec(pgdat));
6722 }
6723 
zone_init_internals(struct zone * zone,enum zone_type idx,int nid,unsigned long remaining_pages)6724 static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
6725 							unsigned long remaining_pages)
6726 {
6727 	atomic_long_set(&zone->managed_pages, remaining_pages);
6728 	zone_set_nid(zone, nid);
6729 	zone->name = zone_names[idx];
6730 	zone->zone_pgdat = NODE_DATA(nid);
6731 	spin_lock_init(&zone->lock);
6732 	zone_seqlock_init(zone);
6733 	zone_pcp_init(zone);
6734 }
6735 
6736 /*
6737  * Set up the zone data structures
6738  * - init pgdat internals
6739  * - init all zones belonging to this node
6740  *
6741  * NOTE: this function is only called during memory hotplug
6742  */
6743 #ifdef CONFIG_MEMORY_HOTPLUG
free_area_init_core_hotplug(int nid)6744 void __ref free_area_init_core_hotplug(int nid)
6745 {
6746 	enum zone_type z;
6747 	pg_data_t *pgdat = NODE_DATA(nid);
6748 
6749 	pgdat_init_internals(pgdat);
6750 	for (z = 0; z < MAX_NR_ZONES; z++)
6751 		zone_init_internals(&pgdat->node_zones[z], z, nid, 0);
6752 }
6753 #endif
6754 
6755 /*
6756  * Set up the zone data structures:
6757  *   - mark all pages reserved
6758  *   - mark all memory queues empty
6759  *   - clear the memory bitmaps
6760  *
6761  * NOTE: pgdat should get zeroed by caller.
6762  * NOTE: this function is only called during early init.
6763  */
free_area_init_core(struct pglist_data * pgdat)6764 static void __init free_area_init_core(struct pglist_data *pgdat)
6765 {
6766 	enum zone_type j;
6767 	int nid = pgdat->node_id;
6768 
6769 	pgdat_init_internals(pgdat);
6770 	pgdat->per_cpu_nodestats = &boot_nodestats;
6771 
6772 	for (j = 0; j < MAX_NR_ZONES; j++) {
6773 		struct zone *zone = pgdat->node_zones + j;
6774 		unsigned long size, freesize, memmap_pages;
6775 		unsigned long zone_start_pfn = zone->zone_start_pfn;
6776 
6777 		size = zone->spanned_pages;
6778 		freesize = zone->present_pages;
6779 
6780 		/*
6781 		 * Adjust freesize so that it accounts for how much memory
6782 		 * is used by this zone for memmap. This affects the watermark
6783 		 * and per-cpu initialisations
6784 		 */
6785 		memmap_pages = calc_memmap_size(size, freesize);
6786 		if (!is_highmem_idx(j)) {
6787 			if (freesize >= memmap_pages) {
6788 				freesize -= memmap_pages;
6789 				if (memmap_pages)
6790 					printk(KERN_DEBUG
6791 					       "  %s zone: %lu pages used for memmap\n",
6792 					       zone_names[j], memmap_pages);
6793 			} else
6794 				pr_warn("  %s zone: %lu pages exceeds freesize %lu\n",
6795 					zone_names[j], memmap_pages, freesize);
6796 		}
6797 
6798 		/* Account for reserved pages */
6799 		if (j == 0 && freesize > dma_reserve) {
6800 			freesize -= dma_reserve;
6801 			printk(KERN_DEBUG "  %s zone: %lu pages reserved\n",
6802 					zone_names[0], dma_reserve);
6803 		}
6804 
6805 		if (!is_highmem_idx(j))
6806 			nr_kernel_pages += freesize;
6807 		/* Charge for highmem memmap if there are enough kernel pages */
6808 		else if (nr_kernel_pages > memmap_pages * 2)
6809 			nr_kernel_pages -= memmap_pages;
6810 		nr_all_pages += freesize;
6811 
6812 		/*
6813 		 * Set an approximate value for lowmem here, it will be adjusted
6814 		 * when the bootmem allocator frees pages into the buddy system.
6815 		 * And all highmem pages will be managed by the buddy system.
6816 		 */
6817 		zone_init_internals(zone, j, nid, freesize);
6818 
6819 		if (!size)
6820 			continue;
6821 
6822 		set_pageblock_order();
6823 		setup_usemap(pgdat, zone, zone_start_pfn, size);
6824 		init_currently_empty_zone(zone, zone_start_pfn, size);
6825 		memmap_init(size, nid, j, zone_start_pfn);
6826 	}
6827 }
6828 
6829 #ifdef CONFIG_FLAT_NODE_MEM_MAP
alloc_node_mem_map(struct pglist_data * pgdat)6830 static void __ref alloc_node_mem_map(struct pglist_data *pgdat)
6831 {
6832 	unsigned long __maybe_unused start = 0;
6833 	unsigned long __maybe_unused offset = 0;
6834 
6835 	/* Skip empty nodes */
6836 	if (!pgdat->node_spanned_pages)
6837 		return;
6838 
6839 	start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
6840 	offset = pgdat->node_start_pfn - start;
6841 	/* ia64 gets its own node_mem_map, before this, without bootmem */
6842 	if (!pgdat->node_mem_map) {
6843 		unsigned long size, end;
6844 		struct page *map;
6845 
6846 		/*
6847 		 * The zone's endpoints aren't required to be MAX_ORDER
6848 		 * aligned but the node_mem_map endpoints must be in order
6849 		 * for the buddy allocator to function correctly.
6850 		 */
6851 		end = pgdat_end_pfn(pgdat);
6852 		end = ALIGN(end, MAX_ORDER_NR_PAGES);
6853 		size =  (end - start) * sizeof(struct page);
6854 		map = memblock_alloc_node(size, SMP_CACHE_BYTES,
6855 					  pgdat->node_id);
6856 		if (!map)
6857 			panic("Failed to allocate %ld bytes for node %d memory map\n",
6858 			      size, pgdat->node_id);
6859 		pgdat->node_mem_map = map + offset;
6860 	}
6861 	pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
6862 				__func__, pgdat->node_id, (unsigned long)pgdat,
6863 				(unsigned long)pgdat->node_mem_map);
6864 #ifndef CONFIG_NEED_MULTIPLE_NODES
6865 	/*
6866 	 * With no DISCONTIG, the global mem_map is just set as node 0's
6867 	 */
6868 	if (pgdat == NODE_DATA(0)) {
6869 		mem_map = NODE_DATA(0)->node_mem_map;
6870 #if defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) || defined(CONFIG_FLATMEM)
6871 		if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
6872 			mem_map -= offset;
6873 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
6874 	}
6875 #endif
6876 }
6877 #else
alloc_node_mem_map(struct pglist_data * pgdat)6878 static void __ref alloc_node_mem_map(struct pglist_data *pgdat) { }
6879 #endif /* CONFIG_FLAT_NODE_MEM_MAP */
6880 
6881 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
pgdat_set_deferred_range(pg_data_t * pgdat)6882 static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
6883 {
6884 	pgdat->first_deferred_pfn = ULONG_MAX;
6885 }
6886 #else
pgdat_set_deferred_range(pg_data_t * pgdat)6887 static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
6888 #endif
6889 
free_area_init_node(int nid,unsigned long * zones_size,unsigned long node_start_pfn,unsigned long * zholes_size)6890 void __init free_area_init_node(int nid, unsigned long *zones_size,
6891 				   unsigned long node_start_pfn,
6892 				   unsigned long *zholes_size)
6893 {
6894 	pg_data_t *pgdat = NODE_DATA(nid);
6895 	unsigned long start_pfn = 0;
6896 	unsigned long end_pfn = 0;
6897 
6898 	/* pg_data_t should be reset to zero when it's allocated */
6899 	WARN_ON(pgdat->nr_zones || pgdat->kswapd_classzone_idx);
6900 
6901 	pgdat->node_id = nid;
6902 	pgdat->node_start_pfn = node_start_pfn;
6903 	pgdat->per_cpu_nodestats = NULL;
6904 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6905 	get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
6906 	pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
6907 		(u64)start_pfn << PAGE_SHIFT,
6908 		end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
6909 #else
6910 	start_pfn = node_start_pfn;
6911 #endif
6912 	calculate_node_totalpages(pgdat, start_pfn, end_pfn,
6913 				  zones_size, zholes_size);
6914 
6915 	alloc_node_mem_map(pgdat);
6916 	pgdat_set_deferred_range(pgdat);
6917 
6918 	free_area_init_core(pgdat);
6919 }
6920 
6921 #if !defined(CONFIG_FLAT_NODE_MEM_MAP)
6922 /*
6923  * Zero all valid struct pages in range [spfn, epfn), return number of struct
6924  * pages zeroed
6925  */
zero_pfn_range(unsigned long spfn,unsigned long epfn)6926 static u64 zero_pfn_range(unsigned long spfn, unsigned long epfn)
6927 {
6928 	unsigned long pfn;
6929 	u64 pgcnt = 0;
6930 
6931 	for (pfn = spfn; pfn < epfn; pfn++) {
6932 		if (!pfn_valid(ALIGN_DOWN(pfn, pageblock_nr_pages))) {
6933 			pfn = ALIGN_DOWN(pfn, pageblock_nr_pages)
6934 				+ pageblock_nr_pages - 1;
6935 			continue;
6936 		}
6937 		mm_zero_struct_page(pfn_to_page(pfn));
6938 		pgcnt++;
6939 	}
6940 
6941 	return pgcnt;
6942 }
6943 
6944 /*
6945  * Only struct pages that are backed by physical memory are zeroed and
6946  * initialized by going through __init_single_page(). But, there are some
6947  * struct pages which are reserved in memblock allocator and their fields
6948  * may be accessed (for example page_to_pfn() on some configuration accesses
6949  * flags). We must explicitly zero those struct pages.
6950  *
6951  * This function also addresses a similar issue where struct pages are left
6952  * uninitialized because the physical address range is not covered by
6953  * memblock.memory or memblock.reserved. That could happen when memblock
6954  * layout is manually configured via memmap=.
6955  */
zero_resv_unavail(void)6956 void __init zero_resv_unavail(void)
6957 {
6958 	phys_addr_t start, end;
6959 	u64 i, pgcnt;
6960 	phys_addr_t next = 0;
6961 
6962 	/*
6963 	 * Loop through unavailable ranges not covered by memblock.memory.
6964 	 */
6965 	pgcnt = 0;
6966 	for_each_mem_range(i, &memblock.memory, NULL,
6967 			NUMA_NO_NODE, MEMBLOCK_NONE, &start, &end, NULL) {
6968 		if (next < start)
6969 			pgcnt += zero_pfn_range(PFN_DOWN(next), PFN_UP(start));
6970 		next = end;
6971 	}
6972 	pgcnt += zero_pfn_range(PFN_DOWN(next), max_pfn);
6973 
6974 	/*
6975 	 * Struct pages that do not have backing memory. This could be because
6976 	 * firmware is using some of this memory, or for some other reasons.
6977 	 */
6978 	if (pgcnt)
6979 		pr_info("Zeroed struct page in unavailable ranges: %lld pages", pgcnt);
6980 }
6981 #endif /* !CONFIG_FLAT_NODE_MEM_MAP */
6982 
6983 #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
6984 
6985 #if MAX_NUMNODES > 1
6986 /*
6987  * Figure out the number of possible node ids.
6988  */
setup_nr_node_ids(void)6989 void __init setup_nr_node_ids(void)
6990 {
6991 	unsigned int highest;
6992 
6993 	highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
6994 	nr_node_ids = highest + 1;
6995 }
6996 #endif
6997 
6998 /**
6999  * node_map_pfn_alignment - determine the maximum internode alignment
7000  *
7001  * This function should be called after node map is populated and sorted.
7002  * It calculates the maximum power of two alignment which can distinguish
7003  * all the nodes.
7004  *
7005  * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
7006  * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)).  If the
7007  * nodes are shifted by 256MiB, 256MiB.  Note that if only the last node is
7008  * shifted, 1GiB is enough and this function will indicate so.
7009  *
7010  * This is used to test whether pfn -> nid mapping of the chosen memory
7011  * model has fine enough granularity to avoid incorrect mapping for the
7012  * populated node map.
7013  *
7014  * Return: the determined alignment in pfn's.  0 if there is no alignment
7015  * requirement (single node).
7016  */
node_map_pfn_alignment(void)7017 unsigned long __init node_map_pfn_alignment(void)
7018 {
7019 	unsigned long accl_mask = 0, last_end = 0;
7020 	unsigned long start, end, mask;
7021 	int last_nid = NUMA_NO_NODE;
7022 	int i, nid;
7023 
7024 	for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
7025 		if (!start || last_nid < 0 || last_nid == nid) {
7026 			last_nid = nid;
7027 			last_end = end;
7028 			continue;
7029 		}
7030 
7031 		/*
7032 		 * Start with a mask granular enough to pin-point to the
7033 		 * start pfn and tick off bits one-by-one until it becomes
7034 		 * too coarse to separate the current node from the last.
7035 		 */
7036 		mask = ~((1 << __ffs(start)) - 1);
7037 		while (mask && last_end <= (start & (mask << 1)))
7038 			mask <<= 1;
7039 
7040 		/* accumulate all internode masks */
7041 		accl_mask |= mask;
7042 	}
7043 
7044 	/* convert mask to number of pages */
7045 	return ~accl_mask + 1;
7046 }
7047 
7048 /* Find the lowest pfn for a node */
find_min_pfn_for_node(int nid)7049 static unsigned long __init find_min_pfn_for_node(int nid)
7050 {
7051 	unsigned long min_pfn = ULONG_MAX;
7052 	unsigned long start_pfn;
7053 	int i;
7054 
7055 	for_each_mem_pfn_range(i, nid, &start_pfn, NULL, NULL)
7056 		min_pfn = min(min_pfn, start_pfn);
7057 
7058 	if (min_pfn == ULONG_MAX) {
7059 		pr_warn("Could not find start_pfn for node %d\n", nid);
7060 		return 0;
7061 	}
7062 
7063 	return min_pfn;
7064 }
7065 
7066 /**
7067  * find_min_pfn_with_active_regions - Find the minimum PFN registered
7068  *
7069  * Return: the minimum PFN based on information provided via
7070  * memblock_set_node().
7071  */
find_min_pfn_with_active_regions(void)7072 unsigned long __init find_min_pfn_with_active_regions(void)
7073 {
7074 	return find_min_pfn_for_node(MAX_NUMNODES);
7075 }
7076 
7077 /*
7078  * early_calculate_totalpages()
7079  * Sum pages in active regions for movable zone.
7080  * Populate N_MEMORY for calculating usable_nodes.
7081  */
early_calculate_totalpages(void)7082 static unsigned long __init early_calculate_totalpages(void)
7083 {
7084 	unsigned long totalpages = 0;
7085 	unsigned long start_pfn, end_pfn;
7086 	int i, nid;
7087 
7088 	for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7089 		unsigned long pages = end_pfn - start_pfn;
7090 
7091 		totalpages += pages;
7092 		if (pages)
7093 			node_set_state(nid, N_MEMORY);
7094 	}
7095 	return totalpages;
7096 }
7097 
7098 /*
7099  * Find the PFN the Movable zone begins in each node. Kernel memory
7100  * is spread evenly between nodes as long as the nodes have enough
7101  * memory. When they don't, some nodes will have more kernelcore than
7102  * others
7103  */
find_zone_movable_pfns_for_nodes(void)7104 static void __init find_zone_movable_pfns_for_nodes(void)
7105 {
7106 	int i, nid;
7107 	unsigned long usable_startpfn;
7108 	unsigned long kernelcore_node, kernelcore_remaining;
7109 	/* save the state before borrow the nodemask */
7110 	nodemask_t saved_node_state = node_states[N_MEMORY];
7111 	unsigned long totalpages = early_calculate_totalpages();
7112 	int usable_nodes = nodes_weight(node_states[N_MEMORY]);
7113 	struct memblock_region *r;
7114 
7115 	/* Need to find movable_zone earlier when movable_node is specified. */
7116 	find_usable_zone_for_movable();
7117 
7118 	/*
7119 	 * If movable_node is specified, ignore kernelcore and movablecore
7120 	 * options.
7121 	 */
7122 	if (movable_node_is_enabled()) {
7123 		for_each_memblock(memory, r) {
7124 			if (!memblock_is_hotpluggable(r))
7125 				continue;
7126 
7127 			nid = r->nid;
7128 
7129 			usable_startpfn = PFN_DOWN(r->base);
7130 			zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7131 				min(usable_startpfn, zone_movable_pfn[nid]) :
7132 				usable_startpfn;
7133 		}
7134 
7135 		goto out2;
7136 	}
7137 
7138 	/*
7139 	 * If kernelcore=mirror is specified, ignore movablecore option
7140 	 */
7141 	if (mirrored_kernelcore) {
7142 		bool mem_below_4gb_not_mirrored = false;
7143 
7144 		for_each_memblock(memory, r) {
7145 			if (memblock_is_mirror(r))
7146 				continue;
7147 
7148 			nid = r->nid;
7149 
7150 			usable_startpfn = memblock_region_memory_base_pfn(r);
7151 
7152 			if (usable_startpfn < 0x100000) {
7153 				mem_below_4gb_not_mirrored = true;
7154 				continue;
7155 			}
7156 
7157 			zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
7158 				min(usable_startpfn, zone_movable_pfn[nid]) :
7159 				usable_startpfn;
7160 		}
7161 
7162 		if (mem_below_4gb_not_mirrored)
7163 			pr_warn("This configuration results in unmirrored kernel memory.");
7164 
7165 		goto out2;
7166 	}
7167 
7168 	/*
7169 	 * If kernelcore=nn% or movablecore=nn% was specified, calculate the
7170 	 * amount of necessary memory.
7171 	 */
7172 	if (required_kernelcore_percent)
7173 		required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
7174 				       10000UL;
7175 	if (required_movablecore_percent)
7176 		required_movablecore = (totalpages * 100 * required_movablecore_percent) /
7177 					10000UL;
7178 
7179 	/*
7180 	 * If movablecore= was specified, calculate what size of
7181 	 * kernelcore that corresponds so that memory usable for
7182 	 * any allocation type is evenly spread. If both kernelcore
7183 	 * and movablecore are specified, then the value of kernelcore
7184 	 * will be used for required_kernelcore if it's greater than
7185 	 * what movablecore would have allowed.
7186 	 */
7187 	if (required_movablecore) {
7188 		unsigned long corepages;
7189 
7190 		/*
7191 		 * Round-up so that ZONE_MOVABLE is at least as large as what
7192 		 * was requested by the user
7193 		 */
7194 		required_movablecore =
7195 			roundup(required_movablecore, MAX_ORDER_NR_PAGES);
7196 		required_movablecore = min(totalpages, required_movablecore);
7197 		corepages = totalpages - required_movablecore;
7198 
7199 		required_kernelcore = max(required_kernelcore, corepages);
7200 	}
7201 
7202 	/*
7203 	 * If kernelcore was not specified or kernelcore size is larger
7204 	 * than totalpages, there is no ZONE_MOVABLE.
7205 	 */
7206 	if (!required_kernelcore || required_kernelcore >= totalpages)
7207 		goto out;
7208 
7209 	/* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
7210 	usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
7211 
7212 restart:
7213 	/* Spread kernelcore memory as evenly as possible throughout nodes */
7214 	kernelcore_node = required_kernelcore / usable_nodes;
7215 	for_each_node_state(nid, N_MEMORY) {
7216 		unsigned long start_pfn, end_pfn;
7217 
7218 		/*
7219 		 * Recalculate kernelcore_node if the division per node
7220 		 * now exceeds what is necessary to satisfy the requested
7221 		 * amount of memory for the kernel
7222 		 */
7223 		if (required_kernelcore < kernelcore_node)
7224 			kernelcore_node = required_kernelcore / usable_nodes;
7225 
7226 		/*
7227 		 * As the map is walked, we track how much memory is usable
7228 		 * by the kernel using kernelcore_remaining. When it is
7229 		 * 0, the rest of the node is usable by ZONE_MOVABLE
7230 		 */
7231 		kernelcore_remaining = kernelcore_node;
7232 
7233 		/* Go through each range of PFNs within this node */
7234 		for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
7235 			unsigned long size_pages;
7236 
7237 			start_pfn = max(start_pfn, zone_movable_pfn[nid]);
7238 			if (start_pfn >= end_pfn)
7239 				continue;
7240 
7241 			/* Account for what is only usable for kernelcore */
7242 			if (start_pfn < usable_startpfn) {
7243 				unsigned long kernel_pages;
7244 				kernel_pages = min(end_pfn, usable_startpfn)
7245 								- start_pfn;
7246 
7247 				kernelcore_remaining -= min(kernel_pages,
7248 							kernelcore_remaining);
7249 				required_kernelcore -= min(kernel_pages,
7250 							required_kernelcore);
7251 
7252 				/* Continue if range is now fully accounted */
7253 				if (end_pfn <= usable_startpfn) {
7254 
7255 					/*
7256 					 * Push zone_movable_pfn to the end so
7257 					 * that if we have to rebalance
7258 					 * kernelcore across nodes, we will
7259 					 * not double account here
7260 					 */
7261 					zone_movable_pfn[nid] = end_pfn;
7262 					continue;
7263 				}
7264 				start_pfn = usable_startpfn;
7265 			}
7266 
7267 			/*
7268 			 * The usable PFN range for ZONE_MOVABLE is from
7269 			 * start_pfn->end_pfn. Calculate size_pages as the
7270 			 * number of pages used as kernelcore
7271 			 */
7272 			size_pages = end_pfn - start_pfn;
7273 			if (size_pages > kernelcore_remaining)
7274 				size_pages = kernelcore_remaining;
7275 			zone_movable_pfn[nid] = start_pfn + size_pages;
7276 
7277 			/*
7278 			 * Some kernelcore has been met, update counts and
7279 			 * break if the kernelcore for this node has been
7280 			 * satisfied
7281 			 */
7282 			required_kernelcore -= min(required_kernelcore,
7283 								size_pages);
7284 			kernelcore_remaining -= size_pages;
7285 			if (!kernelcore_remaining)
7286 				break;
7287 		}
7288 	}
7289 
7290 	/*
7291 	 * If there is still required_kernelcore, we do another pass with one
7292 	 * less node in the count. This will push zone_movable_pfn[nid] further
7293 	 * along on the nodes that still have memory until kernelcore is
7294 	 * satisfied
7295 	 */
7296 	usable_nodes--;
7297 	if (usable_nodes && required_kernelcore > usable_nodes)
7298 		goto restart;
7299 
7300 out2:
7301 	/* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
7302 	for (nid = 0; nid < MAX_NUMNODES; nid++)
7303 		zone_movable_pfn[nid] =
7304 			roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
7305 
7306 out:
7307 	/* restore the node_state */
7308 	node_states[N_MEMORY] = saved_node_state;
7309 }
7310 
7311 /* Any regular or high memory on that node ? */
check_for_memory(pg_data_t * pgdat,int nid)7312 static void check_for_memory(pg_data_t *pgdat, int nid)
7313 {
7314 	enum zone_type zone_type;
7315 
7316 	for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
7317 		struct zone *zone = &pgdat->node_zones[zone_type];
7318 		if (populated_zone(zone)) {
7319 			if (IS_ENABLED(CONFIG_HIGHMEM))
7320 				node_set_state(nid, N_HIGH_MEMORY);
7321 			if (zone_type <= ZONE_NORMAL)
7322 				node_set_state(nid, N_NORMAL_MEMORY);
7323 			break;
7324 		}
7325 	}
7326 }
7327 
7328 /**
7329  * free_area_init_nodes - Initialise all pg_data_t and zone data
7330  * @max_zone_pfn: an array of max PFNs for each zone
7331  *
7332  * This will call free_area_init_node() for each active node in the system.
7333  * Using the page ranges provided by memblock_set_node(), the size of each
7334  * zone in each node and their holes is calculated. If the maximum PFN
7335  * between two adjacent zones match, it is assumed that the zone is empty.
7336  * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
7337  * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
7338  * starts where the previous one ended. For example, ZONE_DMA32 starts
7339  * at arch_max_dma_pfn.
7340  */
free_area_init_nodes(unsigned long * max_zone_pfn)7341 void __init free_area_init_nodes(unsigned long *max_zone_pfn)
7342 {
7343 	unsigned long start_pfn, end_pfn;
7344 	int i, nid;
7345 
7346 	/* Record where the zone boundaries are */
7347 	memset(arch_zone_lowest_possible_pfn, 0,
7348 				sizeof(arch_zone_lowest_possible_pfn));
7349 	memset(arch_zone_highest_possible_pfn, 0,
7350 				sizeof(arch_zone_highest_possible_pfn));
7351 
7352 	start_pfn = find_min_pfn_with_active_regions();
7353 
7354 	for (i = 0; i < MAX_NR_ZONES; i++) {
7355 		if (i == ZONE_MOVABLE)
7356 			continue;
7357 
7358 		end_pfn = max(max_zone_pfn[i], start_pfn);
7359 		arch_zone_lowest_possible_pfn[i] = start_pfn;
7360 		arch_zone_highest_possible_pfn[i] = end_pfn;
7361 
7362 		start_pfn = end_pfn;
7363 	}
7364 
7365 	/* Find the PFNs that ZONE_MOVABLE begins at in each node */
7366 	memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
7367 	find_zone_movable_pfns_for_nodes();
7368 
7369 	/* Print out the zone ranges */
7370 	pr_info("Zone ranges:\n");
7371 	for (i = 0; i < MAX_NR_ZONES; i++) {
7372 		if (i == ZONE_MOVABLE)
7373 			continue;
7374 		pr_info("  %-8s ", zone_names[i]);
7375 		if (arch_zone_lowest_possible_pfn[i] ==
7376 				arch_zone_highest_possible_pfn[i])
7377 			pr_cont("empty\n");
7378 		else
7379 			pr_cont("[mem %#018Lx-%#018Lx]\n",
7380 				(u64)arch_zone_lowest_possible_pfn[i]
7381 					<< PAGE_SHIFT,
7382 				((u64)arch_zone_highest_possible_pfn[i]
7383 					<< PAGE_SHIFT) - 1);
7384 	}
7385 
7386 	/* Print out the PFNs ZONE_MOVABLE begins at in each node */
7387 	pr_info("Movable zone start for each node\n");
7388 	for (i = 0; i < MAX_NUMNODES; i++) {
7389 		if (zone_movable_pfn[i])
7390 			pr_info("  Node %d: %#018Lx\n", i,
7391 			       (u64)zone_movable_pfn[i] << PAGE_SHIFT);
7392 	}
7393 
7394 	/*
7395 	 * Print out the early node map, and initialize the
7396 	 * subsection-map relative to active online memory ranges to
7397 	 * enable future "sub-section" extensions of the memory map.
7398 	 */
7399 	pr_info("Early memory node ranges\n");
7400 	for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
7401 		pr_info("  node %3d: [mem %#018Lx-%#018Lx]\n", nid,
7402 			(u64)start_pfn << PAGE_SHIFT,
7403 			((u64)end_pfn << PAGE_SHIFT) - 1);
7404 		subsection_map_init(start_pfn, end_pfn - start_pfn);
7405 	}
7406 
7407 	/* Initialise every node */
7408 	mminit_verify_pageflags_layout();
7409 	setup_nr_node_ids();
7410 	zero_resv_unavail();
7411 	for_each_online_node(nid) {
7412 		pg_data_t *pgdat = NODE_DATA(nid);
7413 		free_area_init_node(nid, NULL,
7414 				find_min_pfn_for_node(nid), NULL);
7415 
7416 		/* Any memory on that node */
7417 		if (pgdat->node_present_pages)
7418 			node_set_state(nid, N_MEMORY);
7419 		check_for_memory(pgdat, nid);
7420 	}
7421 }
7422 
cmdline_parse_core(char * p,unsigned long * core,unsigned long * percent)7423 static int __init cmdline_parse_core(char *p, unsigned long *core,
7424 				     unsigned long *percent)
7425 {
7426 	unsigned long long coremem;
7427 	char *endptr;
7428 
7429 	if (!p)
7430 		return -EINVAL;
7431 
7432 	/* Value may be a percentage of total memory, otherwise bytes */
7433 	coremem = simple_strtoull(p, &endptr, 0);
7434 	if (*endptr == '%') {
7435 		/* Paranoid check for percent values greater than 100 */
7436 		WARN_ON(coremem > 100);
7437 
7438 		*percent = coremem;
7439 	} else {
7440 		coremem = memparse(p, &p);
7441 		/* Paranoid check that UL is enough for the coremem value */
7442 		WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
7443 
7444 		*core = coremem >> PAGE_SHIFT;
7445 		*percent = 0UL;
7446 	}
7447 	return 0;
7448 }
7449 
7450 /*
7451  * kernelcore=size sets the amount of memory for use for allocations that
7452  * cannot be reclaimed or migrated.
7453  */
cmdline_parse_kernelcore(char * p)7454 static int __init cmdline_parse_kernelcore(char *p)
7455 {
7456 	/* parse kernelcore=mirror */
7457 	if (parse_option_str(p, "mirror")) {
7458 		mirrored_kernelcore = true;
7459 		return 0;
7460 	}
7461 
7462 	return cmdline_parse_core(p, &required_kernelcore,
7463 				  &required_kernelcore_percent);
7464 }
7465 
7466 /*
7467  * movablecore=size sets the amount of memory for use for allocations that
7468  * can be reclaimed or migrated.
7469  */
cmdline_parse_movablecore(char * p)7470 static int __init cmdline_parse_movablecore(char *p)
7471 {
7472 	return cmdline_parse_core(p, &required_movablecore,
7473 				  &required_movablecore_percent);
7474 }
7475 
7476 early_param("kernelcore", cmdline_parse_kernelcore);
7477 early_param("movablecore", cmdline_parse_movablecore);
7478 
7479 #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
7480 
adjust_managed_page_count(struct page * page,long count)7481 void adjust_managed_page_count(struct page *page, long count)
7482 {
7483 	atomic_long_add(count, &page_zone(page)->managed_pages);
7484 	totalram_pages_add(count);
7485 #ifdef CONFIG_HIGHMEM
7486 	if (PageHighMem(page))
7487 		totalhigh_pages_add(count);
7488 #endif
7489 }
7490 EXPORT_SYMBOL(adjust_managed_page_count);
7491 
free_reserved_area(void * start,void * end,int poison,const char * s)7492 unsigned long free_reserved_area(void *start, void *end, int poison, const char *s)
7493 {
7494 	void *pos;
7495 	unsigned long pages = 0;
7496 
7497 	start = (void *)PAGE_ALIGN((unsigned long)start);
7498 	end = (void *)((unsigned long)end & PAGE_MASK);
7499 	for (pos = start; pos < end; pos += PAGE_SIZE, pages++) {
7500 		struct page *page = virt_to_page(pos);
7501 		void *direct_map_addr;
7502 
7503 		/*
7504 		 * 'direct_map_addr' might be different from 'pos'
7505 		 * because some architectures' virt_to_page()
7506 		 * work with aliases.  Getting the direct map
7507 		 * address ensures that we get a _writeable_
7508 		 * alias for the memset().
7509 		 */
7510 		direct_map_addr = page_address(page);
7511 		if ((unsigned int)poison <= 0xFF)
7512 			memset(direct_map_addr, poison, PAGE_SIZE);
7513 
7514 		free_reserved_page(page);
7515 	}
7516 
7517 	if (pages && s)
7518 		pr_info("Freeing %s memory: %ldK\n",
7519 			s, pages << (PAGE_SHIFT - 10));
7520 
7521 	return pages;
7522 }
7523 
7524 #ifdef	CONFIG_HIGHMEM
free_highmem_page(struct page * page)7525 void free_highmem_page(struct page *page)
7526 {
7527 	__free_reserved_page(page);
7528 	totalram_pages_inc();
7529 	atomic_long_inc(&page_zone(page)->managed_pages);
7530 	totalhigh_pages_inc();
7531 }
7532 #endif
7533 
7534 
mem_init_print_info(const char * str)7535 void __init mem_init_print_info(const char *str)
7536 {
7537 	unsigned long physpages, codesize, datasize, rosize, bss_size;
7538 	unsigned long init_code_size, init_data_size;
7539 
7540 	physpages = get_num_physpages();
7541 	codesize = _etext - _stext;
7542 	datasize = _edata - _sdata;
7543 	rosize = __end_rodata - __start_rodata;
7544 	bss_size = __bss_stop - __bss_start;
7545 	init_data_size = __init_end - __init_begin;
7546 	init_code_size = _einittext - _sinittext;
7547 
7548 	/*
7549 	 * Detect special cases and adjust section sizes accordingly:
7550 	 * 1) .init.* may be embedded into .data sections
7551 	 * 2) .init.text.* may be out of [__init_begin, __init_end],
7552 	 *    please refer to arch/tile/kernel/vmlinux.lds.S.
7553 	 * 3) .rodata.* may be embedded into .text or .data sections.
7554 	 */
7555 #define adj_init_size(start, end, size, pos, adj) \
7556 	do { \
7557 		if (start <= pos && pos < end && size > adj) \
7558 			size -= adj; \
7559 	} while (0)
7560 
7561 	adj_init_size(__init_begin, __init_end, init_data_size,
7562 		     _sinittext, init_code_size);
7563 	adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
7564 	adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
7565 	adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
7566 	adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
7567 
7568 #undef	adj_init_size
7569 
7570 	pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
7571 #ifdef	CONFIG_HIGHMEM
7572 		", %luK highmem"
7573 #endif
7574 		"%s%s)\n",
7575 		nr_free_pages() << (PAGE_SHIFT - 10),
7576 		physpages << (PAGE_SHIFT - 10),
7577 		codesize >> 10, datasize >> 10, rosize >> 10,
7578 		(init_data_size + init_code_size) >> 10, bss_size >> 10,
7579 		(physpages - totalram_pages() - totalcma_pages) << (PAGE_SHIFT - 10),
7580 		totalcma_pages << (PAGE_SHIFT - 10),
7581 #ifdef	CONFIG_HIGHMEM
7582 		totalhigh_pages() << (PAGE_SHIFT - 10),
7583 #endif
7584 		str ? ", " : "", str ? str : "");
7585 }
7586 
7587 /**
7588  * set_dma_reserve - set the specified number of pages reserved in the first zone
7589  * @new_dma_reserve: The number of pages to mark reserved
7590  *
7591  * The per-cpu batchsize and zone watermarks are determined by managed_pages.
7592  * In the DMA zone, a significant percentage may be consumed by kernel image
7593  * and other unfreeable allocations which can skew the watermarks badly. This
7594  * function may optionally be used to account for unfreeable pages in the
7595  * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and
7596  * smaller per-cpu batchsize.
7597  */
set_dma_reserve(unsigned long new_dma_reserve)7598 void __init set_dma_reserve(unsigned long new_dma_reserve)
7599 {
7600 	dma_reserve = new_dma_reserve;
7601 }
7602 
free_area_init(unsigned long * zones_size)7603 void __init free_area_init(unsigned long *zones_size)
7604 {
7605 	zero_resv_unavail();
7606 	free_area_init_node(0, zones_size,
7607 			__pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL);
7608 }
7609 
page_alloc_cpu_dead(unsigned int cpu)7610 static int page_alloc_cpu_dead(unsigned int cpu)
7611 {
7612 
7613 	lru_add_drain_cpu(cpu);
7614 	drain_pages(cpu);
7615 
7616 	/*
7617 	 * Spill the event counters of the dead processor
7618 	 * into the current processors event counters.
7619 	 * This artificially elevates the count of the current
7620 	 * processor.
7621 	 */
7622 	vm_events_fold_cpu(cpu);
7623 
7624 	/*
7625 	 * Zero the differential counters of the dead processor
7626 	 * so that the vm statistics are consistent.
7627 	 *
7628 	 * This is only okay since the processor is dead and cannot
7629 	 * race with what we are doing.
7630 	 */
7631 	cpu_vm_stats_fold(cpu);
7632 	return 0;
7633 }
7634 
7635 #ifdef CONFIG_NUMA
7636 int hashdist = HASHDIST_DEFAULT;
7637 
set_hashdist(char * str)7638 static int __init set_hashdist(char *str)
7639 {
7640 	if (!str)
7641 		return 0;
7642 	hashdist = simple_strtoul(str, &str, 0);
7643 	return 1;
7644 }
7645 __setup("hashdist=", set_hashdist);
7646 #endif
7647 
page_alloc_init(void)7648 void __init page_alloc_init(void)
7649 {
7650 	int ret;
7651 
7652 #ifdef CONFIG_NUMA
7653 	if (num_node_state(N_MEMORY) == 1)
7654 		hashdist = 0;
7655 #endif
7656 
7657 	ret = cpuhp_setup_state_nocalls(CPUHP_PAGE_ALLOC_DEAD,
7658 					"mm/page_alloc:dead", NULL,
7659 					page_alloc_cpu_dead);
7660 	WARN_ON(ret < 0);
7661 }
7662 
7663 /*
7664  * calculate_totalreserve_pages - called when sysctl_lowmem_reserve_ratio
7665  *	or min_free_kbytes changes.
7666  */
calculate_totalreserve_pages(void)7667 static void calculate_totalreserve_pages(void)
7668 {
7669 	struct pglist_data *pgdat;
7670 	unsigned long reserve_pages = 0;
7671 	enum zone_type i, j;
7672 
7673 	for_each_online_pgdat(pgdat) {
7674 
7675 		pgdat->totalreserve_pages = 0;
7676 
7677 		for (i = 0; i < MAX_NR_ZONES; i++) {
7678 			struct zone *zone = pgdat->node_zones + i;
7679 			long max = 0;
7680 			unsigned long managed_pages = zone_managed_pages(zone);
7681 
7682 			/* Find valid and maximum lowmem_reserve in the zone */
7683 			for (j = i; j < MAX_NR_ZONES; j++) {
7684 				if (zone->lowmem_reserve[j] > max)
7685 					max = zone->lowmem_reserve[j];
7686 			}
7687 
7688 			/* we treat the high watermark as reserved pages. */
7689 			max += high_wmark_pages(zone);
7690 
7691 			if (max > managed_pages)
7692 				max = managed_pages;
7693 
7694 			pgdat->totalreserve_pages += max;
7695 
7696 			reserve_pages += max;
7697 		}
7698 	}
7699 	totalreserve_pages = reserve_pages;
7700 }
7701 
7702 /*
7703  * setup_per_zone_lowmem_reserve - called whenever
7704  *	sysctl_lowmem_reserve_ratio changes.  Ensures that each zone
7705  *	has a correct pages reserved value, so an adequate number of
7706  *	pages are left in the zone after a successful __alloc_pages().
7707  */
setup_per_zone_lowmem_reserve(void)7708 static void setup_per_zone_lowmem_reserve(void)
7709 {
7710 	struct pglist_data *pgdat;
7711 	enum zone_type j, idx;
7712 
7713 	for_each_online_pgdat(pgdat) {
7714 		for (j = 0; j < MAX_NR_ZONES; j++) {
7715 			struct zone *zone = pgdat->node_zones + j;
7716 			unsigned long managed_pages = zone_managed_pages(zone);
7717 
7718 			zone->lowmem_reserve[j] = 0;
7719 
7720 			idx = j;
7721 			while (idx) {
7722 				struct zone *lower_zone;
7723 
7724 				idx--;
7725 				lower_zone = pgdat->node_zones + idx;
7726 
7727 				if (sysctl_lowmem_reserve_ratio[idx] < 1) {
7728 					sysctl_lowmem_reserve_ratio[idx] = 0;
7729 					lower_zone->lowmem_reserve[j] = 0;
7730 				} else {
7731 					lower_zone->lowmem_reserve[j] =
7732 						managed_pages / sysctl_lowmem_reserve_ratio[idx];
7733 				}
7734 				managed_pages += zone_managed_pages(lower_zone);
7735 			}
7736 		}
7737 	}
7738 
7739 	/* update totalreserve_pages */
7740 	calculate_totalreserve_pages();
7741 }
7742 
__setup_per_zone_wmarks(void)7743 static void __setup_per_zone_wmarks(void)
7744 {
7745 	unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
7746 	unsigned long pages_low = extra_free_kbytes >> (PAGE_SHIFT - 10);
7747 	unsigned long lowmem_pages = 0;
7748 	struct zone *zone;
7749 	unsigned long flags;
7750 
7751 	/* Calculate total number of !ZONE_HIGHMEM pages */
7752 	for_each_zone(zone) {
7753 		if (!is_highmem(zone))
7754 			lowmem_pages += zone_managed_pages(zone);
7755 	}
7756 
7757 	for_each_zone(zone) {
7758 		u64 tmp, low;
7759 
7760 		spin_lock_irqsave(&zone->lock, flags);
7761 		tmp = (u64)pages_min * zone_managed_pages(zone);
7762 		do_div(tmp, lowmem_pages);
7763 		low = (u64)pages_low * zone_managed_pages(zone);
7764 		do_div(low, vm_total_pages);
7765 		if (is_highmem(zone)) {
7766 			/*
7767 			 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
7768 			 * need highmem pages, so cap pages_min to a small
7769 			 * value here.
7770 			 *
7771 			 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
7772 			 * deltas control async page reclaim, and so should
7773 			 * not be capped for highmem.
7774 			 */
7775 			unsigned long min_pages;
7776 
7777 			min_pages = zone_managed_pages(zone) / 1024;
7778 			min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
7779 			zone->_watermark[WMARK_MIN] = min_pages;
7780 		} else {
7781 			/*
7782 			 * If it's a lowmem zone, reserve a number of pages
7783 			 * proportionate to the zone's size.
7784 			 */
7785 			zone->_watermark[WMARK_MIN] = tmp;
7786 		}
7787 
7788 		/*
7789 		 * Set the kswapd watermarks distance according to the
7790 		 * scale factor in proportion to available memory, but
7791 		 * ensure a minimum size on small systems.
7792 		 */
7793 		tmp = max_t(u64, tmp >> 2,
7794 			    mult_frac(zone_managed_pages(zone),
7795 				      watermark_scale_factor, 10000));
7796 
7797 		zone->_watermark[WMARK_LOW]  = min_wmark_pages(zone) +
7798 					low + tmp;
7799 		zone->_watermark[WMARK_HIGH] = min_wmark_pages(zone) +
7800 					low + tmp * 2;
7801 		zone->watermark_boost = 0;
7802 
7803 		spin_unlock_irqrestore(&zone->lock, flags);
7804 	}
7805 
7806 	/* update totalreserve_pages */
7807 	calculate_totalreserve_pages();
7808 }
7809 
7810 /**
7811  * setup_per_zone_wmarks - called when min_free_kbytes changes
7812  * or when memory is hot-{added|removed}
7813  *
7814  * Ensures that the watermark[min,low,high] values for each zone are set
7815  * correctly with respect to min_free_kbytes.
7816  */
setup_per_zone_wmarks(void)7817 void setup_per_zone_wmarks(void)
7818 {
7819 	static DEFINE_SPINLOCK(lock);
7820 
7821 	spin_lock(&lock);
7822 	__setup_per_zone_wmarks();
7823 	spin_unlock(&lock);
7824 }
7825 
7826 /*
7827  * Initialise min_free_kbytes.
7828  *
7829  * For small machines we want it small (128k min).  For large machines
7830  * we want it large (64MB max).  But it is not linear, because network
7831  * bandwidth does not increase linearly with machine size.  We use
7832  *
7833  *	min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
7834  *	min_free_kbytes = sqrt(lowmem_kbytes * 16)
7835  *
7836  * which yields
7837  *
7838  * 16MB:	512k
7839  * 32MB:	724k
7840  * 64MB:	1024k
7841  * 128MB:	1448k
7842  * 256MB:	2048k
7843  * 512MB:	2896k
7844  * 1024MB:	4096k
7845  * 2048MB:	5792k
7846  * 4096MB:	8192k
7847  * 8192MB:	11584k
7848  * 16384MB:	16384k
7849  */
init_per_zone_wmark_min(void)7850 int __meminit init_per_zone_wmark_min(void)
7851 {
7852 	unsigned long lowmem_kbytes;
7853 	int new_min_free_kbytes;
7854 
7855 	lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10);
7856 	new_min_free_kbytes = int_sqrt(lowmem_kbytes * 16);
7857 
7858 	if (new_min_free_kbytes > user_min_free_kbytes) {
7859 		min_free_kbytes = new_min_free_kbytes;
7860 		if (min_free_kbytes < 128)
7861 			min_free_kbytes = 128;
7862 		if (min_free_kbytes > 65536)
7863 			min_free_kbytes = 65536;
7864 	} else {
7865 		pr_warn("min_free_kbytes is not updated to %d because user defined value %d is preferred\n",
7866 				new_min_free_kbytes, user_min_free_kbytes);
7867 	}
7868 	setup_per_zone_wmarks();
7869 	refresh_zone_stat_thresholds();
7870 	setup_per_zone_lowmem_reserve();
7871 
7872 #ifdef CONFIG_NUMA
7873 	setup_min_unmapped_ratio();
7874 	setup_min_slab_ratio();
7875 #endif
7876 
7877 	return 0;
7878 }
core_initcall(init_per_zone_wmark_min)7879 core_initcall(init_per_zone_wmark_min)
7880 
7881 /*
7882  * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so
7883  *	that we can call two helper functions whenever min_free_kbytes
7884  *	or extra_free_kbytes changes.
7885  */
7886 int min_free_kbytes_sysctl_handler(struct ctl_table *table, int write,
7887 	void __user *buffer, size_t *length, loff_t *ppos)
7888 {
7889 	int rc;
7890 
7891 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7892 	if (rc)
7893 		return rc;
7894 
7895 	if (write) {
7896 		user_min_free_kbytes = min_free_kbytes;
7897 		setup_per_zone_wmarks();
7898 	}
7899 	return 0;
7900 }
7901 
watermark_boost_factor_sysctl_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)7902 int watermark_boost_factor_sysctl_handler(struct ctl_table *table, int write,
7903 	void __user *buffer, size_t *length, loff_t *ppos)
7904 {
7905 	int rc;
7906 
7907 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7908 	if (rc)
7909 		return rc;
7910 
7911 	return 0;
7912 }
7913 
watermark_scale_factor_sysctl_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)7914 int watermark_scale_factor_sysctl_handler(struct ctl_table *table, int write,
7915 	void __user *buffer, size_t *length, loff_t *ppos)
7916 {
7917 	int rc;
7918 
7919 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7920 	if (rc)
7921 		return rc;
7922 
7923 	if (write)
7924 		setup_per_zone_wmarks();
7925 
7926 	return 0;
7927 }
7928 
7929 #ifdef CONFIG_NUMA
setup_min_unmapped_ratio(void)7930 static void setup_min_unmapped_ratio(void)
7931 {
7932 	pg_data_t *pgdat;
7933 	struct zone *zone;
7934 
7935 	for_each_online_pgdat(pgdat)
7936 		pgdat->min_unmapped_pages = 0;
7937 
7938 	for_each_zone(zone)
7939 		zone->zone_pgdat->min_unmapped_pages += (zone_managed_pages(zone) *
7940 						         sysctl_min_unmapped_ratio) / 100;
7941 }
7942 
7943 
sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)7944 int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *table, int write,
7945 	void __user *buffer, size_t *length, loff_t *ppos)
7946 {
7947 	int rc;
7948 
7949 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7950 	if (rc)
7951 		return rc;
7952 
7953 	setup_min_unmapped_ratio();
7954 
7955 	return 0;
7956 }
7957 
setup_min_slab_ratio(void)7958 static void setup_min_slab_ratio(void)
7959 {
7960 	pg_data_t *pgdat;
7961 	struct zone *zone;
7962 
7963 	for_each_online_pgdat(pgdat)
7964 		pgdat->min_slab_pages = 0;
7965 
7966 	for_each_zone(zone)
7967 		zone->zone_pgdat->min_slab_pages += (zone_managed_pages(zone) *
7968 						     sysctl_min_slab_ratio) / 100;
7969 }
7970 
sysctl_min_slab_ratio_sysctl_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)7971 int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *table, int write,
7972 	void __user *buffer, size_t *length, loff_t *ppos)
7973 {
7974 	int rc;
7975 
7976 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
7977 	if (rc)
7978 		return rc;
7979 
7980 	setup_min_slab_ratio();
7981 
7982 	return 0;
7983 }
7984 #endif
7985 
7986 /*
7987  * lowmem_reserve_ratio_sysctl_handler - just a wrapper around
7988  *	proc_dointvec() so that we can call setup_per_zone_lowmem_reserve()
7989  *	whenever sysctl_lowmem_reserve_ratio changes.
7990  *
7991  * The reserve ratio obviously has absolutely no relation with the
7992  * minimum watermarks. The lowmem reserve ratio can only make sense
7993  * if in function of the boot time zone sizes.
7994  */
lowmem_reserve_ratio_sysctl_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)7995 int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *table, int write,
7996 	void __user *buffer, size_t *length, loff_t *ppos)
7997 {
7998 	proc_dointvec_minmax(table, write, buffer, length, ppos);
7999 	setup_per_zone_lowmem_reserve();
8000 	return 0;
8001 }
8002 
8003 /*
8004  * percpu_pagelist_fraction - changes the pcp->high for each zone on each
8005  * cpu.  It is the fraction of total pages in each zone that a hot per cpu
8006  * pagelist can have before it gets flushed back to buddy allocator.
8007  */
percpu_pagelist_fraction_sysctl_handler(struct ctl_table * table,int write,void __user * buffer,size_t * length,loff_t * ppos)8008 int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *table, int write,
8009 	void __user *buffer, size_t *length, loff_t *ppos)
8010 {
8011 	struct zone *zone;
8012 	int old_percpu_pagelist_fraction;
8013 	int ret;
8014 
8015 	mutex_lock(&pcp_batch_high_lock);
8016 	old_percpu_pagelist_fraction = percpu_pagelist_fraction;
8017 
8018 	ret = proc_dointvec_minmax(table, write, buffer, length, ppos);
8019 	if (!write || ret < 0)
8020 		goto out;
8021 
8022 	/* Sanity checking to avoid pcp imbalance */
8023 	if (percpu_pagelist_fraction &&
8024 	    percpu_pagelist_fraction < MIN_PERCPU_PAGELIST_FRACTION) {
8025 		percpu_pagelist_fraction = old_percpu_pagelist_fraction;
8026 		ret = -EINVAL;
8027 		goto out;
8028 	}
8029 
8030 	/* No change? */
8031 	if (percpu_pagelist_fraction == old_percpu_pagelist_fraction)
8032 		goto out;
8033 
8034 	for_each_populated_zone(zone) {
8035 		unsigned int cpu;
8036 
8037 		for_each_possible_cpu(cpu)
8038 			pageset_set_high_and_batch(zone,
8039 					per_cpu_ptr(zone->pageset, cpu));
8040 	}
8041 out:
8042 	mutex_unlock(&pcp_batch_high_lock);
8043 	return ret;
8044 }
8045 
8046 #ifndef __HAVE_ARCH_RESERVED_KERNEL_PAGES
8047 /*
8048  * Returns the number of pages that arch has reserved but
8049  * is not known to alloc_large_system_hash().
8050  */
arch_reserved_kernel_pages(void)8051 static unsigned long __init arch_reserved_kernel_pages(void)
8052 {
8053 	return 0;
8054 }
8055 #endif
8056 
8057 /*
8058  * Adaptive scale is meant to reduce sizes of hash tables on large memory
8059  * machines. As memory size is increased the scale is also increased but at
8060  * slower pace.  Starting from ADAPT_SCALE_BASE (64G), every time memory
8061  * quadruples the scale is increased by one, which means the size of hash table
8062  * only doubles, instead of quadrupling as well.
8063  * Because 32-bit systems cannot have large physical memory, where this scaling
8064  * makes sense, it is disabled on such platforms.
8065  */
8066 #if __BITS_PER_LONG > 32
8067 #define ADAPT_SCALE_BASE	(64ul << 30)
8068 #define ADAPT_SCALE_SHIFT	2
8069 #define ADAPT_SCALE_NPAGES	(ADAPT_SCALE_BASE >> PAGE_SHIFT)
8070 #endif
8071 
8072 /*
8073  * allocate a large system hash table from bootmem
8074  * - it is assumed that the hash table must contain an exact power-of-2
8075  *   quantity of entries
8076  * - limit is the number of hash buckets, not the total allocation size
8077  */
alloc_large_system_hash(const char * tablename,unsigned long bucketsize,unsigned long numentries,int scale,int flags,unsigned int * _hash_shift,unsigned int * _hash_mask,unsigned long low_limit,unsigned long high_limit)8078 void *__init alloc_large_system_hash(const char *tablename,
8079 				     unsigned long bucketsize,
8080 				     unsigned long numentries,
8081 				     int scale,
8082 				     int flags,
8083 				     unsigned int *_hash_shift,
8084 				     unsigned int *_hash_mask,
8085 				     unsigned long low_limit,
8086 				     unsigned long high_limit)
8087 {
8088 	unsigned long long max = high_limit;
8089 	unsigned long log2qty, size;
8090 	void *table = NULL;
8091 	gfp_t gfp_flags;
8092 	bool virt;
8093 
8094 	/* allow the kernel cmdline to have a say */
8095 	if (!numentries) {
8096 		/* round applicable memory size up to nearest megabyte */
8097 		numentries = nr_kernel_pages;
8098 		numentries -= arch_reserved_kernel_pages();
8099 
8100 		/* It isn't necessary when PAGE_SIZE >= 1MB */
8101 		if (PAGE_SHIFT < 20)
8102 			numentries = round_up(numentries, (1<<20)/PAGE_SIZE);
8103 
8104 #if __BITS_PER_LONG > 32
8105 		if (!high_limit) {
8106 			unsigned long adapt;
8107 
8108 			for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
8109 			     adapt <<= ADAPT_SCALE_SHIFT)
8110 				scale++;
8111 		}
8112 #endif
8113 
8114 		/* limit to 1 bucket per 2^scale bytes of low memory */
8115 		if (scale > PAGE_SHIFT)
8116 			numentries >>= (scale - PAGE_SHIFT);
8117 		else
8118 			numentries <<= (PAGE_SHIFT - scale);
8119 
8120 		/* Make sure we've got at least a 0-order allocation.. */
8121 		if (unlikely(flags & HASH_SMALL)) {
8122 			/* Makes no sense without HASH_EARLY */
8123 			WARN_ON(!(flags & HASH_EARLY));
8124 			if (!(numentries >> *_hash_shift)) {
8125 				numentries = 1UL << *_hash_shift;
8126 				BUG_ON(!numentries);
8127 			}
8128 		} else if (unlikely((numentries * bucketsize) < PAGE_SIZE))
8129 			numentries = PAGE_SIZE / bucketsize;
8130 	}
8131 	numentries = roundup_pow_of_two(numentries);
8132 
8133 	/* limit allocation size to 1/16 total memory by default */
8134 	if (max == 0) {
8135 		max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
8136 		do_div(max, bucketsize);
8137 	}
8138 	max = min(max, 0x80000000ULL);
8139 
8140 	if (numentries < low_limit)
8141 		numentries = low_limit;
8142 	if (numentries > max)
8143 		numentries = max;
8144 
8145 	log2qty = ilog2(numentries);
8146 
8147 	gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
8148 	do {
8149 		virt = false;
8150 		size = bucketsize << log2qty;
8151 		if (flags & HASH_EARLY) {
8152 			if (flags & HASH_ZERO)
8153 				table = memblock_alloc(size, SMP_CACHE_BYTES);
8154 			else
8155 				table = memblock_alloc_raw(size,
8156 							   SMP_CACHE_BYTES);
8157 		} else if (get_order(size) >= MAX_ORDER || hashdist) {
8158 			table = __vmalloc(size, gfp_flags, PAGE_KERNEL);
8159 			virt = true;
8160 		} else {
8161 			/*
8162 			 * If bucketsize is not a power-of-two, we may free
8163 			 * some pages at the end of hash table which
8164 			 * alloc_pages_exact() automatically does
8165 			 */
8166 			table = alloc_pages_exact(size, gfp_flags);
8167 			kmemleak_alloc(table, size, 1, gfp_flags);
8168 		}
8169 	} while (!table && size > PAGE_SIZE && --log2qty);
8170 
8171 	if (!table)
8172 		panic("Failed to allocate %s hash table\n", tablename);
8173 
8174 	pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n",
8175 		tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size,
8176 		virt ? "vmalloc" : "linear");
8177 
8178 	if (_hash_shift)
8179 		*_hash_shift = log2qty;
8180 	if (_hash_mask)
8181 		*_hash_mask = (1 << log2qty) - 1;
8182 
8183 	return table;
8184 }
8185 
8186 /*
8187  * This function checks whether pageblock includes unmovable pages or not.
8188  * If @count is not zero, it is okay to include less @count unmovable pages
8189  *
8190  * PageLRU check without isolation or lru_lock could race so that
8191  * MIGRATE_MOVABLE block might include unmovable pages. And __PageMovable
8192  * check without lock_page also may miss some movable non-lru pages at
8193  * race condition. So you can't expect this function should be exact.
8194  */
has_unmovable_pages(struct zone * zone,struct page * page,int count,int migratetype,int flags)8195 bool has_unmovable_pages(struct zone *zone, struct page *page, int count,
8196 			 int migratetype, int flags)
8197 {
8198 	unsigned long found;
8199 	unsigned long iter = 0;
8200 	unsigned long pfn = page_to_pfn(page);
8201 	const char *reason = "unmovable page";
8202 
8203 	/*
8204 	 * TODO we could make this much more efficient by not checking every
8205 	 * page in the range if we know all of them are in MOVABLE_ZONE and
8206 	 * that the movable zone guarantees that pages are migratable but
8207 	 * the later is not the case right now unfortunatelly. E.g. movablecore
8208 	 * can still lead to having bootmem allocations in zone_movable.
8209 	 */
8210 
8211 	if (is_migrate_cma_page(page)) {
8212 		/*
8213 		 * CMA allocations (alloc_contig_range) really need to mark
8214 		 * isolate CMA pageblocks even when they are not movable in fact
8215 		 * so consider them movable here.
8216 		 */
8217 		if (is_migrate_cma(migratetype))
8218 			return false;
8219 
8220 		reason = "CMA page";
8221 		goto unmovable;
8222 	}
8223 
8224 	for (found = 0; iter < pageblock_nr_pages; iter++) {
8225 		unsigned long check = pfn + iter;
8226 
8227 		if (!pfn_valid_within(check))
8228 			continue;
8229 
8230 		page = pfn_to_page(check);
8231 
8232 		if (PageReserved(page))
8233 			goto unmovable;
8234 
8235 		/*
8236 		 * If the zone is movable and we have ruled out all reserved
8237 		 * pages then it should be reasonably safe to assume the rest
8238 		 * is movable.
8239 		 */
8240 		if (zone_idx(zone) == ZONE_MOVABLE)
8241 			continue;
8242 
8243 		/*
8244 		 * Hugepages are not in LRU lists, but they're movable.
8245 		 * We need not scan over tail pages because we don't
8246 		 * handle each tail page individually in migration.
8247 		 */
8248 		if (PageHuge(page)) {
8249 			struct page *head = compound_head(page);
8250 			unsigned int skip_pages;
8251 
8252 			if (!hugepage_migration_supported(page_hstate(head)))
8253 				goto unmovable;
8254 
8255 			skip_pages = compound_nr(head) - (page - head);
8256 			iter += skip_pages - 1;
8257 			continue;
8258 		}
8259 
8260 		/*
8261 		 * We can't use page_count without pin a page
8262 		 * because another CPU can free compound page.
8263 		 * This check already skips compound tails of THP
8264 		 * because their page->_refcount is zero at all time.
8265 		 */
8266 		if (!page_ref_count(page)) {
8267 			if (PageBuddy(page))
8268 				iter += (1 << page_order(page)) - 1;
8269 			continue;
8270 		}
8271 
8272 		/*
8273 		 * The HWPoisoned page may be not in buddy system, and
8274 		 * page_count() is not 0.
8275 		 */
8276 		if ((flags & SKIP_HWPOISON) && PageHWPoison(page))
8277 			continue;
8278 
8279 		if (__PageMovable(page))
8280 			continue;
8281 
8282 		if (!PageLRU(page))
8283 			found++;
8284 		/*
8285 		 * If there are RECLAIMABLE pages, we need to check
8286 		 * it.  But now, memory offline itself doesn't call
8287 		 * shrink_node_slabs() and it still to be fixed.
8288 		 */
8289 		/*
8290 		 * If the page is not RAM, page_count()should be 0.
8291 		 * we don't need more check. This is an _used_ not-movable page.
8292 		 *
8293 		 * The problematic thing here is PG_reserved pages. PG_reserved
8294 		 * is set to both of a memory hole page and a _used_ kernel
8295 		 * page at boot.
8296 		 */
8297 		if (found > count)
8298 			goto unmovable;
8299 	}
8300 	return false;
8301 unmovable:
8302 	WARN_ON_ONCE(zone_idx(zone) == ZONE_MOVABLE);
8303 	if (flags & REPORT_FAILURE)
8304 		dump_page(pfn_to_page(pfn + iter), reason);
8305 	return true;
8306 }
8307 
8308 #ifdef CONFIG_CONTIG_ALLOC
pfn_max_align_down(unsigned long pfn)8309 static unsigned long pfn_max_align_down(unsigned long pfn)
8310 {
8311 	return pfn & ~(max_t(unsigned long, MAX_ORDER_NR_PAGES,
8312 			     pageblock_nr_pages) - 1);
8313 }
8314 
pfn_max_align_up(unsigned long pfn)8315 static unsigned long pfn_max_align_up(unsigned long pfn)
8316 {
8317 	return ALIGN(pfn, max_t(unsigned long, MAX_ORDER_NR_PAGES,
8318 				pageblock_nr_pages));
8319 }
8320 
8321 /* [start, end) must belong to a single zone. */
__alloc_contig_migrate_range(struct compact_control * cc,unsigned long start,unsigned long end)8322 static int __alloc_contig_migrate_range(struct compact_control *cc,
8323 					unsigned long start, unsigned long end)
8324 {
8325 	/* This function is based on compact_zone() from compaction.c. */
8326 	unsigned long nr_reclaimed;
8327 	unsigned long pfn = start;
8328 	unsigned int tries = 0;
8329 	int ret = 0;
8330 
8331 	migrate_prep();
8332 
8333 	while (pfn < end || !list_empty(&cc->migratepages)) {
8334 		if (fatal_signal_pending(current)) {
8335 			ret = -EINTR;
8336 			break;
8337 		}
8338 
8339 		if (list_empty(&cc->migratepages)) {
8340 			cc->nr_migratepages = 0;
8341 			pfn = isolate_migratepages_range(cc, pfn, end);
8342 			if (!pfn) {
8343 				ret = -EINTR;
8344 				break;
8345 			}
8346 			tries = 0;
8347 		} else if (++tries == 5) {
8348 			ret = ret < 0 ? ret : -EBUSY;
8349 			break;
8350 		}
8351 
8352 		nr_reclaimed = reclaim_clean_pages_from_list(cc->zone,
8353 							&cc->migratepages);
8354 		cc->nr_migratepages -= nr_reclaimed;
8355 
8356 		ret = migrate_pages(&cc->migratepages, alloc_migrate_target,
8357 				    NULL, 0, cc->mode, MR_CONTIG_RANGE);
8358 	}
8359 	if (ret < 0) {
8360 		putback_movable_pages(&cc->migratepages);
8361 		return ret;
8362 	}
8363 	return 0;
8364 }
8365 
8366 /**
8367  * alloc_contig_range() -- tries to allocate given range of pages
8368  * @start:	start PFN to allocate
8369  * @end:	one-past-the-last PFN to allocate
8370  * @migratetype:	migratetype of the underlaying pageblocks (either
8371  *			#MIGRATE_MOVABLE or #MIGRATE_CMA).  All pageblocks
8372  *			in range must have the same migratetype and it must
8373  *			be either of the two.
8374  * @gfp_mask:	GFP mask to use during compaction
8375  *
8376  * The PFN range does not have to be pageblock or MAX_ORDER_NR_PAGES
8377  * aligned.  The PFN range must belong to a single zone.
8378  *
8379  * The first thing this routine does is attempt to MIGRATE_ISOLATE all
8380  * pageblocks in the range.  Once isolated, the pageblocks should not
8381  * be modified by others.
8382  *
8383  * Return: zero on success or negative error code.  On success all
8384  * pages which PFN is in [start, end) are allocated for the caller and
8385  * need to be freed with free_contig_range().
8386  */
alloc_contig_range(unsigned long start,unsigned long end,unsigned migratetype,gfp_t gfp_mask)8387 int alloc_contig_range(unsigned long start, unsigned long end,
8388 		       unsigned migratetype, gfp_t gfp_mask)
8389 {
8390 	unsigned long outer_start, outer_end;
8391 	unsigned int order;
8392 	int ret = 0;
8393 
8394 	struct compact_control cc = {
8395 		.nr_migratepages = 0,
8396 		.order = -1,
8397 		.zone = page_zone(pfn_to_page(start)),
8398 		.mode = MIGRATE_SYNC,
8399 		.ignore_skip_hint = true,
8400 		.no_set_skip_hint = true,
8401 		.gfp_mask = current_gfp_context(gfp_mask),
8402 	};
8403 	INIT_LIST_HEAD(&cc.migratepages);
8404 
8405 	/*
8406 	 * What we do here is we mark all pageblocks in range as
8407 	 * MIGRATE_ISOLATE.  Because pageblock and max order pages may
8408 	 * have different sizes, and due to the way page allocator
8409 	 * work, we align the range to biggest of the two pages so
8410 	 * that page allocator won't try to merge buddies from
8411 	 * different pageblocks and change MIGRATE_ISOLATE to some
8412 	 * other migration type.
8413 	 *
8414 	 * Once the pageblocks are marked as MIGRATE_ISOLATE, we
8415 	 * migrate the pages from an unaligned range (ie. pages that
8416 	 * we are interested in).  This will put all the pages in
8417 	 * range back to page allocator as MIGRATE_ISOLATE.
8418 	 *
8419 	 * When this is done, we take the pages in range from page
8420 	 * allocator removing them from the buddy system.  This way
8421 	 * page allocator will never consider using them.
8422 	 *
8423 	 * This lets us mark the pageblocks back as
8424 	 * MIGRATE_CMA/MIGRATE_MOVABLE so that free pages in the
8425 	 * aligned range but not in the unaligned, original range are
8426 	 * put back to page allocator so that buddy can use them.
8427 	 */
8428 
8429 	ret = start_isolate_page_range(pfn_max_align_down(start),
8430 				       pfn_max_align_up(end), migratetype, 0);
8431 	if (ret < 0)
8432 		return ret;
8433 
8434 	/*
8435 	 * In case of -EBUSY, we'd like to know which page causes problem.
8436 	 * So, just fall through. test_pages_isolated() has a tracepoint
8437 	 * which will report the busy page.
8438 	 *
8439 	 * It is possible that busy pages could become available before
8440 	 * the call to test_pages_isolated, and the range will actually be
8441 	 * allocated.  So, if we fall through be sure to clear ret so that
8442 	 * -EBUSY is not accidentally used or returned to caller.
8443 	 */
8444 	ret = __alloc_contig_migrate_range(&cc, start, end);
8445 	if (ret && ret != -EBUSY)
8446 		goto done;
8447 	ret =0;
8448 
8449 	/*
8450 	 * Pages from [start, end) are within a MAX_ORDER_NR_PAGES
8451 	 * aligned blocks that are marked as MIGRATE_ISOLATE.  What's
8452 	 * more, all pages in [start, end) are free in page allocator.
8453 	 * What we are going to do is to allocate all pages from
8454 	 * [start, end) (that is remove them from page allocator).
8455 	 *
8456 	 * The only problem is that pages at the beginning and at the
8457 	 * end of interesting range may be not aligned with pages that
8458 	 * page allocator holds, ie. they can be part of higher order
8459 	 * pages.  Because of this, we reserve the bigger range and
8460 	 * once this is done free the pages we are not interested in.
8461 	 *
8462 	 * We don't have to hold zone->lock here because the pages are
8463 	 * isolated thus they won't get removed from buddy.
8464 	 */
8465 
8466 	lru_add_drain_all();
8467 
8468 	order = 0;
8469 	outer_start = start;
8470 	while (!PageBuddy(pfn_to_page(outer_start))) {
8471 		if (++order >= MAX_ORDER) {
8472 			outer_start = start;
8473 			break;
8474 		}
8475 		outer_start &= ~0UL << order;
8476 	}
8477 
8478 	if (outer_start != start) {
8479 		order = page_order(pfn_to_page(outer_start));
8480 
8481 		/*
8482 		 * outer_start page could be small order buddy page and
8483 		 * it doesn't include start page. Adjust outer_start
8484 		 * in this case to report failed page properly
8485 		 * on tracepoint in test_pages_isolated()
8486 		 */
8487 		if (outer_start + (1UL << order) <= start)
8488 			outer_start = start;
8489 	}
8490 
8491 	/* Make sure the range is really isolated. */
8492 	if (test_pages_isolated(outer_start, end, false)) {
8493 		pr_info_ratelimited("%s: [%lx, %lx) PFNs busy\n",
8494 			__func__, outer_start, end);
8495 		ret = -EBUSY;
8496 		goto done;
8497 	}
8498 
8499 	/* Grab isolated pages from freelists. */
8500 	outer_end = isolate_freepages_range(&cc, outer_start, end);
8501 	if (!outer_end) {
8502 		ret = -EBUSY;
8503 		goto done;
8504 	}
8505 
8506 	/* Free head and tail (if any) */
8507 	if (start != outer_start)
8508 		free_contig_range(outer_start, start - outer_start);
8509 	if (end != outer_end)
8510 		free_contig_range(end, outer_end - end);
8511 
8512 done:
8513 	undo_isolate_page_range(pfn_max_align_down(start),
8514 				pfn_max_align_up(end), migratetype);
8515 	return ret;
8516 }
8517 #endif /* CONFIG_CONTIG_ALLOC */
8518 
free_contig_range(unsigned long pfn,unsigned int nr_pages)8519 void free_contig_range(unsigned long pfn, unsigned int nr_pages)
8520 {
8521 	unsigned int count = 0;
8522 
8523 	for (; nr_pages--; pfn++) {
8524 		struct page *page = pfn_to_page(pfn);
8525 
8526 		count += page_count(page) != 1;
8527 		__free_page(page);
8528 	}
8529 	WARN(count != 0, "%d pages are still in use!\n", count);
8530 }
8531 
8532 /*
8533  * The zone indicated has a new number of managed_pages; batch sizes and percpu
8534  * page high values need to be recalulated.
8535  */
zone_pcp_update(struct zone * zone)8536 void __meminit zone_pcp_update(struct zone *zone)
8537 {
8538 	unsigned cpu;
8539 	mutex_lock(&pcp_batch_high_lock);
8540 	for_each_possible_cpu(cpu)
8541 		pageset_set_high_and_batch(zone,
8542 				per_cpu_ptr(zone->pageset, cpu));
8543 	mutex_unlock(&pcp_batch_high_lock);
8544 }
8545 
zone_pcp_reset(struct zone * zone)8546 void zone_pcp_reset(struct zone *zone)
8547 {
8548 	unsigned long flags;
8549 	int cpu;
8550 	struct per_cpu_pageset *pset;
8551 
8552 	/* avoid races with drain_pages()  */
8553 	local_irq_save(flags);
8554 	if (zone->pageset != &boot_pageset) {
8555 		for_each_online_cpu(cpu) {
8556 			pset = per_cpu_ptr(zone->pageset, cpu);
8557 			drain_zonestat(zone, pset);
8558 		}
8559 		free_percpu(zone->pageset);
8560 		zone->pageset = &boot_pageset;
8561 	}
8562 	local_irq_restore(flags);
8563 }
8564 
8565 #ifdef CONFIG_MEMORY_HOTREMOVE
8566 /*
8567  * All pages in the range must be in a single zone and isolated
8568  * before calling this.
8569  */
8570 unsigned long
__offline_isolated_pages(unsigned long start_pfn,unsigned long end_pfn)8571 __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn)
8572 {
8573 	struct page *page;
8574 	struct zone *zone;
8575 	unsigned int order, i;
8576 	unsigned long pfn;
8577 	unsigned long flags;
8578 	unsigned long offlined_pages = 0;
8579 
8580 	/* find the first valid pfn */
8581 	for (pfn = start_pfn; pfn < end_pfn; pfn++)
8582 		if (pfn_valid(pfn))
8583 			break;
8584 	if (pfn == end_pfn)
8585 		return offlined_pages;
8586 
8587 	offline_mem_sections(pfn, end_pfn);
8588 	zone = page_zone(pfn_to_page(pfn));
8589 	spin_lock_irqsave(&zone->lock, flags);
8590 	pfn = start_pfn;
8591 	while (pfn < end_pfn) {
8592 		if (!pfn_valid(pfn)) {
8593 			pfn++;
8594 			continue;
8595 		}
8596 		page = pfn_to_page(pfn);
8597 		/*
8598 		 * The HWPoisoned page may be not in buddy system, and
8599 		 * page_count() is not 0.
8600 		 */
8601 		if (unlikely(!PageBuddy(page) && PageHWPoison(page))) {
8602 			pfn++;
8603 			SetPageReserved(page);
8604 			offlined_pages++;
8605 			continue;
8606 		}
8607 
8608 		BUG_ON(page_count(page));
8609 		BUG_ON(!PageBuddy(page));
8610 		order = page_order(page);
8611 		offlined_pages += 1 << order;
8612 #ifdef CONFIG_DEBUG_VM
8613 		pr_info("remove from free list %lx %d %lx\n",
8614 			pfn, 1 << order, end_pfn);
8615 #endif
8616 		del_page_from_free_area(page, &zone->free_area[order]);
8617 		for (i = 0; i < (1 << order); i++)
8618 			SetPageReserved((page+i));
8619 		pfn += (1 << order);
8620 	}
8621 	spin_unlock_irqrestore(&zone->lock, flags);
8622 
8623 	return offlined_pages;
8624 }
8625 #endif
8626 
is_free_buddy_page(struct page * page)8627 bool is_free_buddy_page(struct page *page)
8628 {
8629 	struct zone *zone = page_zone(page);
8630 	unsigned long pfn = page_to_pfn(page);
8631 	unsigned long flags;
8632 	unsigned int order;
8633 
8634 	spin_lock_irqsave(&zone->lock, flags);
8635 	for (order = 0; order < MAX_ORDER; order++) {
8636 		struct page *page_head = page - (pfn & ((1 << order) - 1));
8637 
8638 		if (PageBuddy(page_head) && page_order(page_head) >= order)
8639 			break;
8640 	}
8641 	spin_unlock_irqrestore(&zone->lock, flags);
8642 
8643 	return order < MAX_ORDER;
8644 }
8645 
8646 #ifdef CONFIG_MEMORY_FAILURE
8647 /*
8648  * Set PG_hwpoison flag if a given page is confirmed to be a free page.  This
8649  * test is performed under the zone lock to prevent a race against page
8650  * allocation.
8651  */
set_hwpoison_free_buddy_page(struct page * page)8652 bool set_hwpoison_free_buddy_page(struct page *page)
8653 {
8654 	struct zone *zone = page_zone(page);
8655 	unsigned long pfn = page_to_pfn(page);
8656 	unsigned long flags;
8657 	unsigned int order;
8658 	bool hwpoisoned = false;
8659 
8660 	spin_lock_irqsave(&zone->lock, flags);
8661 	for (order = 0; order < MAX_ORDER; order++) {
8662 		struct page *page_head = page - (pfn & ((1 << order) - 1));
8663 
8664 		if (PageBuddy(page_head) && page_order(page_head) >= order) {
8665 			if (!TestSetPageHWPoison(page))
8666 				hwpoisoned = true;
8667 			break;
8668 		}
8669 	}
8670 	spin_unlock_irqrestore(&zone->lock, flags);
8671 
8672 	return hwpoisoned;
8673 }
8674 #endif
8675