xref: /linux/mm/mm_init.c (revision 4127e13c9302f6892f73793f133ea4b4fffb2964)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * mm_init.c - Memory initialisation verification and debugging
4  *
5  * Copyright 2008 IBM Corporation, 2008
6  * Author Mel Gorman <mel@csn.ul.ie>
7  *
8  */
9 #include <linux/kernel.h>
10 #include <linux/init.h>
11 #include <linux/kobject.h>
12 #include <linux/export.h>
13 #include <linux/memory.h>
14 #include <linux/notifier.h>
15 #include <linux/sched.h>
16 #include <linux/mman.h>
17 #include <linux/memblock.h>
18 #include <linux/page-isolation.h>
19 #include <linux/padata.h>
20 #include <linux/nmi.h>
21 #include <linux/buffer_head.h>
22 #include <linux/kmemleak.h>
23 #include <linux/kfence.h>
24 #include <linux/page_ext.h>
25 #include <linux/pti.h>
26 #include <linux/pgtable.h>
27 #include <linux/stackdepot.h>
28 #include <linux/swap.h>
29 #include <linux/cma.h>
30 #include <linux/crash_dump.h>
31 #include <linux/execmem.h>
32 #include <linux/vmstat.h>
33 #include <linux/hugetlb.h>
34 #include "internal.h"
35 #include "slab.h"
36 #include "shuffle.h"
37 
38 #include <asm/setup.h>
39 
40 #ifdef CONFIG_DEBUG_MEMORY_INIT
41 int __meminitdata mminit_loglevel;
42 
43 /* The zonelists are simply reported, validation is manual. */
44 void __init mminit_verify_zonelist(void)
45 {
46 	int nid;
47 
48 	if (mminit_loglevel < MMINIT_VERIFY)
49 		return;
50 
51 	for_each_online_node(nid) {
52 		pg_data_t *pgdat = NODE_DATA(nid);
53 		struct zone *zone;
54 		struct zoneref *z;
55 		struct zonelist *zonelist;
56 		int i, listid, zoneid;
57 
58 		for (i = 0; i < MAX_ZONELISTS * MAX_NR_ZONES; i++) {
59 
60 			/* Identify the zone and nodelist */
61 			zoneid = i % MAX_NR_ZONES;
62 			listid = i / MAX_NR_ZONES;
63 			zonelist = &pgdat->node_zonelists[listid];
64 			zone = &pgdat->node_zones[zoneid];
65 			if (!populated_zone(zone))
66 				continue;
67 
68 			/* Print information about the zonelist */
69 			printk(KERN_DEBUG "mminit::zonelist %s %d:%s = ",
70 				listid > 0 ? "thisnode" : "general", nid,
71 				zone->name);
72 
73 			/* Iterate the zonelist */
74 			for_each_zone_zonelist(zone, z, zonelist, zoneid)
75 				pr_cont("%d:%s ", zone_to_nid(zone), zone->name);
76 			pr_cont("\n");
77 		}
78 	}
79 }
80 
81 void __init mminit_verify_pageflags_layout(void)
82 {
83 	int shift, width;
84 	unsigned long or_mask, add_mask;
85 
86 	shift = BITS_PER_LONG;
87 	width = shift - NR_NON_PAGEFLAG_BITS;
88 	mminit_dprintk(MMINIT_TRACE, "pageflags_layout_widths",
89 		"Section %d Node %d Zone %d Lastcpupid %d Kasantag %d Gen %d Tier %d Flags %d\n",
90 		SECTIONS_WIDTH,
91 		NODES_WIDTH,
92 		ZONES_WIDTH,
93 		LAST_CPUPID_WIDTH,
94 		KASAN_TAG_WIDTH,
95 		LRU_GEN_WIDTH,
96 		LRU_REFS_WIDTH,
97 		NR_PAGEFLAGS);
98 	mminit_dprintk(MMINIT_TRACE, "pageflags_layout_shifts",
99 		"Section %d Node %d Zone %d Lastcpupid %d Kasantag %d\n",
100 		SECTIONS_SHIFT,
101 		NODES_SHIFT,
102 		ZONES_SHIFT,
103 		LAST_CPUPID_SHIFT,
104 		KASAN_TAG_WIDTH);
105 	mminit_dprintk(MMINIT_TRACE, "pageflags_layout_pgshifts",
106 		"Section %lu Node %lu Zone %lu Lastcpupid %lu Kasantag %lu\n",
107 		(unsigned long)SECTIONS_PGSHIFT,
108 		(unsigned long)NODES_PGSHIFT,
109 		(unsigned long)ZONES_PGSHIFT,
110 		(unsigned long)LAST_CPUPID_PGSHIFT,
111 		(unsigned long)KASAN_TAG_PGSHIFT);
112 	mminit_dprintk(MMINIT_TRACE, "pageflags_layout_nodezoneid",
113 		"Node/Zone ID: %lu -> %lu\n",
114 		(unsigned long)(ZONEID_PGOFF + ZONEID_SHIFT),
115 		(unsigned long)ZONEID_PGOFF);
116 	mminit_dprintk(MMINIT_TRACE, "pageflags_layout_usage",
117 		"location: %d -> %d layout %d -> %d unused %d -> %d page-flags\n",
118 		shift, width, width, NR_PAGEFLAGS, NR_PAGEFLAGS, 0);
119 #ifdef NODE_NOT_IN_PAGE_FLAGS
120 	mminit_dprintk(MMINIT_TRACE, "pageflags_layout_nodeflags",
121 		"Node not in page flags");
122 #endif
123 #ifdef LAST_CPUPID_NOT_IN_PAGE_FLAGS
124 	mminit_dprintk(MMINIT_TRACE, "pageflags_layout_nodeflags",
125 		"Last cpupid not in page flags");
126 #endif
127 
128 	if (SECTIONS_WIDTH) {
129 		shift -= SECTIONS_WIDTH;
130 		BUG_ON(shift != SECTIONS_PGSHIFT);
131 	}
132 	if (NODES_WIDTH) {
133 		shift -= NODES_WIDTH;
134 		BUG_ON(shift != NODES_PGSHIFT);
135 	}
136 	if (ZONES_WIDTH) {
137 		shift -= ZONES_WIDTH;
138 		BUG_ON(shift != ZONES_PGSHIFT);
139 	}
140 
141 	/* Check for bitmask overlaps */
142 	or_mask = (ZONES_MASK << ZONES_PGSHIFT) |
143 			(NODES_MASK << NODES_PGSHIFT) |
144 			(SECTIONS_MASK << SECTIONS_PGSHIFT);
145 	add_mask = (ZONES_MASK << ZONES_PGSHIFT) +
146 			(NODES_MASK << NODES_PGSHIFT) +
147 			(SECTIONS_MASK << SECTIONS_PGSHIFT);
148 	BUG_ON(or_mask != add_mask);
149 }
150 
151 static __init int set_mminit_loglevel(char *str)
152 {
153 	get_option(&str, &mminit_loglevel);
154 	return 0;
155 }
156 early_param("mminit_loglevel", set_mminit_loglevel);
157 #endif /* CONFIG_DEBUG_MEMORY_INIT */
158 
159 struct kobject *mm_kobj;
160 
161 #ifdef CONFIG_SMP
162 s32 vm_committed_as_batch = 32;
163 
164 void mm_compute_batch(int overcommit_policy)
165 {
166 	u64 memsized_batch;
167 	s32 nr = num_present_cpus();
168 	s32 batch = max_t(s32, nr*2, 32);
169 	unsigned long ram_pages = totalram_pages();
170 
171 	/*
172 	 * For policy OVERCOMMIT_NEVER, set batch size to 0.4% of
173 	 * (total memory/#cpus), and lift it to 25% for other policies
174 	 * to easy the possible lock contention for percpu_counter
175 	 * vm_committed_as, while the max limit is INT_MAX
176 	 */
177 	if (overcommit_policy == OVERCOMMIT_NEVER)
178 		memsized_batch = min_t(u64, ram_pages/nr/256, INT_MAX);
179 	else
180 		memsized_batch = min_t(u64, ram_pages/nr/4, INT_MAX);
181 
182 	vm_committed_as_batch = max_t(s32, memsized_batch, batch);
183 }
184 
185 static int __meminit mm_compute_batch_notifier(struct notifier_block *self,
186 					unsigned long action, void *arg)
187 {
188 	switch (action) {
189 	case MEM_ONLINE:
190 	case MEM_OFFLINE:
191 		mm_compute_batch(sysctl_overcommit_memory);
192 		break;
193 	default:
194 		break;
195 	}
196 	return NOTIFY_OK;
197 }
198 
199 static int __init mm_compute_batch_init(void)
200 {
201 	mm_compute_batch(sysctl_overcommit_memory);
202 	hotplug_memory_notifier(mm_compute_batch_notifier, MM_COMPUTE_BATCH_PRI);
203 	return 0;
204 }
205 
206 __initcall(mm_compute_batch_init);
207 
208 #endif
209 
210 static int __init mm_sysfs_init(void)
211 {
212 	mm_kobj = kobject_create_and_add("mm", kernel_kobj);
213 	if (!mm_kobj)
214 		return -ENOMEM;
215 
216 	return 0;
217 }
218 postcore_initcall(mm_sysfs_init);
219 
220 static unsigned long arch_zone_lowest_possible_pfn[MAX_NR_ZONES] __initdata;
221 static unsigned long arch_zone_highest_possible_pfn[MAX_NR_ZONES] __initdata;
222 static unsigned long zone_movable_pfn[MAX_NUMNODES] __initdata;
223 
224 static unsigned long required_kernelcore __initdata;
225 static unsigned long required_kernelcore_percent __initdata;
226 static unsigned long required_movablecore __initdata;
227 static unsigned long required_movablecore_percent __initdata;
228 
229 static unsigned long nr_kernel_pages __initdata;
230 static unsigned long nr_all_pages __initdata;
231 
232 static bool deferred_struct_pages __meminitdata;
233 
234 static DEFINE_PER_CPU(struct per_cpu_nodestat, boot_nodestats);
235 
236 static int __init cmdline_parse_core(char *p, unsigned long *core,
237 				     unsigned long *percent)
238 {
239 	unsigned long long coremem;
240 	char *endptr;
241 
242 	if (!p)
243 		return -EINVAL;
244 
245 	/* Value may be a percentage of total memory, otherwise bytes */
246 	coremem = simple_strtoull(p, &endptr, 0);
247 	if (*endptr == '%') {
248 		/* Paranoid check for percent values greater than 100 */
249 		WARN_ON(coremem > 100);
250 
251 		*percent = coremem;
252 	} else {
253 		coremem = memparse(p, &p);
254 		/* Paranoid check that UL is enough for the coremem value */
255 		WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX);
256 
257 		*core = coremem >> PAGE_SHIFT;
258 		*percent = 0UL;
259 	}
260 	return 0;
261 }
262 
263 bool mirrored_kernelcore __initdata_memblock;
264 
265 /*
266  * kernelcore=size sets the amount of memory for use for allocations that
267  * cannot be reclaimed or migrated.
268  */
269 static int __init cmdline_parse_kernelcore(char *p)
270 {
271 	/* parse kernelcore=mirror */
272 	if (parse_option_str(p, "mirror")) {
273 		mirrored_kernelcore = true;
274 		return 0;
275 	}
276 
277 	return cmdline_parse_core(p, &required_kernelcore,
278 				  &required_kernelcore_percent);
279 }
280 early_param("kernelcore", cmdline_parse_kernelcore);
281 
282 /*
283  * movablecore=size sets the amount of memory for use for allocations that
284  * can be reclaimed or migrated.
285  */
286 static int __init cmdline_parse_movablecore(char *p)
287 {
288 	return cmdline_parse_core(p, &required_movablecore,
289 				  &required_movablecore_percent);
290 }
291 early_param("movablecore", cmdline_parse_movablecore);
292 
293 /*
294  * early_calculate_totalpages()
295  * Sum pages in active regions for movable zone.
296  * Populate N_MEMORY for calculating usable_nodes.
297  */
298 static unsigned long __init early_calculate_totalpages(void)
299 {
300 	unsigned long totalpages = 0;
301 	unsigned long start_pfn, end_pfn;
302 	int i, nid;
303 
304 	for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
305 		unsigned long pages = end_pfn - start_pfn;
306 
307 		totalpages += pages;
308 		if (pages)
309 			node_set_state(nid, N_MEMORY);
310 	}
311 	return totalpages;
312 }
313 
314 /*
315  * This finds a zone that can be used for ZONE_MOVABLE pages. The
316  * assumption is made that zones within a node are ordered in monotonic
317  * increasing memory addresses so that the "highest" populated zone is used
318  */
319 static void __init find_usable_zone_for_movable(void)
320 {
321 	int zone_index;
322 	for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) {
323 		if (zone_index == ZONE_MOVABLE)
324 			continue;
325 
326 		if (arch_zone_highest_possible_pfn[zone_index] >
327 				arch_zone_lowest_possible_pfn[zone_index])
328 			break;
329 	}
330 
331 	VM_BUG_ON(zone_index == -1);
332 	movable_zone = zone_index;
333 }
334 
335 /*
336  * Find the PFN the Movable zone begins in each node. Kernel memory
337  * is spread evenly between nodes as long as the nodes have enough
338  * memory. When they don't, some nodes will have more kernelcore than
339  * others
340  */
341 static void __init find_zone_movable_pfns_for_nodes(void)
342 {
343 	int i, nid;
344 	unsigned long usable_startpfn;
345 	unsigned long kernelcore_node, kernelcore_remaining;
346 	/* save the state before borrow the nodemask */
347 	nodemask_t saved_node_state = node_states[N_MEMORY];
348 	unsigned long totalpages = early_calculate_totalpages();
349 	int usable_nodes = nodes_weight(node_states[N_MEMORY]);
350 	struct memblock_region *r;
351 
352 	/* Need to find movable_zone earlier when movable_node is specified. */
353 	find_usable_zone_for_movable();
354 
355 	/*
356 	 * If movable_node is specified, ignore kernelcore and movablecore
357 	 * options.
358 	 */
359 	if (movable_node_is_enabled()) {
360 		for_each_mem_region(r) {
361 			if (!memblock_is_hotpluggable(r))
362 				continue;
363 
364 			nid = memblock_get_region_node(r);
365 
366 			usable_startpfn = memblock_region_memory_base_pfn(r);
367 			zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
368 				min(usable_startpfn, zone_movable_pfn[nid]) :
369 				usable_startpfn;
370 		}
371 
372 		goto out2;
373 	}
374 
375 	/*
376 	 * If kernelcore=mirror is specified, ignore movablecore option
377 	 */
378 	if (mirrored_kernelcore) {
379 		bool mem_below_4gb_not_mirrored = false;
380 
381 		if (!memblock_has_mirror()) {
382 			pr_warn("The system has no mirror memory, ignore kernelcore=mirror.\n");
383 			goto out;
384 		}
385 
386 		if (is_kdump_kernel()) {
387 			pr_warn("The system is under kdump, ignore kernelcore=mirror.\n");
388 			goto out;
389 		}
390 
391 		for_each_mem_region(r) {
392 			if (memblock_is_mirror(r))
393 				continue;
394 
395 			nid = memblock_get_region_node(r);
396 
397 			usable_startpfn = memblock_region_memory_base_pfn(r);
398 
399 			if (usable_startpfn < PHYS_PFN(SZ_4G)) {
400 				mem_below_4gb_not_mirrored = true;
401 				continue;
402 			}
403 
404 			zone_movable_pfn[nid] = zone_movable_pfn[nid] ?
405 				min(usable_startpfn, zone_movable_pfn[nid]) :
406 				usable_startpfn;
407 		}
408 
409 		if (mem_below_4gb_not_mirrored)
410 			pr_warn("This configuration results in unmirrored kernel memory.\n");
411 
412 		goto out2;
413 	}
414 
415 	/*
416 	 * If kernelcore=nn% or movablecore=nn% was specified, calculate the
417 	 * amount of necessary memory.
418 	 */
419 	if (required_kernelcore_percent)
420 		required_kernelcore = (totalpages * 100 * required_kernelcore_percent) /
421 				       10000UL;
422 	if (required_movablecore_percent)
423 		required_movablecore = (totalpages * 100 * required_movablecore_percent) /
424 					10000UL;
425 
426 	/*
427 	 * If movablecore= was specified, calculate what size of
428 	 * kernelcore that corresponds so that memory usable for
429 	 * any allocation type is evenly spread. If both kernelcore
430 	 * and movablecore are specified, then the value of kernelcore
431 	 * will be used for required_kernelcore if it's greater than
432 	 * what movablecore would have allowed.
433 	 */
434 	if (required_movablecore) {
435 		unsigned long corepages;
436 
437 		/*
438 		 * Round-up so that ZONE_MOVABLE is at least as large as what
439 		 * was requested by the user
440 		 */
441 		required_movablecore =
442 			round_up(required_movablecore, MAX_ORDER_NR_PAGES);
443 		required_movablecore = min(totalpages, required_movablecore);
444 		corepages = totalpages - required_movablecore;
445 
446 		required_kernelcore = max(required_kernelcore, corepages);
447 	}
448 
449 	/*
450 	 * If kernelcore was not specified or kernelcore size is larger
451 	 * than totalpages, there is no ZONE_MOVABLE.
452 	 */
453 	if (!required_kernelcore || required_kernelcore >= totalpages)
454 		goto out;
455 
456 	/* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */
457 	usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone];
458 
459 restart:
460 	/* Spread kernelcore memory as evenly as possible throughout nodes */
461 	kernelcore_node = required_kernelcore / usable_nodes;
462 	for_each_node_state(nid, N_MEMORY) {
463 		unsigned long start_pfn, end_pfn;
464 
465 		/*
466 		 * Recalculate kernelcore_node if the division per node
467 		 * now exceeds what is necessary to satisfy the requested
468 		 * amount of memory for the kernel
469 		 */
470 		if (required_kernelcore < kernelcore_node)
471 			kernelcore_node = required_kernelcore / usable_nodes;
472 
473 		/*
474 		 * As the map is walked, we track how much memory is usable
475 		 * by the kernel using kernelcore_remaining. When it is
476 		 * 0, the rest of the node is usable by ZONE_MOVABLE
477 		 */
478 		kernelcore_remaining = kernelcore_node;
479 
480 		/* Go through each range of PFNs within this node */
481 		for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
482 			unsigned long size_pages;
483 
484 			start_pfn = max(start_pfn, zone_movable_pfn[nid]);
485 			if (start_pfn >= end_pfn)
486 				continue;
487 
488 			/* Account for what is only usable for kernelcore */
489 			if (start_pfn < usable_startpfn) {
490 				unsigned long kernel_pages;
491 				kernel_pages = min(end_pfn, usable_startpfn)
492 								- start_pfn;
493 
494 				kernelcore_remaining -= min(kernel_pages,
495 							kernelcore_remaining);
496 				required_kernelcore -= min(kernel_pages,
497 							required_kernelcore);
498 
499 				/* Continue if range is now fully accounted */
500 				if (end_pfn <= usable_startpfn) {
501 
502 					/*
503 					 * Push zone_movable_pfn to the end so
504 					 * that if we have to rebalance
505 					 * kernelcore across nodes, we will
506 					 * not double account here
507 					 */
508 					zone_movable_pfn[nid] = end_pfn;
509 					continue;
510 				}
511 				start_pfn = usable_startpfn;
512 			}
513 
514 			/*
515 			 * The usable PFN range for ZONE_MOVABLE is from
516 			 * start_pfn->end_pfn. Calculate size_pages as the
517 			 * number of pages used as kernelcore
518 			 */
519 			size_pages = end_pfn - start_pfn;
520 			if (size_pages > kernelcore_remaining)
521 				size_pages = kernelcore_remaining;
522 			zone_movable_pfn[nid] = start_pfn + size_pages;
523 
524 			/*
525 			 * Some kernelcore has been met, update counts and
526 			 * break if the kernelcore for this node has been
527 			 * satisfied
528 			 */
529 			required_kernelcore -= min(required_kernelcore,
530 								size_pages);
531 			kernelcore_remaining -= size_pages;
532 			if (!kernelcore_remaining)
533 				break;
534 		}
535 	}
536 
537 	/*
538 	 * If there is still required_kernelcore, we do another pass with one
539 	 * less node in the count. This will push zone_movable_pfn[nid] further
540 	 * along on the nodes that still have memory until kernelcore is
541 	 * satisfied
542 	 */
543 	usable_nodes--;
544 	if (usable_nodes && required_kernelcore > usable_nodes)
545 		goto restart;
546 
547 out2:
548 	/* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */
549 	for_each_node_state(nid, N_MEMORY) {
550 		unsigned long start_pfn, end_pfn;
551 
552 		zone_movable_pfn[nid] =
553 			round_up(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES);
554 
555 		get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
556 		if (zone_movable_pfn[nid] >= end_pfn)
557 			zone_movable_pfn[nid] = 0;
558 	}
559 
560 out:
561 	/* restore the node_state */
562 	node_states[N_MEMORY] = saved_node_state;
563 }
564 
565 void __meminit __init_single_page(struct page *page, unsigned long pfn,
566 				unsigned long zone, int nid)
567 {
568 	mm_zero_struct_page(page);
569 	set_page_links(page, zone, nid, pfn);
570 	init_page_count(page);
571 	atomic_set(&page->_mapcount, -1);
572 	page_cpupid_reset_last(page);
573 	page_kasan_tag_reset(page);
574 
575 	INIT_LIST_HEAD(&page->lru);
576 #ifdef WANT_PAGE_VIRTUAL
577 	/* The shift won't overflow because ZONE_NORMAL is below 4G. */
578 	if (!is_highmem_idx(zone))
579 		set_page_address(page, __va(pfn << PAGE_SHIFT));
580 #endif
581 }
582 
583 #ifdef CONFIG_NUMA
584 /*
585  * During memory init memblocks map pfns to nids. The search is expensive and
586  * this caches recent lookups. The implementation of __early_pfn_to_nid
587  * treats start/end as pfns.
588  */
589 struct mminit_pfnnid_cache {
590 	unsigned long last_start;
591 	unsigned long last_end;
592 	int last_nid;
593 };
594 
595 static struct mminit_pfnnid_cache early_pfnnid_cache __meminitdata;
596 
597 /*
598  * Required by SPARSEMEM. Given a PFN, return what node the PFN is on.
599  */
600 static int __meminit __early_pfn_to_nid(unsigned long pfn,
601 					struct mminit_pfnnid_cache *state)
602 {
603 	unsigned long start_pfn, end_pfn;
604 	int nid;
605 
606 	if (state->last_start <= pfn && pfn < state->last_end)
607 		return state->last_nid;
608 
609 	nid = memblock_search_pfn_nid(pfn, &start_pfn, &end_pfn);
610 	if (nid != NUMA_NO_NODE) {
611 		state->last_start = start_pfn;
612 		state->last_end = end_pfn;
613 		state->last_nid = nid;
614 	}
615 
616 	return nid;
617 }
618 
619 int __meminit early_pfn_to_nid(unsigned long pfn)
620 {
621 	static DEFINE_SPINLOCK(early_pfn_lock);
622 	int nid;
623 
624 	spin_lock(&early_pfn_lock);
625 	nid = __early_pfn_to_nid(pfn, &early_pfnnid_cache);
626 	if (nid < 0)
627 		nid = first_online_node;
628 	spin_unlock(&early_pfn_lock);
629 
630 	return nid;
631 }
632 
633 int hashdist = HASHDIST_DEFAULT;
634 
635 static int __init set_hashdist(char *str)
636 {
637 	if (!str)
638 		return 0;
639 	hashdist = simple_strtoul(str, &str, 0);
640 	return 1;
641 }
642 __setup("hashdist=", set_hashdist);
643 
644 static inline void fixup_hashdist(void)
645 {
646 	if (num_node_state(N_MEMORY) == 1)
647 		hashdist = 0;
648 }
649 #else
650 static inline void fixup_hashdist(void) {}
651 #endif /* CONFIG_NUMA */
652 
653 /*
654  * Initialize a reserved page unconditionally, finding its zone first.
655  */
656 void __meminit __init_reserved_page_zone(unsigned long pfn, int nid)
657 {
658 	pg_data_t *pgdat;
659 	int zid;
660 
661 	pgdat = NODE_DATA(nid);
662 
663 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
664 		struct zone *zone = &pgdat->node_zones[zid];
665 
666 		if (zone_spans_pfn(zone, pfn))
667 			break;
668 	}
669 	__init_single_page(pfn_to_page(pfn), pfn, zid, nid);
670 
671 	if (pageblock_aligned(pfn))
672 		set_pageblock_migratetype(pfn_to_page(pfn), MIGRATE_MOVABLE);
673 }
674 
675 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
676 static inline void pgdat_set_deferred_range(pg_data_t *pgdat)
677 {
678 	pgdat->first_deferred_pfn = ULONG_MAX;
679 }
680 
681 /* Returns true if the struct page for the pfn is initialised */
682 static inline bool __meminit early_page_initialised(unsigned long pfn, int nid)
683 {
684 	if (node_online(nid) && pfn >= NODE_DATA(nid)->first_deferred_pfn)
685 		return false;
686 
687 	return true;
688 }
689 
690 /*
691  * Returns true when the remaining initialisation should be deferred until
692  * later in the boot cycle when it can be parallelised.
693  */
694 static bool __meminit
695 defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
696 {
697 	static unsigned long prev_end_pfn, nr_initialised;
698 
699 	if (early_page_ext_enabled())
700 		return false;
701 
702 	/* Always populate low zones for address-constrained allocations */
703 	if (end_pfn < pgdat_end_pfn(NODE_DATA(nid)))
704 		return false;
705 
706 	if (NODE_DATA(nid)->first_deferred_pfn != ULONG_MAX)
707 		return true;
708 
709 	/*
710 	 * prev_end_pfn static that contains the end of previous zone
711 	 * No need to protect because called very early in boot before smp_init.
712 	 */
713 	if (prev_end_pfn != end_pfn) {
714 		prev_end_pfn = end_pfn;
715 		nr_initialised = 0;
716 	}
717 
718 	/*
719 	 * We start only with one section of pages, more pages are added as
720 	 * needed until the rest of deferred pages are initialized.
721 	 */
722 	nr_initialised++;
723 	if ((nr_initialised > PAGES_PER_SECTION) &&
724 	    (pfn & (PAGES_PER_SECTION - 1)) == 0) {
725 		NODE_DATA(nid)->first_deferred_pfn = pfn;
726 		return true;
727 	}
728 	return false;
729 }
730 
731 static void __meminit init_reserved_page(unsigned long pfn, int nid)
732 {
733 	if (early_page_initialised(pfn, nid))
734 		return;
735 
736 	__init_reserved_page_zone(pfn, nid);
737 }
738 #else
739 static inline void pgdat_set_deferred_range(pg_data_t *pgdat) {}
740 
741 static inline bool early_page_initialised(unsigned long pfn, int nid)
742 {
743 	return true;
744 }
745 
746 static inline bool defer_init(int nid, unsigned long pfn, unsigned long end_pfn)
747 {
748 	return false;
749 }
750 
751 static inline void init_reserved_page(unsigned long pfn, int nid)
752 {
753 }
754 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
755 
756 /*
757  * Initialised pages do not have PageReserved set. This function is
758  * called for each range allocated by the bootmem allocator and
759  * marks the pages PageReserved. The remaining valid pages are later
760  * sent to the buddy page allocator.
761  */
762 void __meminit reserve_bootmem_region(phys_addr_t start,
763 				      phys_addr_t end, int nid)
764 {
765 	unsigned long start_pfn = PFN_DOWN(start);
766 	unsigned long end_pfn = PFN_UP(end);
767 
768 	for (; start_pfn < end_pfn; start_pfn++) {
769 		if (pfn_valid(start_pfn)) {
770 			struct page *page = pfn_to_page(start_pfn);
771 
772 			init_reserved_page(start_pfn, nid);
773 
774 			/*
775 			 * no need for atomic set_bit because the struct
776 			 * page is not visible yet so nobody should
777 			 * access it yet.
778 			 */
779 			__SetPageReserved(page);
780 		}
781 	}
782 }
783 
784 /* If zone is ZONE_MOVABLE but memory is mirrored, it is an overlapped init */
785 static bool __meminit
786 overlap_memmap_init(unsigned long zone, unsigned long *pfn)
787 {
788 	static struct memblock_region *r;
789 
790 	if (mirrored_kernelcore && zone == ZONE_MOVABLE) {
791 		if (!r || *pfn >= memblock_region_memory_end_pfn(r)) {
792 			for_each_mem_region(r) {
793 				if (*pfn < memblock_region_memory_end_pfn(r))
794 					break;
795 			}
796 		}
797 		if (*pfn >= memblock_region_memory_base_pfn(r) &&
798 		    memblock_is_mirror(r)) {
799 			*pfn = memblock_region_memory_end_pfn(r);
800 			return true;
801 		}
802 	}
803 	return false;
804 }
805 
806 /*
807  * Only struct pages that correspond to ranges defined by memblock.memory
808  * are zeroed and initialized by going through __init_single_page() during
809  * memmap_init_zone_range().
810  *
811  * But, there could be struct pages that correspond to holes in
812  * memblock.memory. This can happen because of the following reasons:
813  * - physical memory bank size is not necessarily the exact multiple of the
814  *   arbitrary section size
815  * - early reserved memory may not be listed in memblock.memory
816  * - non-memory regions covered by the contigious flatmem mapping
817  * - memory layouts defined with memmap= kernel parameter may not align
818  *   nicely with memmap sections
819  *
820  * Explicitly initialize those struct pages so that:
821  * - PG_Reserved is set
822  * - zone and node links point to zone and node that span the page if the
823  *   hole is in the middle of a zone
824  * - zone and node links point to adjacent zone/node if the hole falls on
825  *   the zone boundary; the pages in such holes will be prepended to the
826  *   zone/node above the hole except for the trailing pages in the last
827  *   section that will be appended to the zone/node below.
828  */
829 static void __init init_unavailable_range(unsigned long spfn,
830 					  unsigned long epfn,
831 					  int zone, int node)
832 {
833 	unsigned long pfn;
834 	u64 pgcnt = 0;
835 
836 	for (pfn = spfn; pfn < epfn; pfn++) {
837 		if (!pfn_valid(pageblock_start_pfn(pfn))) {
838 			pfn = pageblock_end_pfn(pfn) - 1;
839 			continue;
840 		}
841 		__init_single_page(pfn_to_page(pfn), pfn, zone, node);
842 		__SetPageReserved(pfn_to_page(pfn));
843 		pgcnt++;
844 	}
845 
846 	if (pgcnt)
847 		pr_info("On node %d, zone %s: %lld pages in unavailable ranges\n",
848 			node, zone_names[zone], pgcnt);
849 }
850 
851 /*
852  * Initially all pages are reserved - free ones are freed
853  * up by memblock_free_all() once the early boot process is
854  * done. Non-atomic initialization, single-pass.
855  *
856  * All aligned pageblocks are initialized to the specified migratetype
857  * (usually MIGRATE_MOVABLE). Besides setting the migratetype, no related
858  * zone stats (e.g., nr_isolate_pageblock) are touched.
859  */
860 void __meminit memmap_init_range(unsigned long size, int nid, unsigned long zone,
861 		unsigned long start_pfn, unsigned long zone_end_pfn,
862 		enum meminit_context context,
863 		struct vmem_altmap *altmap, int migratetype)
864 {
865 	unsigned long pfn, end_pfn = start_pfn + size;
866 	struct page *page;
867 
868 	if (highest_memmap_pfn < end_pfn - 1)
869 		highest_memmap_pfn = end_pfn - 1;
870 
871 #ifdef CONFIG_ZONE_DEVICE
872 	/*
873 	 * Honor reservation requested by the driver for this ZONE_DEVICE
874 	 * memory. We limit the total number of pages to initialize to just
875 	 * those that might contain the memory mapping. We will defer the
876 	 * ZONE_DEVICE page initialization until after we have released
877 	 * the hotplug lock.
878 	 */
879 	if (zone == ZONE_DEVICE) {
880 		if (!altmap)
881 			return;
882 
883 		if (start_pfn == altmap->base_pfn)
884 			start_pfn += altmap->reserve;
885 		end_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
886 	}
887 #endif
888 
889 	for (pfn = start_pfn; pfn < end_pfn; ) {
890 		/*
891 		 * There can be holes in boot-time mem_map[]s handed to this
892 		 * function.  They do not exist on hotplugged memory.
893 		 */
894 		if (context == MEMINIT_EARLY) {
895 			if (overlap_memmap_init(zone, &pfn))
896 				continue;
897 			if (defer_init(nid, pfn, zone_end_pfn)) {
898 				deferred_struct_pages = true;
899 				break;
900 			}
901 		}
902 
903 		page = pfn_to_page(pfn);
904 		__init_single_page(page, pfn, zone, nid);
905 		if (context == MEMINIT_HOTPLUG) {
906 #ifdef CONFIG_ZONE_DEVICE
907 			if (zone == ZONE_DEVICE)
908 				__SetPageReserved(page);
909 			else
910 #endif
911 				__SetPageOffline(page);
912 		}
913 
914 		/*
915 		 * Usually, we want to mark the pageblock MIGRATE_MOVABLE,
916 		 * such that unmovable allocations won't be scattered all
917 		 * over the place during system boot.
918 		 */
919 		if (pageblock_aligned(pfn)) {
920 			set_pageblock_migratetype(page, migratetype);
921 			cond_resched();
922 		}
923 		pfn++;
924 	}
925 }
926 
927 static void __init memmap_init_zone_range(struct zone *zone,
928 					  unsigned long start_pfn,
929 					  unsigned long end_pfn,
930 					  unsigned long *hole_pfn)
931 {
932 	unsigned long zone_start_pfn = zone->zone_start_pfn;
933 	unsigned long zone_end_pfn = zone_start_pfn + zone->spanned_pages;
934 	int nid = zone_to_nid(zone), zone_id = zone_idx(zone);
935 
936 	start_pfn = clamp(start_pfn, zone_start_pfn, zone_end_pfn);
937 	end_pfn = clamp(end_pfn, zone_start_pfn, zone_end_pfn);
938 
939 	if (start_pfn >= end_pfn)
940 		return;
941 
942 	memmap_init_range(end_pfn - start_pfn, nid, zone_id, start_pfn,
943 			  zone_end_pfn, MEMINIT_EARLY, NULL, MIGRATE_MOVABLE);
944 
945 	if (*hole_pfn < start_pfn)
946 		init_unavailable_range(*hole_pfn, start_pfn, zone_id, nid);
947 
948 	*hole_pfn = end_pfn;
949 }
950 
951 static void __init memmap_init(void)
952 {
953 	unsigned long start_pfn, end_pfn;
954 	unsigned long hole_pfn = 0;
955 	int i, j, zone_id = 0, nid;
956 
957 	for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
958 		struct pglist_data *node = NODE_DATA(nid);
959 
960 		for (j = 0; j < MAX_NR_ZONES; j++) {
961 			struct zone *zone = node->node_zones + j;
962 
963 			if (!populated_zone(zone))
964 				continue;
965 
966 			memmap_init_zone_range(zone, start_pfn, end_pfn,
967 					       &hole_pfn);
968 			zone_id = j;
969 		}
970 	}
971 
972 #ifdef CONFIG_SPARSEMEM
973 	/*
974 	 * Initialize the memory map for hole in the range [memory_end,
975 	 * section_end].
976 	 * Append the pages in this hole to the highest zone in the last
977 	 * node.
978 	 * The call to init_unavailable_range() is outside the ifdef to
979 	 * silence the compiler warining about zone_id set but not used;
980 	 * for FLATMEM it is a nop anyway
981 	 */
982 	end_pfn = round_up(end_pfn, PAGES_PER_SECTION);
983 	if (hole_pfn < end_pfn)
984 #endif
985 		init_unavailable_range(hole_pfn, end_pfn, zone_id, nid);
986 }
987 
988 #ifdef CONFIG_ZONE_DEVICE
989 static void __ref __init_zone_device_page(struct page *page, unsigned long pfn,
990 					  unsigned long zone_idx, int nid,
991 					  struct dev_pagemap *pgmap)
992 {
993 
994 	__init_single_page(page, pfn, zone_idx, nid);
995 
996 	/*
997 	 * Mark page reserved as it will need to wait for onlining
998 	 * phase for it to be fully associated with a zone.
999 	 *
1000 	 * We can use the non-atomic __set_bit operation for setting
1001 	 * the flag as we are still initializing the pages.
1002 	 */
1003 	__SetPageReserved(page);
1004 
1005 	/*
1006 	 * ZONE_DEVICE pages union ->lru with a ->pgmap back pointer
1007 	 * and zone_device_data.  It is a bug if a ZONE_DEVICE page is
1008 	 * ever freed or placed on a driver-private list.
1009 	 */
1010 	page->pgmap = pgmap;
1011 	page->zone_device_data = NULL;
1012 
1013 	/*
1014 	 * Mark the block movable so that blocks are reserved for
1015 	 * movable at startup. This will force kernel allocations
1016 	 * to reserve their blocks rather than leaking throughout
1017 	 * the address space during boot when many long-lived
1018 	 * kernel allocations are made.
1019 	 *
1020 	 * Please note that MEMINIT_HOTPLUG path doesn't clear memmap
1021 	 * because this is done early in section_activate()
1022 	 */
1023 	if (pageblock_aligned(pfn)) {
1024 		set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1025 		cond_resched();
1026 	}
1027 
1028 	/*
1029 	 * ZONE_DEVICE pages are released directly to the driver page allocator
1030 	 * which will set the page count to 1 when allocating the page.
1031 	 */
1032 	if (pgmap->type == MEMORY_DEVICE_PRIVATE ||
1033 	    pgmap->type == MEMORY_DEVICE_COHERENT)
1034 		set_page_count(page, 0);
1035 }
1036 
1037 /*
1038  * With compound page geometry and when struct pages are stored in ram most
1039  * tail pages are reused. Consequently, the amount of unique struct pages to
1040  * initialize is a lot smaller that the total amount of struct pages being
1041  * mapped. This is a paired / mild layering violation with explicit knowledge
1042  * of how the sparse_vmemmap internals handle compound pages in the lack
1043  * of an altmap. See vmemmap_populate_compound_pages().
1044  */
1045 static inline unsigned long compound_nr_pages(struct vmem_altmap *altmap,
1046 					      struct dev_pagemap *pgmap)
1047 {
1048 	if (!vmemmap_can_optimize(altmap, pgmap))
1049 		return pgmap_vmemmap_nr(pgmap);
1050 
1051 	return VMEMMAP_RESERVE_NR * (PAGE_SIZE / sizeof(struct page));
1052 }
1053 
1054 static void __ref memmap_init_compound(struct page *head,
1055 				       unsigned long head_pfn,
1056 				       unsigned long zone_idx, int nid,
1057 				       struct dev_pagemap *pgmap,
1058 				       unsigned long nr_pages)
1059 {
1060 	unsigned long pfn, end_pfn = head_pfn + nr_pages;
1061 	unsigned int order = pgmap->vmemmap_shift;
1062 
1063 	__SetPageHead(head);
1064 	for (pfn = head_pfn + 1; pfn < end_pfn; pfn++) {
1065 		struct page *page = pfn_to_page(pfn);
1066 
1067 		__init_zone_device_page(page, pfn, zone_idx, nid, pgmap);
1068 		prep_compound_tail(head, pfn - head_pfn);
1069 		set_page_count(page, 0);
1070 
1071 		/*
1072 		 * The first tail page stores important compound page info.
1073 		 * Call prep_compound_head() after the first tail page has
1074 		 * been initialized, to not have the data overwritten.
1075 		 */
1076 		if (pfn == head_pfn + 1)
1077 			prep_compound_head(head, order);
1078 	}
1079 }
1080 
1081 void __ref memmap_init_zone_device(struct zone *zone,
1082 				   unsigned long start_pfn,
1083 				   unsigned long nr_pages,
1084 				   struct dev_pagemap *pgmap)
1085 {
1086 	unsigned long pfn, end_pfn = start_pfn + nr_pages;
1087 	struct pglist_data *pgdat = zone->zone_pgdat;
1088 	struct vmem_altmap *altmap = pgmap_altmap(pgmap);
1089 	unsigned int pfns_per_compound = pgmap_vmemmap_nr(pgmap);
1090 	unsigned long zone_idx = zone_idx(zone);
1091 	unsigned long start = jiffies;
1092 	int nid = pgdat->node_id;
1093 
1094 	if (WARN_ON_ONCE(!pgmap || zone_idx != ZONE_DEVICE))
1095 		return;
1096 
1097 	/*
1098 	 * The call to memmap_init should have already taken care
1099 	 * of the pages reserved for the memmap, so we can just jump to
1100 	 * the end of that region and start processing the device pages.
1101 	 */
1102 	if (altmap) {
1103 		start_pfn = altmap->base_pfn + vmem_altmap_offset(altmap);
1104 		nr_pages = end_pfn - start_pfn;
1105 	}
1106 
1107 	for (pfn = start_pfn; pfn < end_pfn; pfn += pfns_per_compound) {
1108 		struct page *page = pfn_to_page(pfn);
1109 
1110 		__init_zone_device_page(page, pfn, zone_idx, nid, pgmap);
1111 
1112 		if (pfns_per_compound == 1)
1113 			continue;
1114 
1115 		memmap_init_compound(page, pfn, zone_idx, nid, pgmap,
1116 				     compound_nr_pages(altmap, pgmap));
1117 	}
1118 
1119 	pr_debug("%s initialised %lu pages in %ums\n", __func__,
1120 		nr_pages, jiffies_to_msecs(jiffies - start));
1121 }
1122 #endif
1123 
1124 /*
1125  * The zone ranges provided by the architecture do not include ZONE_MOVABLE
1126  * because it is sized independent of architecture. Unlike the other zones,
1127  * the starting point for ZONE_MOVABLE is not fixed. It may be different
1128  * in each node depending on the size of each node and how evenly kernelcore
1129  * is distributed. This helper function adjusts the zone ranges
1130  * provided by the architecture for a given node by using the end of the
1131  * highest usable zone for ZONE_MOVABLE. This preserves the assumption that
1132  * zones within a node are in order of monotonic increases memory addresses
1133  */
1134 static void __init adjust_zone_range_for_zone_movable(int nid,
1135 					unsigned long zone_type,
1136 					unsigned long node_end_pfn,
1137 					unsigned long *zone_start_pfn,
1138 					unsigned long *zone_end_pfn)
1139 {
1140 	/* Only adjust if ZONE_MOVABLE is on this node */
1141 	if (zone_movable_pfn[nid]) {
1142 		/* Size ZONE_MOVABLE */
1143 		if (zone_type == ZONE_MOVABLE) {
1144 			*zone_start_pfn = zone_movable_pfn[nid];
1145 			*zone_end_pfn = min(node_end_pfn,
1146 				arch_zone_highest_possible_pfn[movable_zone]);
1147 
1148 		/* Adjust for ZONE_MOVABLE starting within this range */
1149 		} else if (!mirrored_kernelcore &&
1150 			*zone_start_pfn < zone_movable_pfn[nid] &&
1151 			*zone_end_pfn > zone_movable_pfn[nid]) {
1152 			*zone_end_pfn = zone_movable_pfn[nid];
1153 
1154 		/* Check if this whole range is within ZONE_MOVABLE */
1155 		} else if (*zone_start_pfn >= zone_movable_pfn[nid])
1156 			*zone_start_pfn = *zone_end_pfn;
1157 	}
1158 }
1159 
1160 /*
1161  * Return the number of holes in a range on a node. If nid is MAX_NUMNODES,
1162  * then all holes in the requested range will be accounted for.
1163  */
1164 static unsigned long __init __absent_pages_in_range(int nid,
1165 				unsigned long range_start_pfn,
1166 				unsigned long range_end_pfn)
1167 {
1168 	unsigned long nr_absent = range_end_pfn - range_start_pfn;
1169 	unsigned long start_pfn, end_pfn;
1170 	int i;
1171 
1172 	for_each_mem_pfn_range(i, nid, &start_pfn, &end_pfn, NULL) {
1173 		start_pfn = clamp(start_pfn, range_start_pfn, range_end_pfn);
1174 		end_pfn = clamp(end_pfn, range_start_pfn, range_end_pfn);
1175 		nr_absent -= end_pfn - start_pfn;
1176 	}
1177 	return nr_absent;
1178 }
1179 
1180 /**
1181  * absent_pages_in_range - Return number of page frames in holes within a range
1182  * @start_pfn: The start PFN to start searching for holes
1183  * @end_pfn: The end PFN to stop searching for holes
1184  *
1185  * Return: the number of pages frames in memory holes within a range.
1186  */
1187 unsigned long __init absent_pages_in_range(unsigned long start_pfn,
1188 							unsigned long end_pfn)
1189 {
1190 	return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn);
1191 }
1192 
1193 /* Return the number of page frames in holes in a zone on a node */
1194 static unsigned long __init zone_absent_pages_in_node(int nid,
1195 					unsigned long zone_type,
1196 					unsigned long zone_start_pfn,
1197 					unsigned long zone_end_pfn)
1198 {
1199 	unsigned long nr_absent;
1200 
1201 	/* zone is empty, we don't have any absent pages */
1202 	if (zone_start_pfn == zone_end_pfn)
1203 		return 0;
1204 
1205 	nr_absent = __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn);
1206 
1207 	/*
1208 	 * ZONE_MOVABLE handling.
1209 	 * Treat pages to be ZONE_MOVABLE in ZONE_NORMAL as absent pages
1210 	 * and vice versa.
1211 	 */
1212 	if (mirrored_kernelcore && zone_movable_pfn[nid]) {
1213 		unsigned long start_pfn, end_pfn;
1214 		struct memblock_region *r;
1215 
1216 		for_each_mem_region(r) {
1217 			start_pfn = clamp(memblock_region_memory_base_pfn(r),
1218 					  zone_start_pfn, zone_end_pfn);
1219 			end_pfn = clamp(memblock_region_memory_end_pfn(r),
1220 					zone_start_pfn, zone_end_pfn);
1221 
1222 			if (zone_type == ZONE_MOVABLE &&
1223 			    memblock_is_mirror(r))
1224 				nr_absent += end_pfn - start_pfn;
1225 
1226 			if (zone_type == ZONE_NORMAL &&
1227 			    !memblock_is_mirror(r))
1228 				nr_absent += end_pfn - start_pfn;
1229 		}
1230 	}
1231 
1232 	return nr_absent;
1233 }
1234 
1235 /*
1236  * Return the number of pages a zone spans in a node, including holes
1237  * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node()
1238  */
1239 static unsigned long __init zone_spanned_pages_in_node(int nid,
1240 					unsigned long zone_type,
1241 					unsigned long node_start_pfn,
1242 					unsigned long node_end_pfn,
1243 					unsigned long *zone_start_pfn,
1244 					unsigned long *zone_end_pfn)
1245 {
1246 	unsigned long zone_low = arch_zone_lowest_possible_pfn[zone_type];
1247 	unsigned long zone_high = arch_zone_highest_possible_pfn[zone_type];
1248 
1249 	/* Get the start and end of the zone */
1250 	*zone_start_pfn = clamp(node_start_pfn, zone_low, zone_high);
1251 	*zone_end_pfn = clamp(node_end_pfn, zone_low, zone_high);
1252 	adjust_zone_range_for_zone_movable(nid, zone_type, node_end_pfn,
1253 					   zone_start_pfn, zone_end_pfn);
1254 
1255 	/* Check that this node has pages within the zone's required range */
1256 	if (*zone_end_pfn < node_start_pfn || *zone_start_pfn > node_end_pfn)
1257 		return 0;
1258 
1259 	/* Move the zone boundaries inside the node if necessary */
1260 	*zone_end_pfn = min(*zone_end_pfn, node_end_pfn);
1261 	*zone_start_pfn = max(*zone_start_pfn, node_start_pfn);
1262 
1263 	/* Return the spanned pages */
1264 	return *zone_end_pfn - *zone_start_pfn;
1265 }
1266 
1267 static void __init reset_memoryless_node_totalpages(struct pglist_data *pgdat)
1268 {
1269 	struct zone *z;
1270 
1271 	for (z = pgdat->node_zones; z < pgdat->node_zones + MAX_NR_ZONES; z++) {
1272 		z->zone_start_pfn = 0;
1273 		z->spanned_pages = 0;
1274 		z->present_pages = 0;
1275 #if defined(CONFIG_MEMORY_HOTPLUG)
1276 		z->present_early_pages = 0;
1277 #endif
1278 	}
1279 
1280 	pgdat->node_spanned_pages = 0;
1281 	pgdat->node_present_pages = 0;
1282 	pr_debug("On node %d totalpages: 0\n", pgdat->node_id);
1283 }
1284 
1285 static void __init calc_nr_kernel_pages(void)
1286 {
1287 	unsigned long start_pfn, end_pfn;
1288 	phys_addr_t start_addr, end_addr;
1289 	u64 u;
1290 #ifdef CONFIG_HIGHMEM
1291 	unsigned long high_zone_low = arch_zone_lowest_possible_pfn[ZONE_HIGHMEM];
1292 #endif
1293 
1294 	for_each_free_mem_range(u, NUMA_NO_NODE, MEMBLOCK_NONE, &start_addr, &end_addr, NULL) {
1295 		start_pfn = PFN_UP(start_addr);
1296 		end_pfn   = PFN_DOWN(end_addr);
1297 
1298 		if (start_pfn < end_pfn) {
1299 			nr_all_pages += end_pfn - start_pfn;
1300 #ifdef CONFIG_HIGHMEM
1301 			start_pfn = clamp(start_pfn, 0, high_zone_low);
1302 			end_pfn = clamp(end_pfn, 0, high_zone_low);
1303 #endif
1304 			nr_kernel_pages += end_pfn - start_pfn;
1305 		}
1306 	}
1307 }
1308 
1309 static void __init calculate_node_totalpages(struct pglist_data *pgdat,
1310 						unsigned long node_start_pfn,
1311 						unsigned long node_end_pfn)
1312 {
1313 	unsigned long realtotalpages = 0, totalpages = 0;
1314 	enum zone_type i;
1315 
1316 	for (i = 0; i < MAX_NR_ZONES; i++) {
1317 		struct zone *zone = pgdat->node_zones + i;
1318 		unsigned long zone_start_pfn, zone_end_pfn;
1319 		unsigned long spanned, absent;
1320 		unsigned long real_size;
1321 
1322 		spanned = zone_spanned_pages_in_node(pgdat->node_id, i,
1323 						     node_start_pfn,
1324 						     node_end_pfn,
1325 						     &zone_start_pfn,
1326 						     &zone_end_pfn);
1327 		absent = zone_absent_pages_in_node(pgdat->node_id, i,
1328 						   zone_start_pfn,
1329 						   zone_end_pfn);
1330 
1331 		real_size = spanned - absent;
1332 
1333 		if (spanned)
1334 			zone->zone_start_pfn = zone_start_pfn;
1335 		else
1336 			zone->zone_start_pfn = 0;
1337 		zone->spanned_pages = spanned;
1338 		zone->present_pages = real_size;
1339 #if defined(CONFIG_MEMORY_HOTPLUG)
1340 		zone->present_early_pages = real_size;
1341 #endif
1342 
1343 		totalpages += spanned;
1344 		realtotalpages += real_size;
1345 	}
1346 
1347 	pgdat->node_spanned_pages = totalpages;
1348 	pgdat->node_present_pages = realtotalpages;
1349 	pr_debug("On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages);
1350 }
1351 
1352 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1353 static void pgdat_init_split_queue(struct pglist_data *pgdat)
1354 {
1355 	struct deferred_split *ds_queue = &pgdat->deferred_split_queue;
1356 
1357 	spin_lock_init(&ds_queue->split_queue_lock);
1358 	INIT_LIST_HEAD(&ds_queue->split_queue);
1359 	ds_queue->split_queue_len = 0;
1360 }
1361 #else
1362 static void pgdat_init_split_queue(struct pglist_data *pgdat) {}
1363 #endif
1364 
1365 #ifdef CONFIG_COMPACTION
1366 static void pgdat_init_kcompactd(struct pglist_data *pgdat)
1367 {
1368 	init_waitqueue_head(&pgdat->kcompactd_wait);
1369 }
1370 #else
1371 static void pgdat_init_kcompactd(struct pglist_data *pgdat) {}
1372 #endif
1373 
1374 static void __meminit pgdat_init_internals(struct pglist_data *pgdat)
1375 {
1376 	int i;
1377 
1378 	pgdat_resize_init(pgdat);
1379 	pgdat_kswapd_lock_init(pgdat);
1380 
1381 	pgdat_init_split_queue(pgdat);
1382 	pgdat_init_kcompactd(pgdat);
1383 
1384 	init_waitqueue_head(&pgdat->kswapd_wait);
1385 	init_waitqueue_head(&pgdat->pfmemalloc_wait);
1386 
1387 	for (i = 0; i < NR_VMSCAN_THROTTLE; i++)
1388 		init_waitqueue_head(&pgdat->reclaim_wait[i]);
1389 
1390 	pgdat_page_ext_init(pgdat);
1391 	lruvec_init(&pgdat->__lruvec);
1392 }
1393 
1394 static void __meminit zone_init_internals(struct zone *zone, enum zone_type idx, int nid,
1395 							unsigned long remaining_pages)
1396 {
1397 	atomic_long_set(&zone->managed_pages, remaining_pages);
1398 	zone_set_nid(zone, nid);
1399 	zone->name = zone_names[idx];
1400 	zone->zone_pgdat = NODE_DATA(nid);
1401 	spin_lock_init(&zone->lock);
1402 	zone_seqlock_init(zone);
1403 	zone_pcp_init(zone);
1404 }
1405 
1406 static void __meminit zone_init_free_lists(struct zone *zone)
1407 {
1408 	unsigned int order, t;
1409 	for_each_migratetype_order(order, t) {
1410 		INIT_LIST_HEAD(&zone->free_area[order].free_list[t]);
1411 		zone->free_area[order].nr_free = 0;
1412 	}
1413 
1414 #ifdef CONFIG_UNACCEPTED_MEMORY
1415 	INIT_LIST_HEAD(&zone->unaccepted_pages);
1416 #endif
1417 }
1418 
1419 void __meminit init_currently_empty_zone(struct zone *zone,
1420 					unsigned long zone_start_pfn,
1421 					unsigned long size)
1422 {
1423 	struct pglist_data *pgdat = zone->zone_pgdat;
1424 	int zone_idx = zone_idx(zone) + 1;
1425 
1426 	if (zone_idx > pgdat->nr_zones)
1427 		pgdat->nr_zones = zone_idx;
1428 
1429 	zone->zone_start_pfn = zone_start_pfn;
1430 
1431 	mminit_dprintk(MMINIT_TRACE, "memmap_init",
1432 			"Initialising map node %d zone %lu pfns %lu -> %lu\n",
1433 			pgdat->node_id,
1434 			(unsigned long)zone_idx(zone),
1435 			zone_start_pfn, (zone_start_pfn + size));
1436 
1437 	zone_init_free_lists(zone);
1438 	zone->initialized = 1;
1439 }
1440 
1441 #ifndef CONFIG_SPARSEMEM
1442 /*
1443  * Calculate the size of the zone->pageblock_flags rounded to an unsigned long
1444  * Start by making sure zonesize is a multiple of pageblock_order by rounding
1445  * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally
1446  * round what is now in bits to nearest long in bits, then return it in
1447  * bytes.
1448  */
1449 static unsigned long __init usemap_size(unsigned long zone_start_pfn, unsigned long zonesize)
1450 {
1451 	unsigned long usemapsize;
1452 
1453 	zonesize += zone_start_pfn & (pageblock_nr_pages-1);
1454 	usemapsize = round_up(zonesize, pageblock_nr_pages);
1455 	usemapsize = usemapsize >> pageblock_order;
1456 	usemapsize *= NR_PAGEBLOCK_BITS;
1457 	usemapsize = round_up(usemapsize, BITS_PER_LONG);
1458 
1459 	return usemapsize / BITS_PER_BYTE;
1460 }
1461 
1462 static void __ref setup_usemap(struct zone *zone)
1463 {
1464 	unsigned long usemapsize = usemap_size(zone->zone_start_pfn,
1465 					       zone->spanned_pages);
1466 	zone->pageblock_flags = NULL;
1467 	if (usemapsize) {
1468 		zone->pageblock_flags =
1469 			memblock_alloc_node(usemapsize, SMP_CACHE_BYTES,
1470 					    zone_to_nid(zone));
1471 		if (!zone->pageblock_flags)
1472 			panic("Failed to allocate %ld bytes for zone %s pageblock flags on node %d\n",
1473 			      usemapsize, zone->name, zone_to_nid(zone));
1474 	}
1475 }
1476 #else
1477 static inline void setup_usemap(struct zone *zone) {}
1478 #endif /* CONFIG_SPARSEMEM */
1479 
1480 #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE
1481 
1482 /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */
1483 void __init set_pageblock_order(void)
1484 {
1485 	unsigned int order = MAX_PAGE_ORDER;
1486 
1487 	/* Check that pageblock_nr_pages has not already been setup */
1488 	if (pageblock_order)
1489 		return;
1490 
1491 	/* Don't let pageblocks exceed the maximum allocation granularity. */
1492 	if (HPAGE_SHIFT > PAGE_SHIFT && HUGETLB_PAGE_ORDER < order)
1493 		order = HUGETLB_PAGE_ORDER;
1494 
1495 	/*
1496 	 * Assume the largest contiguous order of interest is a huge page.
1497 	 * This value may be variable depending on boot parameters on powerpc.
1498 	 */
1499 	pageblock_order = order;
1500 }
1501 #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
1502 
1503 /*
1504  * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order()
1505  * is unused as pageblock_order is set at compile-time. See
1506  * include/linux/pageblock-flags.h for the values of pageblock_order based on
1507  * the kernel config
1508  */
1509 void __init set_pageblock_order(void)
1510 {
1511 }
1512 
1513 #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */
1514 
1515 /*
1516  * Set up the zone data structures
1517  * - init pgdat internals
1518  * - init all zones belonging to this node
1519  *
1520  * NOTE: this function is only called during memory hotplug
1521  */
1522 #ifdef CONFIG_MEMORY_HOTPLUG
1523 void __ref free_area_init_core_hotplug(struct pglist_data *pgdat)
1524 {
1525 	int nid = pgdat->node_id;
1526 	enum zone_type z;
1527 	int cpu;
1528 
1529 	pgdat_init_internals(pgdat);
1530 
1531 	if (pgdat->per_cpu_nodestats == &boot_nodestats)
1532 		pgdat->per_cpu_nodestats = alloc_percpu(struct per_cpu_nodestat);
1533 
1534 	/*
1535 	 * Reset the nr_zones, order and highest_zoneidx before reuse.
1536 	 * Note that kswapd will init kswapd_highest_zoneidx properly
1537 	 * when it starts in the near future.
1538 	 */
1539 	pgdat->nr_zones = 0;
1540 	pgdat->kswapd_order = 0;
1541 	pgdat->kswapd_highest_zoneidx = 0;
1542 	pgdat->node_start_pfn = 0;
1543 	pgdat->node_present_pages = 0;
1544 
1545 	for_each_online_cpu(cpu) {
1546 		struct per_cpu_nodestat *p;
1547 
1548 		p = per_cpu_ptr(pgdat->per_cpu_nodestats, cpu);
1549 		memset(p, 0, sizeof(*p));
1550 	}
1551 
1552 	/*
1553 	 * When memory is hot-added, all the memory is in offline state. So
1554 	 * clear all zones' present_pages and managed_pages because they will
1555 	 * be updated in online_pages() and offline_pages().
1556 	 */
1557 	for (z = 0; z < MAX_NR_ZONES; z++) {
1558 		struct zone *zone = pgdat->node_zones + z;
1559 
1560 		zone->present_pages = 0;
1561 		zone_init_internals(zone, z, nid, 0);
1562 	}
1563 }
1564 #endif
1565 
1566 static void __init free_area_init_core(struct pglist_data *pgdat)
1567 {
1568 	enum zone_type j;
1569 	int nid = pgdat->node_id;
1570 
1571 	pgdat_init_internals(pgdat);
1572 	pgdat->per_cpu_nodestats = &boot_nodestats;
1573 
1574 	for (j = 0; j < MAX_NR_ZONES; j++) {
1575 		struct zone *zone = pgdat->node_zones + j;
1576 		unsigned long size = zone->spanned_pages;
1577 
1578 		/*
1579 		 * Initialize zone->managed_pages as 0 , it will be reset
1580 		 * when memblock allocator frees pages into buddy system.
1581 		 */
1582 		zone_init_internals(zone, j, nid, zone->present_pages);
1583 
1584 		if (!size)
1585 			continue;
1586 
1587 		setup_usemap(zone);
1588 		init_currently_empty_zone(zone, zone->zone_start_pfn, size);
1589 	}
1590 }
1591 
1592 void __init *memmap_alloc(phys_addr_t size, phys_addr_t align,
1593 			  phys_addr_t min_addr, int nid, bool exact_nid)
1594 {
1595 	void *ptr;
1596 
1597 	/*
1598 	 * Kmemleak will explicitly scan mem_map by traversing all valid
1599 	 * `struct *page`,so memblock does not need to be added to the scan list.
1600 	 */
1601 	if (exact_nid)
1602 		ptr = memblock_alloc_exact_nid_raw(size, align, min_addr,
1603 						   MEMBLOCK_ALLOC_NOLEAKTRACE,
1604 						   nid);
1605 	else
1606 		ptr = memblock_alloc_try_nid_raw(size, align, min_addr,
1607 						 MEMBLOCK_ALLOC_NOLEAKTRACE,
1608 						 nid);
1609 
1610 	if (ptr && size > 0)
1611 		page_init_poison(ptr, size);
1612 
1613 	return ptr;
1614 }
1615 
1616 #ifdef CONFIG_FLATMEM
1617 static void __init alloc_node_mem_map(struct pglist_data *pgdat)
1618 {
1619 	unsigned long start, offset, size, end;
1620 	struct page *map;
1621 
1622 	/* Skip empty nodes */
1623 	if (!pgdat->node_spanned_pages)
1624 		return;
1625 
1626 	start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1);
1627 	offset = pgdat->node_start_pfn - start;
1628 	/*
1629 		 * The zone's endpoints aren't required to be MAX_PAGE_ORDER
1630 	 * aligned but the node_mem_map endpoints must be in order
1631 	 * for the buddy allocator to function correctly.
1632 	 */
1633 	end = ALIGN(pgdat_end_pfn(pgdat), MAX_ORDER_NR_PAGES);
1634 	size =  (end - start) * sizeof(struct page);
1635 	map = memmap_alloc(size, SMP_CACHE_BYTES, MEMBLOCK_LOW_LIMIT,
1636 			   pgdat->node_id, false);
1637 	if (!map)
1638 		panic("Failed to allocate %ld bytes for node %d memory map\n",
1639 		      size, pgdat->node_id);
1640 	pgdat->node_mem_map = map + offset;
1641 	memmap_boot_pages_add(DIV_ROUND_UP(size, PAGE_SIZE));
1642 	pr_debug("%s: node %d, pgdat %08lx, node_mem_map %08lx\n",
1643 		 __func__, pgdat->node_id, (unsigned long)pgdat,
1644 		 (unsigned long)pgdat->node_mem_map);
1645 #ifndef CONFIG_NUMA
1646 	/* the global mem_map is just set as node 0's */
1647 	if (pgdat == NODE_DATA(0)) {
1648 		mem_map = NODE_DATA(0)->node_mem_map;
1649 		if (page_to_pfn(mem_map) != pgdat->node_start_pfn)
1650 			mem_map -= offset;
1651 	}
1652 #endif
1653 }
1654 #else
1655 static inline void alloc_node_mem_map(struct pglist_data *pgdat) { }
1656 #endif /* CONFIG_FLATMEM */
1657 
1658 /**
1659  * get_pfn_range_for_nid - Return the start and end page frames for a node
1660  * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned.
1661  * @start_pfn: Passed by reference. On return, it will have the node start_pfn.
1662  * @end_pfn: Passed by reference. On return, it will have the node end_pfn.
1663  *
1664  * It returns the start and end page frame of a node based on information
1665  * provided by memblock_set_node(). If called for a node
1666  * with no available memory, the start and end PFNs will be 0.
1667  */
1668 void __init get_pfn_range_for_nid(unsigned int nid,
1669 			unsigned long *start_pfn, unsigned long *end_pfn)
1670 {
1671 	unsigned long this_start_pfn, this_end_pfn;
1672 	int i;
1673 
1674 	*start_pfn = -1UL;
1675 	*end_pfn = 0;
1676 
1677 	for_each_mem_pfn_range(i, nid, &this_start_pfn, &this_end_pfn, NULL) {
1678 		*start_pfn = min(*start_pfn, this_start_pfn);
1679 		*end_pfn = max(*end_pfn, this_end_pfn);
1680 	}
1681 
1682 	if (*start_pfn == -1UL)
1683 		*start_pfn = 0;
1684 }
1685 
1686 static void __init free_area_init_node(int nid)
1687 {
1688 	pg_data_t *pgdat = NODE_DATA(nid);
1689 	unsigned long start_pfn = 0;
1690 	unsigned long end_pfn = 0;
1691 
1692 	/* pg_data_t should be reset to zero when it's allocated */
1693 	WARN_ON(pgdat->nr_zones || pgdat->kswapd_highest_zoneidx);
1694 
1695 	get_pfn_range_for_nid(nid, &start_pfn, &end_pfn);
1696 
1697 	pgdat->node_id = nid;
1698 	pgdat->node_start_pfn = start_pfn;
1699 	pgdat->per_cpu_nodestats = NULL;
1700 
1701 	if (start_pfn != end_pfn) {
1702 		pr_info("Initmem setup node %d [mem %#018Lx-%#018Lx]\n", nid,
1703 			(u64)start_pfn << PAGE_SHIFT,
1704 			end_pfn ? ((u64)end_pfn << PAGE_SHIFT) - 1 : 0);
1705 
1706 		calculate_node_totalpages(pgdat, start_pfn, end_pfn);
1707 	} else {
1708 		pr_info("Initmem setup node %d as memoryless\n", nid);
1709 
1710 		reset_memoryless_node_totalpages(pgdat);
1711 	}
1712 
1713 	alloc_node_mem_map(pgdat);
1714 	pgdat_set_deferred_range(pgdat);
1715 
1716 	free_area_init_core(pgdat);
1717 	lru_gen_init_pgdat(pgdat);
1718 }
1719 
1720 /* Any regular or high memory on that node ? */
1721 static void __init check_for_memory(pg_data_t *pgdat)
1722 {
1723 	enum zone_type zone_type;
1724 
1725 	for (zone_type = 0; zone_type <= ZONE_MOVABLE - 1; zone_type++) {
1726 		struct zone *zone = &pgdat->node_zones[zone_type];
1727 		if (populated_zone(zone)) {
1728 			if (IS_ENABLED(CONFIG_HIGHMEM))
1729 				node_set_state(pgdat->node_id, N_HIGH_MEMORY);
1730 			if (zone_type <= ZONE_NORMAL)
1731 				node_set_state(pgdat->node_id, N_NORMAL_MEMORY);
1732 			break;
1733 		}
1734 	}
1735 }
1736 
1737 #if MAX_NUMNODES > 1
1738 /*
1739  * Figure out the number of possible node ids.
1740  */
1741 void __init setup_nr_node_ids(void)
1742 {
1743 	unsigned int highest;
1744 
1745 	highest = find_last_bit(node_possible_map.bits, MAX_NUMNODES);
1746 	nr_node_ids = highest + 1;
1747 }
1748 #endif
1749 
1750 /*
1751  * Some architectures, e.g. ARC may have ZONE_HIGHMEM below ZONE_NORMAL. For
1752  * such cases we allow max_zone_pfn sorted in the descending order
1753  */
1754 static bool arch_has_descending_max_zone_pfns(void)
1755 {
1756 	return IS_ENABLED(CONFIG_ARC) && !IS_ENABLED(CONFIG_ARC_HAS_PAE40);
1757 }
1758 
1759 /**
1760  * free_area_init - Initialise all pg_data_t and zone data
1761  * @max_zone_pfn: an array of max PFNs for each zone
1762  *
1763  * This will call free_area_init_node() for each active node in the system.
1764  * Using the page ranges provided by memblock_set_node(), the size of each
1765  * zone in each node and their holes is calculated. If the maximum PFN
1766  * between two adjacent zones match, it is assumed that the zone is empty.
1767  * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed
1768  * that arch_max_dma32_pfn has no pages. It is also assumed that a zone
1769  * starts where the previous one ended. For example, ZONE_DMA32 starts
1770  * at arch_max_dma_pfn.
1771  */
1772 void __init free_area_init(unsigned long *max_zone_pfn)
1773 {
1774 	unsigned long start_pfn, end_pfn;
1775 	int i, nid, zone;
1776 	bool descending;
1777 
1778 	/* Record where the zone boundaries are */
1779 	memset(arch_zone_lowest_possible_pfn, 0,
1780 				sizeof(arch_zone_lowest_possible_pfn));
1781 	memset(arch_zone_highest_possible_pfn, 0,
1782 				sizeof(arch_zone_highest_possible_pfn));
1783 
1784 	start_pfn = PHYS_PFN(memblock_start_of_DRAM());
1785 	descending = arch_has_descending_max_zone_pfns();
1786 
1787 	for (i = 0; i < MAX_NR_ZONES; i++) {
1788 		if (descending)
1789 			zone = MAX_NR_ZONES - i - 1;
1790 		else
1791 			zone = i;
1792 
1793 		if (zone == ZONE_MOVABLE)
1794 			continue;
1795 
1796 		end_pfn = max(max_zone_pfn[zone], start_pfn);
1797 		arch_zone_lowest_possible_pfn[zone] = start_pfn;
1798 		arch_zone_highest_possible_pfn[zone] = end_pfn;
1799 
1800 		start_pfn = end_pfn;
1801 	}
1802 
1803 	/* Find the PFNs that ZONE_MOVABLE begins at in each node */
1804 	memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn));
1805 	find_zone_movable_pfns_for_nodes();
1806 
1807 	/* Print out the zone ranges */
1808 	pr_info("Zone ranges:\n");
1809 	for (i = 0; i < MAX_NR_ZONES; i++) {
1810 		if (i == ZONE_MOVABLE)
1811 			continue;
1812 		pr_info("  %-8s ", zone_names[i]);
1813 		if (arch_zone_lowest_possible_pfn[i] ==
1814 				arch_zone_highest_possible_pfn[i])
1815 			pr_cont("empty\n");
1816 		else
1817 			pr_cont("[mem %#018Lx-%#018Lx]\n",
1818 				(u64)arch_zone_lowest_possible_pfn[i]
1819 					<< PAGE_SHIFT,
1820 				((u64)arch_zone_highest_possible_pfn[i]
1821 					<< PAGE_SHIFT) - 1);
1822 	}
1823 
1824 	/* Print out the PFNs ZONE_MOVABLE begins at in each node */
1825 	pr_info("Movable zone start for each node\n");
1826 	for (i = 0; i < MAX_NUMNODES; i++) {
1827 		if (zone_movable_pfn[i])
1828 			pr_info("  Node %d: %#018Lx\n", i,
1829 			       (u64)zone_movable_pfn[i] << PAGE_SHIFT);
1830 	}
1831 
1832 	/*
1833 	 * Print out the early node map, and initialize the
1834 	 * subsection-map relative to active online memory ranges to
1835 	 * enable future "sub-section" extensions of the memory map.
1836 	 */
1837 	pr_info("Early memory node ranges\n");
1838 	for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
1839 		pr_info("  node %3d: [mem %#018Lx-%#018Lx]\n", nid,
1840 			(u64)start_pfn << PAGE_SHIFT,
1841 			((u64)end_pfn << PAGE_SHIFT) - 1);
1842 		subsection_map_init(start_pfn, end_pfn - start_pfn);
1843 	}
1844 
1845 	/* Initialise every node */
1846 	mminit_verify_pageflags_layout();
1847 	setup_nr_node_ids();
1848 	set_pageblock_order();
1849 
1850 	for_each_node(nid) {
1851 		pg_data_t *pgdat;
1852 
1853 		if (!node_online(nid))
1854 			alloc_offline_node_data(nid);
1855 
1856 		pgdat = NODE_DATA(nid);
1857 		free_area_init_node(nid);
1858 
1859 		/*
1860 		 * No sysfs hierarcy will be created via register_one_node()
1861 		 *for memory-less node because here it's not marked as N_MEMORY
1862 		 *and won't be set online later. The benefit is userspace
1863 		 *program won't be confused by sysfs files/directories of
1864 		 *memory-less node. The pgdat will get fully initialized by
1865 		 *hotadd_init_pgdat() when memory is hotplugged into this node.
1866 		 */
1867 		if (pgdat->node_present_pages) {
1868 			node_set_state(nid, N_MEMORY);
1869 			check_for_memory(pgdat);
1870 		}
1871 	}
1872 
1873 	for_each_node_state(nid, N_MEMORY)
1874 		sparse_vmemmap_init_nid_late(nid);
1875 
1876 	calc_nr_kernel_pages();
1877 	memmap_init();
1878 
1879 	/* disable hash distribution for systems with a single node */
1880 	fixup_hashdist();
1881 }
1882 
1883 /**
1884  * node_map_pfn_alignment - determine the maximum internode alignment
1885  *
1886  * This function should be called after node map is populated and sorted.
1887  * It calculates the maximum power of two alignment which can distinguish
1888  * all the nodes.
1889  *
1890  * For example, if all nodes are 1GiB and aligned to 1GiB, the return value
1891  * would indicate 1GiB alignment with (1 << (30 - PAGE_SHIFT)).  If the
1892  * nodes are shifted by 256MiB, 256MiB.  Note that if only the last node is
1893  * shifted, 1GiB is enough and this function will indicate so.
1894  *
1895  * This is used to test whether pfn -> nid mapping of the chosen memory
1896  * model has fine enough granularity to avoid incorrect mapping for the
1897  * populated node map.
1898  *
1899  * Return: the determined alignment in pfn's.  0 if there is no alignment
1900  * requirement (single node).
1901  */
1902 unsigned long __init node_map_pfn_alignment(void)
1903 {
1904 	unsigned long accl_mask = 0, last_end = 0;
1905 	unsigned long start, end, mask;
1906 	int last_nid = NUMA_NO_NODE;
1907 	int i, nid;
1908 
1909 	for_each_mem_pfn_range(i, MAX_NUMNODES, &start, &end, &nid) {
1910 		if (!start || last_nid < 0 || last_nid == nid) {
1911 			last_nid = nid;
1912 			last_end = end;
1913 			continue;
1914 		}
1915 
1916 		/*
1917 		 * Start with a mask granular enough to pin-point to the
1918 		 * start pfn and tick off bits one-by-one until it becomes
1919 		 * too coarse to separate the current node from the last.
1920 		 */
1921 		mask = ~((1 << __ffs(start)) - 1);
1922 		while (mask && last_end <= (start & (mask << 1)))
1923 			mask <<= 1;
1924 
1925 		/* accumulate all internode masks */
1926 		accl_mask |= mask;
1927 	}
1928 
1929 	/* convert mask to number of pages */
1930 	return ~accl_mask + 1;
1931 }
1932 
1933 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
1934 static void __init deferred_free_pages(unsigned long pfn,
1935 		unsigned long nr_pages)
1936 {
1937 	struct page *page;
1938 	unsigned long i;
1939 
1940 	if (!nr_pages)
1941 		return;
1942 
1943 	page = pfn_to_page(pfn);
1944 
1945 	/* Free a large naturally-aligned chunk if possible */
1946 	if (nr_pages == MAX_ORDER_NR_PAGES && IS_MAX_ORDER_ALIGNED(pfn)) {
1947 		for (i = 0; i < nr_pages; i += pageblock_nr_pages)
1948 			set_pageblock_migratetype(page + i, MIGRATE_MOVABLE);
1949 		__free_pages_core(page, MAX_PAGE_ORDER, MEMINIT_EARLY);
1950 		return;
1951 	}
1952 
1953 	/* Accept chunks smaller than MAX_PAGE_ORDER upfront */
1954 	accept_memory(PFN_PHYS(pfn), nr_pages * PAGE_SIZE);
1955 
1956 	for (i = 0; i < nr_pages; i++, page++, pfn++) {
1957 		if (pageblock_aligned(pfn))
1958 			set_pageblock_migratetype(page, MIGRATE_MOVABLE);
1959 		__free_pages_core(page, 0, MEMINIT_EARLY);
1960 	}
1961 }
1962 
1963 /* Completion tracking for deferred_init_memmap() threads */
1964 static atomic_t pgdat_init_n_undone __initdata;
1965 static __initdata DECLARE_COMPLETION(pgdat_init_all_done_comp);
1966 
1967 static inline void __init pgdat_init_report_one_done(void)
1968 {
1969 	if (atomic_dec_and_test(&pgdat_init_n_undone))
1970 		complete(&pgdat_init_all_done_comp);
1971 }
1972 
1973 /*
1974  * Initialize struct pages.  We minimize pfn page lookups and scheduler checks
1975  * by performing it only once every MAX_ORDER_NR_PAGES.
1976  * Return number of pages initialized.
1977  */
1978 static unsigned long __init deferred_init_pages(struct zone *zone,
1979 		unsigned long pfn, unsigned long end_pfn)
1980 {
1981 	int nid = zone_to_nid(zone);
1982 	unsigned long nr_pages = end_pfn - pfn;
1983 	int zid = zone_idx(zone);
1984 	struct page *page = pfn_to_page(pfn);
1985 
1986 	for (; pfn < end_pfn; pfn++, page++)
1987 		__init_single_page(page, pfn, zid, nid);
1988 	return nr_pages;
1989 }
1990 
1991 /*
1992  * This function is meant to pre-load the iterator for the zone init from
1993  * a given point.
1994  * Specifically it walks through the ranges starting with initial index
1995  * passed to it until we are caught up to the first_init_pfn value and
1996  * exits there. If we never encounter the value we return false indicating
1997  * there are no valid ranges left.
1998  */
1999 static bool __init
2000 deferred_init_mem_pfn_range_in_zone(u64 *i, struct zone *zone,
2001 				    unsigned long *spfn, unsigned long *epfn,
2002 				    unsigned long first_init_pfn)
2003 {
2004 	u64 j = *i;
2005 
2006 	if (j == 0)
2007 		__next_mem_pfn_range_in_zone(&j, zone, spfn, epfn);
2008 
2009 	/*
2010 	 * Start out by walking through the ranges in this zone that have
2011 	 * already been initialized. We don't need to do anything with them
2012 	 * so we just need to flush them out of the system.
2013 	 */
2014 	for_each_free_mem_pfn_range_in_zone_from(j, zone, spfn, epfn) {
2015 		if (*epfn <= first_init_pfn)
2016 			continue;
2017 		if (*spfn < first_init_pfn)
2018 			*spfn = first_init_pfn;
2019 		*i = j;
2020 		return true;
2021 	}
2022 
2023 	return false;
2024 }
2025 
2026 /*
2027  * Initialize and free pages. We do it in two loops: first we initialize
2028  * struct page, then free to buddy allocator, because while we are
2029  * freeing pages we can access pages that are ahead (computing buddy
2030  * page in __free_one_page()).
2031  *
2032  * In order to try and keep some memory in the cache we have the loop
2033  * broken along max page order boundaries. This way we will not cause
2034  * any issues with the buddy page computation.
2035  */
2036 static unsigned long __init
2037 deferred_init_maxorder(u64 *i, struct zone *zone, unsigned long *start_pfn,
2038 		       unsigned long *end_pfn)
2039 {
2040 	unsigned long mo_pfn = ALIGN(*start_pfn + 1, MAX_ORDER_NR_PAGES);
2041 	unsigned long spfn = *start_pfn, epfn = *end_pfn;
2042 	unsigned long nr_pages = 0;
2043 	u64 j = *i;
2044 
2045 	/* First we loop through and initialize the page values */
2046 	for_each_free_mem_pfn_range_in_zone_from(j, zone, start_pfn, end_pfn) {
2047 		unsigned long t;
2048 
2049 		if (mo_pfn <= *start_pfn)
2050 			break;
2051 
2052 		t = min(mo_pfn, *end_pfn);
2053 		nr_pages += deferred_init_pages(zone, *start_pfn, t);
2054 
2055 		if (mo_pfn < *end_pfn) {
2056 			*start_pfn = mo_pfn;
2057 			break;
2058 		}
2059 	}
2060 
2061 	/* Reset values and now loop through freeing pages as needed */
2062 	swap(j, *i);
2063 
2064 	for_each_free_mem_pfn_range_in_zone_from(j, zone, &spfn, &epfn) {
2065 		unsigned long t;
2066 
2067 		if (mo_pfn <= spfn)
2068 			break;
2069 
2070 		t = min(mo_pfn, epfn);
2071 		deferred_free_pages(spfn, t - spfn);
2072 
2073 		if (mo_pfn <= epfn)
2074 			break;
2075 	}
2076 
2077 	return nr_pages;
2078 }
2079 
2080 static void __init
2081 deferred_init_memmap_chunk(unsigned long start_pfn, unsigned long end_pfn,
2082 			   void *arg)
2083 {
2084 	unsigned long spfn, epfn;
2085 	struct zone *zone = arg;
2086 	u64 i = 0;
2087 
2088 	deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, start_pfn);
2089 
2090 	/*
2091 	 * Initialize and free pages in MAX_PAGE_ORDER sized increments so that
2092 	 * we can avoid introducing any issues with the buddy allocator.
2093 	 */
2094 	while (spfn < end_pfn) {
2095 		deferred_init_maxorder(&i, zone, &spfn, &epfn);
2096 		cond_resched();
2097 	}
2098 }
2099 
2100 static unsigned int __init
2101 deferred_page_init_max_threads(const struct cpumask *node_cpumask)
2102 {
2103 	return max(cpumask_weight(node_cpumask), 1U);
2104 }
2105 
2106 /* Initialise remaining memory on a node */
2107 static int __init deferred_init_memmap(void *data)
2108 {
2109 	pg_data_t *pgdat = data;
2110 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
2111 	unsigned long spfn = 0, epfn = 0;
2112 	unsigned long first_init_pfn, flags;
2113 	unsigned long start = jiffies;
2114 	struct zone *zone;
2115 	int max_threads;
2116 	u64 i = 0;
2117 
2118 	/* Bind memory initialisation thread to a local node if possible */
2119 	if (!cpumask_empty(cpumask))
2120 		set_cpus_allowed_ptr(current, cpumask);
2121 
2122 	pgdat_resize_lock(pgdat, &flags);
2123 	first_init_pfn = pgdat->first_deferred_pfn;
2124 	if (first_init_pfn == ULONG_MAX) {
2125 		pgdat_resize_unlock(pgdat, &flags);
2126 		pgdat_init_report_one_done();
2127 		return 0;
2128 	}
2129 
2130 	/* Sanity check boundaries */
2131 	BUG_ON(pgdat->first_deferred_pfn < pgdat->node_start_pfn);
2132 	BUG_ON(pgdat->first_deferred_pfn > pgdat_end_pfn(pgdat));
2133 	pgdat->first_deferred_pfn = ULONG_MAX;
2134 
2135 	/*
2136 	 * Once we unlock here, the zone cannot be grown anymore, thus if an
2137 	 * interrupt thread must allocate this early in boot, zone must be
2138 	 * pre-grown prior to start of deferred page initialization.
2139 	 */
2140 	pgdat_resize_unlock(pgdat, &flags);
2141 
2142 	/* Only the highest zone is deferred */
2143 	zone = pgdat->node_zones + pgdat->nr_zones - 1;
2144 
2145 	max_threads = deferred_page_init_max_threads(cpumask);
2146 
2147 	while (deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn, first_init_pfn)) {
2148 		first_init_pfn = ALIGN(epfn, PAGES_PER_SECTION);
2149 		struct padata_mt_job job = {
2150 			.thread_fn   = deferred_init_memmap_chunk,
2151 			.fn_arg      = zone,
2152 			.start       = spfn,
2153 			.size        = first_init_pfn - spfn,
2154 			.align       = PAGES_PER_SECTION,
2155 			.min_chunk   = PAGES_PER_SECTION,
2156 			.max_threads = max_threads,
2157 			.numa_aware  = false,
2158 		};
2159 
2160 		padata_do_multithreaded(&job);
2161 	}
2162 
2163 	/* Sanity check that the next zone really is unpopulated */
2164 	WARN_ON(pgdat->nr_zones < MAX_NR_ZONES && populated_zone(++zone));
2165 
2166 	pr_info("node %d deferred pages initialised in %ums\n",
2167 		pgdat->node_id, jiffies_to_msecs(jiffies - start));
2168 
2169 	pgdat_init_report_one_done();
2170 	return 0;
2171 }
2172 
2173 /*
2174  * If this zone has deferred pages, try to grow it by initializing enough
2175  * deferred pages to satisfy the allocation specified by order, rounded up to
2176  * the nearest PAGES_PER_SECTION boundary.  So we're adding memory in increments
2177  * of SECTION_SIZE bytes by initializing struct pages in increments of
2178  * PAGES_PER_SECTION * sizeof(struct page) bytes.
2179  *
2180  * Return true when zone was grown, otherwise return false. We return true even
2181  * when we grow less than requested, to let the caller decide if there are
2182  * enough pages to satisfy the allocation.
2183  */
2184 bool __init deferred_grow_zone(struct zone *zone, unsigned int order)
2185 {
2186 	unsigned long nr_pages_needed = ALIGN(1 << order, PAGES_PER_SECTION);
2187 	pg_data_t *pgdat = zone->zone_pgdat;
2188 	unsigned long first_deferred_pfn = pgdat->first_deferred_pfn;
2189 	unsigned long spfn, epfn, flags;
2190 	unsigned long nr_pages = 0;
2191 	u64 i = 0;
2192 
2193 	/* Only the last zone may have deferred pages */
2194 	if (zone_end_pfn(zone) != pgdat_end_pfn(pgdat))
2195 		return false;
2196 
2197 	pgdat_resize_lock(pgdat, &flags);
2198 
2199 	/*
2200 	 * If someone grew this zone while we were waiting for spinlock, return
2201 	 * true, as there might be enough pages already.
2202 	 */
2203 	if (first_deferred_pfn != pgdat->first_deferred_pfn) {
2204 		pgdat_resize_unlock(pgdat, &flags);
2205 		return true;
2206 	}
2207 
2208 	/* If the zone is empty somebody else may have cleared out the zone */
2209 	if (!deferred_init_mem_pfn_range_in_zone(&i, zone, &spfn, &epfn,
2210 						 first_deferred_pfn)) {
2211 		pgdat->first_deferred_pfn = ULONG_MAX;
2212 		pgdat_resize_unlock(pgdat, &flags);
2213 		/* Retry only once. */
2214 		return first_deferred_pfn != ULONG_MAX;
2215 	}
2216 
2217 	/*
2218 	 * Initialize and free pages in MAX_PAGE_ORDER sized increments so
2219 	 * that we can avoid introducing any issues with the buddy
2220 	 * allocator.
2221 	 */
2222 	while (spfn < epfn) {
2223 		/* update our first deferred PFN for this section */
2224 		first_deferred_pfn = spfn;
2225 
2226 		nr_pages += deferred_init_maxorder(&i, zone, &spfn, &epfn);
2227 		touch_nmi_watchdog();
2228 
2229 		/* We should only stop along section boundaries */
2230 		if ((first_deferred_pfn ^ spfn) < PAGES_PER_SECTION)
2231 			continue;
2232 
2233 		/* If our quota has been met we can stop here */
2234 		if (nr_pages >= nr_pages_needed)
2235 			break;
2236 	}
2237 
2238 	pgdat->first_deferred_pfn = spfn;
2239 	pgdat_resize_unlock(pgdat, &flags);
2240 
2241 	return nr_pages > 0;
2242 }
2243 
2244 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
2245 
2246 #ifdef CONFIG_CMA
2247 void __init init_cma_reserved_pageblock(struct page *page)
2248 {
2249 	unsigned i = pageblock_nr_pages;
2250 	struct page *p = page;
2251 
2252 	do {
2253 		__ClearPageReserved(p);
2254 		set_page_count(p, 0);
2255 	} while (++p, --i);
2256 
2257 	set_pageblock_migratetype(page, MIGRATE_CMA);
2258 	set_page_refcounted(page);
2259 	/* pages were reserved and not allocated */
2260 	clear_page_tag_ref(page);
2261 	__free_pages(page, pageblock_order);
2262 
2263 	adjust_managed_page_count(page, pageblock_nr_pages);
2264 	page_zone(page)->cma_pages += pageblock_nr_pages;
2265 }
2266 /*
2267  * Similar to above, but only set the migrate type and stats.
2268  */
2269 void __init init_cma_pageblock(struct page *page)
2270 {
2271 	set_pageblock_migratetype(page, MIGRATE_CMA);
2272 	adjust_managed_page_count(page, pageblock_nr_pages);
2273 	page_zone(page)->cma_pages += pageblock_nr_pages;
2274 }
2275 #endif
2276 
2277 void set_zone_contiguous(struct zone *zone)
2278 {
2279 	unsigned long block_start_pfn = zone->zone_start_pfn;
2280 	unsigned long block_end_pfn;
2281 
2282 	block_end_pfn = pageblock_end_pfn(block_start_pfn);
2283 	for (; block_start_pfn < zone_end_pfn(zone);
2284 			block_start_pfn = block_end_pfn,
2285 			 block_end_pfn += pageblock_nr_pages) {
2286 
2287 		block_end_pfn = min(block_end_pfn, zone_end_pfn(zone));
2288 
2289 		if (!__pageblock_pfn_to_page(block_start_pfn,
2290 					     block_end_pfn, zone))
2291 			return;
2292 		cond_resched();
2293 	}
2294 
2295 	/* We confirm that there is no hole */
2296 	zone->contiguous = true;
2297 }
2298 
2299 /*
2300  * Check if a PFN range intersects multiple zones on one or more
2301  * NUMA nodes. Specify the @nid argument if it is known that this
2302  * PFN range is on one node, NUMA_NO_NODE otherwise.
2303  */
2304 bool pfn_range_intersects_zones(int nid, unsigned long start_pfn,
2305 			   unsigned long nr_pages)
2306 {
2307 	struct zone *zone, *izone = NULL;
2308 
2309 	for_each_zone(zone) {
2310 		if (nid != NUMA_NO_NODE && zone_to_nid(zone) != nid)
2311 			continue;
2312 
2313 		if (zone_intersects(zone, start_pfn, nr_pages)) {
2314 			if (izone != NULL)
2315 				return true;
2316 			izone = zone;
2317 		}
2318 
2319 	}
2320 
2321 	return false;
2322 }
2323 
2324 static void __init mem_init_print_info(void);
2325 void __init page_alloc_init_late(void)
2326 {
2327 	struct zone *zone;
2328 	int nid;
2329 
2330 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
2331 
2332 	/* There will be num_node_state(N_MEMORY) threads */
2333 	atomic_set(&pgdat_init_n_undone, num_node_state(N_MEMORY));
2334 	for_each_node_state(nid, N_MEMORY) {
2335 		kthread_run(deferred_init_memmap, NODE_DATA(nid), "pgdatinit%d", nid);
2336 	}
2337 
2338 	/* Block until all are initialised */
2339 	wait_for_completion(&pgdat_init_all_done_comp);
2340 
2341 	/*
2342 	 * We initialized the rest of the deferred pages.  Permanently disable
2343 	 * on-demand struct page initialization.
2344 	 */
2345 	static_branch_disable(&deferred_pages);
2346 
2347 	/* Reinit limits that are based on free pages after the kernel is up */
2348 	files_maxfiles_init();
2349 #endif
2350 
2351 	/* Accounting of total+free memory is stable at this point. */
2352 	mem_init_print_info();
2353 	buffer_init();
2354 
2355 	/* Discard memblock private memory */
2356 	memblock_discard();
2357 
2358 	for_each_node_state(nid, N_MEMORY)
2359 		shuffle_free_memory(NODE_DATA(nid));
2360 
2361 	for_each_populated_zone(zone)
2362 		set_zone_contiguous(zone);
2363 
2364 	/* Initialize page ext after all struct pages are initialized. */
2365 	if (deferred_struct_pages)
2366 		page_ext_init();
2367 
2368 	page_alloc_sysctl_init();
2369 }
2370 
2371 /*
2372  * Adaptive scale is meant to reduce sizes of hash tables on large memory
2373  * machines. As memory size is increased the scale is also increased but at
2374  * slower pace.  Starting from ADAPT_SCALE_BASE (64G), every time memory
2375  * quadruples the scale is increased by one, which means the size of hash table
2376  * only doubles, instead of quadrupling as well.
2377  * Because 32-bit systems cannot have large physical memory, where this scaling
2378  * makes sense, it is disabled on such platforms.
2379  */
2380 #if __BITS_PER_LONG > 32
2381 #define ADAPT_SCALE_BASE	(64ul << 30)
2382 #define ADAPT_SCALE_SHIFT	2
2383 #define ADAPT_SCALE_NPAGES	(ADAPT_SCALE_BASE >> PAGE_SHIFT)
2384 #endif
2385 
2386 /*
2387  * allocate a large system hash table from bootmem
2388  * - it is assumed that the hash table must contain an exact power-of-2
2389  *   quantity of entries
2390  * - limit is the number of hash buckets, not the total allocation size
2391  */
2392 void *__init alloc_large_system_hash(const char *tablename,
2393 				     unsigned long bucketsize,
2394 				     unsigned long numentries,
2395 				     int scale,
2396 				     int flags,
2397 				     unsigned int *_hash_shift,
2398 				     unsigned int *_hash_mask,
2399 				     unsigned long low_limit,
2400 				     unsigned long high_limit)
2401 {
2402 	unsigned long long max = high_limit;
2403 	unsigned long log2qty, size;
2404 	void *table;
2405 	gfp_t gfp_flags;
2406 	bool virt;
2407 	bool huge;
2408 
2409 	/* allow the kernel cmdline to have a say */
2410 	if (!numentries) {
2411 		/* round applicable memory size up to nearest megabyte */
2412 		numentries = nr_kernel_pages;
2413 
2414 		/* It isn't necessary when PAGE_SIZE >= 1MB */
2415 		if (PAGE_SIZE < SZ_1M)
2416 			numentries = round_up(numentries, SZ_1M / PAGE_SIZE);
2417 
2418 #if __BITS_PER_LONG > 32
2419 		if (!high_limit) {
2420 			unsigned long adapt;
2421 
2422 			for (adapt = ADAPT_SCALE_NPAGES; adapt < numentries;
2423 			     adapt <<= ADAPT_SCALE_SHIFT)
2424 				scale++;
2425 		}
2426 #endif
2427 
2428 		/* limit to 1 bucket per 2^scale bytes of low memory */
2429 		if (scale > PAGE_SHIFT)
2430 			numentries >>= (scale - PAGE_SHIFT);
2431 		else
2432 			numentries <<= (PAGE_SHIFT - scale);
2433 
2434 		if (unlikely((numentries * bucketsize) < PAGE_SIZE))
2435 			numentries = PAGE_SIZE / bucketsize;
2436 	}
2437 	numentries = roundup_pow_of_two(numentries);
2438 
2439 	/* limit allocation size to 1/16 total memory by default */
2440 	if (max == 0) {
2441 		max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4;
2442 		do_div(max, bucketsize);
2443 	}
2444 	max = min(max, 0x80000000ULL);
2445 
2446 	if (numentries < low_limit)
2447 		numentries = low_limit;
2448 	if (numentries > max)
2449 		numentries = max;
2450 
2451 	log2qty = ilog2(numentries);
2452 
2453 	gfp_flags = (flags & HASH_ZERO) ? GFP_ATOMIC | __GFP_ZERO : GFP_ATOMIC;
2454 	do {
2455 		virt = false;
2456 		size = bucketsize << log2qty;
2457 		if (flags & HASH_EARLY) {
2458 			if (flags & HASH_ZERO)
2459 				table = memblock_alloc(size, SMP_CACHE_BYTES);
2460 			else
2461 				table = memblock_alloc_raw(size,
2462 							   SMP_CACHE_BYTES);
2463 		} else if (get_order(size) > MAX_PAGE_ORDER || hashdist) {
2464 			table = vmalloc_huge(size, gfp_flags);
2465 			virt = true;
2466 			if (table)
2467 				huge = is_vm_area_hugepages(table);
2468 		} else {
2469 			/*
2470 			 * If bucketsize is not a power-of-two, we may free
2471 			 * some pages at the end of hash table which
2472 			 * alloc_pages_exact() automatically does
2473 			 */
2474 			table = alloc_pages_exact(size, gfp_flags);
2475 			kmemleak_alloc(table, size, 1, gfp_flags);
2476 		}
2477 	} while (!table && size > PAGE_SIZE && --log2qty);
2478 
2479 	if (!table)
2480 		panic("Failed to allocate %s hash table\n", tablename);
2481 
2482 	pr_info("%s hash table entries: %ld (order: %d, %lu bytes, %s)\n",
2483 		tablename, 1UL << log2qty, ilog2(size) - PAGE_SHIFT, size,
2484 		virt ? (huge ? "vmalloc hugepage" : "vmalloc") : "linear");
2485 
2486 	if (_hash_shift)
2487 		*_hash_shift = log2qty;
2488 	if (_hash_mask)
2489 		*_hash_mask = (1 << log2qty) - 1;
2490 
2491 	return table;
2492 }
2493 
2494 void __init memblock_free_pages(struct page *page, unsigned long pfn,
2495 							unsigned int order)
2496 {
2497 	if (IS_ENABLED(CONFIG_DEFERRED_STRUCT_PAGE_INIT)) {
2498 		int nid = early_pfn_to_nid(pfn);
2499 
2500 		if (!early_page_initialised(pfn, nid))
2501 			return;
2502 	}
2503 
2504 	if (!kmsan_memblock_free_pages(page, order)) {
2505 		/* KMSAN will take care of these pages. */
2506 		return;
2507 	}
2508 
2509 	/* pages were reserved and not allocated */
2510 	clear_page_tag_ref(page);
2511 	__free_pages_core(page, order, MEMINIT_EARLY);
2512 }
2513 
2514 DEFINE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_ALLOC_DEFAULT_ON, init_on_alloc);
2515 EXPORT_SYMBOL(init_on_alloc);
2516 
2517 DEFINE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_FREE_DEFAULT_ON, init_on_free);
2518 EXPORT_SYMBOL(init_on_free);
2519 
2520 static bool _init_on_alloc_enabled_early __read_mostly
2521 				= IS_ENABLED(CONFIG_INIT_ON_ALLOC_DEFAULT_ON);
2522 static int __init early_init_on_alloc(char *buf)
2523 {
2524 
2525 	return kstrtobool(buf, &_init_on_alloc_enabled_early);
2526 }
2527 early_param("init_on_alloc", early_init_on_alloc);
2528 
2529 static bool _init_on_free_enabled_early __read_mostly
2530 				= IS_ENABLED(CONFIG_INIT_ON_FREE_DEFAULT_ON);
2531 static int __init early_init_on_free(char *buf)
2532 {
2533 	return kstrtobool(buf, &_init_on_free_enabled_early);
2534 }
2535 early_param("init_on_free", early_init_on_free);
2536 
2537 DEFINE_STATIC_KEY_MAYBE(CONFIG_DEBUG_VM, check_pages_enabled);
2538 
2539 /*
2540  * Enable static keys related to various memory debugging and hardening options.
2541  * Some override others, and depend on early params that are evaluated in the
2542  * order of appearance. So we need to first gather the full picture of what was
2543  * enabled, and then make decisions.
2544  */
2545 static void __init mem_debugging_and_hardening_init(void)
2546 {
2547 	bool page_poisoning_requested = false;
2548 	bool want_check_pages = false;
2549 
2550 #ifdef CONFIG_PAGE_POISONING
2551 	/*
2552 	 * Page poisoning is debug page alloc for some arches. If
2553 	 * either of those options are enabled, enable poisoning.
2554 	 */
2555 	if (page_poisoning_enabled() ||
2556 	     (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_DEBUG_PAGEALLOC) &&
2557 	      debug_pagealloc_enabled())) {
2558 		static_branch_enable(&_page_poisoning_enabled);
2559 		page_poisoning_requested = true;
2560 		want_check_pages = true;
2561 	}
2562 #endif
2563 
2564 	if ((_init_on_alloc_enabled_early || _init_on_free_enabled_early) &&
2565 	    page_poisoning_requested) {
2566 		pr_info("mem auto-init: CONFIG_PAGE_POISONING is on, "
2567 			"will take precedence over init_on_alloc and init_on_free\n");
2568 		_init_on_alloc_enabled_early = false;
2569 		_init_on_free_enabled_early = false;
2570 	}
2571 
2572 	if (_init_on_alloc_enabled_early) {
2573 		want_check_pages = true;
2574 		static_branch_enable(&init_on_alloc);
2575 	} else {
2576 		static_branch_disable(&init_on_alloc);
2577 	}
2578 
2579 	if (_init_on_free_enabled_early) {
2580 		want_check_pages = true;
2581 		static_branch_enable(&init_on_free);
2582 	} else {
2583 		static_branch_disable(&init_on_free);
2584 	}
2585 
2586 	if (IS_ENABLED(CONFIG_KMSAN) &&
2587 	    (_init_on_alloc_enabled_early || _init_on_free_enabled_early))
2588 		pr_info("mem auto-init: please make sure init_on_alloc and init_on_free are disabled when running KMSAN\n");
2589 
2590 #ifdef CONFIG_DEBUG_PAGEALLOC
2591 	if (debug_pagealloc_enabled()) {
2592 		want_check_pages = true;
2593 		static_branch_enable(&_debug_pagealloc_enabled);
2594 
2595 		if (debug_guardpage_minorder())
2596 			static_branch_enable(&_debug_guardpage_enabled);
2597 	}
2598 #endif
2599 
2600 	/*
2601 	 * Any page debugging or hardening option also enables sanity checking
2602 	 * of struct pages being allocated or freed. With CONFIG_DEBUG_VM it's
2603 	 * enabled already.
2604 	 */
2605 	if (!IS_ENABLED(CONFIG_DEBUG_VM) && want_check_pages)
2606 		static_branch_enable(&check_pages_enabled);
2607 }
2608 
2609 /* Report memory auto-initialization states for this boot. */
2610 static void __init report_meminit(void)
2611 {
2612 	const char *stack;
2613 
2614 	if (IS_ENABLED(CONFIG_INIT_STACK_ALL_PATTERN))
2615 		stack = "all(pattern)";
2616 	else if (IS_ENABLED(CONFIG_INIT_STACK_ALL_ZERO))
2617 		stack = "all(zero)";
2618 	else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF_ALL))
2619 		stack = "byref_all(zero)";
2620 	else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF))
2621 		stack = "byref(zero)";
2622 	else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_USER))
2623 		stack = "__user(zero)";
2624 	else
2625 		stack = "off";
2626 
2627 	pr_info("mem auto-init: stack:%s, heap alloc:%s, heap free:%s\n",
2628 		stack, str_on_off(want_init_on_alloc(GFP_KERNEL)),
2629 		str_on_off(want_init_on_free()));
2630 	if (want_init_on_free())
2631 		pr_info("mem auto-init: clearing system memory may take some time...\n");
2632 }
2633 
2634 static void __init mem_init_print_info(void)
2635 {
2636 	unsigned long physpages, codesize, datasize, rosize, bss_size;
2637 	unsigned long init_code_size, init_data_size;
2638 
2639 	physpages = get_num_physpages();
2640 	codesize = _etext - _stext;
2641 	datasize = _edata - _sdata;
2642 	rosize = __end_rodata - __start_rodata;
2643 	bss_size = __bss_stop - __bss_start;
2644 	init_data_size = __init_end - __init_begin;
2645 	init_code_size = _einittext - _sinittext;
2646 
2647 	/*
2648 	 * Detect special cases and adjust section sizes accordingly:
2649 	 * 1) .init.* may be embedded into .data sections
2650 	 * 2) .init.text.* may be out of [__init_begin, __init_end],
2651 	 *    please refer to arch/tile/kernel/vmlinux.lds.S.
2652 	 * 3) .rodata.* may be embedded into .text or .data sections.
2653 	 */
2654 #define adj_init_size(start, end, size, pos, adj) \
2655 	do { \
2656 		if (&start[0] <= &pos[0] && &pos[0] < &end[0] && size > adj) \
2657 			size -= adj; \
2658 	} while (0)
2659 
2660 	adj_init_size(__init_begin, __init_end, init_data_size,
2661 		     _sinittext, init_code_size);
2662 	adj_init_size(_stext, _etext, codesize, _sinittext, init_code_size);
2663 	adj_init_size(_sdata, _edata, datasize, __init_begin, init_data_size);
2664 	adj_init_size(_stext, _etext, codesize, __start_rodata, rosize);
2665 	adj_init_size(_sdata, _edata, datasize, __start_rodata, rosize);
2666 
2667 #undef	adj_init_size
2668 
2669 	pr_info("Memory: %luK/%luK available (%luK kernel code, %luK rwdata, %luK rodata, %luK init, %luK bss, %luK reserved, %luK cma-reserved"
2670 #ifdef	CONFIG_HIGHMEM
2671 		", %luK highmem"
2672 #endif
2673 		")\n",
2674 		K(nr_free_pages()), K(physpages),
2675 		codesize / SZ_1K, datasize / SZ_1K, rosize / SZ_1K,
2676 		(init_data_size + init_code_size) / SZ_1K, bss_size / SZ_1K,
2677 		K(physpages - totalram_pages() - totalcma_pages),
2678 		K(totalcma_pages)
2679 #ifdef	CONFIG_HIGHMEM
2680 		, K(totalhigh_pages())
2681 #endif
2682 		);
2683 }
2684 
2685 /*
2686  * Set up kernel memory allocators
2687  */
2688 void __init mm_core_init(void)
2689 {
2690 	hugetlb_bootmem_alloc();
2691 
2692 	/* Initializations relying on SMP setup */
2693 	BUILD_BUG_ON(MAX_ZONELISTS > 2);
2694 	build_all_zonelists(NULL);
2695 	page_alloc_init_cpuhp();
2696 	alloc_tag_sec_init();
2697 	/*
2698 	 * page_ext requires contiguous pages,
2699 	 * bigger than MAX_PAGE_ORDER unless SPARSEMEM.
2700 	 */
2701 	page_ext_init_flatmem();
2702 	mem_debugging_and_hardening_init();
2703 	kfence_alloc_pool_and_metadata();
2704 	report_meminit();
2705 	kmsan_init_shadow();
2706 	stack_depot_early_init();
2707 	mem_init();
2708 	kmem_cache_init();
2709 	/*
2710 	 * page_owner must be initialized after buddy is ready, and also after
2711 	 * slab is ready so that stack_depot_init() works properly
2712 	 */
2713 	page_ext_init_flatmem_late();
2714 	kmemleak_init();
2715 	ptlock_cache_init();
2716 	pgtable_cache_init();
2717 	debug_objects_mem_init();
2718 	vmalloc_init();
2719 	/* If no deferred init page_ext now, as vmap is fully initialized */
2720 	if (!deferred_struct_pages)
2721 		page_ext_init();
2722 	/* Should be run before the first non-init thread is created */
2723 	init_espfix_bsp();
2724 	/* Should be run after espfix64 is set up. */
2725 	pti_init();
2726 	kmsan_init_runtime();
2727 	mm_cache_init();
2728 	execmem_init();
2729 }
2730