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