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