memblock: make memblock_find_in_range method private
[linux-2.6-microblaze.git] / arch / arm64 / mm / init.c
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-direct.h>
24 #include <linux/dma-map-ops.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 #include <linux/hugetlb.h>
32 #include <linux/acpi_iort.h>
33
34 #include <asm/boot.h>
35 #include <asm/fixmap.h>
36 #include <asm/kasan.h>
37 #include <asm/kernel-pgtable.h>
38 #include <asm/kvm_host.h>
39 #include <asm/memory.h>
40 #include <asm/numa.h>
41 #include <asm/sections.h>
42 #include <asm/setup.h>
43 #include <linux/sizes.h>
44 #include <asm/tlb.h>
45 #include <asm/alternative.h>
46 #include <asm/xen/swiotlb-xen.h>
47
48 /*
49  * We need to be able to catch inadvertent references to memstart_addr
50  * that occur (potentially in generic code) before arm64_memblock_init()
51  * executes, which assigns it its actual value. So use a default value
52  * that cannot be mistaken for a real physical address.
53  */
54 s64 memstart_addr __ro_after_init = -1;
55 EXPORT_SYMBOL(memstart_addr);
56
57 /*
58  * If the corresponding config options are enabled, we create both ZONE_DMA
59  * and ZONE_DMA32. By default ZONE_DMA covers the 32-bit addressable memory
60  * unless restricted on specific platforms (e.g. 30-bit on Raspberry Pi 4).
61  * In such case, ZONE_DMA32 covers the rest of the 32-bit addressable memory,
62  * otherwise it is empty.
63  */
64 phys_addr_t arm64_dma_phys_limit __ro_after_init;
65
66 #ifdef CONFIG_KEXEC_CORE
67 /*
68  * reserve_crashkernel() - reserves memory for crash kernel
69  *
70  * This function reserves memory area given in "crashkernel=" kernel command
71  * line parameter. The memory reserved is used by dump capture kernel when
72  * primary kernel is crashing.
73  */
74 static void __init reserve_crashkernel(void)
75 {
76         unsigned long long crash_base, crash_size;
77         unsigned long long crash_max = arm64_dma_phys_limit;
78         int ret;
79
80         ret = parse_crashkernel(boot_command_line, memblock_phys_mem_size(),
81                                 &crash_size, &crash_base);
82         /* no crashkernel= or invalid value specified */
83         if (ret || !crash_size)
84                 return;
85
86         crash_size = PAGE_ALIGN(crash_size);
87
88         /* User specifies base address explicitly. */
89         if (crash_base)
90                 crash_max = crash_base + crash_size;
91
92         /* Current arm64 boot protocol requires 2MB alignment */
93         crash_base = memblock_phys_alloc_range(crash_size, SZ_2M,
94                                                crash_base, crash_max);
95         if (!crash_base) {
96                 pr_warn("cannot allocate crashkernel (size:0x%llx)\n",
97                         crash_size);
98                 return;
99         }
100
101         pr_info("crashkernel reserved: 0x%016llx - 0x%016llx (%lld MB)\n",
102                 crash_base, crash_base + crash_size, crash_size >> 20);
103
104         crashk_res.start = crash_base;
105         crashk_res.end = crash_base + crash_size - 1;
106 }
107 #else
108 static void __init reserve_crashkernel(void)
109 {
110 }
111 #endif /* CONFIG_KEXEC_CORE */
112
113 #ifdef CONFIG_CRASH_DUMP
114 static int __init early_init_dt_scan_elfcorehdr(unsigned long node,
115                 const char *uname, int depth, void *data)
116 {
117         const __be32 *reg;
118         int len;
119
120         if (depth != 1 || strcmp(uname, "chosen") != 0)
121                 return 0;
122
123         reg = of_get_flat_dt_prop(node, "linux,elfcorehdr", &len);
124         if (!reg || (len < (dt_root_addr_cells + dt_root_size_cells)))
125                 return 1;
126
127         elfcorehdr_addr = dt_mem_next_cell(dt_root_addr_cells, &reg);
128         elfcorehdr_size = dt_mem_next_cell(dt_root_size_cells, &reg);
129
130         return 1;
131 }
132
133 /*
134  * reserve_elfcorehdr() - reserves memory for elf core header
135  *
136  * This function reserves the memory occupied by an elf core header
137  * described in the device tree. This region contains all the
138  * information about primary kernel's core image and is used by a dump
139  * capture kernel to access the system memory on primary kernel.
140  */
141 static void __init reserve_elfcorehdr(void)
142 {
143         of_scan_flat_dt(early_init_dt_scan_elfcorehdr, NULL);
144
145         if (!elfcorehdr_size)
146                 return;
147
148         if (memblock_is_region_reserved(elfcorehdr_addr, elfcorehdr_size)) {
149                 pr_warn("elfcorehdr is overlapped\n");
150                 return;
151         }
152
153         memblock_reserve(elfcorehdr_addr, elfcorehdr_size);
154
155         pr_info("Reserving %lldKB of memory at 0x%llx for elfcorehdr\n",
156                 elfcorehdr_size >> 10, elfcorehdr_addr);
157 }
158 #else
159 static void __init reserve_elfcorehdr(void)
160 {
161 }
162 #endif /* CONFIG_CRASH_DUMP */
163
164 /*
165  * Return the maximum physical address for a zone accessible by the given bits
166  * limit. If DRAM starts above 32-bit, expand the zone to the maximum
167  * available memory, otherwise cap it at 32-bit.
168  */
169 static phys_addr_t __init max_zone_phys(unsigned int zone_bits)
170 {
171         phys_addr_t zone_mask = DMA_BIT_MASK(zone_bits);
172         phys_addr_t phys_start = memblock_start_of_DRAM();
173
174         if (phys_start > U32_MAX)
175                 zone_mask = PHYS_ADDR_MAX;
176         else if (phys_start > zone_mask)
177                 zone_mask = U32_MAX;
178
179         return min(zone_mask, memblock_end_of_DRAM() - 1) + 1;
180 }
181
182 static void __init zone_sizes_init(unsigned long min, unsigned long max)
183 {
184         unsigned long max_zone_pfns[MAX_NR_ZONES]  = {0};
185         unsigned int __maybe_unused acpi_zone_dma_bits;
186         unsigned int __maybe_unused dt_zone_dma_bits;
187         phys_addr_t __maybe_unused dma32_phys_limit = max_zone_phys(32);
188
189 #ifdef CONFIG_ZONE_DMA
190         acpi_zone_dma_bits = fls64(acpi_iort_dma_get_max_cpu_address());
191         dt_zone_dma_bits = fls64(of_dma_get_max_cpu_address(NULL));
192         zone_dma_bits = min3(32U, dt_zone_dma_bits, acpi_zone_dma_bits);
193         arm64_dma_phys_limit = max_zone_phys(zone_dma_bits);
194         max_zone_pfns[ZONE_DMA] = PFN_DOWN(arm64_dma_phys_limit);
195 #endif
196 #ifdef CONFIG_ZONE_DMA32
197         max_zone_pfns[ZONE_DMA32] = PFN_DOWN(dma32_phys_limit);
198         if (!arm64_dma_phys_limit)
199                 arm64_dma_phys_limit = dma32_phys_limit;
200 #endif
201         if (!arm64_dma_phys_limit)
202                 arm64_dma_phys_limit = PHYS_MASK + 1;
203         max_zone_pfns[ZONE_NORMAL] = max;
204
205         free_area_init(max_zone_pfns);
206 }
207
208 int pfn_valid(unsigned long pfn)
209 {
210         phys_addr_t addr = PFN_PHYS(pfn);
211         struct mem_section *ms;
212
213         /*
214          * Ensure the upper PAGE_SHIFT bits are clear in the
215          * pfn. Else it might lead to false positives when
216          * some of the upper bits are set, but the lower bits
217          * match a valid pfn.
218          */
219         if (PHYS_PFN(addr) != pfn)
220                 return 0;
221
222         if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS)
223                 return 0;
224
225         ms = __pfn_to_section(pfn);
226         if (!valid_section(ms))
227                 return 0;
228
229         /*
230          * ZONE_DEVICE memory does not have the memblock entries.
231          * memblock_is_map_memory() check for ZONE_DEVICE based
232          * addresses will always fail. Even the normal hotplugged
233          * memory will never have MEMBLOCK_NOMAP flag set in their
234          * memblock entries. Skip memblock search for all non early
235          * memory sections covering all of hotplug memory including
236          * both normal and ZONE_DEVICE based.
237          */
238         if (!early_section(ms))
239                 return pfn_section_valid(ms, pfn);
240
241         return memblock_is_memory(addr);
242 }
243 EXPORT_SYMBOL(pfn_valid);
244
245 int pfn_is_map_memory(unsigned long pfn)
246 {
247         phys_addr_t addr = PFN_PHYS(pfn);
248
249         /* avoid false positives for bogus PFNs, see comment in pfn_valid() */
250         if (PHYS_PFN(addr) != pfn)
251                 return 0;
252
253         return memblock_is_map_memory(addr);
254 }
255 EXPORT_SYMBOL(pfn_is_map_memory);
256
257 static phys_addr_t memory_limit = PHYS_ADDR_MAX;
258
259 /*
260  * Limit the memory size that was specified via FDT.
261  */
262 static int __init early_mem(char *p)
263 {
264         if (!p)
265                 return 1;
266
267         memory_limit = memparse(p, &p) & PAGE_MASK;
268         pr_notice("Memory limited to %lldMB\n", memory_limit >> 20);
269
270         return 0;
271 }
272 early_param("mem", early_mem);
273
274 static int __init early_init_dt_scan_usablemem(unsigned long node,
275                 const char *uname, int depth, void *data)
276 {
277         struct memblock_region *usablemem = data;
278         const __be32 *reg;
279         int len;
280
281         if (depth != 1 || strcmp(uname, "chosen") != 0)
282                 return 0;
283
284         reg = of_get_flat_dt_prop(node, "linux,usable-memory-range", &len);
285         if (!reg || (len < (dt_root_addr_cells + dt_root_size_cells)))
286                 return 1;
287
288         usablemem->base = dt_mem_next_cell(dt_root_addr_cells, &reg);
289         usablemem->size = dt_mem_next_cell(dt_root_size_cells, &reg);
290
291         return 1;
292 }
293
294 static void __init fdt_enforce_memory_region(void)
295 {
296         struct memblock_region reg = {
297                 .size = 0,
298         };
299
300         of_scan_flat_dt(early_init_dt_scan_usablemem, &reg);
301
302         if (reg.size)
303                 memblock_cap_memory_range(reg.base, reg.size);
304 }
305
306 void __init arm64_memblock_init(void)
307 {
308         const s64 linear_region_size = PAGE_END - _PAGE_OFFSET(vabits_actual);
309
310         /* Handle linux,usable-memory-range property */
311         fdt_enforce_memory_region();
312
313         /* Remove memory above our supported physical address size */
314         memblock_remove(1ULL << PHYS_MASK_SHIFT, ULLONG_MAX);
315
316         /*
317          * Select a suitable value for the base of physical memory.
318          */
319         memstart_addr = round_down(memblock_start_of_DRAM(),
320                                    ARM64_MEMSTART_ALIGN);
321
322         if ((memblock_end_of_DRAM() - memstart_addr) > linear_region_size)
323                 pr_warn("Memory doesn't fit in the linear mapping, VA_BITS too small\n");
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          * If we are running with a 52-bit kernel VA config on a system that
341          * does not support it, we have to place the available physical
342          * memory in the 48-bit addressable part of the linear region, i.e.,
343          * we have to move it upward. Since memstart_addr represents the
344          * physical address of PAGE_OFFSET, we have to *subtract* from it.
345          */
346         if (IS_ENABLED(CONFIG_ARM64_VA_BITS_52) && (vabits_actual != 52))
347                 memstart_addr -= _PAGE_OFFSET(48) - _PAGE_OFFSET(52);
348
349         /*
350          * Apply the memory limit if it was set. Since the kernel may be loaded
351          * high up in memory, add back the kernel region that must be accessible
352          * via the linear mapping.
353          */
354         if (memory_limit != PHYS_ADDR_MAX) {
355                 memblock_mem_limit_remove_map(memory_limit);
356                 memblock_add(__pa_symbol(_text), (u64)(_end - _text));
357         }
358
359         if (IS_ENABLED(CONFIG_BLK_DEV_INITRD) && phys_initrd_size) {
360                 /*
361                  * Add back the memory we just removed if it results in the
362                  * initrd to become inaccessible via the linear mapping.
363                  * Otherwise, this is a no-op
364                  */
365                 u64 base = phys_initrd_start & PAGE_MASK;
366                 u64 size = PAGE_ALIGN(phys_initrd_start + phys_initrd_size) - base;
367
368                 /*
369                  * We can only add back the initrd memory if we don't end up
370                  * with more memory than we can address via the linear mapping.
371                  * It is up to the bootloader to position the kernel and the
372                  * initrd reasonably close to each other (i.e., within 32 GB of
373                  * each other) so that all granule/#levels combinations can
374                  * always access both.
375                  */
376                 if (WARN(base < memblock_start_of_DRAM() ||
377                          base + size > memblock_start_of_DRAM() +
378                                        linear_region_size,
379                         "initrd not fully accessible via the linear mapping -- please check your bootloader ...\n")) {
380                         phys_initrd_size = 0;
381                 } else {
382                         memblock_remove(base, size); /* clear MEMBLOCK_ flags */
383                         memblock_add(base, size);
384                         memblock_reserve(base, size);
385                 }
386         }
387
388         if (IS_ENABLED(CONFIG_RANDOMIZE_BASE)) {
389                 extern u16 memstart_offset_seed;
390                 u64 mmfr0 = read_cpuid(ID_AA64MMFR0_EL1);
391                 int parange = cpuid_feature_extract_unsigned_field(
392                                         mmfr0, ID_AA64MMFR0_PARANGE_SHIFT);
393                 s64 range = linear_region_size -
394                             BIT(id_aa64mmfr0_parange_to_phys_shift(parange));
395
396                 /*
397                  * If the size of the linear region exceeds, by a sufficient
398                  * margin, the size of the region that the physical memory can
399                  * span, randomize the linear region as well.
400                  */
401                 if (memstart_offset_seed > 0 && range >= (s64)ARM64_MEMSTART_ALIGN) {
402                         range /= ARM64_MEMSTART_ALIGN;
403                         memstart_addr -= ARM64_MEMSTART_ALIGN *
404                                          ((range * memstart_offset_seed) >> 16);
405                 }
406         }
407
408         /*
409          * Register the kernel text, kernel data, initrd, and initial
410          * pagetables with memblock.
411          */
412         memblock_reserve(__pa_symbol(_stext), _end - _stext);
413         if (IS_ENABLED(CONFIG_BLK_DEV_INITRD) && phys_initrd_size) {
414                 /* the generic initrd code expects virtual addresses */
415                 initrd_start = __phys_to_virt(phys_initrd_start);
416                 initrd_end = initrd_start + phys_initrd_size;
417         }
418
419         early_init_fdt_scan_reserved_mem();
420
421         reserve_elfcorehdr();
422
423         high_memory = __va(memblock_end_of_DRAM() - 1) + 1;
424 }
425
426 void __init bootmem_init(void)
427 {
428         unsigned long min, max;
429
430         min = PFN_UP(memblock_start_of_DRAM());
431         max = PFN_DOWN(memblock_end_of_DRAM());
432
433         early_memtest(min << PAGE_SHIFT, max << PAGE_SHIFT);
434
435         max_pfn = max_low_pfn = max;
436         min_low_pfn = min;
437
438         arch_numa_init();
439
440         /*
441          * must be done after arch_numa_init() which calls numa_init() to
442          * initialize node_online_map that gets used in hugetlb_cma_reserve()
443          * while allocating required CMA size across online nodes.
444          */
445 #if defined(CONFIG_HUGETLB_PAGE) && defined(CONFIG_CMA)
446         arm64_hugetlb_cma_reserve();
447 #endif
448
449         dma_pernuma_cma_reserve();
450
451         kvm_hyp_reserve();
452
453         /*
454          * sparse_init() tries to allocate memory from memblock, so must be
455          * done after the fixed reservations
456          */
457         sparse_init();
458         zone_sizes_init(min, max);
459
460         /*
461          * Reserve the CMA area after arm64_dma_phys_limit was initialised.
462          */
463         dma_contiguous_reserve(arm64_dma_phys_limit);
464
465         /*
466          * request_standard_resources() depends on crashkernel's memory being
467          * reserved, so do it here.
468          */
469         reserve_crashkernel();
470
471         memblock_dump_all();
472 }
473
474 /*
475  * mem_init() marks the free areas in the mem_map and tells us how much memory
476  * is free.  This is done after various parts of the system have claimed their
477  * memory after the kernel image.
478  */
479 void __init mem_init(void)
480 {
481         if (swiotlb_force == SWIOTLB_FORCE ||
482             max_pfn > PFN_DOWN(arm64_dma_phys_limit))
483                 swiotlb_init(1);
484         else if (!xen_swiotlb_detect())
485                 swiotlb_force = SWIOTLB_NO_FORCE;
486
487         set_max_mapnr(max_pfn - PHYS_PFN_OFFSET);
488
489         /* this will put all unused low memory onto the freelists */
490         memblock_free_all();
491
492         /*
493          * Check boundaries twice: Some fundamental inconsistencies can be
494          * detected at build time already.
495          */
496 #ifdef CONFIG_COMPAT
497         BUILD_BUG_ON(TASK_SIZE_32 > DEFAULT_MAP_WINDOW_64);
498 #endif
499
500         /*
501          * Selected page table levels should match when derived from
502          * scratch using the virtual address range and page size.
503          */
504         BUILD_BUG_ON(ARM64_HW_PGTABLE_LEVELS(CONFIG_ARM64_VA_BITS) !=
505                      CONFIG_PGTABLE_LEVELS);
506
507         if (PAGE_SIZE >= 16384 && get_num_physpages() <= 128) {
508                 extern int sysctl_overcommit_memory;
509                 /*
510                  * On a machine this small we won't get anywhere without
511                  * overcommit, so turn it on by default.
512                  */
513                 sysctl_overcommit_memory = OVERCOMMIT_ALWAYS;
514         }
515 }
516
517 void free_initmem(void)
518 {
519         free_reserved_area(lm_alias(__init_begin),
520                            lm_alias(__init_end),
521                            POISON_FREE_INITMEM, "unused kernel");
522         /*
523          * Unmap the __init region but leave the VM area in place. This
524          * prevents the region from being reused for kernel modules, which
525          * is not supported by kallsyms.
526          */
527         vunmap_range((u64)__init_begin, (u64)__init_end);
528 }
529
530 void dump_mem_limit(void)
531 {
532         if (memory_limit != PHYS_ADDR_MAX) {
533                 pr_emerg("Memory Limit: %llu MB\n", memory_limit >> 20);
534         } else {
535                 pr_emerg("Memory Limit: none\n");
536         }
537 }