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