mb/google/brya/var/orisa: Update Type C DisplayPort HPD Configuration
[coreboot2.git] / src / commonlib / device_tree.c
blobcb7a596bc57d4f02681b7a3df5ff31f5396b57dc
1 /* Taken from depthcharge: src/base/device_tree.c */
2 /* SPDX-License-Identifier: GPL-2.0-or-later */
4 #include <assert.h>
5 #include <commonlib/device_tree.h>
6 #include <ctype.h>
7 #include <endian.h>
8 #include <stdbool.h>
9 #include <stdint.h>
10 #ifdef __COREBOOT__
11 #include <console/console.h>
12 #else
13 #include <stdio.h>
14 #define printk(level, ...) printf(__VA_ARGS__)
15 #endif
16 #include <stdio.h>
17 #include <string.h>
18 #include <stddef.h>
19 #include <stdlib.h>
20 #include <limits.h>
22 #define FDT_PATH_MAX_DEPTH 10 // should be a good enough upper bound
23 #define FDT_PATH_MAX_LEN 128 // should be a good enough upper bound
24 #define FDT_MAX_MEMORY_NODES 4 // should be a good enough upper bound
25 #define FDT_MAX_MEMORY_REGIONS 16 // should be a good enough upper bound
28 * libpayload's malloc() has a linear allocation complexity, which means that it
29 * degrades massively if we make a few thousand small allocations. Preventing
30 * that problem with a custom scratchpad is well-worth some increase in BSS
31 * size (64 * 2000 + 40 * 10000 = ~1/2 MB).
34 /* Try to give these a healthy margin above what the average kernel DT needs. */
35 #define LP_ALLOC_NODE_SCRATCH_COUNT 2000
36 #define LP_ALLOC_PROP_SCRATCH_COUNT 10000
38 static struct device_tree_node *alloc_node(void)
40 #ifndef __COREBOOT__
41 static struct device_tree_node scratch[LP_ALLOC_NODE_SCRATCH_COUNT];
42 static int counter = 0;
44 if (counter < ARRAY_SIZE(scratch))
45 return &scratch[counter++];
46 #endif
47 return xzalloc(sizeof(struct device_tree_node));
50 static struct device_tree_property *alloc_prop(void)
52 #ifndef __COREBOOT__
53 static struct device_tree_property scratch[LP_ALLOC_PROP_SCRATCH_COUNT];
54 static int counter = 0;
56 if (counter < ARRAY_SIZE(scratch))
57 return &scratch[counter++];
58 #endif
59 return xzalloc(sizeof(struct device_tree_property));
64 * internal functions used by both unflattened and flattened device tree variants
68 static size_t read_reg_prop(struct fdt_property *prop, u32 addr_cells, u32 size_cells,
69 struct device_tree_region regions[], size_t regions_count)
71 // we found the reg property, no need to parse all regions in 'reg'
72 size_t count = prop->size / (4 * addr_cells + 4 * size_cells);
73 if (count > regions_count) {
74 printk(BIOS_ERR, "reg property has more entries (%zd) than regions array can hold (%zd)\n", count, regions_count);
75 count = regions_count;
77 if (addr_cells > 2 || size_cells > 2) {
78 printk(BIOS_ERR, "addr_cells (%d) or size_cells (%d) bigger than 2\n",
79 addr_cells, size_cells);
80 return 0;
82 uint32_t *ptr = prop->data;
83 for (int i = 0; i < count; i++) {
84 if (addr_cells == 1)
85 regions[i].addr = be32dec(ptr);
86 else if (addr_cells == 2)
87 regions[i].addr = be64dec(ptr);
88 ptr += addr_cells;
89 if (size_cells == 1)
90 regions[i].size = be32dec(ptr);
91 else if (size_cells == 2)
92 regions[i].size = be64dec(ptr);
93 ptr += size_cells;
96 return count; // return the number of regions found in the reg property
101 * Functions for picking apart flattened trees.
105 static int fdt_skip_nops(const void *blob, uint32_t offset)
107 uint32_t *ptr = (uint32_t *)(((uint8_t *)blob) + offset);
109 int index = 0;
110 while (be32toh(ptr[index]) == FDT_TOKEN_NOP)
111 index++;
113 return index * sizeof(uint32_t);
116 int fdt_next_property(const void *blob, uint32_t offset,
117 struct fdt_property *prop)
119 struct fdt_header *header = (struct fdt_header *)blob;
120 uint32_t *ptr = (uint32_t *)(((uint8_t *)blob) + offset);
122 // skip NOP tokens
123 offset += fdt_skip_nops(blob, offset);
125 int index = 0;
126 if (be32toh(ptr[index++]) != FDT_TOKEN_PROPERTY)
127 return 0;
129 uint32_t size = be32toh(ptr[index++]);
130 uint32_t name_offset = be32toh(ptr[index++]);
131 name_offset += be32toh(header->strings_offset);
133 if (prop) {
134 prop->name = (char *)((uint8_t *)blob + name_offset);
135 prop->data = &ptr[index];
136 prop->size = size;
139 index += DIV_ROUND_UP(size, sizeof(uint32_t));
141 return index * sizeof(uint32_t);
145 * fdt_next_node_name reads a node name
147 * @params blob address of FDT
148 * @params offset offset to the node to read the name from
149 * @params name parameter to hold the name that has been read or NULL
151 * @returns Either 0 on error or offset to the properties that come after the node name
153 int fdt_next_node_name(const void *blob, uint32_t offset, const char **name)
155 // skip NOP tokens
156 offset += fdt_skip_nops(blob, offset);
158 char *ptr = ((char *)blob) + offset;
159 if (be32dec(ptr) != FDT_TOKEN_BEGIN_NODE)
160 return 0;
162 ptr += 4;
163 if (name)
164 *name = ptr;
166 return ALIGN_UP(strlen(ptr) + 1, 4) + 4;
170 * A utility function to skip past nodes in flattened trees.
172 int fdt_skip_node(const void *blob, uint32_t start_offset)
174 uint32_t offset = start_offset;
176 const char *name;
177 int size = fdt_next_node_name(blob, offset, &name);
178 if (!size)
179 return 0;
180 offset += size;
182 while ((size = fdt_next_property(blob, offset, NULL)))
183 offset += size;
185 while ((size = fdt_skip_node(blob, offset)))
186 offset += size;
188 // skip NOP tokens
189 offset += fdt_skip_nops(blob, offset);
191 return offset - start_offset + sizeof(uint32_t);
195 * fdt_read_prop reads a property inside a node
197 * @params blob address of FDT
198 * @params node_offset offset to the node to read the property from
199 * @params prop_name name of the property to read
200 * @params fdt_prop property is saved inside this parameter
202 * @returns Either 0 if no property has been found or an offset that points to the location
203 * of the property
205 u32 fdt_read_prop(const void *blob, u32 node_offset, const char *prop_name,
206 struct fdt_property *fdt_prop)
208 u32 offset = node_offset;
210 offset += fdt_next_node_name(blob, offset, NULL); // skip node name
212 size_t size;
213 while ((size = fdt_next_property(blob, offset, fdt_prop))) {
214 if (strcmp(fdt_prop->name, prop_name) == 0)
215 return offset;
216 offset += size;
218 return 0; // property not found
222 * fdt_read_reg_prop reads the reg property inside a node
224 * @params blob address of FDT
225 * @params node_offset offset to the node to read the reg property from
226 * @params addr_cells number of cells used for one address
227 * @params size_cells number of cells used for one size
228 * @params regions all regions that are read inside the reg property are saved inside
229 * this array
230 * @params regions_count maximum number of entries that can be saved inside the regions array.
232 * Returns: Either 0 on error or returns the number of regions put into the regions array.
234 u32 fdt_read_reg_prop(const void *blob, u32 node_offset, u32 addr_cells, u32 size_cells,
235 struct device_tree_region regions[], size_t regions_count)
237 struct fdt_property prop;
238 u32 offset = fdt_read_prop(blob, node_offset, "reg", &prop);
240 if (!offset) {
241 printk(BIOS_DEBUG, "no reg property found in node_offset: %x\n", node_offset);
242 return 0;
245 return read_reg_prop(&prop, addr_cells, size_cells, regions, regions_count);
248 static u32 fdt_read_cell_props(const void *blob, u32 node_offset, u32 *addrcp, u32 *sizecp)
250 struct fdt_property prop;
251 u32 offset = node_offset;
252 size_t size;
253 while ((size = fdt_next_property(blob, offset, &prop))) {
254 if (addrcp && !strcmp(prop.name, "#address-cells"))
255 *addrcp = be32dec(prop.data);
256 if (sizecp && !strcmp(prop.name, "#size-cells"))
257 *sizecp = be32dec(prop.data);
258 offset += size;
260 return offset;
264 * fdt_find_node searches for a node relative to another node
266 * @params blob address of FDT
268 * @params parent_node_offset offset to node from which to traverse the tree
270 * @params path null terminated array of node names specifying a
271 * relative path (e.g: { "cpus", "cpu0", NULL })
273 * @params addrcp/sizecp If any address-cells and size-cells properties are found that are
274 * part of the parent node of the node we are looking, addrcp and sizecp
275 * are set to these respectively.
277 * @returns: Either 0 if no node has been found or the offset to the node found
279 static u32 fdt_find_node(const void *blob, u32 parent_node_offset, char **path,
280 u32 *addrcp, u32 *sizecp)
282 if (*path == NULL)
283 return parent_node_offset; // node found
285 size_t size = fdt_next_node_name(blob, parent_node_offset, NULL); // skip node name
288 * get address-cells and size-cells properties while skipping the others.
289 * According to spec address-cells and size-cells are not inherited, but we
290 * intentionally follow the Linux implementation here and treat them as inheritable.
292 u32 node_offset = fdt_read_cell_props(blob, parent_node_offset + size, addrcp, sizecp);
294 const char *node_name;
295 // walk all children nodes
296 while ((size = fdt_next_node_name(blob, node_offset, &node_name))) {
297 if (!strcmp(*path, node_name)) {
298 // traverse one level deeper into the path
299 return fdt_find_node(blob, node_offset, path + 1, addrcp, sizecp);
301 // node is not the correct one. skip current node
302 node_offset += fdt_skip_node(blob, node_offset);
305 // we have searched everything and could not find a fitting node
306 return 0;
310 * fdt_find_node_by_path finds a node behind a given node path
312 * @params blob address of FDT
313 * @params path absolute path to the node that should be searched for
315 * @params addrcp/sizecp Pointer that will be updated with any #address-cells and #size-cells
316 * value found in the node of the node specified by node_offset. Either
317 * may be NULL to ignore. If no #address-cells and #size-cells is found
318 * default values of #address-cells=2 and #size-cells=1 are returned.
320 * @returns Either 0 on error or the offset to the node found behind the path
322 u32 fdt_find_node_by_path(const void *blob, const char *path, u32 *addrcp, u32 *sizecp)
324 // sanity check
325 if (path[0] != '/') {
326 printk(BIOS_ERR, "devicetree path must start with a /\n");
327 return 0;
329 if (!blob) {
330 printk(BIOS_ERR, "devicetree blob is NULL\n");
331 return 0;
334 if (addrcp)
335 *addrcp = 2;
336 if (sizecp)
337 *sizecp = 1;
339 struct fdt_header *fdt_hdr = (struct fdt_header *)blob;
342 * split path into separate nodes
343 * e.g: "/cpus/cpu0" -> { "cpus", "cpu0" }
345 char *path_array[FDT_PATH_MAX_DEPTH];
346 size_t path_size = strlen(path);
347 assert(path_size < FDT_PATH_MAX_LEN);
348 char path_copy[FDT_PATH_MAX_LEN];
349 memcpy(path_copy, path, path_size + 1);
350 char *cur = path_copy;
351 int i;
352 for (i = 0; i < FDT_PATH_MAX_DEPTH; i++) {
353 path_array[i] = strtok_r(NULL, "/", &cur);
354 if (!path_array[i])
355 break;
357 assert(i < FDT_PATH_MAX_DEPTH);
359 return fdt_find_node(blob, be32toh(fdt_hdr->structure_offset), path_array, addrcp, sizecp);
363 * fdt_find_subnodes_by_prefix finds a node with a given prefix relative to a parent node
365 * @params blob The FDT to search.
367 * @params node_offset offset to the node of which the children should be searched
369 * @params prefix A string to search for a node with a given prefix. This can for example
370 * be 'cpu' to look for all nodes matching this prefix. Only children of
371 * node_offset are searched. Therefore in order to search all nodes matching
372 * the 'cpu' prefix, node_offset should probably point to the 'cpus' node.
373 * An empty prefix ("") searches for all children nodes of node_offset.
375 * @params addrcp/sizecp Pointer that will be updated with any #address-cells and #size-cells
376 * value found in the node of the node specified by node_offset. Either
377 * may be NULL to ignore. If no #address-cells and #size-cells is found
378 * addrcp and sizecp are left untouched.
380 * @params results Array of offsets pointing to each node matching the given prefix.
381 * @params results_len Number of entries allocated for the 'results' array
383 * @returns offset to last node found behind path or 0 if no node has been found
385 size_t fdt_find_subnodes_by_prefix(const void *blob, u32 node_offset, const char *prefix,
386 u32 *addrcp, u32 *sizecp, u32 *results, size_t results_len)
388 // sanity checks
389 if (!blob || !results || !prefix) {
390 printk(BIOS_ERR, "%s: input parameter cannot be null/\n", __func__);
391 return 0;
394 u32 offset = node_offset;
396 // we don't care about the name of the current node
397 u32 size = fdt_next_node_name(blob, offset, NULL);
398 if (!size) {
399 printk(BIOS_ERR, "%s: node_offset: %x does not point to a node\n",
400 __func__, node_offset);
401 return 0;
403 offset += size;
406 * update addrcp and sizecp if the node contains an address-cells and size-cells
407 * property. Otherwise use addrcp and sizecp provided by caller.
409 offset = fdt_read_cell_props(blob, offset, addrcp, sizecp);
411 size_t count_results = 0;
412 int prefix_len = strlen(prefix);
413 const char *node_name;
414 // walk all children nodes of offset
415 while ((size = fdt_next_node_name(blob, offset, &node_name))) {
417 // check if there is space left in the results array
418 if (count_results >= results_len)
419 break;
421 if (!strncmp(prefix, node_name, prefix_len)) {
422 // we found a node that matches the prefix
423 results[count_results++] = offset;
425 // node does not match the prefix. skip current node
426 offset += fdt_skip_node(blob, offset);
429 // return last occurrence
430 return count_results;
433 static const char *fdt_read_alias_prop(const void *blob, const char *alias_name)
435 u32 node_offset = fdt_find_node_by_path(blob, "/aliases", NULL, NULL);
436 if (!node_offset) {
437 printk(BIOS_DEBUG, "no /aliases node found\n");
438 return NULL;
440 struct fdt_property alias_prop;
441 if (!fdt_read_prop(blob, node_offset, alias_name, &alias_prop)) {
442 printk(BIOS_DEBUG, "property %s in /aliases node not found\n", alias_name);
443 return NULL;
445 return (const char *)alias_prop.data;
449 * Find a node in the tree from a string device tree path.
451 * @params blob Address to the FDT
452 * @params alias_name node name alias that should be searched for.
453 * @params addrcp/sizecp Pointer that will be updated with any #address-cells and #size-cells
454 * value found in the node of the node specified by node_offset. Either
455 * may be NULL to ignore. If no #address-cells and #size-cells is found
456 * default values of #address-cells=2 and #size-cells=1 are returned.
458 * @returns offset to last node found behind path or 0 if no node has been found
460 u32 fdt_find_node_by_alias(const void *blob, const char *alias_name, u32 *addrcp, u32 *sizecp)
462 const char *node_name = fdt_read_alias_prop(blob, alias_name);
463 if (!node_name) {
464 printk(BIOS_DEBUG, "alias %s not found\n", alias_name);
465 return 0;
468 u32 node_offset = fdt_find_node_by_path(blob, node_name, addrcp, sizecp);
469 if (!node_offset) {
470 // This should not happen (invalid devicetree)
471 printk(BIOS_WARNING,
472 "Could not find node '%s', which alias was referring to '%s'\n",
473 node_name, alias_name);
474 return 0;
476 return node_offset;
481 * Functions for printing flattened trees.
484 static void print_indent(int depth)
486 printk(BIOS_DEBUG, "%*s", depth * 8, "");
489 static void print_property(const struct fdt_property *prop, int depth)
491 int is_string = prop->size > 0 &&
492 ((char *)prop->data)[prop->size - 1] == '\0';
494 if (is_string) {
495 for (int i = 0; i < prop->size - 1; i++) {
496 if (!isprint(((char *)prop->data)[i])) {
497 is_string = 0;
498 break;
503 print_indent(depth);
504 if (is_string) {
505 printk(BIOS_DEBUG, "%s = \"%s\";\n",
506 prop->name, (const char *)prop->data);
507 } else {
508 printk(BIOS_DEBUG, "%s = < ", prop->name);
509 for (int i = 0; i < MIN(128, prop->size); i += 4) {
510 uint32_t val = 0;
511 for (int j = 0; j < MIN(4, prop->size - i); j++)
512 val |= ((uint8_t *)prop->data)[i + j] <<
513 (24 - j * 8);
514 printk(BIOS_DEBUG, "%#.2x ", val);
516 if (prop->size > 128)
517 printk(BIOS_DEBUG, "...");
518 printk(BIOS_DEBUG, ">;\n");
522 static int print_flat_node(const void *blob, uint32_t start_offset, int depth)
524 int offset = start_offset;
525 const char *name;
526 int size;
528 size = fdt_next_node_name(blob, offset, &name);
529 if (!size)
530 return 0;
531 offset += size;
533 print_indent(depth);
534 printk(BIOS_DEBUG, "%s {\n", name);
536 struct fdt_property prop;
537 while ((size = fdt_next_property(blob, offset, &prop))) {
538 print_property(&prop, depth + 1);
540 offset += size;
543 printk(BIOS_DEBUG, "\n"); /* empty line between props and nodes */
545 while ((size = print_flat_node(blob, offset, depth + 1)))
546 offset += size;
548 print_indent(depth);
549 printk(BIOS_DEBUG, "}\n");
551 return offset - start_offset + sizeof(uint32_t);
554 void fdt_print_node(const void *blob, uint32_t offset)
556 print_flat_node(blob, offset, 0);
560 * fdt_read_memory_regions finds memory ranges from a flat device-tree
562 * @params blob address of FDT
563 * @params regions all regions that are read inside the reg property of
564 * memory nodes are saved inside this array
565 * @params regions_count maximum number of entries that can be saved inside
566 * the regions array.
568 * Returns: Either 0 on error or returns the number of regions put into the regions array.
570 size_t fdt_read_memory_regions(const void *blob,
571 struct device_tree_region regions[],
572 size_t regions_count)
574 u32 node, root, addrcp, sizecp;
575 u32 nodes[FDT_MAX_MEMORY_NODES] = {0};
576 size_t region_idx = 0;
577 size_t node_count = 0;
579 if (!fdt_is_valid(blob))
580 return 0;
582 node = fdt_find_node_by_path(blob, "/memory", &addrcp, &sizecp);
583 if (node) {
584 region_idx += fdt_read_reg_prop(blob, node, addrcp, sizecp,
585 regions, regions_count);
586 if (region_idx >= regions_count) {
587 printk(BIOS_WARNING, "FDT: Too many memory regions\n");
588 goto out;
592 root = fdt_find_node_by_path(blob, "/", &addrcp, &sizecp);
593 node_count = fdt_find_subnodes_by_prefix(blob, root, "memory@",
594 &addrcp, &sizecp, nodes,
595 FDT_MAX_MEMORY_NODES);
596 if (node_count >= FDT_MAX_MEMORY_NODES) {
597 printk(BIOS_WARNING, "FDT: Too many memory nodes\n");
598 /* Can still reading the regions for those we got */
601 for (size_t i = 0; i < MIN(node_count, FDT_MAX_MEMORY_NODES); i++) {
602 region_idx += fdt_read_reg_prop(blob, nodes[i], addrcp, sizecp,
603 &regions[region_idx],
604 regions_count - region_idx);
605 if (region_idx >= regions_count) {
606 printk(BIOS_WARNING, "FDT: Too many memory regions\n");
607 goto out;
611 out:
612 for (size_t i = 0; i < MIN(region_idx, regions_count); i++) {
613 printk(BIOS_DEBUG, "FDT: Memory region [%#llx - %#llx]\n",
614 regions[i].addr, regions[i].addr + regions[i].size);
617 return region_idx;
621 * fdt_get_memory_top finds top of memory from a flat device-tree
623 * @params blob address of FDT
625 * Returns: Either 0 on error or returns the maximum memory address
627 uint64_t fdt_get_memory_top(const void *blob)
629 struct device_tree_region regions[FDT_MAX_MEMORY_REGIONS] = {0};
630 uint64_t top = 0;
631 uint64_t total = 0;
632 size_t count;
634 if (!fdt_is_valid(blob))
635 return 0;
637 count = fdt_read_memory_regions(blob, regions, FDT_MAX_MEMORY_REGIONS);
638 for (size_t i = 0; i < MIN(count, FDT_MAX_MEMORY_REGIONS); i++) {
639 top = MAX(top, regions[i].addr + regions[i].size);
640 total += regions[i].size;
643 printk(BIOS_DEBUG, "FDT: Found %u MiB of RAM\n",
644 (uint32_t)(total / MiB));
646 return top;
650 * Functions to turn a flattened tree into an unflattened one.
653 static int dt_prop_is_phandle(struct device_tree_property *prop)
655 return !(strcmp("phandle", prop->prop.name) &&
656 strcmp("linux,phandle", prop->prop.name));
659 static int fdt_unflatten_node(const void *blob, uint32_t start_offset,
660 struct device_tree *tree,
661 struct device_tree_node **new_node)
663 struct list_node *last;
664 int offset = start_offset;
665 const char *name;
666 int size;
668 size = fdt_next_node_name(blob, offset, &name);
669 if (!size)
670 return 0;
671 offset += size;
673 struct device_tree_node *node = alloc_node();
674 *new_node = node;
675 node->name = name;
677 struct fdt_property fprop;
678 last = &node->properties;
679 while ((size = fdt_next_property(blob, offset, &fprop))) {
680 struct device_tree_property *prop = alloc_prop();
681 prop->prop = fprop;
683 if (dt_prop_is_phandle(prop)) {
684 node->phandle = be32dec(prop->prop.data);
685 if (node->phandle > tree->max_phandle)
686 tree->max_phandle = node->phandle;
689 list_insert_after(&prop->list_node, last);
690 last = &prop->list_node;
692 offset += size;
695 struct device_tree_node *child;
696 last = &node->children;
697 while ((size = fdt_unflatten_node(blob, offset, tree, &child))) {
698 list_insert_after(&child->list_node, last);
699 last = &child->list_node;
701 offset += size;
704 return offset - start_offset + sizeof(uint32_t);
707 static int fdt_unflatten_map_entry(const void *blob, uint32_t offset,
708 struct device_tree_reserve_map_entry **new)
710 const uint64_t *ptr = (const uint64_t *)(((uint8_t *)blob) + offset);
711 const uint64_t start = be64toh(ptr[0]);
712 const uint64_t size = be64toh(ptr[1]);
714 if (!size)
715 return 0;
717 struct device_tree_reserve_map_entry *entry = xzalloc(sizeof(*entry));
718 *new = entry;
719 entry->start = start;
720 entry->size = size;
722 return sizeof(uint64_t) * 2;
725 bool fdt_is_valid(const void *blob)
727 const struct fdt_header *header = (const struct fdt_header *)blob;
729 uint32_t magic = be32toh(header->magic);
730 uint32_t version = be32toh(header->version);
731 uint32_t last_comp_version = be32toh(header->last_comp_version);
733 if (magic != FDT_HEADER_MAGIC) {
734 printk(BIOS_ERR, "Invalid device tree magic %#.8x!\n", magic);
735 return false;
737 if (last_comp_version > FDT_SUPPORTED_VERSION) {
738 printk(BIOS_ERR, "Unsupported device tree version %u(>=%u)\n",
739 version, last_comp_version);
740 return false;
742 if (version > FDT_SUPPORTED_VERSION)
743 printk(BIOS_NOTICE, "FDT version %u too new, should add support!\n",
744 version);
745 return true;
748 struct device_tree *fdt_unflatten(const void *blob)
750 struct device_tree *tree = xzalloc(sizeof(*tree));
751 const struct fdt_header *header = (const struct fdt_header *)blob;
752 tree->header = header;
754 if (!fdt_is_valid(blob))
755 return NULL;
757 uint32_t struct_offset = be32toh(header->structure_offset);
758 uint32_t strings_offset = be32toh(header->strings_offset);
759 uint32_t reserve_offset = be32toh(header->reserve_map_offset);
760 uint32_t min_offset = 0;
761 min_offset = MIN(struct_offset, strings_offset);
762 min_offset = MIN(min_offset, reserve_offset);
763 /* Assume everything up to the first non-header component is part of
764 the header and needs to be preserved. This will protect us against
765 new elements being added in the future. */
766 tree->header_size = min_offset;
768 struct device_tree_reserve_map_entry *entry;
769 uint32_t offset = reserve_offset;
770 int size;
771 struct list_node *last = &tree->reserve_map;
772 while ((size = fdt_unflatten_map_entry(blob, offset, &entry))) {
773 list_insert_after(&entry->list_node, last);
774 last = &entry->list_node;
776 offset += size;
779 fdt_unflatten_node(blob, struct_offset, tree, &tree->root);
781 return tree;
787 * Functions to find the size of the device tree if it was flattened.
790 static void dt_flat_prop_size(struct device_tree_property *prop,
791 uint32_t *struct_size, uint32_t *strings_size)
793 /* Starting token. */
794 *struct_size += sizeof(uint32_t);
795 /* Size. */
796 *struct_size += sizeof(uint32_t);
797 /* Name offset. */
798 *struct_size += sizeof(uint32_t);
799 /* Property value. */
800 *struct_size += ALIGN_UP(prop->prop.size, sizeof(uint32_t));
802 /* Property name. */
803 *strings_size += strlen(prop->prop.name) + 1;
806 static void dt_flat_node_size(struct device_tree_node *node,
807 uint32_t *struct_size, uint32_t *strings_size)
809 /* Starting token. */
810 *struct_size += sizeof(uint32_t);
811 /* Node name. */
812 *struct_size += ALIGN_UP(strlen(node->name) + 1, sizeof(uint32_t));
814 struct device_tree_property *prop;
815 list_for_each(prop, node->properties, list_node)
816 dt_flat_prop_size(prop, struct_size, strings_size);
818 struct device_tree_node *child;
819 list_for_each(child, node->children, list_node)
820 dt_flat_node_size(child, struct_size, strings_size);
822 /* End token. */
823 *struct_size += sizeof(uint32_t);
826 uint32_t dt_flat_size(const struct device_tree *tree)
828 uint32_t size = tree->header_size;
829 struct device_tree_reserve_map_entry *entry;
830 list_for_each(entry, tree->reserve_map, list_node)
831 size += sizeof(uint64_t) * 2;
832 size += sizeof(uint64_t) * 2;
834 uint32_t struct_size = 0;
835 uint32_t strings_size = 0;
836 dt_flat_node_size(tree->root, &struct_size, &strings_size);
838 size += struct_size;
839 /* End token. */
840 size += sizeof(uint32_t);
842 size += strings_size;
844 return size;
850 * Functions to flatten a device tree.
853 static void dt_flatten_map_entry(struct device_tree_reserve_map_entry *entry,
854 void **map_start)
856 ((uint64_t *)*map_start)[0] = htobe64(entry->start);
857 ((uint64_t *)*map_start)[1] = htobe64(entry->size);
858 *map_start = ((uint8_t *)*map_start) + sizeof(uint64_t) * 2;
861 static void dt_flatten_prop(struct device_tree_property *prop,
862 void **struct_start, void *strings_base,
863 void **strings_start)
865 uint8_t *dstruct = (uint8_t *)*struct_start;
866 uint8_t *dstrings = (uint8_t *)*strings_start;
868 be32enc(dstruct, FDT_TOKEN_PROPERTY);
869 dstruct += sizeof(uint32_t);
871 be32enc(dstruct, prop->prop.size);
872 dstruct += sizeof(uint32_t);
874 uint32_t name_offset = (uintptr_t)dstrings - (uintptr_t)strings_base;
875 be32enc(dstruct, name_offset);
876 dstruct += sizeof(uint32_t);
878 strcpy((char *)dstrings, prop->prop.name);
879 dstrings += strlen(prop->prop.name) + 1;
881 memcpy(dstruct, prop->prop.data, prop->prop.size);
882 dstruct += ALIGN_UP(prop->prop.size, sizeof(uint32_t));
884 *struct_start = dstruct;
885 *strings_start = dstrings;
888 static void dt_flatten_node(const struct device_tree_node *node,
889 void **struct_start, void *strings_base,
890 void **strings_start)
892 uint8_t *dstruct = (uint8_t *)*struct_start;
893 uint8_t *dstrings = (uint8_t *)*strings_start;
895 be32enc(dstruct, FDT_TOKEN_BEGIN_NODE);
896 dstruct += sizeof(uint32_t);
898 strcpy((char *)dstruct, node->name);
899 dstruct += ALIGN_UP(strlen(node->name) + 1, sizeof(uint32_t));
901 struct device_tree_property *prop;
902 list_for_each(prop, node->properties, list_node)
903 dt_flatten_prop(prop, (void **)&dstruct, strings_base,
904 (void **)&dstrings);
906 struct device_tree_node *child;
907 list_for_each(child, node->children, list_node)
908 dt_flatten_node(child, (void **)&dstruct, strings_base,
909 (void **)&dstrings);
911 be32enc(dstruct, FDT_TOKEN_END_NODE);
912 dstruct += sizeof(uint32_t);
914 *struct_start = dstruct;
915 *strings_start = dstrings;
918 void dt_flatten(const struct device_tree *tree, void *start_dest)
920 uint8_t *dest = (uint8_t *)start_dest;
922 memcpy(dest, tree->header, tree->header_size);
923 struct fdt_header *header = (struct fdt_header *)dest;
924 dest += tree->header_size;
926 struct device_tree_reserve_map_entry *entry;
927 list_for_each(entry, tree->reserve_map, list_node)
928 dt_flatten_map_entry(entry, (void **)&dest);
929 ((uint64_t *)dest)[0] = ((uint64_t *)dest)[1] = 0;
930 dest += sizeof(uint64_t) * 2;
932 uint32_t struct_size = 0;
933 uint32_t strings_size = 0;
934 dt_flat_node_size(tree->root, &struct_size, &strings_size);
936 uint8_t *struct_start = dest;
937 header->structure_offset = htobe32(dest - (uint8_t *)start_dest);
938 header->structure_size = htobe32(struct_size);
939 dest += struct_size;
941 *((uint32_t *)dest) = htobe32(FDT_TOKEN_END);
942 dest += sizeof(uint32_t);
944 uint8_t *strings_start = dest;
945 header->strings_offset = htobe32(dest - (uint8_t *)start_dest);
946 header->strings_size = htobe32(strings_size);
947 dest += strings_size;
949 dt_flatten_node(tree->root, (void **)&struct_start, strings_start,
950 (void **)&strings_start);
952 header->totalsize = htobe32(dest - (uint8_t *)start_dest);
958 * Functions for printing a non-flattened device tree.
961 static void print_node(const struct device_tree_node *node, int depth)
963 print_indent(depth);
964 if (depth == 0) /* root node has no name, print a starting slash */
965 printk(BIOS_DEBUG, "/");
966 printk(BIOS_DEBUG, "%s {\n", node->name);
968 struct device_tree_property *prop;
969 list_for_each(prop, node->properties, list_node)
970 print_property(&prop->prop, depth + 1);
972 printk(BIOS_DEBUG, "\n"); /* empty line between props and nodes */
974 struct device_tree_node *child;
975 list_for_each(child, node->children, list_node)
976 print_node(child, depth + 1);
978 print_indent(depth);
979 printk(BIOS_DEBUG, "};\n");
982 void dt_print_node(const struct device_tree_node *node)
984 print_node(node, 0);
990 * Functions for reading and manipulating an unflattened device tree.
994 * dt_read_reg_prop reads the reg property inside a node
996 * @params node device tree node to read reg property from
997 * @params addr_cells number of cells used for one address
998 * @params size_cells number of cells used for one size
999 * @params regions all regions that are read inside the reg property are saved inside
1000 * this array
1001 * @params regions_count maximum number of entries that can be saved inside the regions array.
1003 * Returns: Either 0 on error or returns the number of regions put into the regions array.
1005 size_t dt_read_reg_prop(struct device_tree_node *node, u32 addr_cells, u32 size_cells,
1006 struct device_tree_region regions[], size_t regions_count)
1008 struct device_tree_property *prop;
1009 bool found = false;
1010 list_for_each(prop, node->properties, list_node) {
1011 if (!strcmp("reg", prop->prop.name)) {
1012 found = true;
1013 break;
1017 if (!found) {
1018 printk(BIOS_DEBUG, "no reg property found\n");
1019 return 0;
1021 return read_reg_prop(&prop->prop, addr_cells, size_cells, regions, regions_count);
1025 * Read #address-cells and #size-cells properties from a node.
1027 * @param node The device tree node to read from.
1028 * @param addrcp Pointer to store #address-cells in, skipped if NULL.
1029 * @param sizecp Pointer to store #size-cells in, skipped if NULL.
1031 void dt_read_cell_props(const struct device_tree_node *node, u32 *addrcp,
1032 u32 *sizecp)
1034 struct device_tree_property *prop;
1035 list_for_each(prop, node->properties, list_node) {
1036 if (addrcp && !strcmp("#address-cells", prop->prop.name))
1037 *addrcp = be32dec(prop->prop.data);
1038 if (sizecp && !strcmp("#size-cells", prop->prop.name))
1039 *sizecp = be32dec(prop->prop.data);
1044 * Find a node from a device tree path, relative to a parent node.
1046 * @param parent The node from which to start the relative path lookup.
1047 * @param path An array of path component strings that will be looked
1048 * up in order to find the node. Must be terminated with
1049 * a NULL pointer. Example: {'firmware', 'coreboot', NULL}
1050 * @param addrcp Pointer that will be updated with any #address-cells
1051 * value found in the path. May be NULL to ignore.
1052 * @param sizecp Pointer that will be updated with any #size-cells
1053 * value found in the path. May be NULL to ignore.
1054 * @param create 1: Create node(s) if not found. 0: Return NULL instead.
1055 * @return The found/created node, or NULL.
1057 struct device_tree_node *dt_find_node(struct device_tree_node *parent,
1058 const char **path, u32 *addrcp,
1059 u32 *sizecp, int create)
1061 struct device_tree_node *node, *found = NULL;
1063 /* Update #address-cells and #size-cells for this level. */
1064 dt_read_cell_props(parent, addrcp, sizecp);
1066 if (!*path)
1067 return parent;
1069 /* Find the next node in the path, if it exists. */
1070 list_for_each(node, parent->children, list_node) {
1071 if (!strcmp(node->name, *path)) {
1072 found = node;
1073 break;
1077 /* Otherwise create it or return NULL. */
1078 if (!found) {
1079 if (!create)
1080 return NULL;
1082 found = alloc_node();
1083 found->name = strdup(*path);
1084 if (!found->name)
1085 return NULL;
1087 list_insert_after(&found->list_node, &parent->children);
1090 return dt_find_node(found, path + 1, addrcp, sizecp, create);
1094 * Find a node in the tree from a string device tree path.
1096 * @param tree The device tree to search.
1097 * @param path A string representing a path in the device tree, with
1098 * nodes separated by '/'. Example: "/firmware/coreboot"
1099 * @param addrcp Pointer that will be updated with any #address-cells
1100 * value found in the path. May be NULL to ignore.
1101 * @param sizecp Pointer that will be updated with any #size-cells
1102 * value found in the path. May be NULL to ignore.
1103 * @param create 1: Create node(s) if not found. 0: Return NULL instead.
1104 * @return The found/created node, or NULL.
1106 * It is the caller responsibility to provide a path string that doesn't end
1107 * with a '/' and doesn't contain any "//". If the path does not start with a
1108 * '/', the first segment is interpreted as an alias. */
1109 struct device_tree_node *dt_find_node_by_path(struct device_tree *tree,
1110 const char *path, u32 *addrcp,
1111 u32 *sizecp, int create)
1113 char *sub_path;
1114 char *duped_str;
1115 struct device_tree_node *parent;
1116 char *next_slash;
1117 /* Hopefully enough depth for any node. */
1118 const char *path_array[15];
1119 int i;
1120 struct device_tree_node *node = NULL;
1122 if (path[0] == '/') { /* regular path */
1123 if (path[1] == '\0') { /* special case: "/" is root node */
1124 dt_read_cell_props(tree->root, addrcp, sizecp);
1125 return tree->root;
1128 sub_path = duped_str = strdup(&path[1]);
1129 if (!sub_path)
1130 return NULL;
1132 parent = tree->root;
1133 } else { /* alias */
1134 char *alias;
1136 alias = duped_str = strdup(path);
1137 if (!alias)
1138 return NULL;
1140 sub_path = strchr(alias, '/');
1141 if (sub_path)
1142 *sub_path = '\0';
1144 parent = dt_find_node_by_alias(tree, alias);
1145 if (!parent) {
1146 printk(BIOS_DEBUG,
1147 "Could not find node '%s', alias '%s' does not exist\n",
1148 path, alias);
1149 free(duped_str);
1150 return NULL;
1153 if (!sub_path) {
1154 /* it's just the alias, no sub-path */
1155 free(duped_str);
1156 return parent;
1159 sub_path++;
1162 next_slash = sub_path;
1163 path_array[0] = sub_path;
1164 for (i = 1; i < (ARRAY_SIZE(path_array) - 1); i++) {
1165 next_slash = strchr(next_slash, '/');
1166 if (!next_slash)
1167 break;
1169 *next_slash++ = '\0';
1170 path_array[i] = next_slash;
1173 if (!next_slash) {
1174 path_array[i] = NULL;
1175 node = dt_find_node(parent, path_array,
1176 addrcp, sizecp, create);
1179 free(duped_str);
1180 return node;
1184 * Find a node from an alias
1186 * @param tree The device tree.
1187 * @param alias The alias name.
1188 * @return The found node, or NULL.
1190 struct device_tree_node *dt_find_node_by_alias(struct device_tree *tree,
1191 const char *alias)
1193 struct device_tree_node *node;
1194 const char *alias_path;
1196 node = dt_find_node_by_path(tree, "/aliases", NULL, NULL, 0);
1197 if (!node)
1198 return NULL;
1200 alias_path = dt_find_string_prop(node, alias);
1201 if (!alias_path)
1202 return NULL;
1204 return dt_find_node_by_path(tree, alias_path, NULL, NULL, 0);
1207 struct device_tree_node *dt_find_node_by_phandle(struct device_tree_node *root,
1208 uint32_t phandle)
1210 if (!root)
1211 return NULL;
1213 if (root->phandle == phandle)
1214 return root;
1216 struct device_tree_node *node;
1217 struct device_tree_node *result;
1218 list_for_each(node, root->children, list_node) {
1219 result = dt_find_node_by_phandle(node, phandle);
1220 if (result)
1221 return result;
1224 return NULL;
1228 * Check if given node is compatible.
1230 * @param node The node which is to be checked for compatible property.
1231 * @param compat The compatible string to match.
1232 * @return 1 = compatible, 0 = not compatible.
1234 static int dt_check_compat_match(struct device_tree_node *node,
1235 const char *compat)
1237 struct device_tree_property *prop;
1239 list_for_each(prop, node->properties, list_node) {
1240 if (!strcmp("compatible", prop->prop.name)) {
1241 size_t bytes = prop->prop.size;
1242 const char *str = prop->prop.data;
1243 while (bytes > 0) {
1244 if (!strncmp(compat, str, bytes))
1245 return 1;
1246 size_t len = strnlen(str, bytes) + 1;
1247 if (bytes <= len)
1248 break;
1249 str += len;
1250 bytes -= len;
1252 break;
1256 return 0;
1260 * Find a node from a compatible string, in the subtree of a parent node.
1262 * @param parent The parent node under which to look.
1263 * @param compat The compatible string to find.
1264 * @return The found node, or NULL.
1266 struct device_tree_node *dt_find_compat(struct device_tree_node *parent,
1267 const char *compat)
1269 /* Check if the parent node itself is compatible. */
1270 if (dt_check_compat_match(parent, compat))
1271 return parent;
1273 struct device_tree_node *child;
1274 list_for_each(child, parent->children, list_node) {
1275 struct device_tree_node *found = dt_find_compat(child, compat);
1276 if (found)
1277 return found;
1280 return NULL;
1284 * Find the next compatible child of a given parent. All children up to the
1285 * child passed in by caller are ignored. If child is NULL, it considers all the
1286 * children to find the first child which is compatible.
1288 * @param parent The parent node under which to look.
1289 * @param child The child node to start search from (exclusive). If NULL
1290 * consider all children.
1291 * @param compat The compatible string to find.
1292 * @return The found node, or NULL.
1294 struct device_tree_node *
1295 dt_find_next_compat_child(struct device_tree_node *parent,
1296 struct device_tree_node *child,
1297 const char *compat)
1299 struct device_tree_node *next;
1300 int ignore = 0;
1302 if (child)
1303 ignore = 1;
1305 list_for_each(next, parent->children, list_node) {
1306 if (ignore) {
1307 if (child == next)
1308 ignore = 0;
1309 continue;
1312 if (dt_check_compat_match(next, compat))
1313 return next;
1316 return NULL;
1320 * Find a node with matching property value, in the subtree of a parent node.
1322 * @param parent The parent node under which to look.
1323 * @param name The property name to look for.
1324 * @param data The property value to look for.
1325 * @param size The property size.
1327 struct device_tree_node *dt_find_prop_value(struct device_tree_node *parent,
1328 const char *name, void *data,
1329 size_t size)
1331 struct device_tree_property *prop;
1333 /* Check if parent itself has the required property value. */
1334 list_for_each(prop, parent->properties, list_node) {
1335 if (!strcmp(name, prop->prop.name)) {
1336 size_t bytes = prop->prop.size;
1337 const void *prop_data = prop->prop.data;
1338 if (size != bytes)
1339 break;
1340 if (!memcmp(data, prop_data, size))
1341 return parent;
1342 break;
1346 struct device_tree_node *child;
1347 list_for_each(child, parent->children, list_node) {
1348 struct device_tree_node *found = dt_find_prop_value(child, name,
1349 data, size);
1350 if (found)
1351 return found;
1353 return NULL;
1357 * Write an arbitrary sized big-endian integer into a pointer.
1359 * @param dest Pointer to the DT property data buffer to write.
1360 * @param src The integer to write (in CPU endianness).
1361 * @param length the length of the destination integer in bytes.
1363 void dt_write_int(u8 *dest, u64 src, size_t length)
1365 while (length--) {
1366 dest[length] = (u8)src;
1367 src >>= 8;
1372 * Delete a property by name in a given node if it exists.
1374 * @param node The device tree node to operate on.
1375 * @param name The name of the property to delete.
1377 void dt_delete_prop(struct device_tree_node *node, const char *name)
1379 struct device_tree_property *prop;
1381 list_for_each(prop, node->properties, list_node) {
1382 if (!strcmp(prop->prop.name, name)) {
1383 list_remove(&prop->list_node);
1384 return;
1390 * Add an arbitrary property to a node, or update it if it already exists.
1392 * @param node The device tree node to add to.
1393 * @param name The name of the new property.
1394 * @param data The raw data blob to be stored in the property.
1395 * @param size The size of data in bytes.
1397 void dt_add_bin_prop(struct device_tree_node *node, const char *name,
1398 void *data, size_t size)
1400 struct device_tree_property *prop;
1402 list_for_each(prop, node->properties, list_node) {
1403 if (!strcmp(prop->prop.name, name)) {
1404 prop->prop.data = data;
1405 prop->prop.size = size;
1406 return;
1410 prop = alloc_prop();
1411 list_insert_after(&prop->list_node, &node->properties);
1412 prop->prop.name = name;
1413 prop->prop.data = data;
1414 prop->prop.size = size;
1418 * Find given string property in a node and return its content.
1420 * @param node The device tree node to search.
1421 * @param name The name of the property.
1422 * @return The found string, or NULL.
1424 const char *dt_find_string_prop(const struct device_tree_node *node,
1425 const char *name)
1427 const void *content;
1428 size_t size;
1430 dt_find_bin_prop(node, name, &content, &size);
1432 return content;
1436 * Find given property in a node.
1438 * @param node The device tree node to search.
1439 * @param name The name of the property.
1440 * @param data Pointer to return raw data blob in the property.
1441 * @param size Pointer to return the size of data in bytes.
1443 void dt_find_bin_prop(const struct device_tree_node *node, const char *name,
1444 const void **data, size_t *size)
1446 struct device_tree_property *prop;
1448 *data = NULL;
1449 *size = 0;
1451 list_for_each(prop, node->properties, list_node) {
1452 if (!strcmp(prop->prop.name, name)) {
1453 *data = prop->prop.data;
1454 *size = prop->prop.size;
1455 return;
1461 * Add a string property to a node, or update it if it already exists.
1463 * @param node The device tree node to add to.
1464 * @param name The name of the new property.
1465 * @param str The zero-terminated string to be stored in the property.
1467 void dt_add_string_prop(struct device_tree_node *node, const char *name,
1468 const char *str)
1470 dt_add_bin_prop(node, name, (char *)str, strlen(str) + 1);
1474 * Add a 32-bit integer property to a node, or update it if it already exists.
1476 * @param node The device tree node to add to.
1477 * @param name The name of the new property.
1478 * @param val The integer to be stored in the property.
1480 void dt_add_u32_prop(struct device_tree_node *node, const char *name, u32 val)
1482 u32 *val_ptr = xmalloc(sizeof(val));
1483 *val_ptr = htobe32(val);
1484 dt_add_bin_prop(node, name, val_ptr, sizeof(*val_ptr));
1488 * Add a 64-bit integer property to a node, or update it if it already exists.
1490 * @param node The device tree node to add to.
1491 * @param name The name of the new property.
1492 * @param val The integer to be stored in the property.
1494 void dt_add_u64_prop(struct device_tree_node *node, const char *name, u64 val)
1496 u64 *val_ptr = xmalloc(sizeof(val));
1497 *val_ptr = htobe64(val);
1498 dt_add_bin_prop(node, name, val_ptr, sizeof(*val_ptr));
1502 * Add a 'reg' address list property to a node, or update it if it exists.
1504 * @param node The device tree node to add to.
1505 * @param regions Array of address values to be stored in the property.
1506 * @param sizes Array of corresponding size values to 'addrs'.
1507 * @param count Number of values in 'addrs' and 'sizes' (must be equal).
1508 * @param addr_cells Value of #address-cells property valid for this node.
1509 * @param size_cells Value of #size-cells property valid for this node.
1511 void dt_add_reg_prop(struct device_tree_node *node, u64 *addrs, u64 *sizes,
1512 int count, u32 addr_cells, u32 size_cells)
1514 int i;
1515 size_t length = (addr_cells + size_cells) * sizeof(u32) * count;
1516 u8 *data = xmalloc(length);
1517 u8 *cur = data;
1519 for (i = 0; i < count; i++) {
1520 dt_write_int(cur, addrs[i], addr_cells * sizeof(u32));
1521 cur += addr_cells * sizeof(u32);
1522 dt_write_int(cur, sizes[i], size_cells * sizeof(u32));
1523 cur += size_cells * sizeof(u32);
1526 dt_add_bin_prop(node, "reg", data, length);
1530 * Fixups to apply to a kernel's device tree before booting it.
1533 struct list_node device_tree_fixups;
1535 int dt_apply_fixups(struct device_tree *tree)
1537 struct device_tree_fixup *fixup;
1538 list_for_each(fixup, device_tree_fixups, list_node) {
1539 assert(fixup->fixup);
1540 if (fixup->fixup(fixup, tree))
1541 return 1;
1543 return 0;
1546 int dt_set_bin_prop_by_path(struct device_tree *tree, const char *path,
1547 void *data, size_t data_size, int create)
1549 char *path_copy, *prop_name;
1550 struct device_tree_node *dt_node;
1552 path_copy = strdup(path);
1554 if (!path_copy) {
1555 printk(BIOS_ERR, "Failed to allocate a copy of path %s\n",
1556 path);
1557 return 1;
1560 prop_name = strrchr(path_copy, '/');
1561 if (!prop_name) {
1562 free(path_copy);
1563 printk(BIOS_ERR, "Path %s does not include '/'\n", path);
1564 return 1;
1567 *prop_name++ = '\0'; /* Separate path from the property name. */
1569 dt_node = dt_find_node_by_path(tree, path_copy, NULL,
1570 NULL, create);
1572 if (!dt_node) {
1573 printk(BIOS_ERR, "Failed to %s %s in the device tree\n",
1574 create ? "create" : "find", path_copy);
1575 free(path_copy);
1576 return 1;
1579 dt_add_bin_prop(dt_node, prop_name, data, data_size);
1580 free(path_copy);
1582 return 0;
1586 * Prepare the /reserved-memory/ node.
1588 * Technically, this can be called more than one time, to init and/or retrieve
1589 * the node. But dt_add_u32_prop() may leak a bit of memory if you do.
1591 * @tree: Device tree to add/retrieve from.
1592 * @return: The /reserved-memory/ node (or NULL, if error).
1594 struct device_tree_node *dt_init_reserved_memory_node(struct device_tree *tree)
1596 struct device_tree_node *reserved;
1597 u32 addr = 0, size = 0;
1599 reserved = dt_find_node_by_path(tree, "/reserved-memory", &addr,
1600 &size, 1);
1601 if (!reserved)
1602 return NULL;
1604 /* Binding doc says this should have the same #{address,size}-cells as
1605 the root. */
1606 dt_add_u32_prop(reserved, "#address-cells", addr);
1607 dt_add_u32_prop(reserved, "#size-cells", size);
1608 /* Binding doc says this should be empty (1:1 mapping from root). */
1609 dt_add_bin_prop(reserved, "ranges", NULL, 0);
1611 return reserved;
1615 * Increment a single phandle in prop at a given offset by a given adjustment.
1617 * @param prop Property whose phandle should be adjusted.
1618 * @param adjustment Value that should be added to the existing phandle.
1619 * @param offset Byte offset of the phandle in the property data.
1621 * @return New phandle value, or 0 on error.
1623 static uint32_t dt_adjust_phandle(struct device_tree_property *prop,
1624 uint32_t adjustment, uint32_t offset)
1626 if (offset + 4 > prop->prop.size)
1627 return 0;
1629 uint32_t phandle = be32dec(prop->prop.data + offset);
1630 if (phandle == 0 ||
1631 phandle == FDT_PHANDLE_ILLEGAL ||
1632 phandle == 0xffffffff)
1633 return 0;
1635 phandle += adjustment;
1636 if (phandle >= FDT_PHANDLE_ILLEGAL)
1637 return 0;
1639 be32enc(prop->prop.data + offset, phandle);
1640 return phandle;
1644 * Adjust all phandles in subtree by adding a new base offset.
1646 * @param node Root node of the subtree to work on.
1647 * @param base New phandle base to be added to all phandles.
1649 * @return New highest phandle in the subtree, or 0 on error.
1651 static uint32_t dt_adjust_all_phandles(struct device_tree_node *node,
1652 uint32_t base)
1654 uint32_t new_max = MAX(base, 1); /* make sure we don't return 0 */
1655 struct device_tree_property *prop;
1656 struct device_tree_node *child;
1658 if (!node)
1659 return new_max;
1661 list_for_each(prop, node->properties, list_node)
1662 if (dt_prop_is_phandle(prop)) {
1663 node->phandle = dt_adjust_phandle(prop, base, 0);
1664 if (!node->phandle)
1665 return 0;
1666 new_max = MAX(new_max, node->phandle);
1667 } /* no break -- can have more than one phandle prop */
1669 list_for_each(child, node->children, list_node)
1670 new_max = MAX(new_max, dt_adjust_all_phandles(child, base));
1672 return new_max;
1676 * Apply a /__local_fixup__ subtree to the corresponding overlay subtree.
1678 * @param node Root node of the overlay subtree to fix up.
1679 * @param node Root node of the /__local_fixup__ subtree.
1680 * @param base Adjustment that was added to phandles in the overlay.
1682 * @return 0 on success, -1 on error.
1684 static int dt_fixup_locals(struct device_tree_node *node,
1685 struct device_tree_node *fixup, uint32_t base)
1687 struct device_tree_property *prop;
1688 struct device_tree_property *fixup_prop;
1689 struct device_tree_node *child;
1690 struct device_tree_node *fixup_child;
1691 int i;
1694 * For local fixups the /__local_fixup__ subtree contains the same node
1695 * hierarchy as the main tree we're fixing up. Each property contains
1696 * the fixup offsets for the respective property in the main tree. For
1697 * each property in the fixup node, find the corresponding property in
1698 * the base node and apply fixups to all offsets it specifies.
1700 list_for_each(fixup_prop, fixup->properties, list_node) {
1701 struct device_tree_property *base_prop = NULL;
1702 list_for_each(prop, node->properties, list_node)
1703 if (!strcmp(prop->prop.name, fixup_prop->prop.name)) {
1704 base_prop = prop;
1705 break;
1708 /* We should always find a corresponding base prop for a fixup,
1709 and fixup props contain a list of 32-bit fixup offsets. */
1710 if (!base_prop || fixup_prop->prop.size % sizeof(uint32_t))
1711 return -1;
1713 for (i = 0; i < fixup_prop->prop.size; i += sizeof(uint32_t))
1714 if (!dt_adjust_phandle(base_prop, base, be32dec(
1715 fixup_prop->prop.data + i)))
1716 return -1;
1719 /* Now recursively descend both the base tree and the /__local_fixups__
1720 subtree in sync to apply all fixups. */
1721 list_for_each(fixup_child, fixup->children, list_node) {
1722 struct device_tree_node *base_child = NULL;
1723 list_for_each(child, node->children, list_node)
1724 if (!strcmp(child->name, fixup_child->name)) {
1725 base_child = child;
1726 break;
1729 /* All fixup nodes should have a corresponding base node. */
1730 if (!base_child)
1731 return -1;
1733 if (dt_fixup_locals(base_child, fixup_child, base) < 0)
1734 return -1;
1737 return 0;
1741 * Update all /__symbols__ properties in an overlay that start with
1742 * "/fragment@X/__overlay__" with corresponding path prefix in the base tree.
1744 * @param symbols /__symbols__ done to update.
1745 * @param fragment /fragment@X node that references to should be updated.
1746 * @param base_path Path of base tree node that the fragment overlaid.
1748 static void dt_fix_symbols(struct device_tree_node *symbols,
1749 struct device_tree_node *fragment,
1750 const char *base_path)
1752 struct device_tree_property *prop;
1753 char buf[512]; /* Should be enough for maximum DT path length? */
1754 char node_path[64]; /* easily enough for /fragment@XXXX/__overlay__ */
1756 if (!symbols) /* If the overlay has no /__symbols__ node, we're done! */
1757 return;
1759 int len = snprintf(node_path, sizeof(node_path), "/%s/__overlay__",
1760 fragment->name);
1762 list_for_each(prop, symbols->properties, list_node)
1763 if (!strncmp(prop->prop.data, node_path, len)) {
1764 prop->prop.size = snprintf(buf, sizeof(buf), "%s%s",
1765 base_path, (char *)prop->prop.data + len) + 1;
1766 free(prop->prop.data);
1767 prop->prop.data = strdup(buf);
1772 * Fix up overlay according to a property in /__fixup__. If the fixed property
1773 * is a /fragment@X:target, also update /__symbols__ references to fragment.
1775 * @params overlay Overlay to fix up.
1776 * @params fixup /__fixup__ property.
1777 * @params phandle phandle value to insert where the fixup points to.
1778 * @params base_path Path to the base DT node that the fixup points to.
1779 * @params overlay_symbols /__symbols__ node of the overlay.
1781 * @return 0 on success, -1 on error.
1783 static int dt_fixup_external(struct device_tree *overlay,
1784 struct device_tree_property *fixup,
1785 uint32_t phandle, const char *base_path,
1786 struct device_tree_node *overlay_symbols)
1788 struct device_tree_property *prop;
1790 /* External fixup properties are encoded as "<path>:<prop>:<offset>". */
1791 char *entry = fixup->prop.data;
1792 while ((void *)entry < fixup->prop.data + fixup->prop.size) {
1793 /* okay to destroy fixup property value, won't need it again */
1794 char *node_path = entry;
1795 entry = strchr(node_path, ':');
1796 if (!entry)
1797 return -1;
1798 *entry++ = '\0';
1800 char *prop_name = entry;
1801 entry = strchr(prop_name, ':');
1802 if (!entry)
1803 return -1;
1804 *entry++ = '\0';
1806 struct device_tree_node *ovl_node = dt_find_node_by_path(
1807 overlay, node_path, NULL, NULL, 0);
1808 if (!ovl_node || !isdigit(*entry))
1809 return -1;
1811 struct device_tree_property *ovl_prop = NULL;
1812 list_for_each(prop, ovl_node->properties, list_node)
1813 if (!strcmp(prop->prop.name, prop_name)) {
1814 ovl_prop = prop;
1815 break;
1818 /* Move entry to first char after number, must be a '\0'. */
1819 uint32_t offset = skip_atoi(&entry);
1820 if (!ovl_prop || offset + 4 > ovl_prop->prop.size || entry[0])
1821 return -1;
1822 entry++; /* jump over '\0' to potential next fixup */
1824 be32enc(ovl_prop->prop.data + offset, phandle);
1826 /* If this is a /fragment@X:target property, update references
1827 to this fragment in the overlay __symbols__ now. */
1828 if (offset == 0 && !strcmp(prop_name, "target") &&
1829 !strchr(node_path + 1, '/')) /* only toplevel nodes */
1830 dt_fix_symbols(overlay_symbols, ovl_node, base_path);
1833 return 0;
1837 * Apply all /__fixup__ properties in the overlay. This will destroy the
1838 * property data in /__fixup__ and it should not be accessed again.
1840 * @params tree Base device tree that the overlay updates.
1841 * @params symbols /__symbols__ node of the base device tree.
1842 * @params overlay Overlay to fix up.
1843 * @params fixups /__fixup__ node in the overlay.
1844 * @params overlay_symbols /__symbols__ node of the overlay.
1846 * @return 0 on success, -1 on error.
1848 static int dt_fixup_all_externals(struct device_tree *tree,
1849 struct device_tree_node *symbols,
1850 struct device_tree *overlay,
1851 struct device_tree_node *fixups,
1852 struct device_tree_node *overlay_symbols)
1854 struct device_tree_property *fix;
1856 /* If we have any external fixups, base tree must have /__symbols__. */
1857 if (!symbols)
1858 return -1;
1861 * Unlike /__local_fixups__, /__fixups__ is not a whole subtree that
1862 * mirrors the node hierarchy. It's just a directory of fixup properties
1863 * that each directly contain all information necessary to apply them.
1865 list_for_each(fix, fixups->properties, list_node) {
1866 /* The name of a fixup property is the label of the node we want
1867 a property to phandle-reference. Look up in /__symbols__. */
1868 const char *path = dt_find_string_prop(symbols, fix->prop.name);
1869 if (!path)
1870 return -1;
1872 /* Find node the label pointed to figure out its phandle. */
1873 struct device_tree_node *node = dt_find_node_by_path(tree, path,
1874 NULL, NULL, 0);
1875 if (!node)
1876 return -1;
1878 /* Write into the overlay property(s) pointing to that node. */
1879 if (dt_fixup_external(overlay, fix, node->phandle,
1880 path, overlay_symbols) < 0)
1881 return -1;
1884 return 0;
1888 * Copy all nodes and properties from one DT subtree into another. This is a
1889 * shallow copy so both trees will point to the same property data afterwards.
1891 * @params dst Destination subtree to copy into.
1892 * @params src Source subtree to copy from.
1893 * @params upd 1 to overwrite same-name properties, 0 to discard them.
1895 static void dt_copy_subtree(struct device_tree_node *dst,
1896 struct device_tree_node *src, int upd)
1898 struct device_tree_property *prop;
1899 struct device_tree_property *src_prop;
1900 list_for_each(src_prop, src->properties, list_node) {
1901 if (dt_prop_is_phandle(src_prop) ||
1902 !strcmp(src_prop->prop.name, "name")) {
1903 printk(BIOS_DEBUG,
1904 "WARNING: ignoring illegal overlay prop '%s'\n",
1905 src_prop->prop.name);
1906 continue;
1909 struct device_tree_property *dst_prop = NULL;
1910 list_for_each(prop, dst->properties, list_node)
1911 if (!strcmp(prop->prop.name, src_prop->prop.name)) {
1912 dst_prop = prop;
1913 break;
1916 if (dst_prop) {
1917 if (!upd) {
1918 printk(BIOS_DEBUG,
1919 "WARNING: ignoring prop update '%s'\n",
1920 src_prop->prop.name);
1921 continue;
1923 } else {
1924 dst_prop = alloc_prop();
1925 list_insert_after(&dst_prop->list_node,
1926 &dst->properties);
1929 dst_prop->prop = src_prop->prop;
1932 struct device_tree_node *node;
1933 struct device_tree_node *src_node;
1934 list_for_each(src_node, src->children, list_node) {
1935 struct device_tree_node *dst_node = NULL;
1936 list_for_each(node, dst->children, list_node)
1937 if (!strcmp(node->name, src_node->name)) {
1938 dst_node = node;
1939 break;
1942 if (!dst_node) {
1943 dst_node = alloc_node();
1944 *dst_node = *src_node;
1945 list_insert_after(&dst_node->list_node, &dst->children);
1946 } else {
1947 dt_copy_subtree(dst_node, src_node, upd);
1953 * Apply an overlay /fragment@X node to a base device tree.
1955 * @param tree Base device tree.
1956 * @param fragment /fragment@X node.
1957 * @params overlay_symbols /__symbols__ node of the overlay.
1959 * @return 0 on success, -1 on error.
1961 static int dt_import_fragment(struct device_tree *tree,
1962 struct device_tree_node *fragment,
1963 struct device_tree_node *overlay_symbols)
1965 /* The actual overlaid nodes/props are in an __overlay__ child node. */
1966 static const char *overlay_path[] = { "__overlay__", NULL };
1967 struct device_tree_node *overlay = dt_find_node(fragment, overlay_path,
1968 NULL, NULL, 0);
1970 /* If it doesn't have an __overlay__ child, it's not a fragment. */
1971 if (!overlay)
1972 return 0;
1974 /* Target node of the fragment can be given by path or by phandle. */
1975 struct device_tree_property *prop;
1976 struct device_tree_property *phandle = NULL;
1977 struct device_tree_property *path = NULL;
1978 list_for_each(prop, fragment->properties, list_node) {
1979 if (!strcmp(prop->prop.name, "target")) {
1980 phandle = prop;
1981 break; /* phandle target has priority, stop looking */
1983 if (!strcmp(prop->prop.name, "target-path"))
1984 path = prop;
1987 struct device_tree_node *target = NULL;
1988 if (phandle) {
1989 if (phandle->prop.size != sizeof(uint32_t))
1990 return -1;
1991 target = dt_find_node_by_phandle(tree->root,
1992 be32dec(phandle->prop.data));
1993 /* Symbols already updated as part of dt_fixup_external(). */
1994 } else if (path) {
1995 target = dt_find_node_by_path(tree, path->prop.data,
1996 NULL, NULL, 0);
1997 dt_fix_symbols(overlay_symbols, fragment, path->prop.data);
1999 if (!target)
2000 return -1;
2002 dt_copy_subtree(target, overlay, 1);
2003 return 0;
2007 * Apply a device tree overlay to a base device tree. This will
2008 * destroy/incorporate the overlay data, so it should not be freed or reused.
2009 * See dtc.git/Documentation/dt-object-internal.txt for overlay format details.
2011 * @param tree Unflattened base device tree to add the overlay into.
2012 * @param overlay Unflattened overlay device tree to apply to the base.
2014 * @return 0 on success, -1 on error.
2016 int dt_apply_overlay(struct device_tree *tree, struct device_tree *overlay)
2019 * First, we need to make sure phandles inside the overlay don't clash
2020 * with those in the base tree. We just define the highest phandle value
2021 * in the base tree as the "phandle offset" for this overlay and
2022 * increment all phandles in it by that value.
2024 uint32_t phandle_base = tree->max_phandle;
2025 uint32_t new_max = dt_adjust_all_phandles(overlay->root, phandle_base);
2026 if (!new_max) {
2027 printk(BIOS_ERR, "invalid phandles in overlay\n");
2028 return -1;
2030 tree->max_phandle = new_max;
2032 /* Now that we changed phandles in the overlay, we need to update any
2033 nodes referring to them. Those are listed in /__local_fixups__. */
2034 struct device_tree_node *local_fixups = dt_find_node_by_path(overlay,
2035 "/__local_fixups__", NULL, NULL, 0);
2036 if (local_fixups && dt_fixup_locals(overlay->root, local_fixups,
2037 phandle_base) < 0) {
2038 printk(BIOS_ERR, "invalid local fixups in overlay\n");
2039 return -1;
2043 * Besides local phandle references (from nodes within the overlay to
2044 * other nodes within the overlay), the overlay may also contain phandle
2045 * references to the base tree. These are stored with invalid values and
2046 * must be updated now. /__symbols__ contains a list of all labels in
2047 * the base tree, and /__fixups__ describes all nodes in the overlay
2048 * that contain external phandle references.
2049 * We also take this opportunity to update all /fragment@X/__overlay__/
2050 * prefixes in the overlay's /__symbols__ node to the correct path that
2051 * the fragment will be placed in later, since this is the only step
2052 * where we have all necessary information for that easily available.
2054 struct device_tree_node *symbols = dt_find_node_by_path(tree,
2055 "/__symbols__", NULL, NULL, 0);
2056 struct device_tree_node *fixups = dt_find_node_by_path(overlay,
2057 "/__fixups__", NULL, NULL, 0);
2058 struct device_tree_node *overlay_symbols = dt_find_node_by_path(overlay,
2059 "/__symbols__", NULL, NULL, 0);
2060 if (fixups && dt_fixup_all_externals(tree, symbols, overlay,
2061 fixups, overlay_symbols) < 0) {
2062 printk(BIOS_ERR, "cannot match external fixups from overlay\n");
2063 return -1;
2066 /* After all this fixing up, we can finally merge overlay into the tree
2067 (one fragment at a time, because for some reason it's split up). */
2068 struct device_tree_node *fragment;
2069 list_for_each(fragment, overlay->root->children, list_node)
2070 if (dt_import_fragment(tree, fragment, overlay_symbols) < 0) {
2071 printk(BIOS_ERR, "bad DT fragment '%s'\n",
2072 fragment->name);
2073 return -1;
2077 * We need to also update /__symbols__ to include labels from this
2078 * overlay, in case we want to load further overlays with external
2079 * phandle references to it. If the base tree already has a /__symbols__
2080 * we merge them together, otherwise we just insert the overlay's
2081 * /__symbols__ node into the base tree root.
2083 if (overlay_symbols) {
2084 if (symbols)
2085 dt_copy_subtree(symbols, overlay_symbols, 0);
2086 else
2087 list_insert_after(&overlay_symbols->list_node,
2088 &tree->root->children);
2091 return 0;