1 // SPDX-License-Identifier: GPL-2.0-only
3 #include <linux/kernel.h>
4 #include <linux/libfdt.h>
5 #include <linux/sizes.h>
7 static const void *get_prop(const void *fdt, const char *node_path,
8 const char *property, int minlen)
13 offset = fdt_path_offset(fdt, node_path);
17 prop = fdt_getprop(fdt, offset, property, &len);
18 if (!prop || len < minlen)
24 static uint32_t get_cells(const void *fdt, const char *name)
26 const fdt32_t *prop = get_prop(fdt, "/", name, sizeof(fdt32_t));
33 return fdt32_ld(prop);
36 static uint64_t get_val(const fdt32_t *cells, uint32_t ncells)
42 r = (r << 32) | fdt32_ld(cells + 1);
48 * Check the start of physical memory
50 * Traditionally, the start address of physical memory is obtained by masking
51 * the program counter. However, this does require that this address is a
52 * multiple of 128 MiB, precluding booting Linux on platforms where this
53 * requirement is not fulfilled.
54 * Hence validate the calculated address against the memory information in the
55 * DTB, and, if out-of-range, replace it by the real start address.
56 * To preserve backwards compatibility (systems reserving a block of memory
57 * at the start of physical memory, kdump, ...), the traditional method is
58 * always used if it yields a valid address.
60 * Return value: start address of physical memory to use
62 uint32_t fdt_check_mem_start(uint32_t mem_start, const void *fdt)
64 uint32_t addr_cells, size_cells, base;
65 uint32_t fdt_mem_start = 0xffffffff;
66 const fdt32_t *reg, *endp;
74 if (fdt_magic(fdt) != FDT_MAGIC)
77 /* There may be multiple cells on LPAE platforms */
78 addr_cells = get_cells(fdt, "#address-cells");
79 size_cells = get_cells(fdt, "#size-cells");
80 if (addr_cells > 2 || size_cells > 2)
83 /* Walk all memory nodes and regions */
84 for (offset = fdt_next_node(fdt, -1, NULL); offset >= 0;
85 offset = fdt_next_node(fdt, offset, NULL)) {
86 type = fdt_getprop(fdt, offset, "device_type", NULL);
87 if (!type || strcmp(type, "memory"))
90 reg = fdt_getprop(fdt, offset, "linux,usable-memory", &len);
92 reg = fdt_getprop(fdt, offset, "reg", &len);
96 for (endp = reg + (len / sizeof(fdt32_t));
97 endp - reg >= addr_cells + size_cells;
98 reg += addr_cells + size_cells) {
99 size = get_val(reg + addr_cells, size_cells);
103 if (addr_cells > 1 && fdt32_ld(reg)) {
104 /* Outside 32-bit address space, skipping */
108 base = fdt32_ld(reg + addr_cells - 1);
110 if (mem_start >= base && mem_start < end) {
111 /* Calculated address is valid, use it */
115 if (base < fdt_mem_start)
116 fdt_mem_start = base;
120 if (fdt_mem_start == 0xffffffff) {
121 /* No usable memory found, falling back to default */
126 * The calculated address is not usable.
127 * Use the lowest usable physical memory address from the DTB instead,
128 * and make sure this is a multiple of 2 MiB for phys/virt patching.
130 return round_up(fdt_mem_start, SZ_2M);