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