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