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