xref: /openbmc/linux/arch/arm64/mm/init.c (revision 2f5947df)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Based on arch/arm/mm/init.c
4  *
5  * Copyright (C) 1995-2005 Russell King
6  * Copyright (C) 2012 ARM Ltd.
7  */
8 
9 #include <linux/kernel.h>
10 #include <linux/export.h>
11 #include <linux/errno.h>
12 #include <linux/swap.h>
13 #include <linux/init.h>
14 #include <linux/cache.h>
15 #include <linux/mman.h>
16 #include <linux/nodemask.h>
17 #include <linux/initrd.h>
18 #include <linux/gfp.h>
19 #include <linux/memblock.h>
20 #include <linux/sort.h>
21 #include <linux/of.h>
22 #include <linux/of_fdt.h>
23 #include <linux/dma-mapping.h>
24 #include <linux/dma-contiguous.h>
25 #include <linux/efi.h>
26 #include <linux/swiotlb.h>
27 #include <linux/vmalloc.h>
28 #include <linux/mm.h>
29 #include <linux/kexec.h>
30 #include <linux/crash_dump.h>
31 
32 #include <asm/boot.h>
33 #include <asm/fixmap.h>
34 #include <asm/kasan.h>
35 #include <asm/kernel-pgtable.h>
36 #include <asm/memory.h>
37 #include <asm/numa.h>
38 #include <asm/sections.h>
39 #include <asm/setup.h>
40 #include <linux/sizes.h>
41 #include <asm/tlb.h>
42 #include <asm/alternative.h>
43 
44 /*
45  * We need to be able to catch inadvertent references to memstart_addr
46  * that occur (potentially in generic code) before arm64_memblock_init()
47  * executes, which assigns it its actual value. So use a default value
48  * that cannot be mistaken for a real physical address.
49  */
50 s64 memstart_addr __ro_after_init = -1;
51 EXPORT_SYMBOL(memstart_addr);
52 
53 phys_addr_t arm64_dma_phys_limit __ro_after_init;
54 
55 #ifdef CONFIG_KEXEC_CORE
56 /*
57  * reserve_crashkernel() - reserves memory for crash kernel
58  *
59  * This function reserves memory area given in "crashkernel=" kernel command
60  * line parameter. The memory reserved is used by dump capture kernel when
61  * primary kernel is crashing.
62  */
63 static void __init reserve_crashkernel(void)
64 {
65 	unsigned long long crash_base, crash_size;
66 	int ret;
67 
68 	ret = parse_crashkernel(boot_command_line, memblock_phys_mem_size(),
69 				&crash_size, &crash_base);
70 	/* no crashkernel= or invalid value specified */
71 	if (ret || !crash_size)
72 		return;
73 
74 	crash_size = PAGE_ALIGN(crash_size);
75 
76 	if (crash_base == 0) {
77 		/* Current arm64 boot protocol requires 2MB alignment */
78 		crash_base = memblock_find_in_range(0, ARCH_LOW_ADDRESS_LIMIT,
79 				crash_size, SZ_2M);
80 		if (crash_base == 0) {
81 			pr_warn("cannot allocate crashkernel (size:0x%llx)\n",
82 				crash_size);
83 			return;
84 		}
85 	} else {
86 		/* User specifies base address explicitly. */
87 		if (!memblock_is_region_memory(crash_base, crash_size)) {
88 			pr_warn("cannot reserve crashkernel: region is not memory\n");
89 			return;
90 		}
91 
92 		if (memblock_is_region_reserved(crash_base, crash_size)) {
93 			pr_warn("cannot reserve crashkernel: region overlaps reserved memory\n");
94 			return;
95 		}
96 
97 		if (!IS_ALIGNED(crash_base, SZ_2M)) {
98 			pr_warn("cannot reserve crashkernel: base address is not 2MB aligned\n");
99 			return;
100 		}
101 	}
102 	memblock_reserve(crash_base, crash_size);
103 
104 	pr_info("crashkernel reserved: 0x%016llx - 0x%016llx (%lld MB)\n",
105 		crash_base, crash_base + crash_size, crash_size >> 20);
106 
107 	crashk_res.start = crash_base;
108 	crashk_res.end = crash_base + crash_size - 1;
109 }
110 #else
111 static void __init reserve_crashkernel(void)
112 {
113 }
114 #endif /* CONFIG_KEXEC_CORE */
115 
116 #ifdef CONFIG_CRASH_DUMP
117 static int __init early_init_dt_scan_elfcorehdr(unsigned long node,
118 		const char *uname, int depth, void *data)
119 {
120 	const __be32 *reg;
121 	int len;
122 
123 	if (depth != 1 || strcmp(uname, "chosen") != 0)
124 		return 0;
125 
126 	reg = of_get_flat_dt_prop(node, "linux,elfcorehdr", &len);
127 	if (!reg || (len < (dt_root_addr_cells + dt_root_size_cells)))
128 		return 1;
129 
130 	elfcorehdr_addr = dt_mem_next_cell(dt_root_addr_cells, &reg);
131 	elfcorehdr_size = dt_mem_next_cell(dt_root_size_cells, &reg);
132 
133 	return 1;
134 }
135 
136 /*
137  * reserve_elfcorehdr() - reserves memory for elf core header
138  *
139  * This function reserves the memory occupied by an elf core header
140  * described in the device tree. This region contains all the
141  * information about primary kernel's core image and is used by a dump
142  * capture kernel to access the system memory on primary kernel.
143  */
144 static void __init reserve_elfcorehdr(void)
145 {
146 	of_scan_flat_dt(early_init_dt_scan_elfcorehdr, NULL);
147 
148 	if (!elfcorehdr_size)
149 		return;
150 
151 	if (memblock_is_region_reserved(elfcorehdr_addr, elfcorehdr_size)) {
152 		pr_warn("elfcorehdr is overlapped\n");
153 		return;
154 	}
155 
156 	memblock_reserve(elfcorehdr_addr, elfcorehdr_size);
157 
158 	pr_info("Reserving %lldKB of memory at 0x%llx for elfcorehdr\n",
159 		elfcorehdr_size >> 10, elfcorehdr_addr);
160 }
161 #else
162 static void __init reserve_elfcorehdr(void)
163 {
164 }
165 #endif /* CONFIG_CRASH_DUMP */
166 /*
167  * Return the maximum physical address for ZONE_DMA32 (DMA_BIT_MASK(32)). It
168  * currently assumes that for memory starting above 4G, 32-bit devices will
169  * use a DMA offset.
170  */
171 static phys_addr_t __init max_zone_dma_phys(void)
172 {
173 	phys_addr_t offset = memblock_start_of_DRAM() & GENMASK_ULL(63, 32);
174 	return min(offset + (1ULL << 32), memblock_end_of_DRAM());
175 }
176 
177 #ifdef CONFIG_NUMA
178 
179 static void __init zone_sizes_init(unsigned long min, unsigned long max)
180 {
181 	unsigned long max_zone_pfns[MAX_NR_ZONES]  = {0};
182 
183 #ifdef CONFIG_ZONE_DMA32
184 	max_zone_pfns[ZONE_DMA32] = PFN_DOWN(max_zone_dma_phys());
185 #endif
186 	max_zone_pfns[ZONE_NORMAL] = max;
187 
188 	free_area_init_nodes(max_zone_pfns);
189 }
190 
191 #else
192 
193 static void __init zone_sizes_init(unsigned long min, unsigned long max)
194 {
195 	struct memblock_region *reg;
196 	unsigned long zone_size[MAX_NR_ZONES], zhole_size[MAX_NR_ZONES];
197 	unsigned long max_dma = min;
198 
199 	memset(zone_size, 0, sizeof(zone_size));
200 
201 	/* 4GB maximum for 32-bit only capable devices */
202 #ifdef CONFIG_ZONE_DMA32
203 	max_dma = PFN_DOWN(arm64_dma_phys_limit);
204 	zone_size[ZONE_DMA32] = max_dma - min;
205 #endif
206 	zone_size[ZONE_NORMAL] = max - max_dma;
207 
208 	memcpy(zhole_size, zone_size, sizeof(zhole_size));
209 
210 	for_each_memblock(memory, reg) {
211 		unsigned long start = memblock_region_memory_base_pfn(reg);
212 		unsigned long end = memblock_region_memory_end_pfn(reg);
213 
214 		if (start >= max)
215 			continue;
216 
217 #ifdef CONFIG_ZONE_DMA32
218 		if (start < max_dma) {
219 			unsigned long dma_end = min(end, max_dma);
220 			zhole_size[ZONE_DMA32] -= dma_end - start;
221 		}
222 #endif
223 		if (end > max_dma) {
224 			unsigned long normal_end = min(end, max);
225 			unsigned long normal_start = max(start, max_dma);
226 			zhole_size[ZONE_NORMAL] -= normal_end - normal_start;
227 		}
228 	}
229 
230 	free_area_init_node(0, zone_size, min, zhole_size);
231 }
232 
233 #endif /* CONFIG_NUMA */
234 
235 int pfn_valid(unsigned long pfn)
236 {
237 	phys_addr_t addr = pfn << PAGE_SHIFT;
238 
239 	if ((addr >> PAGE_SHIFT) != pfn)
240 		return 0;
241 
242 #ifdef CONFIG_SPARSEMEM
243 	if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS)
244 		return 0;
245 
246 	if (!valid_section(__nr_to_section(pfn_to_section_nr(pfn))))
247 		return 0;
248 #endif
249 	return memblock_is_map_memory(addr);
250 }
251 EXPORT_SYMBOL(pfn_valid);
252 
253 static phys_addr_t memory_limit = PHYS_ADDR_MAX;
254 
255 /*
256  * Limit the memory size that was specified via FDT.
257  */
258 static int __init early_mem(char *p)
259 {
260 	if (!p)
261 		return 1;
262 
263 	memory_limit = memparse(p, &p) & PAGE_MASK;
264 	pr_notice("Memory limited to %lldMB\n", memory_limit >> 20);
265 
266 	return 0;
267 }
268 early_param("mem", early_mem);
269 
270 static int __init early_init_dt_scan_usablemem(unsigned long node,
271 		const char *uname, int depth, void *data)
272 {
273 	struct memblock_region *usablemem = data;
274 	const __be32 *reg;
275 	int len;
276 
277 	if (depth != 1 || strcmp(uname, "chosen") != 0)
278 		return 0;
279 
280 	reg = of_get_flat_dt_prop(node, "linux,usable-memory-range", &len);
281 	if (!reg || (len < (dt_root_addr_cells + dt_root_size_cells)))
282 		return 1;
283 
284 	usablemem->base = dt_mem_next_cell(dt_root_addr_cells, &reg);
285 	usablemem->size = dt_mem_next_cell(dt_root_size_cells, &reg);
286 
287 	return 1;
288 }
289 
290 static void __init fdt_enforce_memory_region(void)
291 {
292 	struct memblock_region reg = {
293 		.size = 0,
294 	};
295 
296 	of_scan_flat_dt(early_init_dt_scan_usablemem, &reg);
297 
298 	if (reg.size)
299 		memblock_cap_memory_range(reg.base, reg.size);
300 }
301 
302 void __init arm64_memblock_init(void)
303 {
304 	const s64 linear_region_size = -(s64)PAGE_OFFSET;
305 
306 	/* Handle linux,usable-memory-range property */
307 	fdt_enforce_memory_region();
308 
309 	/* Remove memory above our supported physical address size */
310 	memblock_remove(1ULL << PHYS_MASK_SHIFT, ULLONG_MAX);
311 
312 	/*
313 	 * Ensure that the linear region takes up exactly half of the kernel
314 	 * virtual address space. This way, we can distinguish a linear address
315 	 * from a kernel/module/vmalloc address by testing a single bit.
316 	 */
317 	BUILD_BUG_ON(linear_region_size != BIT(VA_BITS - 1));
318 
319 	/*
320 	 * Select a suitable value for the base of physical memory.
321 	 */
322 	memstart_addr = round_down(memblock_start_of_DRAM(),
323 				   ARM64_MEMSTART_ALIGN);
324 
325 	/*
326 	 * Remove the memory that we will not be able to cover with the
327 	 * linear mapping. Take care not to clip the kernel which may be
328 	 * high in memory.
329 	 */
330 	memblock_remove(max_t(u64, memstart_addr + linear_region_size,
331 			__pa_symbol(_end)), ULLONG_MAX);
332 	if (memstart_addr + linear_region_size < memblock_end_of_DRAM()) {
333 		/* ensure that memstart_addr remains sufficiently aligned */
334 		memstart_addr = round_up(memblock_end_of_DRAM() - linear_region_size,
335 					 ARM64_MEMSTART_ALIGN);
336 		memblock_remove(0, memstart_addr);
337 	}
338 
339 	/*
340 	 * Apply the memory limit if it was set. Since the kernel may be loaded
341 	 * high up in memory, add back the kernel region that must be accessible
342 	 * via the linear mapping.
343 	 */
344 	if (memory_limit != PHYS_ADDR_MAX) {
345 		memblock_mem_limit_remove_map(memory_limit);
346 		memblock_add(__pa_symbol(_text), (u64)(_end - _text));
347 	}
348 
349 	if (IS_ENABLED(CONFIG_BLK_DEV_INITRD) && phys_initrd_size) {
350 		/*
351 		 * Add back the memory we just removed if it results in the
352 		 * initrd to become inaccessible via the linear mapping.
353 		 * Otherwise, this is a no-op
354 		 */
355 		u64 base = phys_initrd_start & PAGE_MASK;
356 		u64 size = PAGE_ALIGN(phys_initrd_start + phys_initrd_size) - base;
357 
358 		/*
359 		 * We can only add back the initrd memory if we don't end up
360 		 * with more memory than we can address via the linear mapping.
361 		 * It is up to the bootloader to position the kernel and the
362 		 * initrd reasonably close to each other (i.e., within 32 GB of
363 		 * each other) so that all granule/#levels combinations can
364 		 * always access both.
365 		 */
366 		if (WARN(base < memblock_start_of_DRAM() ||
367 			 base + size > memblock_start_of_DRAM() +
368 				       linear_region_size,
369 			"initrd not fully accessible via the linear mapping -- please check your bootloader ...\n")) {
370 			phys_initrd_size = 0;
371 		} else {
372 			memblock_remove(base, size); /* clear MEMBLOCK_ flags */
373 			memblock_add(base, size);
374 			memblock_reserve(base, size);
375 		}
376 	}
377 
378 	if (IS_ENABLED(CONFIG_RANDOMIZE_BASE)) {
379 		extern u16 memstart_offset_seed;
380 		u64 range = linear_region_size -
381 			    (memblock_end_of_DRAM() - memblock_start_of_DRAM());
382 
383 		/*
384 		 * If the size of the linear region exceeds, by a sufficient
385 		 * margin, the size of the region that the available physical
386 		 * memory spans, randomize the linear region as well.
387 		 */
388 		if (memstart_offset_seed > 0 && range >= ARM64_MEMSTART_ALIGN) {
389 			range /= ARM64_MEMSTART_ALIGN;
390 			memstart_addr -= ARM64_MEMSTART_ALIGN *
391 					 ((range * memstart_offset_seed) >> 16);
392 		}
393 	}
394 
395 	/*
396 	 * Register the kernel text, kernel data, initrd, and initial
397 	 * pagetables with memblock.
398 	 */
399 	memblock_reserve(__pa_symbol(_text), _end - _text);
400 	if (IS_ENABLED(CONFIG_BLK_DEV_INITRD) && phys_initrd_size) {
401 		/* the generic initrd code expects virtual addresses */
402 		initrd_start = __phys_to_virt(phys_initrd_start);
403 		initrd_end = initrd_start + phys_initrd_size;
404 	}
405 
406 	early_init_fdt_scan_reserved_mem();
407 
408 	/* 4GB maximum for 32-bit only capable devices */
409 	if (IS_ENABLED(CONFIG_ZONE_DMA32))
410 		arm64_dma_phys_limit = max_zone_dma_phys();
411 	else
412 		arm64_dma_phys_limit = PHYS_MASK + 1;
413 
414 	reserve_crashkernel();
415 
416 	reserve_elfcorehdr();
417 
418 	high_memory = __va(memblock_end_of_DRAM() - 1) + 1;
419 
420 	dma_contiguous_reserve(arm64_dma_phys_limit);
421 }
422 
423 void __init bootmem_init(void)
424 {
425 	unsigned long min, max;
426 
427 	min = PFN_UP(memblock_start_of_DRAM());
428 	max = PFN_DOWN(memblock_end_of_DRAM());
429 
430 	early_memtest(min << PAGE_SHIFT, max << PAGE_SHIFT);
431 
432 	max_pfn = max_low_pfn = max;
433 	min_low_pfn = min;
434 
435 	arm64_numa_init();
436 	/*
437 	 * Sparsemem tries to allocate bootmem in memory_present(), so must be
438 	 * done after the fixed reservations.
439 	 */
440 	memblocks_present();
441 
442 	sparse_init();
443 	zone_sizes_init(min, max);
444 
445 	memblock_dump_all();
446 }
447 
448 #ifndef CONFIG_SPARSEMEM_VMEMMAP
449 static inline void free_memmap(unsigned long start_pfn, unsigned long end_pfn)
450 {
451 	struct page *start_pg, *end_pg;
452 	unsigned long pg, pgend;
453 
454 	/*
455 	 * Convert start_pfn/end_pfn to a struct page pointer.
456 	 */
457 	start_pg = pfn_to_page(start_pfn - 1) + 1;
458 	end_pg = pfn_to_page(end_pfn - 1) + 1;
459 
460 	/*
461 	 * Convert to physical addresses, and round start upwards and end
462 	 * downwards.
463 	 */
464 	pg = (unsigned long)PAGE_ALIGN(__pa(start_pg));
465 	pgend = (unsigned long)__pa(end_pg) & PAGE_MASK;
466 
467 	/*
468 	 * If there are free pages between these, free the section of the
469 	 * memmap array.
470 	 */
471 	if (pg < pgend)
472 		memblock_free(pg, pgend - pg);
473 }
474 
475 /*
476  * The mem_map array can get very big. Free the unused area of the memory map.
477  */
478 static void __init free_unused_memmap(void)
479 {
480 	unsigned long start, prev_end = 0;
481 	struct memblock_region *reg;
482 
483 	for_each_memblock(memory, reg) {
484 		start = __phys_to_pfn(reg->base);
485 
486 #ifdef CONFIG_SPARSEMEM
487 		/*
488 		 * Take care not to free memmap entries that don't exist due
489 		 * to SPARSEMEM sections which aren't present.
490 		 */
491 		start = min(start, ALIGN(prev_end, PAGES_PER_SECTION));
492 #endif
493 		/*
494 		 * If we had a previous bank, and there is a space between the
495 		 * current bank and the previous, free it.
496 		 */
497 		if (prev_end && prev_end < start)
498 			free_memmap(prev_end, start);
499 
500 		/*
501 		 * Align up here since the VM subsystem insists that the
502 		 * memmap entries are valid from the bank end aligned to
503 		 * MAX_ORDER_NR_PAGES.
504 		 */
505 		prev_end = ALIGN(__phys_to_pfn(reg->base + reg->size),
506 				 MAX_ORDER_NR_PAGES);
507 	}
508 
509 #ifdef CONFIG_SPARSEMEM
510 	if (!IS_ALIGNED(prev_end, PAGES_PER_SECTION))
511 		free_memmap(prev_end, ALIGN(prev_end, PAGES_PER_SECTION));
512 #endif
513 }
514 #endif	/* !CONFIG_SPARSEMEM_VMEMMAP */
515 
516 /*
517  * mem_init() marks the free areas in the mem_map and tells us how much memory
518  * is free.  This is done after various parts of the system have claimed their
519  * memory after the kernel image.
520  */
521 void __init mem_init(void)
522 {
523 	if (swiotlb_force == SWIOTLB_FORCE ||
524 	    max_pfn > (arm64_dma_phys_limit >> PAGE_SHIFT))
525 		swiotlb_init(1);
526 	else
527 		swiotlb_force = SWIOTLB_NO_FORCE;
528 
529 	set_max_mapnr(max_pfn - PHYS_PFN_OFFSET);
530 
531 #ifndef CONFIG_SPARSEMEM_VMEMMAP
532 	free_unused_memmap();
533 #endif
534 	/* this will put all unused low memory onto the freelists */
535 	memblock_free_all();
536 
537 	mem_init_print_info(NULL);
538 
539 	/*
540 	 * Check boundaries twice: Some fundamental inconsistencies can be
541 	 * detected at build time already.
542 	 */
543 #ifdef CONFIG_COMPAT
544 	BUILD_BUG_ON(TASK_SIZE_32 > DEFAULT_MAP_WINDOW_64);
545 #endif
546 
547 	if (PAGE_SIZE >= 16384 && get_num_physpages() <= 128) {
548 		extern int sysctl_overcommit_memory;
549 		/*
550 		 * On a machine this small we won't get anywhere without
551 		 * overcommit, so turn it on by default.
552 		 */
553 		sysctl_overcommit_memory = OVERCOMMIT_ALWAYS;
554 	}
555 }
556 
557 void free_initmem(void)
558 {
559 	free_reserved_area(lm_alias(__init_begin),
560 			   lm_alias(__init_end),
561 			   0, "unused kernel");
562 	/*
563 	 * Unmap the __init region but leave the VM area in place. This
564 	 * prevents the region from being reused for kernel modules, which
565 	 * is not supported by kallsyms.
566 	 */
567 	unmap_kernel_range((u64)__init_begin, (u64)(__init_end - __init_begin));
568 }
569 
570 #ifdef CONFIG_BLK_DEV_INITRD
571 void __init free_initrd_mem(unsigned long start, unsigned long end)
572 {
573 	free_reserved_area((void *)start, (void *)end, 0, "initrd");
574 	memblock_free(__virt_to_phys(start), end - start);
575 }
576 #endif
577 
578 /*
579  * Dump out memory limit information on panic.
580  */
581 static int dump_mem_limit(struct notifier_block *self, unsigned long v, void *p)
582 {
583 	if (memory_limit != PHYS_ADDR_MAX) {
584 		pr_emerg("Memory Limit: %llu MB\n", memory_limit >> 20);
585 	} else {
586 		pr_emerg("Memory Limit: none\n");
587 	}
588 	return 0;
589 }
590 
591 static struct notifier_block mem_limit_notifier = {
592 	.notifier_call = dump_mem_limit,
593 };
594 
595 static int __init register_mem_limit_dumper(void)
596 {
597 	atomic_notifier_chain_register(&panic_notifier_list,
598 				       &mem_limit_notifier);
599 	return 0;
600 }
601 __initcall(register_mem_limit_dumper);
602