soc/intel: Remove blank lines before '}' and after '{'
[coreboot2.git] / src / lib / device_tree.c
bloba36798619b78cf6dc104425c7a198df3f68c3443
1 /* Taken from depthcharge: src/base/device_tree.c */
2 /* SPDX-License-Identifier: GPL-2.0-or-later */
4 #include <assert.h>
5 #include <console/console.h>
6 #include <ctype.h>
7 #include <device_tree.h>
8 #include <endian.h>
9 #include <stdint.h>
10 #include <string.h>
11 #include <stddef.h>
12 #include <stdlib.h>
15 * Functions for picking apart flattened trees.
18 int fdt_next_property(const void *blob, uint32_t offset,
19 struct fdt_property *prop)
21 struct fdt_header *header = (struct fdt_header *)blob;
22 uint32_t *ptr = (uint32_t *)(((uint8_t *)blob) + offset);
24 int index = 0;
25 if (be32toh(ptr[index++]) != FDT_TOKEN_PROPERTY)
26 return 0;
28 uint32_t size = be32toh(ptr[index++]);
29 uint32_t name_offset = be32toh(ptr[index++]);
30 name_offset += be32toh(header->strings_offset);
32 if (prop) {
33 prop->name = (char *)((uint8_t *)blob + name_offset);
34 prop->data = &ptr[index];
35 prop->size = size;
38 index += DIV_ROUND_UP(size, sizeof(uint32_t));
40 return index * sizeof(uint32_t);
43 int fdt_node_name(const void *blob, uint32_t offset, const char **name)
45 uint8_t *ptr = ((uint8_t *)blob) + offset;
46 if (be32dec(ptr) != FDT_TOKEN_BEGIN_NODE)
47 return 0;
49 ptr += 4;
50 if (name)
51 *name = (char *)ptr;
52 return ALIGN_UP(strlen((char *)ptr) + 1, sizeof(uint32_t)) + 4;
55 static int dt_prop_is_phandle(struct device_tree_property *prop)
57 return !(strcmp("phandle", prop->prop.name) &&
58 strcmp("linux,phandle", prop->prop.name));
64 * Functions for printing flattened trees.
67 static void print_indent(int depth)
69 printk(BIOS_DEBUG, "%*s", depth * 8, "");
72 static void print_property(const struct fdt_property *prop, int depth)
74 int is_string = prop->size > 0 &&
75 ((char *)prop->data)[prop->size - 1] == '\0';
77 if (is_string) {
78 for (int i = 0; i < prop->size - 1; i++) {
79 if (!isprint(((char *)prop->data)[i])) {
80 is_string = 0;
81 break;
86 print_indent(depth);
87 if (is_string) {
88 printk(BIOS_DEBUG, "%s = \"%s\";\n",
89 prop->name, (const char *)prop->data);
90 } else {
91 printk(BIOS_DEBUG, "%s = < ", prop->name);
92 for (int i = 0; i < MIN(128, prop->size); i += 4) {
93 uint32_t val = 0;
94 for (int j = 0; j < MIN(4, prop->size - i); j++)
95 val |= ((uint8_t *)prop->data)[i + j] <<
96 (24 - j * 8);
97 printk(BIOS_DEBUG, "%#.2x ", val);
99 if (prop->size > 128)
100 printk(BIOS_DEBUG, "...");
101 printk(BIOS_DEBUG, ">;\n");
105 static int print_flat_node(const void *blob, uint32_t start_offset, int depth)
107 int offset = start_offset;
108 const char *name;
109 int size;
111 size = fdt_node_name(blob, offset, &name);
112 if (!size)
113 return 0;
114 offset += size;
116 print_indent(depth);
117 printk(BIOS_DEBUG, "%s {\n", name);
119 struct fdt_property prop;
120 while ((size = fdt_next_property(blob, offset, &prop))) {
121 print_property(&prop, depth + 1);
123 offset += size;
126 printk(BIOS_DEBUG, "\n"); /* empty line between props and nodes */
128 while ((size = print_flat_node(blob, offset, depth + 1)))
129 offset += size;
131 print_indent(depth);
132 printk(BIOS_DEBUG, "}\n");
134 return offset - start_offset + sizeof(uint32_t);
137 void fdt_print_node(const void *blob, uint32_t offset)
139 print_flat_node(blob, offset, 0);
145 * A utility function to skip past nodes in flattened trees.
148 int fdt_skip_node(const void *blob, uint32_t start_offset)
150 int offset = start_offset;
151 int size;
153 const char *name;
154 size = fdt_node_name(blob, offset, &name);
155 if (!size)
156 return 0;
157 offset += size;
159 while ((size = fdt_next_property(blob, offset, NULL)))
160 offset += size;
162 while ((size = fdt_skip_node(blob, offset)))
163 offset += size;
165 return offset - start_offset + sizeof(uint32_t);
171 * Functions to turn a flattened tree into an unflattened one.
174 static int fdt_unflatten_node(const void *blob, uint32_t start_offset,
175 struct device_tree *tree,
176 struct device_tree_node **new_node)
178 struct list_node *last;
179 int offset = start_offset;
180 const char *name;
181 int size;
183 size = fdt_node_name(blob, offset, &name);
184 if (!size)
185 return 0;
186 offset += size;
188 struct device_tree_node *node = xzalloc(sizeof(*node));
189 *new_node = node;
190 node->name = name;
192 struct fdt_property fprop;
193 last = &node->properties;
194 while ((size = fdt_next_property(blob, offset, &fprop))) {
195 struct device_tree_property *prop = xzalloc(sizeof(*prop));
196 prop->prop = fprop;
198 if (dt_prop_is_phandle(prop)) {
199 node->phandle = be32dec(prop->prop.data);
200 if (node->phandle > tree->max_phandle)
201 tree->max_phandle = node->phandle;
204 list_insert_after(&prop->list_node, last);
205 last = &prop->list_node;
207 offset += size;
210 struct device_tree_node *child;
211 last = &node->children;
212 while ((size = fdt_unflatten_node(blob, offset, tree, &child))) {
213 list_insert_after(&child->list_node, last);
214 last = &child->list_node;
216 offset += size;
219 return offset - start_offset + sizeof(uint32_t);
222 static int fdt_unflatten_map_entry(const void *blob, uint32_t offset,
223 struct device_tree_reserve_map_entry **new)
225 const uint64_t *ptr = (const uint64_t *)(((uint8_t *)blob) + offset);
226 const uint64_t start = be64toh(ptr[0]);
227 const uint64_t size = be64toh(ptr[1]);
229 if (!size)
230 return 0;
232 struct device_tree_reserve_map_entry *entry = xzalloc(sizeof(*entry));
233 *new = entry;
234 entry->start = start;
235 entry->size = size;
237 return sizeof(uint64_t) * 2;
240 struct device_tree *fdt_unflatten(const void *blob)
242 struct device_tree *tree = xzalloc(sizeof(*tree));
243 const struct fdt_header *header = (const struct fdt_header *)blob;
244 tree->header = header;
246 uint32_t magic = be32toh(header->magic);
247 uint32_t version = be32toh(header->version);
248 uint32_t last_comp_version = be32toh(header->last_comp_version);
250 if (magic != FDT_HEADER_MAGIC) {
251 printk(BIOS_DEBUG, "Invalid device tree magic %#.8x!\n", magic);
252 free(tree);
253 return NULL;
255 if (last_comp_version > FDT_SUPPORTED_VERSION) {
256 printk(BIOS_DEBUG, "Unsupported device tree version %u(>=%u)\n",
257 version, last_comp_version);
258 free(tree);
259 return NULL;
261 if (version > FDT_SUPPORTED_VERSION)
262 printk(BIOS_NOTICE, "FDT version %u too new, should add support!\n",
263 version);
265 uint32_t struct_offset = be32toh(header->structure_offset);
266 uint32_t strings_offset = be32toh(header->strings_offset);
267 uint32_t reserve_offset = be32toh(header->reserve_map_offset);
268 uint32_t min_offset = 0;
269 min_offset = MIN(struct_offset, strings_offset);
270 min_offset = MIN(min_offset, reserve_offset);
271 /* Assume everything up to the first non-header component is part of
272 the header and needs to be preserved. This will protect us against
273 new elements being added in the future. */
274 tree->header_size = min_offset;
276 struct device_tree_reserve_map_entry *entry;
277 uint32_t offset = reserve_offset;
278 int size;
279 struct list_node *last = &tree->reserve_map;
280 while ((size = fdt_unflatten_map_entry(blob, offset, &entry))) {
281 list_insert_after(&entry->list_node, last);
282 last = &entry->list_node;
284 offset += size;
287 fdt_unflatten_node(blob, struct_offset, tree, &tree->root);
289 return tree;
295 * Functions to find the size of the device tree if it was flattened.
298 static void dt_flat_prop_size(struct device_tree_property *prop,
299 uint32_t *struct_size, uint32_t *strings_size)
301 /* Starting token. */
302 *struct_size += sizeof(uint32_t);
303 /* Size. */
304 *struct_size += sizeof(uint32_t);
305 /* Name offset. */
306 *struct_size += sizeof(uint32_t);
307 /* Property value. */
308 *struct_size += ALIGN_UP(prop->prop.size, sizeof(uint32_t));
310 /* Property name. */
311 *strings_size += strlen(prop->prop.name) + 1;
314 static void dt_flat_node_size(struct device_tree_node *node,
315 uint32_t *struct_size, uint32_t *strings_size)
317 /* Starting token. */
318 *struct_size += sizeof(uint32_t);
319 /* Node name. */
320 *struct_size += ALIGN_UP(strlen(node->name) + 1, sizeof(uint32_t));
322 struct device_tree_property *prop;
323 list_for_each(prop, node->properties, list_node)
324 dt_flat_prop_size(prop, struct_size, strings_size);
326 struct device_tree_node *child;
327 list_for_each(child, node->children, list_node)
328 dt_flat_node_size(child, struct_size, strings_size);
330 /* End token. */
331 *struct_size += sizeof(uint32_t);
334 uint32_t dt_flat_size(const struct device_tree *tree)
336 uint32_t size = tree->header_size;
337 struct device_tree_reserve_map_entry *entry;
338 list_for_each(entry, tree->reserve_map, list_node)
339 size += sizeof(uint64_t) * 2;
340 size += sizeof(uint64_t) * 2;
342 uint32_t struct_size = 0;
343 uint32_t strings_size = 0;
344 dt_flat_node_size(tree->root, &struct_size, &strings_size);
346 size += struct_size;
347 /* End token. */
348 size += sizeof(uint32_t);
350 size += strings_size;
352 return size;
358 * Functions to flatten a device tree.
361 static void dt_flatten_map_entry(struct device_tree_reserve_map_entry *entry,
362 void **map_start)
364 ((uint64_t *)*map_start)[0] = htobe64(entry->start);
365 ((uint64_t *)*map_start)[1] = htobe64(entry->size);
366 *map_start = ((uint8_t *)*map_start) + sizeof(uint64_t) * 2;
369 static void dt_flatten_prop(struct device_tree_property *prop,
370 void **struct_start, void *strings_base,
371 void **strings_start)
373 uint8_t *dstruct = (uint8_t *)*struct_start;
374 uint8_t *dstrings = (uint8_t *)*strings_start;
376 be32enc(dstruct, FDT_TOKEN_PROPERTY);
377 dstruct += sizeof(uint32_t);
379 be32enc(dstruct, prop->prop.size);
380 dstruct += sizeof(uint32_t);
382 uint32_t name_offset = (uintptr_t)dstrings - (uintptr_t)strings_base;
383 be32enc(dstruct, name_offset);
384 dstruct += sizeof(uint32_t);
386 strcpy((char *)dstrings, prop->prop.name);
387 dstrings += strlen(prop->prop.name) + 1;
389 memcpy(dstruct, prop->prop.data, prop->prop.size);
390 dstruct += ALIGN_UP(prop->prop.size, sizeof(uint32_t));
392 *struct_start = dstruct;
393 *strings_start = dstrings;
396 static void dt_flatten_node(const struct device_tree_node *node,
397 void **struct_start, void *strings_base,
398 void **strings_start)
400 uint8_t *dstruct = (uint8_t *)*struct_start;
401 uint8_t *dstrings = (uint8_t *)*strings_start;
403 be32enc(dstruct, FDT_TOKEN_BEGIN_NODE);
404 dstruct += sizeof(uint32_t);
406 strcpy((char *)dstruct, node->name);
407 dstruct += ALIGN_UP(strlen(node->name) + 1, sizeof(uint32_t));
409 struct device_tree_property *prop;
410 list_for_each(prop, node->properties, list_node)
411 dt_flatten_prop(prop, (void **)&dstruct, strings_base,
412 (void **)&dstrings);
414 struct device_tree_node *child;
415 list_for_each(child, node->children, list_node)
416 dt_flatten_node(child, (void **)&dstruct, strings_base,
417 (void **)&dstrings);
419 be32enc(dstruct, FDT_TOKEN_END_NODE);
420 dstruct += sizeof(uint32_t);
422 *struct_start = dstruct;
423 *strings_start = dstrings;
426 void dt_flatten(const struct device_tree *tree, void *start_dest)
428 uint8_t *dest = (uint8_t *)start_dest;
430 memcpy(dest, tree->header, tree->header_size);
431 struct fdt_header *header = (struct fdt_header *)dest;
432 dest += tree->header_size;
434 struct device_tree_reserve_map_entry *entry;
435 list_for_each(entry, tree->reserve_map, list_node)
436 dt_flatten_map_entry(entry, (void **)&dest);
437 ((uint64_t *)dest)[0] = ((uint64_t *)dest)[1] = 0;
438 dest += sizeof(uint64_t) * 2;
440 uint32_t struct_size = 0;
441 uint32_t strings_size = 0;
442 dt_flat_node_size(tree->root, &struct_size, &strings_size);
444 uint8_t *struct_start = dest;
445 header->structure_offset = htobe32(dest - (uint8_t *)start_dest);
446 header->structure_size = htobe32(struct_size);
447 dest += struct_size;
449 *((uint32_t *)dest) = htobe32(FDT_TOKEN_END);
450 dest += sizeof(uint32_t);
452 uint8_t *strings_start = dest;
453 header->strings_offset = htobe32(dest - (uint8_t *)start_dest);
454 header->strings_size = htobe32(strings_size);
455 dest += strings_size;
457 dt_flatten_node(tree->root, (void **)&struct_start, strings_start,
458 (void **)&strings_start);
460 header->totalsize = htobe32(dest - (uint8_t *)start_dest);
466 * Functions for printing a non-flattened device tree.
469 static void print_node(const struct device_tree_node *node, int depth)
471 print_indent(depth);
472 if (depth == 0) /* root node has no name, print a starting slash */
473 printk(BIOS_DEBUG, "/");
474 printk(BIOS_DEBUG, "%s {\n", node->name);
476 struct device_tree_property *prop;
477 list_for_each(prop, node->properties, list_node)
478 print_property(&prop->prop, depth + 1);
480 printk(BIOS_DEBUG, "\n"); /* empty line between props and nodes */
482 struct device_tree_node *child;
483 list_for_each(child, node->children, list_node)
484 print_node(child, depth + 1);
486 print_indent(depth);
487 printk(BIOS_DEBUG, "};\n");
490 void dt_print_node(const struct device_tree_node *node)
492 print_node(node, 0);
498 * Functions for reading and manipulating an unflattened device tree.
502 * Read #address-cells and #size-cells properties from a node.
504 * @param node The device tree node to read from.
505 * @param addrcp Pointer to store #address-cells in, skipped if NULL.
506 * @param sizecp Pointer to store #size-cells in, skipped if NULL.
508 void dt_read_cell_props(const struct device_tree_node *node, u32 *addrcp,
509 u32 *sizecp)
511 struct device_tree_property *prop;
512 list_for_each(prop, node->properties, list_node) {
513 if (addrcp && !strcmp("#address-cells", prop->prop.name))
514 *addrcp = be32dec(prop->prop.data);
515 if (sizecp && !strcmp("#size-cells", prop->prop.name))
516 *sizecp = be32dec(prop->prop.data);
521 * Find a node from a device tree path, relative to a parent node.
523 * @param parent The node from which to start the relative path lookup.
524 * @param path An array of path component strings that will be looked
525 * up in order to find the node. Must be terminated with
526 * a NULL pointer. Example: {'firmware', 'coreboot', NULL}
527 * @param addrcp Pointer that will be updated with any #address-cells
528 * value found in the path. May be NULL to ignore.
529 * @param sizecp Pointer that will be updated with any #size-cells
530 * value found in the path. May be NULL to ignore.
531 * @param create 1: Create node(s) if not found. 0: Return NULL instead.
532 * @return The found/created node, or NULL.
534 struct device_tree_node *dt_find_node(struct device_tree_node *parent,
535 const char **path, u32 *addrcp,
536 u32 *sizecp, int create)
538 struct device_tree_node *node, *found = NULL;
540 /* Update #address-cells and #size-cells for this level. */
541 dt_read_cell_props(parent, addrcp, sizecp);
543 if (!*path)
544 return parent;
546 /* Find the next node in the path, if it exists. */
547 list_for_each(node, parent->children, list_node) {
548 if (!strcmp(node->name, *path)) {
549 found = node;
550 break;
554 /* Otherwise create it or return NULL. */
555 if (!found) {
556 if (!create)
557 return NULL;
559 found = calloc(1, sizeof(*found));
560 if (!found)
561 return NULL;
562 found->name = strdup(*path);
563 if (!found->name)
564 return NULL;
566 list_insert_after(&found->list_node, &parent->children);
569 return dt_find_node(found, path + 1, addrcp, sizecp, create);
573 * Find a node in the tree from a string device tree path.
575 * @param tree The device tree to search.
576 * @param path A string representing a path in the device tree, with
577 * nodes separated by '/'. Example: "/firmware/coreboot"
578 * @param addrcp Pointer that will be updated with any #address-cells
579 * value found in the path. May be NULL to ignore.
580 * @param sizecp Pointer that will be updated with any #size-cells
581 * value found in the path. May be NULL to ignore.
582 * @param create 1: Create node(s) if not found. 0: Return NULL instead.
583 * @return The found/created node, or NULL.
585 * It is the caller responsibility to provide a path string that doesn't end
586 * with a '/' and doesn't contain any "//". If the path does not start with a
587 * '/', the first segment is interpreted as an alias. */
588 struct device_tree_node *dt_find_node_by_path(struct device_tree *tree,
589 const char *path, u32 *addrcp,
590 u32 *sizecp, int create)
592 char *sub_path;
593 char *duped_str;
594 struct device_tree_node *parent;
595 char *next_slash;
596 /* Hopefully enough depth for any node. */
597 const char *path_array[15];
598 int i;
599 struct device_tree_node *node = NULL;
601 if (path[0] == '/') { /* regular path */
602 if (path[1] == '\0') { /* special case: "/" is root node */
603 dt_read_cell_props(tree->root, addrcp, sizecp);
604 return tree->root;
607 sub_path = duped_str = strdup(&path[1]);
608 if (!sub_path)
609 return NULL;
611 parent = tree->root;
612 } else { /* alias */
613 char *alias;
615 alias = duped_str = strdup(path);
616 if (!alias)
617 return NULL;
619 sub_path = strchr(alias, '/');
620 if (sub_path)
621 *sub_path = '\0';
623 parent = dt_find_node_by_alias(tree, alias);
624 if (!parent) {
625 printk(BIOS_DEBUG,
626 "Could not find node '%s', alias '%s' does not exist\n",
627 path, alias);
628 free(duped_str);
629 return NULL;
632 if (!sub_path) {
633 /* it's just the alias, no sub-path */
634 free(duped_str);
635 return parent;
638 sub_path++;
641 next_slash = sub_path;
642 path_array[0] = sub_path;
643 for (i = 1; i < (ARRAY_SIZE(path_array) - 1); i++) {
644 next_slash = strchr(next_slash, '/');
645 if (!next_slash)
646 break;
648 *next_slash++ = '\0';
649 path_array[i] = next_slash;
652 if (!next_slash) {
653 path_array[i] = NULL;
654 node = dt_find_node(parent, path_array,
655 addrcp, sizecp, create);
658 free(duped_str);
659 return node;
663 * Find a node from an alias
665 * @param tree The device tree.
666 * @param alias The alias name.
667 * @return The found node, or NULL.
669 struct device_tree_node *dt_find_node_by_alias(struct device_tree *tree,
670 const char *alias)
672 struct device_tree_node *node;
673 const char *alias_path;
675 node = dt_find_node_by_path(tree, "/aliases", NULL, NULL, 0);
676 if (!node)
677 return NULL;
679 alias_path = dt_find_string_prop(node, alias);
680 if (!alias_path)
681 return NULL;
683 return dt_find_node_by_path(tree, alias_path, NULL, NULL, 0);
686 struct device_tree_node *dt_find_node_by_phandle(struct device_tree_node *root,
687 uint32_t phandle)
689 if (!root)
690 return NULL;
692 if (root->phandle == phandle)
693 return root;
695 struct device_tree_node *node;
696 struct device_tree_node *result;
697 list_for_each(node, root->children, list_node) {
698 result = dt_find_node_by_phandle(node, phandle);
699 if (result)
700 return result;
703 return NULL;
707 * Check if given node is compatible.
709 * @param node The node which is to be checked for compatible property.
710 * @param compat The compatible string to match.
711 * @return 1 = compatible, 0 = not compatible.
713 static int dt_check_compat_match(struct device_tree_node *node,
714 const char *compat)
716 struct device_tree_property *prop;
718 list_for_each(prop, node->properties, list_node) {
719 if (!strcmp("compatible", prop->prop.name)) {
720 size_t bytes = prop->prop.size;
721 const char *str = prop->prop.data;
722 while (bytes > 0) {
723 if (!strncmp(compat, str, bytes))
724 return 1;
725 size_t len = strnlen(str, bytes) + 1;
726 if (bytes <= len)
727 break;
728 str += len;
729 bytes -= len;
731 break;
735 return 0;
739 * Find a node from a compatible string, in the subtree of a parent node.
741 * @param parent The parent node under which to look.
742 * @param compat The compatible string to find.
743 * @return The found node, or NULL.
745 struct device_tree_node *dt_find_compat(struct device_tree_node *parent,
746 const char *compat)
748 /* Check if the parent node itself is compatible. */
749 if (dt_check_compat_match(parent, compat))
750 return parent;
752 struct device_tree_node *child;
753 list_for_each(child, parent->children, list_node) {
754 struct device_tree_node *found = dt_find_compat(child, compat);
755 if (found)
756 return found;
759 return NULL;
763 * Find the next compatible child of a given parent. All children up to the
764 * child passed in by caller are ignored. If child is NULL, it considers all the
765 * children to find the first child which is compatible.
767 * @param parent The parent node under which to look.
768 * @param child The child node to start search from (exclusive). If NULL
769 * consider all children.
770 * @param compat The compatible string to find.
771 * @return The found node, or NULL.
773 struct device_tree_node *
774 dt_find_next_compat_child(struct device_tree_node *parent,
775 struct device_tree_node *child,
776 const char *compat)
778 struct device_tree_node *next;
779 int ignore = 0;
781 if (child)
782 ignore = 1;
784 list_for_each(next, parent->children, list_node) {
785 if (ignore) {
786 if (child == next)
787 ignore = 0;
788 continue;
791 if (dt_check_compat_match(next, compat))
792 return next;
795 return NULL;
799 * Find a node with matching property value, in the subtree of a parent node.
801 * @param parent The parent node under which to look.
802 * @param name The property name to look for.
803 * @param data The property value to look for.
804 * @param size The property size.
806 struct device_tree_node *dt_find_prop_value(struct device_tree_node *parent,
807 const char *name, void *data,
808 size_t size)
810 struct device_tree_property *prop;
812 /* Check if parent itself has the required property value. */
813 list_for_each(prop, parent->properties, list_node) {
814 if (!strcmp(name, prop->prop.name)) {
815 size_t bytes = prop->prop.size;
816 const void *prop_data = prop->prop.data;
817 if (size != bytes)
818 break;
819 if (!memcmp(data, prop_data, size))
820 return parent;
821 break;
825 struct device_tree_node *child;
826 list_for_each(child, parent->children, list_node) {
827 struct device_tree_node *found = dt_find_prop_value(child, name,
828 data, size);
829 if (found)
830 return found;
832 return NULL;
836 * Write an arbitrary sized big-endian integer into a pointer.
838 * @param dest Pointer to the DT property data buffer to write.
839 * @param src The integer to write (in CPU endianness).
840 * @param length the length of the destination integer in bytes.
842 void dt_write_int(u8 *dest, u64 src, size_t length)
844 while (length--) {
845 dest[length] = (u8)src;
846 src >>= 8;
851 * Delete a property by name in a given node if it exists.
853 * @param node The device tree node to operate on.
854 * @param name The name of the property to delete.
856 void dt_delete_prop(struct device_tree_node *node, const char *name)
858 struct device_tree_property *prop;
860 list_for_each(prop, node->properties, list_node) {
861 if (!strcmp(prop->prop.name, name)) {
862 list_remove(&prop->list_node);
863 return;
869 * Add an arbitrary property to a node, or update it if it already exists.
871 * @param node The device tree node to add to.
872 * @param name The name of the new property.
873 * @param data The raw data blob to be stored in the property.
874 * @param size The size of data in bytes.
876 void dt_add_bin_prop(struct device_tree_node *node, const char *name,
877 void *data, size_t size)
879 struct device_tree_property *prop;
881 list_for_each(prop, node->properties, list_node) {
882 if (!strcmp(prop->prop.name, name)) {
883 prop->prop.data = data;
884 prop->prop.size = size;
885 return;
889 prop = xzalloc(sizeof(*prop));
890 list_insert_after(&prop->list_node, &node->properties);
891 prop->prop.name = name;
892 prop->prop.data = data;
893 prop->prop.size = size;
897 * Find given string property in a node and return its content.
899 * @param node The device tree node to search.
900 * @param name The name of the property.
901 * @return The found string, or NULL.
903 const char *dt_find_string_prop(const struct device_tree_node *node,
904 const char *name)
906 const void *content;
907 size_t size;
909 dt_find_bin_prop(node, name, &content, &size);
911 return content;
915 * Find given property in a node.
917 * @param node The device tree node to search.
918 * @param name The name of the property.
919 * @param data Pointer to return raw data blob in the property.
920 * @param size Pointer to return the size of data in bytes.
922 void dt_find_bin_prop(const struct device_tree_node *node, const char *name,
923 const void **data, size_t *size)
925 struct device_tree_property *prop;
927 *data = NULL;
928 *size = 0;
930 list_for_each(prop, node->properties, list_node) {
931 if (!strcmp(prop->prop.name, name)) {
932 *data = prop->prop.data;
933 *size = prop->prop.size;
934 return;
940 * Add a string property to a node, or update it if it already exists.
942 * @param node The device tree node to add to.
943 * @param name The name of the new property.
944 * @param str The zero-terminated string to be stored in the property.
946 void dt_add_string_prop(struct device_tree_node *node, const char *name,
947 const char *str)
949 dt_add_bin_prop(node, name, (char *)str, strlen(str) + 1);
953 * Add a 32-bit integer property to a node, or update it if it already exists.
955 * @param node The device tree node to add to.
956 * @param name The name of the new property.
957 * @param val The integer to be stored in the property.
959 void dt_add_u32_prop(struct device_tree_node *node, const char *name, u32 val)
961 u32 *val_ptr = xmalloc(sizeof(val));
962 *val_ptr = htobe32(val);
963 dt_add_bin_prop(node, name, val_ptr, sizeof(*val_ptr));
967 * Add a 64-bit integer property to a node, or update it if it already exists.
969 * @param node The device tree node to add to.
970 * @param name The name of the new property.
971 * @param val The integer to be stored in the property.
973 void dt_add_u64_prop(struct device_tree_node *node, const char *name, u64 val)
975 u64 *val_ptr = xmalloc(sizeof(val));
976 *val_ptr = htobe64(val);
977 dt_add_bin_prop(node, name, val_ptr, sizeof(*val_ptr));
981 * Add a 'reg' address list property to a node, or update it if it exists.
983 * @param node The device tree node to add to.
984 * @param addrs Array of address values to be stored in the property.
985 * @param sizes Array of corresponding size values to 'addrs'.
986 * @param count Number of values in 'addrs' and 'sizes' (must be equal).
987 * @param addr_cells Value of #address-cells property valid for this node.
988 * @param size_cells Value of #size-cells property valid for this node.
990 void dt_add_reg_prop(struct device_tree_node *node, u64 *addrs, u64 *sizes,
991 int count, u32 addr_cells, u32 size_cells)
993 int i;
994 size_t length = (addr_cells + size_cells) * sizeof(u32) * count;
995 u8 *data = xmalloc(length);
996 u8 *cur = data;
998 for (i = 0; i < count; i++) {
999 dt_write_int(cur, addrs[i], addr_cells * sizeof(u32));
1000 cur += addr_cells * sizeof(u32);
1001 dt_write_int(cur, sizes[i], size_cells * sizeof(u32));
1002 cur += size_cells * sizeof(u32);
1005 dt_add_bin_prop(node, "reg", data, length);
1009 * Fixups to apply to a kernel's device tree before booting it.
1012 struct list_node device_tree_fixups;
1014 int dt_apply_fixups(struct device_tree *tree)
1016 struct device_tree_fixup *fixup;
1017 list_for_each(fixup, device_tree_fixups, list_node) {
1018 assert(fixup->fixup);
1019 if (fixup->fixup(fixup, tree))
1020 return 1;
1022 return 0;
1025 int dt_set_bin_prop_by_path(struct device_tree *tree, const char *path,
1026 void *data, size_t data_size, int create)
1028 char *path_copy, *prop_name;
1029 struct device_tree_node *dt_node;
1031 path_copy = strdup(path);
1033 if (!path_copy) {
1034 printk(BIOS_ERR, "Failed to allocate a copy of path %s\n",
1035 path);
1036 return 1;
1039 prop_name = strrchr(path_copy, '/');
1040 if (!prop_name) {
1041 free(path_copy);
1042 printk(BIOS_ERR, "Path %s does not include '/'\n", path);
1043 return 1;
1046 *prop_name++ = '\0'; /* Separate path from the property name. */
1048 dt_node = dt_find_node_by_path(tree, path_copy, NULL,
1049 NULL, create);
1051 if (!dt_node) {
1052 printk(BIOS_ERR, "Failed to %s %s in the device tree\n",
1053 create ? "create" : "find", path_copy);
1054 free(path_copy);
1055 return 1;
1058 dt_add_bin_prop(dt_node, prop_name, data, data_size);
1059 free(path_copy);
1061 return 0;
1065 * Prepare the /reserved-memory/ node.
1067 * Technically, this can be called more than one time, to init and/or retrieve
1068 * the node. But dt_add_u32_prop() may leak a bit of memory if you do.
1070 * @tree: Device tree to add/retrieve from.
1071 * @return: The /reserved-memory/ node (or NULL, if error).
1073 struct device_tree_node *dt_init_reserved_memory_node(struct device_tree *tree)
1075 struct device_tree_node *reserved;
1076 u32 addr = 0, size = 0;
1078 reserved = dt_find_node_by_path(tree, "/reserved-memory", &addr,
1079 &size, 1);
1080 if (!reserved)
1081 return NULL;
1083 /* Binding doc says this should have the same #{address,size}-cells as
1084 the root. */
1085 dt_add_u32_prop(reserved, "#address-cells", addr);
1086 dt_add_u32_prop(reserved, "#size-cells", size);
1087 /* Binding doc says this should be empty (1:1 mapping from root). */
1088 dt_add_bin_prop(reserved, "ranges", NULL, 0);
1090 return reserved;
1094 * Increment a single phandle in prop at a given offset by a given adjustment.
1096 * @param prop Property whose phandle should be adjusted.
1097 * @param adjustment Value that should be added to the existing phandle.
1098 * @param offset Byte offset of the phandle in the property data.
1100 * @return New phandle value, or 0 on error.
1102 static uint32_t dt_adjust_phandle(struct device_tree_property *prop,
1103 uint32_t adjustment, uint32_t offset)
1105 if (offset + 4 > prop->prop.size)
1106 return 0;
1108 uint32_t phandle = be32dec(prop->prop.data + offset);
1109 if (phandle == 0 ||
1110 phandle == FDT_PHANDLE_ILLEGAL ||
1111 phandle == 0xffffffff)
1112 return 0;
1114 phandle += adjustment;
1115 if (phandle >= FDT_PHANDLE_ILLEGAL)
1116 return 0;
1118 be32enc(prop->prop.data + offset, phandle);
1119 return phandle;
1123 * Adjust all phandles in subtree by adding a new base offset.
1125 * @param node Root node of the subtree to work on.
1126 * @param base New phandle base to be added to all phandles.
1128 * @return New highest phandle in the subtree, or 0 on error.
1130 static uint32_t dt_adjust_all_phandles(struct device_tree_node *node,
1131 uint32_t base)
1133 uint32_t new_max = MAX(base, 1); /* make sure we don't return 0 */
1134 struct device_tree_property *prop;
1135 struct device_tree_node *child;
1137 if (!node)
1138 return new_max;
1140 list_for_each(prop, node->properties, list_node)
1141 if (dt_prop_is_phandle(prop)) {
1142 node->phandle = dt_adjust_phandle(prop, base, 0);
1143 if (!node->phandle)
1144 return 0;
1145 new_max = MAX(new_max, node->phandle);
1146 } /* no break -- can have more than one phandle prop */
1148 list_for_each(child, node->children, list_node)
1149 new_max = MAX(new_max, dt_adjust_all_phandles(child, base));
1151 return new_max;
1155 * Apply a /__local_fixup__ subtree to the corresponding overlay subtree.
1157 * @param node Root node of the overlay subtree to fix up.
1158 * @param node Root node of the /__local_fixup__ subtree.
1159 * @param base Adjustment that was added to phandles in the overlay.
1161 * @return 0 on success, -1 on error.
1163 static int dt_fixup_locals(struct device_tree_node *node,
1164 struct device_tree_node *fixup, uint32_t base)
1166 struct device_tree_property *prop;
1167 struct device_tree_property *fixup_prop;
1168 struct device_tree_node *child;
1169 struct device_tree_node *fixup_child;
1170 int i;
1173 * For local fixups the /__local_fixup__ subtree contains the same node
1174 * hierarchy as the main tree we're fixing up. Each property contains
1175 * the fixup offsets for the respective property in the main tree. For
1176 * each property in the fixup node, find the corresponding property in
1177 * the base node and apply fixups to all offsets it specifies.
1179 list_for_each(fixup_prop, fixup->properties, list_node) {
1180 struct device_tree_property *base_prop = NULL;
1181 list_for_each(prop, node->properties, list_node)
1182 if (!strcmp(prop->prop.name, fixup_prop->prop.name)) {
1183 base_prop = prop;
1184 break;
1187 /* We should always find a corresponding base prop for a fixup,
1188 and fixup props contain a list of 32-bit fixup offsets. */
1189 if (!base_prop || fixup_prop->prop.size % sizeof(uint32_t))
1190 return -1;
1192 for (i = 0; i < fixup_prop->prop.size; i += sizeof(uint32_t))
1193 if (!dt_adjust_phandle(base_prop, base, be32dec(
1194 fixup_prop->prop.data + i)))
1195 return -1;
1198 /* Now recursively descend both the base tree and the /__local_fixups__
1199 subtree in sync to apply all fixups. */
1200 list_for_each(fixup_child, fixup->children, list_node) {
1201 struct device_tree_node *base_child = NULL;
1202 list_for_each(child, node->children, list_node)
1203 if (!strcmp(child->name, fixup_child->name)) {
1204 base_child = child;
1205 break;
1208 /* All fixup nodes should have a corresponding base node. */
1209 if (!base_child)
1210 return -1;
1212 if (dt_fixup_locals(base_child, fixup_child, base) < 0)
1213 return -1;
1216 return 0;
1220 * Update all /__symbols__ properties in an overlay that start with
1221 * "/fragment@X/__overlay__" with corresponding path prefix in the base tree.
1223 * @param symbols /__symbols__ done to update.
1224 * @param fragment /fragment@X node that references to should be updated.
1225 * @param base_path Path of base tree node that the fragment overlaid.
1227 static void dt_fix_symbols(struct device_tree_node *symbols,
1228 struct device_tree_node *fragment,
1229 const char *base_path)
1231 struct device_tree_property *prop;
1232 char buf[512]; /* Should be enough for maximum DT path length? */
1233 char node_path[64]; /* easily enough for /fragment@XXXX/__overlay__ */
1235 if (!symbols) /* If the overlay has no /__symbols__ node, we're done! */
1236 return;
1238 int len = snprintf(node_path, sizeof(node_path), "/%s/__overlay__",
1239 fragment->name);
1241 list_for_each(prop, symbols->properties, list_node)
1242 if (!strncmp(prop->prop.data, node_path, len)) {
1243 prop->prop.size = snprintf(buf, sizeof(buf), "%s%s",
1244 base_path, (char *)prop->prop.data + len) + 1;
1245 free(prop->prop.data);
1246 prop->prop.data = strdup(buf);
1251 * Fix up overlay according to a property in /__fixup__. If the fixed property
1252 * is a /fragment@X:target, also update /__symbols__ references to fragment.
1254 * @params overlay Overlay to fix up.
1255 * @params fixup /__fixup__ property.
1256 * @params phandle phandle value to insert where the fixup points to.
1257 * @params base_path Path to the base DT node that the fixup points to.
1258 * @params overlay_symbols /__symbols__ node of the overlay.
1260 * @return 0 on success, -1 on error.
1262 static int dt_fixup_external(struct device_tree *overlay,
1263 struct device_tree_property *fixup,
1264 uint32_t phandle, const char *base_path,
1265 struct device_tree_node *overlay_symbols)
1267 struct device_tree_property *prop;
1269 /* External fixup properties are encoded as "<path>:<prop>:<offset>". */
1270 char *entry = fixup->prop.data;
1271 while ((void *)entry < fixup->prop.data + fixup->prop.size) {
1272 /* okay to destroy fixup property value, won't need it again */
1273 char *node_path = entry;
1274 entry = strchr(node_path, ':');
1275 if (!entry)
1276 return -1;
1277 *entry++ = '\0';
1279 char *prop_name = entry;
1280 entry = strchr(prop_name, ':');
1281 if (!entry)
1282 return -1;
1283 *entry++ = '\0';
1285 struct device_tree_node *ovl_node = dt_find_node_by_path(
1286 overlay, node_path, NULL, NULL, 0);
1287 if (!ovl_node || !isdigit(*entry))
1288 return -1;
1290 struct device_tree_property *ovl_prop = NULL;
1291 list_for_each(prop, ovl_node->properties, list_node)
1292 if (!strcmp(prop->prop.name, prop_name)) {
1293 ovl_prop = prop;
1294 break;
1297 /* Move entry to first char after number, must be a '\0'. */
1298 uint32_t offset = skip_atoi(&entry);
1299 if (!ovl_prop || offset + 4 > ovl_prop->prop.size || entry[0])
1300 return -1;
1301 entry++; /* jump over '\0' to potential next fixup */
1303 be32enc(ovl_prop->prop.data + offset, phandle);
1305 /* If this is a /fragment@X:target property, update references
1306 to this fragment in the overlay __symbols__ now. */
1307 if (offset == 0 && !strcmp(prop_name, "target") &&
1308 !strchr(node_path + 1, '/')) /* only toplevel nodes */
1309 dt_fix_symbols(overlay_symbols, ovl_node, base_path);
1312 return 0;
1316 * Apply all /__fixup__ properties in the overlay. This will destroy the
1317 * property data in /__fixup__ and it should not be accessed again.
1319 * @params tree Base device tree that the overlay updates.
1320 * @params symbols /__symbols__ node of the base device tree.
1321 * @params overlay Overlay to fix up.
1322 * @params fixups /__fixup__ node in the overlay.
1323 * @params overlay_symbols /__symbols__ node of the overlay.
1325 * @return 0 on success, -1 on error.
1327 static int dt_fixup_all_externals(struct device_tree *tree,
1328 struct device_tree_node *symbols,
1329 struct device_tree *overlay,
1330 struct device_tree_node *fixups,
1331 struct device_tree_node *overlay_symbols)
1333 struct device_tree_property *fix;
1335 /* If we have any external fixups, base tree must have /__symbols__. */
1336 if (!symbols)
1337 return -1;
1340 * Unlike /__local_fixups__, /__fixups__ is not a whole subtree that
1341 * mirrors the node hierarchy. It's just a directory of fixup properties
1342 * that each directly contain all information necessary to apply them.
1344 list_for_each(fix, fixups->properties, list_node) {
1345 /* The name of a fixup property is the label of the node we want
1346 a property to phandle-reference. Look up in /__symbols__. */
1347 const char *path = dt_find_string_prop(symbols, fix->prop.name);
1348 if (!path)
1349 return -1;
1351 /* Find node the label pointed to figure out its phandle. */
1352 struct device_tree_node *node = dt_find_node_by_path(tree, path,
1353 NULL, NULL, 0);
1354 if (!node)
1355 return -1;
1357 /* Write into the overlay property(s) pointing to that node. */
1358 if (dt_fixup_external(overlay, fix, node->phandle,
1359 path, overlay_symbols) < 0)
1360 return -1;
1363 return 0;
1367 * Copy all nodes and properties from one DT subtree into another. This is a
1368 * shallow copy so both trees will point to the same property data afterwards.
1370 * @params dst Destination subtree to copy into.
1371 * @params src Source subtree to copy from.
1372 * @params upd 1 to overwrite same-name properties, 0 to discard them.
1374 static void dt_copy_subtree(struct device_tree_node *dst,
1375 struct device_tree_node *src, int upd)
1377 struct device_tree_property *prop;
1378 struct device_tree_property *src_prop;
1379 list_for_each(src_prop, src->properties, list_node) {
1380 if (dt_prop_is_phandle(src_prop) ||
1381 !strcmp(src_prop->prop.name, "name")) {
1382 printk(BIOS_DEBUG,
1383 "WARNING: ignoring illegal overlay prop '%s'\n",
1384 src_prop->prop.name);
1385 continue;
1388 struct device_tree_property *dst_prop = NULL;
1389 list_for_each(prop, dst->properties, list_node)
1390 if (!strcmp(prop->prop.name, src_prop->prop.name)) {
1391 dst_prop = prop;
1392 break;
1395 if (dst_prop) {
1396 if (!upd) {
1397 printk(BIOS_DEBUG,
1398 "WARNING: ignoring prop update '%s'\n",
1399 src_prop->prop.name);
1400 continue;
1402 } else {
1403 dst_prop = xzalloc(sizeof(*dst_prop));
1404 list_insert_after(&dst_prop->list_node,
1405 &dst->properties);
1408 dst_prop->prop = src_prop->prop;
1411 struct device_tree_node *node;
1412 struct device_tree_node *src_node;
1413 list_for_each(src_node, src->children, list_node) {
1414 struct device_tree_node *dst_node = NULL;
1415 list_for_each(node, dst->children, list_node)
1416 if (!strcmp(node->name, src_node->name)) {
1417 dst_node = node;
1418 break;
1421 if (!dst_node) {
1422 dst_node = xzalloc(sizeof(*dst_node));
1423 *dst_node = *src_node;
1424 list_insert_after(&dst_node->list_node, &dst->children);
1425 } else {
1426 dt_copy_subtree(dst_node, src_node, upd);
1432 * Apply an overlay /fragment@X node to a base device tree.
1434 * @param tree Base device tree.
1435 * @param fragment /fragment@X node.
1436 * @params overlay_symbols /__symbols__ node of the overlay.
1438 * @return 0 on success, -1 on error.
1440 static int dt_import_fragment(struct device_tree *tree,
1441 struct device_tree_node *fragment,
1442 struct device_tree_node *overlay_symbols)
1444 /* The actual overlaid nodes/props are in an __overlay__ child node. */
1445 static const char *overlay_path[] = { "__overlay__", NULL };
1446 struct device_tree_node *overlay = dt_find_node(fragment, overlay_path,
1447 NULL, NULL, 0);
1449 /* If it doesn't have an __overlay__ child, it's not a fragment. */
1450 if (!overlay)
1451 return 0;
1453 /* Target node of the fragment can be given by path or by phandle. */
1454 struct device_tree_property *prop;
1455 struct device_tree_property *phandle = NULL;
1456 struct device_tree_property *path = NULL;
1457 list_for_each(prop, fragment->properties, list_node) {
1458 if (!strcmp(prop->prop.name, "target")) {
1459 phandle = prop;
1460 break; /* phandle target has priority, stop looking */
1462 if (!strcmp(prop->prop.name, "target-path"))
1463 path = prop;
1466 struct device_tree_node *target = NULL;
1467 if (phandle) {
1468 if (phandle->prop.size != sizeof(uint32_t))
1469 return -1;
1470 target = dt_find_node_by_phandle(tree->root,
1471 be32dec(phandle->prop.data));
1472 /* Symbols already updated as part of dt_fixup_external(). */
1473 } else if (path) {
1474 target = dt_find_node_by_path(tree, path->prop.data,
1475 NULL, NULL, 0);
1476 dt_fix_symbols(overlay_symbols, fragment, path->prop.data);
1478 if (!target)
1479 return -1;
1481 dt_copy_subtree(target, overlay, 1);
1482 return 0;
1486 * Apply a device tree overlay to a base device tree. This will
1487 * destroy/incorporate the overlay data, so it should not be freed or reused.
1488 * See dtc.git/Documentation/dt-object-internal.txt for overlay format details.
1490 * @param tree Unflattened base device tree to add the overlay into.
1491 * @param overlay Unflattened overlay device tree to apply to the base.
1493 * @return 0 on success, -1 on error.
1495 int dt_apply_overlay(struct device_tree *tree, struct device_tree *overlay)
1498 * First, we need to make sure phandles inside the overlay don't clash
1499 * with those in the base tree. We just define the highest phandle value
1500 * in the base tree as the "phandle offset" for this overlay and
1501 * increment all phandles in it by that value.
1503 uint32_t phandle_base = tree->max_phandle;
1504 uint32_t new_max = dt_adjust_all_phandles(overlay->root, phandle_base);
1505 if (!new_max) {
1506 printk(BIOS_ERR, "invalid phandles in overlay\n");
1507 return -1;
1509 tree->max_phandle = new_max;
1511 /* Now that we changed phandles in the overlay, we need to update any
1512 nodes referring to them. Those are listed in /__local_fixups__. */
1513 struct device_tree_node *local_fixups = dt_find_node_by_path(overlay,
1514 "/__local_fixups__", NULL, NULL, 0);
1515 if (local_fixups && dt_fixup_locals(overlay->root, local_fixups,
1516 phandle_base) < 0) {
1517 printk(BIOS_ERR, "invalid local fixups in overlay\n");
1518 return -1;
1522 * Besides local phandle references (from nodes within the overlay to
1523 * other nodes within the overlay), the overlay may also contain phandle
1524 * references to the base tree. These are stored with invalid values and
1525 * must be updated now. /__symbols__ contains a list of all labels in
1526 * the base tree, and /__fixups__ describes all nodes in the overlay
1527 * that contain external phandle references.
1528 * We also take this opportunity to update all /fragment@X/__overlay__/
1529 * prefixes in the overlay's /__symbols__ node to the correct path that
1530 * the fragment will be placed in later, since this is the only step
1531 * where we have all necessary information for that easily available.
1533 struct device_tree_node *symbols = dt_find_node_by_path(tree,
1534 "/__symbols__", NULL, NULL, 0);
1535 struct device_tree_node *fixups = dt_find_node_by_path(overlay,
1536 "/__fixups__", NULL, NULL, 0);
1537 struct device_tree_node *overlay_symbols = dt_find_node_by_path(overlay,
1538 "/__symbols__", NULL, NULL, 0);
1539 if (fixups && dt_fixup_all_externals(tree, symbols, overlay,
1540 fixups, overlay_symbols) < 0) {
1541 printk(BIOS_ERR, "cannot match external fixups from overlay\n");
1542 return -1;
1545 /* After all this fixing up, we can finally merge overlay into the tree
1546 (one fragment at a time, because for some reason it's split up). */
1547 struct device_tree_node *fragment;
1548 list_for_each(fragment, overlay->root->children, list_node)
1549 if (dt_import_fragment(tree, fragment, overlay_symbols) < 0) {
1550 printk(BIOS_ERR, "bad DT fragment '%s'\n",
1551 fragment->name);
1552 return -1;
1556 * We need to also update /__symbols__ to include labels from this
1557 * overlay, in case we want to load further overlays with external
1558 * phandle references to it. If the base tree already has a /__symbols__
1559 * we merge them together, otherwise we just insert the overlay's
1560 * /__symbols__ node into the base tree root.
1562 if (overlay_symbols) {
1563 if (symbols)
1564 dt_copy_subtree(symbols, overlay_symbols, 0);
1565 else
1566 list_insert_after(&overlay_symbols->list_node,
1567 &tree->root->children);
1570 return 0;