xref: /aosp_15_r20/external/coreboot/src/commonlib/device_tree.c (revision b9411a12aaaa7e1e6a6fb7c5e057f44ee179a49c)
1 /* Taken from depthcharge: src/base/device_tree.c */
2 /* SPDX-License-Identifier: GPL-2.0-or-later */
3 
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>
21 
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
26 
27 /*
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).
32  */
33 
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
37 
alloc_node(void)38 static struct device_tree_node *alloc_node(void)
39 {
40 #ifndef __COREBOOT__
41 	static struct device_tree_node scratch[LP_ALLOC_NODE_SCRATCH_COUNT];
42 	static int counter = 0;
43 
44 	if (counter < ARRAY_SIZE(scratch))
45 		return &scratch[counter++];
46 #endif
47 	return xzalloc(sizeof(struct device_tree_node));
48 }
49 
alloc_prop(void)50 static struct device_tree_property *alloc_prop(void)
51 {
52 #ifndef __COREBOOT__
53 	static struct device_tree_property scratch[LP_ALLOC_PROP_SCRATCH_COUNT];
54 	static int counter = 0;
55 
56 	if (counter < ARRAY_SIZE(scratch))
57 		return &scratch[counter++];
58 #endif
59 	return xzalloc(sizeof(struct device_tree_property));
60 }
61 
62 /*
63  * Functions for picking apart flattened trees.
64  */
65 
fdt_skip_nops(const void * blob,uint32_t offset)66 static int fdt_skip_nops(const void *blob, uint32_t offset)
67 {
68 	uint32_t *ptr = (uint32_t *)(((uint8_t *)blob) + offset);
69 
70 	int index = 0;
71 	while (be32toh(ptr[index]) == FDT_TOKEN_NOP)
72 		index++;
73 
74 	return index * sizeof(uint32_t);
75 }
76 
fdt_next_property(const void * blob,uint32_t offset,struct fdt_property * prop)77 int fdt_next_property(const void *blob, uint32_t offset,
78 		      struct fdt_property *prop)
79 {
80 	struct fdt_header *header = (struct fdt_header *)blob;
81 	uint32_t *ptr = (uint32_t *)(((uint8_t *)blob) + offset);
82 
83 	// skip NOP tokens
84 	offset += fdt_skip_nops(blob, offset);
85 
86 	int index = 0;
87 	if (be32toh(ptr[index++]) != FDT_TOKEN_PROPERTY)
88 		return 0;
89 
90 	uint32_t size = be32toh(ptr[index++]);
91 	uint32_t name_offset = be32toh(ptr[index++]);
92 	name_offset += be32toh(header->strings_offset);
93 
94 	if (prop) {
95 		prop->name = (char *)((uint8_t *)blob + name_offset);
96 		prop->data = &ptr[index];
97 		prop->size = size;
98 	}
99 
100 	index += DIV_ROUND_UP(size, sizeof(uint32_t));
101 
102 	return index * sizeof(uint32_t);
103 }
104 
105 /*
106  * fdt_next_node_name  reads a node name
107  *
108  * @params blob    address of FDT
109  * @params offset  offset to the node to read the name from
110  * @params name    parameter to hold the name that has been read or NULL
111  *
112  * @returns  Either 0 on error or offset to the properties that come after the node name
113  */
fdt_next_node_name(const void * blob,uint32_t offset,const char ** name)114 int fdt_next_node_name(const void *blob, uint32_t offset, const char **name)
115 {
116 	// skip NOP tokens
117 	offset += fdt_skip_nops(blob, offset);
118 
119 	char *ptr = ((char *)blob) + offset;
120 	if (be32dec(ptr) != FDT_TOKEN_BEGIN_NODE)
121 		return 0;
122 
123 	ptr += 4;
124 	if (name)
125 		*name = ptr;
126 
127 	return ALIGN_UP(strlen(ptr) + 1, 4) + 4;
128 }
129 
130 /*
131  * A utility function to skip past nodes in flattened trees.
132  */
fdt_skip_node(const void * blob,uint32_t start_offset)133 int fdt_skip_node(const void *blob, uint32_t start_offset)
134 {
135 	uint32_t offset = start_offset;
136 
137 	const char *name;
138 	int size = fdt_next_node_name(blob, offset, &name);
139 	if (!size)
140 		return 0;
141 	offset += size;
142 
143 	while ((size = fdt_next_property(blob, offset, NULL)))
144 		offset += size;
145 
146 	while ((size = fdt_skip_node(blob, offset)))
147 		offset += size;
148 
149 	// skip NOP tokens
150 	offset += fdt_skip_nops(blob, offset);
151 
152 	return offset - start_offset + sizeof(uint32_t);
153 }
154 
155 /*
156  * fdt_read_prop reads a property inside a node
157  *
158  * @params blob         address of FDT
159  * @params node_offset  offset to the node to read the property from
160  * @params prop_name    name of the property to read
161  * @params fdt_prop     property is saved inside this parameter
162  *
163  * @returns  Either 0 if no property has been found or an offset that points to the location
164  *           of the property
165  */
fdt_read_prop(const void * blob,u32 node_offset,const char * prop_name,struct fdt_property * fdt_prop)166 u32 fdt_read_prop(const void *blob, u32 node_offset, const char *prop_name,
167 		  struct fdt_property *fdt_prop)
168 {
169 	u32 offset = node_offset;
170 
171 	offset += fdt_next_node_name(blob, offset, NULL); // skip node name
172 
173 	size_t size;
174 	while ((size = fdt_next_property(blob, offset, fdt_prop))) {
175 		if (strcmp(fdt_prop->name, prop_name) == 0)
176 			return offset;
177 		offset += size;
178 	}
179 	return 0; // property not found
180 }
181 
182 /*
183  * fdt_read_reg_prop reads the reg property inside a node
184  *
185  * @params blob           address of FDT
186  * @params node_offset    offset to the node to read the reg property from
187  * @params addr_cells     number of cells used for one address
188  * @params size_cells     number of cells used for one size
189  * @params regions        all regions that are read inside the reg property are saved inside
190  *                        this array
191  * @params regions_count  maximum number of entries that can be saved inside the regions array.
192  *
193  * Returns: Either 0 on error or returns the number of regions put into the regions array.
194  */
fdt_read_reg_prop(const void * blob,u32 node_offset,u32 addr_cells,u32 size_cells,struct device_tree_region regions[],size_t regions_count)195 u32 fdt_read_reg_prop(const void *blob, u32 node_offset, u32 addr_cells, u32 size_cells,
196 		      struct device_tree_region regions[], size_t regions_count)
197 {
198 	struct fdt_property prop;
199 	u32 offset = fdt_read_prop(blob, node_offset, "reg", &prop);
200 
201 	if (!offset) {
202 		printk(BIOS_DEBUG, "no reg property found in node_offset: %x\n", node_offset);
203 		return 0;
204 	}
205 
206 	// we found the reg property, now need to parse all regions in 'reg'
207 	size_t count = prop.size / (4 * addr_cells + 4 * size_cells);
208 	if (count > regions_count) {
209 		printk(BIOS_ERR, "reg property at node_offset: %x has more entries (%zd) than regions array can hold (%zd)\n", node_offset, count, regions_count);
210 		count = regions_count;
211 	}
212 	if (addr_cells > 2 || size_cells > 2) {
213 		printk(BIOS_ERR, "addr_cells (%d) or size_cells (%d) bigger than 2\n",
214 				  addr_cells, size_cells);
215 		return 0;
216 	}
217 	uint32_t *ptr = prop.data;
218 	for (int i = 0; i < count; i++) {
219 		if (addr_cells == 1)
220 			regions[i].addr = be32dec(ptr);
221 		else if (addr_cells == 2)
222 			regions[i].addr = be64dec(ptr);
223 		ptr += addr_cells;
224 		if (size_cells == 1)
225 			regions[i].size = be32dec(ptr);
226 		else if (size_cells == 2)
227 			regions[i].size = be64dec(ptr);
228 		ptr += size_cells;
229 	}
230 
231 	return count; // return the number of regions found in the reg property
232 }
233 
fdt_read_cell_props(const void * blob,u32 node_offset,u32 * addrcp,u32 * sizecp)234 static u32 fdt_read_cell_props(const void *blob, u32 node_offset, u32 *addrcp, u32 *sizecp)
235 {
236 	struct fdt_property prop;
237 	u32 offset = node_offset;
238 	size_t size;
239 	while ((size = fdt_next_property(blob, offset, &prop))) {
240 		if (addrcp && !strcmp(prop.name, "#address-cells"))
241 			*addrcp = be32dec(prop.data);
242 		if (sizecp && !strcmp(prop.name, "#size-cells"))
243 			*sizecp = be32dec(prop.data);
244 		offset += size;
245 	}
246 	return offset;
247 }
248 
249 /*
250  * fdt_find_node searches for a node relative to another node
251  *
252  * @params blob  address of FDT
253  *
254  * @params parent_node_offset  offset to node from which to traverse the tree
255  *
256  * @params path  null terminated array of node names specifying a
257  *               relative path (e.g: { "cpus", "cpu0", NULL })
258  *
259  * @params addrcp/sizecp  If any address-cells and size-cells properties are found that are
260  *                        part of the parent node of the node we are looking, addrcp and sizecp
261  *                        are set to these respectively.
262  *
263  * @returns: Either 0 if no node has been found or the offset to the node found
264  */
fdt_find_node(const void * blob,u32 parent_node_offset,char ** path,u32 * addrcp,u32 * sizecp)265 static u32 fdt_find_node(const void *blob, u32 parent_node_offset, char **path,
266 			 u32 *addrcp, u32 *sizecp)
267 {
268 	if (*path == NULL)
269 		return parent_node_offset; // node found
270 
271 	size_t size = fdt_next_node_name(blob, parent_node_offset, NULL); // skip node name
272 
273 	/*
274 	 * get address-cells and size-cells properties while skipping the others.
275 	 * According to spec address-cells and size-cells are not inherited, but we
276 	 * intentionally follow the Linux implementation here and treat them as inheritable.
277 	 */
278 	u32 node_offset = fdt_read_cell_props(blob, parent_node_offset + size, addrcp, sizecp);
279 
280 	const char *node_name;
281 	// walk all children nodes
282 	while ((size = fdt_next_node_name(blob, node_offset, &node_name))) {
283 		if (!strcmp(*path, node_name)) {
284 			// traverse one level deeper into the path
285 			return fdt_find_node(blob, node_offset, path + 1, addrcp, sizecp);
286 		}
287 		// node is not the correct one. skip current node
288 		node_offset += fdt_skip_node(blob, node_offset);
289 	}
290 
291 	// we have searched everything and could not find a fitting node
292 	return 0;
293 }
294 
295 /*
296  * fdt_find_node_by_path finds a node behind a given node path
297  *
298  * @params blob  address of FDT
299  * @params path  absolute path to the node that should be searched for
300  *
301  * @params addrcp/sizecp  Pointer that will be updated with any #address-cells and #size-cells
302  *                        value found in the node of the node specified by node_offset. Either
303  *                        may be NULL to ignore. If no #address-cells and #size-cells is found
304  *                        default values of #address-cells=2 and #size-cells=1 are returned.
305  *
306  * @returns Either 0 on error or the offset to the node found behind the path
307  */
fdt_find_node_by_path(const void * blob,const char * path,u32 * addrcp,u32 * sizecp)308 u32 fdt_find_node_by_path(const void *blob, const char *path, u32 *addrcp, u32 *sizecp)
309 {
310 	// sanity check
311 	if (path[0] != '/') {
312 		printk(BIOS_ERR, "devicetree path must start with a /\n");
313 		return 0;
314 	}
315 	if (!blob) {
316 		printk(BIOS_ERR, "devicetree blob is NULL\n");
317 		return 0;
318 	}
319 
320 	if (addrcp)
321 		*addrcp = 2;
322 	if (sizecp)
323 		*sizecp = 1;
324 
325 	struct fdt_header *fdt_hdr = (struct fdt_header *)blob;
326 
327 	/*
328 	 * split path into separate nodes
329 	 * e.g: "/cpus/cpu0" -> { "cpus", "cpu0" }
330 	 */
331 	char *path_array[FDT_PATH_MAX_DEPTH];
332 	size_t path_size = strlen(path);
333 	assert(path_size < FDT_PATH_MAX_LEN);
334 	char path_copy[FDT_PATH_MAX_LEN];
335 	memcpy(path_copy, path, path_size + 1);
336 	char *cur = path_copy;
337 	int i;
338 	for (i = 0; i < FDT_PATH_MAX_DEPTH; i++) {
339 		path_array[i] = strtok_r(NULL, "/", &cur);
340 		if (!path_array[i])
341 			break;
342 	}
343 	assert(i < FDT_PATH_MAX_DEPTH);
344 
345 	return fdt_find_node(blob, be32toh(fdt_hdr->structure_offset), path_array, addrcp, sizecp);
346 }
347 
348 /*
349  * fdt_find_subnodes_by_prefix finds a node with a given prefix relative to a parent node
350  *
351  * @params blob  The FDT to search.
352  *
353  * @params node_offset  offset to the node of which the children should be searched
354  *
355  * @params prefix  A string to search for a node with a given prefix. This can for example
356  *                 be 'cpu' to look for all nodes matching this prefix. Only children of
357  *                 node_offset are searched. Therefore in order to search all nodes matching
358  *                 the 'cpu' prefix, node_offset should probably point to the 'cpus' node.
359  *                 An empty prefix ("") searches for all children nodes of node_offset.
360  *
361  * @params addrcp/sizecp  Pointer that will be updated with any #address-cells and #size-cells
362  *                        value found in the node of the node specified by node_offset. Either
363  *                        may be NULL to ignore. If no #address-cells and #size-cells is found
364  *                        addrcp and sizecp are left untouched.
365  *
366  * @params results      Array of offsets pointing to each node matching the given prefix.
367  * @params results_len  Number of entries allocated for the 'results' array
368  *
369  * @returns  offset to last node found behind path or 0 if no node has been found
370  */
fdt_find_subnodes_by_prefix(const void * blob,u32 node_offset,const char * prefix,u32 * addrcp,u32 * sizecp,u32 * results,size_t results_len)371 size_t fdt_find_subnodes_by_prefix(const void *blob, u32 node_offset, const char *prefix,
372 				   u32 *addrcp, u32 *sizecp, u32 *results, size_t results_len)
373 {
374 	// sanity checks
375 	if (!blob || !results || !prefix) {
376 		printk(BIOS_ERR, "%s: input parameter cannot be null/\n", __func__);
377 		return 0;
378 	}
379 
380 	u32 offset = node_offset;
381 
382 	// we don't care about the name of the current node
383 	u32 size = fdt_next_node_name(blob, offset, NULL);
384 	if (!size) {
385 		printk(BIOS_ERR, "%s: node_offset: %x does not point to a node\n",
386 		       __func__, node_offset);
387 		return 0;
388 	}
389 	offset += size;
390 
391 	/*
392 	 * update addrcp and sizecp if the node contains an address-cells and size-cells
393 	 * property. Otherwise use addrcp and sizecp provided by caller.
394 	 */
395 	offset = fdt_read_cell_props(blob, offset, addrcp, sizecp);
396 
397 	size_t count_results = 0;
398 	int prefix_len = strlen(prefix);
399 	const char *node_name;
400 	// walk all children nodes of offset
401 	while ((size = fdt_next_node_name(blob, offset, &node_name))) {
402 
403 		if (count_results >= results_len) {
404 			printk(BIOS_WARNING,
405 				"%s: results_len (%zd) smaller than count_results (%zd)\n",
406 				__func__, results_len, count_results);
407 			break;
408 		}
409 
410 		if (!strncmp(prefix, node_name, prefix_len)) {
411 			// we found a node that matches the prefix
412 			results[count_results++] = offset;
413 		}
414 
415 		// node does not match the prefix. skip current node
416 		offset += fdt_skip_node(blob, offset);
417 	}
418 
419 	// return last occurrence
420 	return count_results;
421 }
422 
fdt_read_alias_prop(const void * blob,const char * alias_name)423 static const char *fdt_read_alias_prop(const void *blob, const char *alias_name)
424 {
425 	u32 node_offset =  fdt_find_node_by_path(blob, "/aliases", NULL, NULL);
426 	if (!node_offset) {
427 		printk(BIOS_DEBUG, "no /aliases node found\n");
428 		return NULL;
429 	}
430 	struct fdt_property alias_prop;
431 	if (!fdt_read_prop(blob, node_offset, alias_name, &alias_prop)) {
432 		printk(BIOS_DEBUG, "property %s in /aliases node not found\n", alias_name);
433 		return NULL;
434 	}
435 	return (const char *)alias_prop.data;
436 }
437 
438 /*
439  * Find a node in the tree from a string device tree path.
440  *
441  * @params blob           Address to the FDT
442  * @params alias_name     node name alias that should be searched for.
443  * @params addrcp/sizecp  Pointer that will be updated with any #address-cells and #size-cells
444  *                        value found in the node of the node specified by node_offset. Either
445  *                        may be NULL to ignore. If no #address-cells and #size-cells is found
446  *                        default values of #address-cells=2 and #size-cells=1 are returned.
447  *
448  * @returns  offset to last node found behind path or 0 if no node has been found
449  */
fdt_find_node_by_alias(const void * blob,const char * alias_name,u32 * addrcp,u32 * sizecp)450 u32 fdt_find_node_by_alias(const void *blob, const char *alias_name, u32 *addrcp, u32 *sizecp)
451 {
452 	const char *node_name = fdt_read_alias_prop(blob, alias_name);
453 	if (!node_name)  {
454 		printk(BIOS_DEBUG, "alias %s not found\n", alias_name);
455 		return 0;
456 	}
457 
458 	u32 node_offset = fdt_find_node_by_path(blob, node_name, addrcp, sizecp);
459 	if (!node_offset) {
460 		// This should not happen (invalid devicetree)
461 		printk(BIOS_WARNING,
462 		       "Could not find node '%s', which alias was referring to '%s'\n",
463 		       node_name, alias_name);
464 		return 0;
465 	}
466 	return node_offset;
467 }
468 
469 
470 /*
471  * Functions for printing flattened trees.
472  */
473 
print_indent(int depth)474 static void print_indent(int depth)
475 {
476 	printk(BIOS_DEBUG, "%*s", depth * 8, "");
477 }
478 
print_property(const struct fdt_property * prop,int depth)479 static void print_property(const struct fdt_property *prop, int depth)
480 {
481 	int is_string = prop->size > 0 &&
482 			((char *)prop->data)[prop->size - 1] == '\0';
483 
484 	if (is_string) {
485 		for (int i = 0; i < prop->size - 1; i++) {
486 			if (!isprint(((char *)prop->data)[i])) {
487 				is_string = 0;
488 				break;
489 			}
490 		}
491 	}
492 
493 	print_indent(depth);
494 	if (is_string) {
495 		printk(BIOS_DEBUG, "%s = \"%s\";\n",
496 		       prop->name, (const char *)prop->data);
497 	} else {
498 		printk(BIOS_DEBUG, "%s = < ", prop->name);
499 		for (int i = 0; i < MIN(128, prop->size); i += 4) {
500 			uint32_t val = 0;
501 			for (int j = 0; j < MIN(4, prop->size - i); j++)
502 				val |= ((uint8_t *)prop->data)[i + j] <<
503 					(24 - j * 8);
504 			printk(BIOS_DEBUG, "%#.2x ", val);
505 		}
506 		if (prop->size > 128)
507 			printk(BIOS_DEBUG, "...");
508 		printk(BIOS_DEBUG, ">;\n");
509 	}
510 }
511 
print_flat_node(const void * blob,uint32_t start_offset,int depth)512 static int print_flat_node(const void *blob, uint32_t start_offset, int depth)
513 {
514 	int offset = start_offset;
515 	const char *name;
516 	int size;
517 
518 	size = fdt_next_node_name(blob, offset, &name);
519 	if (!size)
520 		return 0;
521 	offset += size;
522 
523 	print_indent(depth);
524 	printk(BIOS_DEBUG, "%s {\n", name);
525 
526 	struct fdt_property prop;
527 	while ((size = fdt_next_property(blob, offset, &prop))) {
528 		print_property(&prop, depth + 1);
529 
530 		offset += size;
531 	}
532 
533 	printk(BIOS_DEBUG, "\n");	/* empty line between props and nodes */
534 
535 	while ((size = print_flat_node(blob, offset, depth + 1)))
536 		offset += size;
537 
538 	print_indent(depth);
539 	printk(BIOS_DEBUG, "}\n");
540 
541 	return offset - start_offset + sizeof(uint32_t);
542 }
543 
fdt_print_node(const void * blob,uint32_t offset)544 void fdt_print_node(const void *blob, uint32_t offset)
545 {
546 	print_flat_node(blob, offset, 0);
547 }
548 
549 /*
550  * fdt_read_memory_regions finds memory ranges from a flat device-tree
551  *
552  * @params blob	          address of FDT
553  * @params regions        all regions that are read inside the reg property of
554  *                        memory nodes are saved inside this array
555  * @params regions_count  maximum number of entries that can be saved inside
556  *                        the regions array.
557  *
558  * Returns: Either 0 on error or returns the number of regions put into the regions array.
559  */
fdt_read_memory_regions(const void * blob,struct device_tree_region regions[],size_t regions_count)560 size_t fdt_read_memory_regions(const void *blob,
561 			       struct device_tree_region regions[],
562 			       size_t regions_count)
563 {
564 	u32 node, root, addrcp, sizecp;
565 	u32 nodes[FDT_MAX_MEMORY_NODES] = {0};
566 	size_t region_idx = 0;
567 	size_t node_count = 0;
568 
569 	if (!fdt_is_valid(blob))
570 		return 0;
571 
572 	node = fdt_find_node_by_path(blob, "/memory",  &addrcp, &sizecp);
573 	if (node) {
574 		region_idx += fdt_read_reg_prop(blob, node, addrcp, sizecp,
575 						regions, regions_count);
576 		if (region_idx >= regions_count) {
577 			printk(BIOS_WARNING, "FDT: Too many memory regions\n");
578 			goto out;
579 		}
580 	}
581 
582 	root = fdt_find_node_by_path(blob, "/",  &addrcp, &sizecp);
583 	node_count = fdt_find_subnodes_by_prefix(blob, root, "memory@",
584 						 &addrcp, &sizecp, nodes,
585 						 FDT_MAX_MEMORY_NODES);
586 	if (node_count >= FDT_MAX_MEMORY_NODES) {
587 		printk(BIOS_WARNING, "FDT: Too many memory nodes\n");
588 		/* Can still reading the regions for those we got */
589 	}
590 
591 	for (size_t i = 0; i < MIN(node_count, FDT_MAX_MEMORY_NODES); i++) {
592 		region_idx += fdt_read_reg_prop(blob, nodes[i], addrcp, sizecp,
593 						&regions[region_idx],
594 						regions_count - region_idx);
595 		if (region_idx >= regions_count) {
596 			printk(BIOS_WARNING, "FDT: Too many memory regions\n");
597 			goto out;
598 		}
599 	}
600 
601 out:
602 	for (size_t i = 0; i < MIN(region_idx, regions_count); i++) {
603 		printk(BIOS_DEBUG, "FDT: Memory region [%#llx - %#llx]\n",
604 		       regions[i].addr, regions[i].addr + regions[i].size);
605 	}
606 
607 	return region_idx;
608 }
609 
610 /*
611  * fdt_get_memory_top finds top of memory from a flat device-tree
612  *
613  * @params blob	          address of FDT
614  *
615  * Returns: Either 0 on error or returns the maximum memory address
616  */
fdt_get_memory_top(const void * blob)617 uint64_t fdt_get_memory_top(const void *blob)
618 {
619 	struct device_tree_region regions[FDT_MAX_MEMORY_REGIONS] = {0};
620 	uint64_t top = 0;
621 	uint64_t total = 0;
622 	size_t count;
623 
624 	if (!fdt_is_valid(blob))
625 		return 0;
626 
627 	count = fdt_read_memory_regions(blob, regions, FDT_MAX_MEMORY_REGIONS);
628 	for (size_t i = 0; i < MIN(count, FDT_MAX_MEMORY_REGIONS); i++) {
629 		top = MAX(top, regions[i].addr + regions[i].size);
630 		total += regions[i].size;
631 	}
632 
633 	printk(BIOS_DEBUG, "FDT: Found %u MiB of RAM\n",
634 	       (uint32_t)(total / MiB));
635 
636 	return top;
637 }
638 
639 /*
640  * Functions to turn a flattened tree into an unflattened one.
641  */
642 
dt_prop_is_phandle(struct device_tree_property * prop)643 static int dt_prop_is_phandle(struct device_tree_property *prop)
644 {
645 	return !(strcmp("phandle", prop->prop.name) &&
646 		 strcmp("linux,phandle", prop->prop.name));
647 }
648 
fdt_unflatten_node(const void * blob,uint32_t start_offset,struct device_tree * tree,struct device_tree_node ** new_node)649 static int fdt_unflatten_node(const void *blob, uint32_t start_offset,
650 			      struct device_tree *tree,
651 			      struct device_tree_node **new_node)
652 {
653 	struct list_node *last;
654 	int offset = start_offset;
655 	const char *name;
656 	int size;
657 
658 	size = fdt_next_node_name(blob, offset, &name);
659 	if (!size)
660 		return 0;
661 	offset += size;
662 
663 	struct device_tree_node *node = alloc_node();
664 	*new_node = node;
665 	node->name = name;
666 
667 	struct fdt_property fprop;
668 	last = &node->properties;
669 	while ((size = fdt_next_property(blob, offset, &fprop))) {
670 		struct device_tree_property *prop = alloc_prop();
671 		prop->prop = fprop;
672 
673 		if (dt_prop_is_phandle(prop)) {
674 			node->phandle = be32dec(prop->prop.data);
675 			if (node->phandle > tree->max_phandle)
676 				tree->max_phandle = node->phandle;
677 		}
678 
679 		list_insert_after(&prop->list_node, last);
680 		last = &prop->list_node;
681 
682 		offset += size;
683 	}
684 
685 	struct device_tree_node *child;
686 	last = &node->children;
687 	while ((size = fdt_unflatten_node(blob, offset, tree, &child))) {
688 		list_insert_after(&child->list_node, last);
689 		last = &child->list_node;
690 
691 		offset += size;
692 	}
693 
694 	return offset - start_offset + sizeof(uint32_t);
695 }
696 
fdt_unflatten_map_entry(const void * blob,uint32_t offset,struct device_tree_reserve_map_entry ** new)697 static int fdt_unflatten_map_entry(const void *blob, uint32_t offset,
698 				   struct device_tree_reserve_map_entry **new)
699 {
700 	const uint64_t *ptr = (const uint64_t *)(((uint8_t *)blob) + offset);
701 	const uint64_t start = be64toh(ptr[0]);
702 	const uint64_t size = be64toh(ptr[1]);
703 
704 	if (!size)
705 		return 0;
706 
707 	struct device_tree_reserve_map_entry *entry = xzalloc(sizeof(*entry));
708 	*new = entry;
709 	entry->start = start;
710 	entry->size = size;
711 
712 	return sizeof(uint64_t) * 2;
713 }
714 
fdt_is_valid(const void * blob)715 bool fdt_is_valid(const void *blob)
716 {
717 	const struct fdt_header *header = (const struct fdt_header *)blob;
718 
719 	uint32_t magic = be32toh(header->magic);
720 	uint32_t version = be32toh(header->version);
721 	uint32_t last_comp_version = be32toh(header->last_comp_version);
722 
723 	if (magic != FDT_HEADER_MAGIC) {
724 		printk(BIOS_ERR, "Invalid device tree magic %#.8x!\n", magic);
725 		return false;
726 	}
727 	if (last_comp_version > FDT_SUPPORTED_VERSION) {
728 		printk(BIOS_ERR, "Unsupported device tree version %u(>=%u)\n",
729 		       version, last_comp_version);
730 		return false;
731 	}
732 	if (version > FDT_SUPPORTED_VERSION)
733 		printk(BIOS_NOTICE, "FDT version %u too new, should add support!\n",
734 		       version);
735 	return true;
736 }
737 
fdt_unflatten(const void * blob)738 struct device_tree *fdt_unflatten(const void *blob)
739 {
740 	struct device_tree *tree = xzalloc(sizeof(*tree));
741 	const struct fdt_header *header = (const struct fdt_header *)blob;
742 	tree->header = header;
743 
744 	if (!fdt_is_valid(blob))
745 		return NULL;
746 
747 	uint32_t struct_offset = be32toh(header->structure_offset);
748 	uint32_t strings_offset = be32toh(header->strings_offset);
749 	uint32_t reserve_offset = be32toh(header->reserve_map_offset);
750 	uint32_t min_offset = 0;
751 	min_offset = MIN(struct_offset, strings_offset);
752 	min_offset = MIN(min_offset, reserve_offset);
753 	/* Assume everything up to the first non-header component is part of
754 	   the header and needs to be preserved. This will protect us against
755 	   new elements being added in the future. */
756 	tree->header_size = min_offset;
757 
758 	struct device_tree_reserve_map_entry *entry;
759 	uint32_t offset = reserve_offset;
760 	int size;
761 	struct list_node *last = &tree->reserve_map;
762 	while ((size = fdt_unflatten_map_entry(blob, offset, &entry))) {
763 		list_insert_after(&entry->list_node, last);
764 		last = &entry->list_node;
765 
766 		offset += size;
767 	}
768 
769 	fdt_unflatten_node(blob, struct_offset, tree, &tree->root);
770 
771 	return tree;
772 }
773 
774 
775 
776 /*
777  * Functions to find the size of the device tree if it was flattened.
778  */
779 
dt_flat_prop_size(struct device_tree_property * prop,uint32_t * struct_size,uint32_t * strings_size)780 static void dt_flat_prop_size(struct device_tree_property *prop,
781 			      uint32_t *struct_size, uint32_t *strings_size)
782 {
783 	/* Starting token. */
784 	*struct_size += sizeof(uint32_t);
785 	/* Size. */
786 	*struct_size += sizeof(uint32_t);
787 	/* Name offset. */
788 	*struct_size += sizeof(uint32_t);
789 	/* Property value. */
790 	*struct_size += ALIGN_UP(prop->prop.size, sizeof(uint32_t));
791 
792 	/* Property name. */
793 	*strings_size += strlen(prop->prop.name) + 1;
794 }
795 
dt_flat_node_size(struct device_tree_node * node,uint32_t * struct_size,uint32_t * strings_size)796 static void dt_flat_node_size(struct device_tree_node *node,
797 			      uint32_t *struct_size, uint32_t *strings_size)
798 {
799 	/* Starting token. */
800 	*struct_size += sizeof(uint32_t);
801 	/* Node name. */
802 	*struct_size += ALIGN_UP(strlen(node->name) + 1, sizeof(uint32_t));
803 
804 	struct device_tree_property *prop;
805 	list_for_each(prop, node->properties, list_node)
806 		dt_flat_prop_size(prop, struct_size, strings_size);
807 
808 	struct device_tree_node *child;
809 	list_for_each(child, node->children, list_node)
810 		dt_flat_node_size(child, struct_size, strings_size);
811 
812 	/* End token. */
813 	*struct_size += sizeof(uint32_t);
814 }
815 
dt_flat_size(const struct device_tree * tree)816 uint32_t dt_flat_size(const struct device_tree *tree)
817 {
818 	uint32_t size = tree->header_size;
819 	struct device_tree_reserve_map_entry *entry;
820 	list_for_each(entry, tree->reserve_map, list_node)
821 		size += sizeof(uint64_t) * 2;
822 	size += sizeof(uint64_t) * 2;
823 
824 	uint32_t struct_size = 0;
825 	uint32_t strings_size = 0;
826 	dt_flat_node_size(tree->root, &struct_size, &strings_size);
827 
828 	size += struct_size;
829 	/* End token. */
830 	size += sizeof(uint32_t);
831 
832 	size += strings_size;
833 
834 	return size;
835 }
836 
837 
838 
839 /*
840  * Functions to flatten a device tree.
841  */
842 
dt_flatten_map_entry(struct device_tree_reserve_map_entry * entry,void ** map_start)843 static void dt_flatten_map_entry(struct device_tree_reserve_map_entry *entry,
844 				 void **map_start)
845 {
846 	((uint64_t *)*map_start)[0] = htobe64(entry->start);
847 	((uint64_t *)*map_start)[1] = htobe64(entry->size);
848 	*map_start = ((uint8_t *)*map_start) + sizeof(uint64_t) * 2;
849 }
850 
dt_flatten_prop(struct device_tree_property * prop,void ** struct_start,void * strings_base,void ** strings_start)851 static void dt_flatten_prop(struct device_tree_property *prop,
852 			    void **struct_start, void *strings_base,
853 			    void **strings_start)
854 {
855 	uint8_t *dstruct = (uint8_t *)*struct_start;
856 	uint8_t *dstrings = (uint8_t *)*strings_start;
857 
858 	be32enc(dstruct, FDT_TOKEN_PROPERTY);
859 	dstruct += sizeof(uint32_t);
860 
861 	be32enc(dstruct, prop->prop.size);
862 	dstruct += sizeof(uint32_t);
863 
864 	uint32_t name_offset = (uintptr_t)dstrings - (uintptr_t)strings_base;
865 	be32enc(dstruct, name_offset);
866 	dstruct += sizeof(uint32_t);
867 
868 	strcpy((char *)dstrings, prop->prop.name);
869 	dstrings += strlen(prop->prop.name) + 1;
870 
871 	memcpy(dstruct, prop->prop.data, prop->prop.size);
872 	dstruct += ALIGN_UP(prop->prop.size, sizeof(uint32_t));
873 
874 	*struct_start = dstruct;
875 	*strings_start = dstrings;
876 }
877 
dt_flatten_node(const struct device_tree_node * node,void ** struct_start,void * strings_base,void ** strings_start)878 static void dt_flatten_node(const struct device_tree_node *node,
879 			    void **struct_start, void *strings_base,
880 			    void **strings_start)
881 {
882 	uint8_t *dstruct = (uint8_t *)*struct_start;
883 	uint8_t *dstrings = (uint8_t *)*strings_start;
884 
885 	be32enc(dstruct, FDT_TOKEN_BEGIN_NODE);
886 	dstruct += sizeof(uint32_t);
887 
888 	strcpy((char *)dstruct, node->name);
889 	dstruct += ALIGN_UP(strlen(node->name) + 1, sizeof(uint32_t));
890 
891 	struct device_tree_property *prop;
892 	list_for_each(prop, node->properties, list_node)
893 		dt_flatten_prop(prop, (void **)&dstruct, strings_base,
894 				(void **)&dstrings);
895 
896 	struct device_tree_node *child;
897 	list_for_each(child, node->children, list_node)
898 		dt_flatten_node(child, (void **)&dstruct, strings_base,
899 				(void **)&dstrings);
900 
901 	be32enc(dstruct, FDT_TOKEN_END_NODE);
902 	dstruct += sizeof(uint32_t);
903 
904 	*struct_start = dstruct;
905 	*strings_start = dstrings;
906 }
907 
dt_flatten(const struct device_tree * tree,void * start_dest)908 void dt_flatten(const struct device_tree *tree, void *start_dest)
909 {
910 	uint8_t *dest = (uint8_t *)start_dest;
911 
912 	memcpy(dest, tree->header, tree->header_size);
913 	struct fdt_header *header = (struct fdt_header *)dest;
914 	dest += tree->header_size;
915 
916 	struct device_tree_reserve_map_entry *entry;
917 	list_for_each(entry, tree->reserve_map, list_node)
918 		dt_flatten_map_entry(entry, (void **)&dest);
919 	((uint64_t *)dest)[0] = ((uint64_t *)dest)[1] = 0;
920 	dest += sizeof(uint64_t) * 2;
921 
922 	uint32_t struct_size = 0;
923 	uint32_t strings_size = 0;
924 	dt_flat_node_size(tree->root, &struct_size, &strings_size);
925 
926 	uint8_t *struct_start = dest;
927 	header->structure_offset = htobe32(dest - (uint8_t *)start_dest);
928 	header->structure_size = htobe32(struct_size);
929 	dest += struct_size;
930 
931 	*((uint32_t *)dest) = htobe32(FDT_TOKEN_END);
932 	dest += sizeof(uint32_t);
933 
934 	uint8_t *strings_start = dest;
935 	header->strings_offset = htobe32(dest - (uint8_t *)start_dest);
936 	header->strings_size = htobe32(strings_size);
937 	dest += strings_size;
938 
939 	dt_flatten_node(tree->root, (void **)&struct_start, strings_start,
940 			(void **)&strings_start);
941 
942 	header->totalsize = htobe32(dest - (uint8_t *)start_dest);
943 }
944 
945 
946 
947 /*
948  * Functions for printing a non-flattened device tree.
949  */
950 
print_node(const struct device_tree_node * node,int depth)951 static void print_node(const struct device_tree_node *node, int depth)
952 {
953 	print_indent(depth);
954 	if (depth == 0)	/* root node has no name, print a starting slash */
955 		printk(BIOS_DEBUG, "/");
956 	printk(BIOS_DEBUG, "%s {\n", node->name);
957 
958 	struct device_tree_property *prop;
959 	list_for_each(prop, node->properties, list_node)
960 		print_property(&prop->prop, depth + 1);
961 
962 	printk(BIOS_DEBUG, "\n");	/* empty line between props and nodes */
963 
964 	struct device_tree_node *child;
965 	list_for_each(child, node->children, list_node)
966 		print_node(child, depth + 1);
967 
968 	print_indent(depth);
969 	printk(BIOS_DEBUG, "};\n");
970 }
971 
dt_print_node(const struct device_tree_node * node)972 void dt_print_node(const struct device_tree_node *node)
973 {
974 	print_node(node, 0);
975 }
976 
977 
978 
979 /*
980  * Functions for reading and manipulating an unflattened device tree.
981  */
982 
983 /*
984  * Read #address-cells and #size-cells properties from a node.
985  *
986  * @param node		The device tree node to read from.
987  * @param addrcp	Pointer to store #address-cells in, skipped if NULL.
988  * @param sizecp	Pointer to store #size-cells in, skipped if NULL.
989  */
dt_read_cell_props(const struct device_tree_node * node,u32 * addrcp,u32 * sizecp)990 void dt_read_cell_props(const struct device_tree_node *node, u32 *addrcp,
991 			u32 *sizecp)
992 {
993 	struct device_tree_property *prop;
994 	list_for_each(prop, node->properties, list_node) {
995 		if (addrcp && !strcmp("#address-cells", prop->prop.name))
996 			*addrcp = be32dec(prop->prop.data);
997 		if (sizecp && !strcmp("#size-cells", prop->prop.name))
998 			*sizecp = be32dec(prop->prop.data);
999 	}
1000 }
1001 
1002 /*
1003  * Find a node from a device tree path, relative to a parent node.
1004  *
1005  * @param parent	The node from which to start the relative path lookup.
1006  * @param path		An array of path component strings that will be looked
1007  *			up in order to find the node. Must be terminated with
1008  *			a NULL pointer. Example: {'firmware', 'coreboot', NULL}
1009  * @param addrcp	Pointer that will be updated with any #address-cells
1010  *			value found in the path. May be NULL to ignore.
1011  * @param sizecp	Pointer that will be updated with any #size-cells
1012  *			value found in the path. May be NULL to ignore.
1013  * @param create	1: Create node(s) if not found. 0: Return NULL instead.
1014  * @return		The found/created node, or NULL.
1015  */
dt_find_node(struct device_tree_node * parent,const char ** path,u32 * addrcp,u32 * sizecp,int create)1016 struct device_tree_node *dt_find_node(struct device_tree_node *parent,
1017 				      const char **path, u32 *addrcp,
1018 				      u32 *sizecp, int create)
1019 {
1020 	struct device_tree_node *node, *found = NULL;
1021 
1022 	/* Update #address-cells and #size-cells for this level. */
1023 	dt_read_cell_props(parent, addrcp, sizecp);
1024 
1025 	if (!*path)
1026 		return parent;
1027 
1028 	/* Find the next node in the path, if it exists. */
1029 	list_for_each(node, parent->children, list_node) {
1030 		if (!strcmp(node->name, *path)) {
1031 			found = node;
1032 			break;
1033 		}
1034 	}
1035 
1036 	/* Otherwise create it or return NULL. */
1037 	if (!found) {
1038 		if (!create)
1039 			return NULL;
1040 
1041 		found = alloc_node();
1042 		found->name = strdup(*path);
1043 		if (!found->name)
1044 			return NULL;
1045 
1046 		list_insert_after(&found->list_node, &parent->children);
1047 	}
1048 
1049 	return dt_find_node(found, path + 1, addrcp, sizecp, create);
1050 }
1051 
1052 /*
1053  * Find a node in the tree from a string device tree path.
1054  *
1055  * @param tree		The device tree to search.
1056  * @param path          A string representing a path in the device tree, with
1057  *			nodes separated by '/'. Example: "/firmware/coreboot"
1058  * @param addrcp	Pointer that will be updated with any #address-cells
1059  *			value found in the path. May be NULL to ignore.
1060  * @param sizecp	Pointer that will be updated with any #size-cells
1061  *			value found in the path. May be NULL to ignore.
1062  * @param create	1: Create node(s) if not found. 0: Return NULL instead.
1063  * @return		The found/created node, or NULL.
1064  *
1065  * It is the caller responsibility to provide a path string that doesn't end
1066  * with a '/' and doesn't contain any "//". If the path does not start with a
1067  * '/', the first segment is interpreted as an alias. */
dt_find_node_by_path(struct device_tree * tree,const char * path,u32 * addrcp,u32 * sizecp,int create)1068 struct device_tree_node *dt_find_node_by_path(struct device_tree *tree,
1069 					      const char *path, u32 *addrcp,
1070 					      u32 *sizecp, int create)
1071 {
1072 	char *sub_path;
1073 	char *duped_str;
1074 	struct device_tree_node *parent;
1075 	char *next_slash;
1076 	/* Hopefully enough depth for any node. */
1077 	const char *path_array[15];
1078 	int i;
1079 	struct device_tree_node *node = NULL;
1080 
1081 	if (path[0] == '/') { /* regular path */
1082 		if (path[1] == '\0') {	/* special case: "/" is root node */
1083 			dt_read_cell_props(tree->root, addrcp, sizecp);
1084 			return tree->root;
1085 		}
1086 
1087 		sub_path = duped_str = strdup(&path[1]);
1088 		if (!sub_path)
1089 			return NULL;
1090 
1091 		parent = tree->root;
1092 	} else { /* alias */
1093 		char *alias;
1094 
1095 		alias = duped_str = strdup(path);
1096 		if (!alias)
1097 			return NULL;
1098 
1099 		sub_path = strchr(alias, '/');
1100 		if (sub_path)
1101 			*sub_path = '\0';
1102 
1103 		parent = dt_find_node_by_alias(tree, alias);
1104 		if (!parent) {
1105 			printk(BIOS_DEBUG,
1106 			       "Could not find node '%s', alias '%s' does not exist\n",
1107 			       path, alias);
1108 			free(duped_str);
1109 			return NULL;
1110 		}
1111 
1112 		if (!sub_path) {
1113 			/* it's just the alias, no sub-path */
1114 			free(duped_str);
1115 			return parent;
1116 		}
1117 
1118 		sub_path++;
1119 	}
1120 
1121 	next_slash = sub_path;
1122 	path_array[0] = sub_path;
1123 	for (i = 1; i < (ARRAY_SIZE(path_array) - 1); i++) {
1124 		next_slash = strchr(next_slash, '/');
1125 		if (!next_slash)
1126 			break;
1127 
1128 		*next_slash++ = '\0';
1129 		path_array[i] = next_slash;
1130 	}
1131 
1132 	if (!next_slash) {
1133 		path_array[i] = NULL;
1134 		node = dt_find_node(parent, path_array,
1135 				    addrcp, sizecp, create);
1136 	}
1137 
1138 	free(duped_str);
1139 	return node;
1140 }
1141 
1142 /*
1143  * Find a node from an alias
1144  *
1145  * @param tree		The device tree.
1146  * @param alias		The alias name.
1147  * @return		The found node, or NULL.
1148  */
dt_find_node_by_alias(struct device_tree * tree,const char * alias)1149 struct device_tree_node *dt_find_node_by_alias(struct device_tree *tree,
1150 					       const char *alias)
1151 {
1152 	struct device_tree_node *node;
1153 	const char *alias_path;
1154 
1155 	node = dt_find_node_by_path(tree, "/aliases", NULL, NULL, 0);
1156 	if (!node)
1157 		return NULL;
1158 
1159 	alias_path = dt_find_string_prop(node, alias);
1160 	if (!alias_path)
1161 		return NULL;
1162 
1163 	return dt_find_node_by_path(tree, alias_path, NULL, NULL, 0);
1164 }
1165 
dt_find_node_by_phandle(struct device_tree_node * root,uint32_t phandle)1166 struct device_tree_node *dt_find_node_by_phandle(struct device_tree_node *root,
1167 						 uint32_t phandle)
1168 {
1169 	if (!root)
1170 		return NULL;
1171 
1172 	if (root->phandle == phandle)
1173 		return root;
1174 
1175 	struct device_tree_node *node;
1176 	struct device_tree_node *result;
1177 	list_for_each(node, root->children, list_node) {
1178 		result = dt_find_node_by_phandle(node, phandle);
1179 		if (result)
1180 			return result;
1181 	}
1182 
1183 	return NULL;
1184 }
1185 
1186 /*
1187  * Check if given node is compatible.
1188  *
1189  * @param node		The node which is to be checked for compatible property.
1190  * @param compat	The compatible string to match.
1191  * @return		1 = compatible, 0 = not compatible.
1192  */
dt_check_compat_match(struct device_tree_node * node,const char * compat)1193 static int dt_check_compat_match(struct device_tree_node *node,
1194 				 const char *compat)
1195 {
1196 	struct device_tree_property *prop;
1197 
1198 	list_for_each(prop, node->properties, list_node) {
1199 		if (!strcmp("compatible", prop->prop.name)) {
1200 			size_t bytes = prop->prop.size;
1201 			const char *str = prop->prop.data;
1202 			while (bytes > 0) {
1203 				if (!strncmp(compat, str, bytes))
1204 					return 1;
1205 				size_t len = strnlen(str, bytes) + 1;
1206 				if (bytes <= len)
1207 					break;
1208 				str += len;
1209 				bytes -= len;
1210 			}
1211 			break;
1212 		}
1213 	}
1214 
1215 	return 0;
1216 }
1217 
1218 /*
1219  * Find a node from a compatible string, in the subtree of a parent node.
1220  *
1221  * @param parent	The parent node under which to look.
1222  * @param compat	The compatible string to find.
1223  * @return		The found node, or NULL.
1224  */
dt_find_compat(struct device_tree_node * parent,const char * compat)1225 struct device_tree_node *dt_find_compat(struct device_tree_node *parent,
1226 					const char *compat)
1227 {
1228 	/* Check if the parent node itself is compatible. */
1229 	if (dt_check_compat_match(parent, compat))
1230 		return parent;
1231 
1232 	struct device_tree_node *child;
1233 	list_for_each(child, parent->children, list_node) {
1234 		struct device_tree_node *found = dt_find_compat(child, compat);
1235 		if (found)
1236 			return found;
1237 	}
1238 
1239 	return NULL;
1240 }
1241 
1242 /*
1243  * Find the next compatible child of a given parent. All children up to the
1244  * child passed in by caller are ignored. If child is NULL, it considers all the
1245  * children to find the first child which is compatible.
1246  *
1247  * @param parent	The parent node under which to look.
1248  * @param child	The child node to start search from (exclusive). If NULL
1249  *                      consider all children.
1250  * @param compat	The compatible string to find.
1251  * @return		The found node, or NULL.
1252  */
1253 struct device_tree_node *
dt_find_next_compat_child(struct device_tree_node * parent,struct device_tree_node * child,const char * compat)1254 dt_find_next_compat_child(struct device_tree_node *parent,
1255 			  struct device_tree_node *child,
1256 			  const char *compat)
1257 {
1258 	struct device_tree_node *next;
1259 	int ignore = 0;
1260 
1261 	if (child)
1262 		ignore = 1;
1263 
1264 	list_for_each(next, parent->children, list_node) {
1265 		if (ignore) {
1266 			if (child == next)
1267 				ignore = 0;
1268 			continue;
1269 		}
1270 
1271 		if (dt_check_compat_match(next, compat))
1272 			return next;
1273 	}
1274 
1275 	return NULL;
1276 }
1277 
1278 /*
1279  * Find a node with matching property value, in the subtree of a parent node.
1280  *
1281  * @param parent	The parent node under which to look.
1282  * @param name		The property name to look for.
1283  * @param data		The property value to look for.
1284  * @param size		The property size.
1285  */
dt_find_prop_value(struct device_tree_node * parent,const char * name,void * data,size_t size)1286 struct device_tree_node *dt_find_prop_value(struct device_tree_node *parent,
1287 					    const char *name, void *data,
1288 					    size_t size)
1289 {
1290 	struct device_tree_property *prop;
1291 
1292 	/* Check if parent itself has the required property value. */
1293 	list_for_each(prop, parent->properties, list_node) {
1294 		if (!strcmp(name, prop->prop.name)) {
1295 			size_t bytes = prop->prop.size;
1296 			const void *prop_data = prop->prop.data;
1297 			if (size != bytes)
1298 				break;
1299 			if (!memcmp(data, prop_data, size))
1300 				return parent;
1301 			break;
1302 		}
1303 	}
1304 
1305 	struct device_tree_node *child;
1306 	list_for_each(child, parent->children, list_node) {
1307 		struct device_tree_node *found = dt_find_prop_value(child, name,
1308 								    data, size);
1309 		if (found)
1310 			return found;
1311 	}
1312 	return NULL;
1313 }
1314 
1315 /*
1316  * Write an arbitrary sized big-endian integer into a pointer.
1317  *
1318  * @param dest		Pointer to the DT property data buffer to write.
1319  * @param src		The integer to write (in CPU endianness).
1320  * @param length	the length of the destination integer in bytes.
1321  */
dt_write_int(u8 * dest,u64 src,size_t length)1322 void dt_write_int(u8 *dest, u64 src, size_t length)
1323 {
1324 	while (length--) {
1325 		dest[length] = (u8)src;
1326 		src >>= 8;
1327 	}
1328 }
1329 
1330 /*
1331  * Delete a property by name in a given node if it exists.
1332  *
1333  * @param node		The device tree node to operate on.
1334  * @param name		The name of the property to delete.
1335  */
dt_delete_prop(struct device_tree_node * node,const char * name)1336 void dt_delete_prop(struct device_tree_node *node, const char *name)
1337 {
1338 	struct device_tree_property *prop;
1339 
1340 	list_for_each(prop, node->properties, list_node) {
1341 		if (!strcmp(prop->prop.name, name)) {
1342 			list_remove(&prop->list_node);
1343 			return;
1344 		}
1345 	}
1346 }
1347 
1348 /*
1349  * Add an arbitrary property to a node, or update it if it already exists.
1350  *
1351  * @param node		The device tree node to add to.
1352  * @param name		The name of the new property.
1353  * @param data		The raw data blob to be stored in the property.
1354  * @param size		The size of data in bytes.
1355  */
dt_add_bin_prop(struct device_tree_node * node,const char * name,void * data,size_t size)1356 void dt_add_bin_prop(struct device_tree_node *node, const char *name,
1357 		     void *data, size_t size)
1358 {
1359 	struct device_tree_property *prop;
1360 
1361 	list_for_each(prop, node->properties, list_node) {
1362 		if (!strcmp(prop->prop.name, name)) {
1363 			prop->prop.data = data;
1364 			prop->prop.size = size;
1365 			return;
1366 		}
1367 	}
1368 
1369 	prop = alloc_prop();
1370 	list_insert_after(&prop->list_node, &node->properties);
1371 	prop->prop.name = name;
1372 	prop->prop.data = data;
1373 	prop->prop.size = size;
1374 }
1375 
1376 /*
1377  * Find given string property in a node and return its content.
1378  *
1379  * @param node		The device tree node to search.
1380  * @param name		The name of the property.
1381  * @return		The found string, or NULL.
1382  */
dt_find_string_prop(const struct device_tree_node * node,const char * name)1383 const char *dt_find_string_prop(const struct device_tree_node *node,
1384 				const char *name)
1385 {
1386 	const void *content;
1387 	size_t size;
1388 
1389 	dt_find_bin_prop(node, name, &content, &size);
1390 
1391 	return content;
1392 }
1393 
1394 /*
1395  * Find given property in a node.
1396  *
1397  * @param node		The device tree node to search.
1398  * @param name		The name of the property.
1399  * @param data		Pointer to return raw data blob in the property.
1400  * @param size		Pointer to return the size of data in bytes.
1401  */
dt_find_bin_prop(const struct device_tree_node * node,const char * name,const void ** data,size_t * size)1402 void dt_find_bin_prop(const struct device_tree_node *node, const char *name,
1403 		      const void **data, size_t *size)
1404 {
1405 	struct device_tree_property *prop;
1406 
1407 	*data = NULL;
1408 	*size = 0;
1409 
1410 	list_for_each(prop, node->properties, list_node) {
1411 		if (!strcmp(prop->prop.name, name)) {
1412 			*data = prop->prop.data;
1413 			*size = prop->prop.size;
1414 			return;
1415 		}
1416 	}
1417 }
1418 
1419 /*
1420  * Add a string property to a node, or update it if it already exists.
1421  *
1422  * @param node		The device tree node to add to.
1423  * @param name		The name of the new property.
1424  * @param str		The zero-terminated string to be stored in the property.
1425  */
dt_add_string_prop(struct device_tree_node * node,const char * name,const char * str)1426 void dt_add_string_prop(struct device_tree_node *node, const char *name,
1427 			const char *str)
1428 {
1429 	dt_add_bin_prop(node, name, (char *)str, strlen(str) + 1);
1430 }
1431 
1432 /*
1433  * Add a 32-bit integer property to a node, or update it if it already exists.
1434  *
1435  * @param node		The device tree node to add to.
1436  * @param name		The name of the new property.
1437  * @param val		The integer to be stored in the property.
1438  */
dt_add_u32_prop(struct device_tree_node * node,const char * name,u32 val)1439 void dt_add_u32_prop(struct device_tree_node *node, const char *name, u32 val)
1440 {
1441 	u32 *val_ptr = xmalloc(sizeof(val));
1442 	*val_ptr = htobe32(val);
1443 	dt_add_bin_prop(node, name, val_ptr, sizeof(*val_ptr));
1444 }
1445 
1446 /*
1447  * Add a 64-bit integer property to a node, or update it if it already exists.
1448  *
1449  * @param node		The device tree node to add to.
1450  * @param name		The name of the new property.
1451  * @param val		The integer to be stored in the property.
1452  */
dt_add_u64_prop(struct device_tree_node * node,const char * name,u64 val)1453 void dt_add_u64_prop(struct device_tree_node *node, const char *name, u64 val)
1454 {
1455 	u64 *val_ptr = xmalloc(sizeof(val));
1456 	*val_ptr = htobe64(val);
1457 	dt_add_bin_prop(node, name, val_ptr, sizeof(*val_ptr));
1458 }
1459 
1460 /*
1461  * Add a 'reg' address list property to a node, or update it if it exists.
1462  *
1463  * @param node		The device tree node to add to.
1464  * @param regions       Array of address values to be stored in the property.
1465  * @param sizes		Array of corresponding size values to 'addrs'.
1466  * @param count		Number of values in 'addrs' and 'sizes' (must be equal).
1467  * @param addr_cells	Value of #address-cells property valid for this node.
1468  * @param size_cells	Value of #size-cells property valid for this node.
1469  */
dt_add_reg_prop(struct device_tree_node * node,u64 * addrs,u64 * sizes,int count,u32 addr_cells,u32 size_cells)1470 void dt_add_reg_prop(struct device_tree_node *node, u64 *addrs, u64 *sizes,
1471 		     int count, u32 addr_cells, u32 size_cells)
1472 {
1473 	int i;
1474 	size_t length = (addr_cells + size_cells) * sizeof(u32) * count;
1475 	u8 *data = xmalloc(length);
1476 	u8 *cur = data;
1477 
1478 	for (i = 0; i < count; i++) {
1479 		dt_write_int(cur, addrs[i], addr_cells * sizeof(u32));
1480 		cur += addr_cells * sizeof(u32);
1481 		dt_write_int(cur, sizes[i], size_cells * sizeof(u32));
1482 		cur += size_cells * sizeof(u32);
1483 	}
1484 
1485 	dt_add_bin_prop(node, "reg", data, length);
1486 }
1487 
1488 /*
1489  * Fixups to apply to a kernel's device tree before booting it.
1490  */
1491 
1492 struct list_node device_tree_fixups;
1493 
dt_apply_fixups(struct device_tree * tree)1494 int dt_apply_fixups(struct device_tree *tree)
1495 {
1496 	struct device_tree_fixup *fixup;
1497 	list_for_each(fixup, device_tree_fixups, list_node) {
1498 		assert(fixup->fixup);
1499 		if (fixup->fixup(fixup, tree))
1500 			return 1;
1501 	}
1502 	return 0;
1503 }
1504 
dt_set_bin_prop_by_path(struct device_tree * tree,const char * path,void * data,size_t data_size,int create)1505 int dt_set_bin_prop_by_path(struct device_tree *tree, const char *path,
1506 			    void *data, size_t data_size, int create)
1507 {
1508 	char *path_copy, *prop_name;
1509 	struct device_tree_node *dt_node;
1510 
1511 	path_copy = strdup(path);
1512 
1513 	if (!path_copy) {
1514 		printk(BIOS_ERR, "Failed to allocate a copy of path %s\n",
1515 		       path);
1516 		return 1;
1517 	}
1518 
1519 	prop_name = strrchr(path_copy, '/');
1520 	if (!prop_name) {
1521 		free(path_copy);
1522 		printk(BIOS_ERR, "Path %s does not include '/'\n", path);
1523 		return 1;
1524 	}
1525 
1526 	*prop_name++ = '\0'; /* Separate path from the property name. */
1527 
1528 	dt_node = dt_find_node_by_path(tree, path_copy, NULL,
1529 				       NULL, create);
1530 
1531 	if (!dt_node) {
1532 		printk(BIOS_ERR, "Failed to %s %s in the device tree\n",
1533 		       create ? "create" : "find", path_copy);
1534 		free(path_copy);
1535 		return 1;
1536 	}
1537 
1538 	dt_add_bin_prop(dt_node, prop_name, data, data_size);
1539 	free(path_copy);
1540 
1541 	return 0;
1542 }
1543 
1544 /*
1545  * Prepare the /reserved-memory/ node.
1546  *
1547  * Technically, this can be called more than one time, to init and/or retrieve
1548  * the node. But dt_add_u32_prop() may leak a bit of memory if you do.
1549  *
1550  * @tree: Device tree to add/retrieve from.
1551  * @return: The /reserved-memory/ node (or NULL, if error).
1552  */
dt_init_reserved_memory_node(struct device_tree * tree)1553 struct device_tree_node *dt_init_reserved_memory_node(struct device_tree *tree)
1554 {
1555 	struct device_tree_node *reserved;
1556 	u32 addr = 0, size = 0;
1557 
1558 	reserved = dt_find_node_by_path(tree, "/reserved-memory", &addr,
1559 					&size, 1);
1560 	if (!reserved)
1561 		return NULL;
1562 
1563 	/* Binding doc says this should have the same #{address,size}-cells as
1564 	   the root. */
1565 	dt_add_u32_prop(reserved, "#address-cells", addr);
1566 	dt_add_u32_prop(reserved, "#size-cells", size);
1567 	/* Binding doc says this should be empty (1:1 mapping from root). */
1568 	dt_add_bin_prop(reserved, "ranges", NULL, 0);
1569 
1570 	return reserved;
1571 }
1572 
1573 /*
1574  * Increment a single phandle in prop at a given offset by a given adjustment.
1575  *
1576  * @param prop		Property whose phandle should be adjusted.
1577  * @param adjustment	Value that should be added to the existing phandle.
1578  * @param offset	Byte offset of the phandle in the property data.
1579  *
1580  * @return		New phandle value, or 0 on error.
1581  */
dt_adjust_phandle(struct device_tree_property * prop,uint32_t adjustment,uint32_t offset)1582 static uint32_t dt_adjust_phandle(struct device_tree_property *prop,
1583 				  uint32_t adjustment, uint32_t offset)
1584 {
1585 	if (offset + 4 > prop->prop.size)
1586 		return 0;
1587 
1588 	uint32_t phandle = be32dec(prop->prop.data + offset);
1589 	if (phandle == 0 ||
1590 	    phandle == FDT_PHANDLE_ILLEGAL ||
1591 	    phandle == 0xffffffff)
1592 		return 0;
1593 
1594 	phandle += adjustment;
1595 	if (phandle >= FDT_PHANDLE_ILLEGAL)
1596 		return 0;
1597 
1598 	be32enc(prop->prop.data + offset, phandle);
1599 	return phandle;
1600 }
1601 
1602 /*
1603  * Adjust all phandles in subtree by adding a new base offset.
1604  *
1605  * @param node		Root node of the subtree to work on.
1606  * @param base		New phandle base to be added to all phandles.
1607  *
1608  * @return		New highest phandle in the subtree, or 0 on error.
1609  */
dt_adjust_all_phandles(struct device_tree_node * node,uint32_t base)1610 static uint32_t dt_adjust_all_phandles(struct device_tree_node *node,
1611 				       uint32_t base)
1612 {
1613 	uint32_t new_max = MAX(base, 1);  /* make sure we don't return 0 */
1614 	struct device_tree_property *prop;
1615 	struct device_tree_node *child;
1616 
1617 	if (!node)
1618 		return new_max;
1619 
1620 	list_for_each(prop, node->properties, list_node)
1621 		if (dt_prop_is_phandle(prop)) {
1622 			node->phandle = dt_adjust_phandle(prop, base, 0);
1623 			if (!node->phandle)
1624 				return 0;
1625 			new_max = MAX(new_max, node->phandle);
1626 		}  /* no break -- can have more than one phandle prop */
1627 
1628 	list_for_each(child, node->children, list_node)
1629 		new_max = MAX(new_max, dt_adjust_all_phandles(child, base));
1630 
1631 	return new_max;
1632 }
1633 
1634 /*
1635  * Apply a /__local_fixup__ subtree to the corresponding overlay subtree.
1636  *
1637  * @param node		Root node of the overlay subtree to fix up.
1638  * @param node		Root node of the /__local_fixup__ subtree.
1639  * @param base		Adjustment that was added to phandles in the overlay.
1640  *
1641  * @return		0 on success, -1 on error.
1642  */
dt_fixup_locals(struct device_tree_node * node,struct device_tree_node * fixup,uint32_t base)1643 static int dt_fixup_locals(struct device_tree_node *node,
1644 		    struct device_tree_node *fixup, uint32_t base)
1645 {
1646 	struct device_tree_property *prop;
1647 	struct device_tree_property *fixup_prop;
1648 	struct device_tree_node *child;
1649 	struct device_tree_node *fixup_child;
1650 	int i;
1651 
1652 	/*
1653 	 * For local fixups the /__local_fixup__ subtree contains the same node
1654 	 * hierarchy as the main tree we're fixing up. Each property contains
1655 	 * the fixup offsets for the respective property in the main tree. For
1656 	 * each property in the fixup node, find the corresponding property in
1657 	 * the base node and apply fixups to all offsets it specifies.
1658 	 */
1659 	list_for_each(fixup_prop, fixup->properties, list_node) {
1660 		struct device_tree_property *base_prop = NULL;
1661 		list_for_each(prop, node->properties, list_node)
1662 			if (!strcmp(prop->prop.name, fixup_prop->prop.name)) {
1663 				base_prop = prop;
1664 				break;
1665 			}
1666 
1667 		/* We should always find a corresponding base prop for a fixup,
1668 		   and fixup props contain a list of 32-bit fixup offsets. */
1669 		if (!base_prop || fixup_prop->prop.size % sizeof(uint32_t))
1670 			return -1;
1671 
1672 		for (i = 0; i < fixup_prop->prop.size; i += sizeof(uint32_t))
1673 			if (!dt_adjust_phandle(base_prop, base, be32dec(
1674 					fixup_prop->prop.data + i)))
1675 				return -1;
1676 	}
1677 
1678 	/* Now recursively descend both the base tree and the /__local_fixups__
1679 	   subtree in sync to apply all fixups. */
1680 	list_for_each(fixup_child, fixup->children, list_node) {
1681 		struct device_tree_node *base_child = NULL;
1682 		list_for_each(child, node->children, list_node)
1683 			if (!strcmp(child->name, fixup_child->name)) {
1684 				base_child = child;
1685 				break;
1686 			}
1687 
1688 		/* All fixup nodes should have a corresponding base node. */
1689 		if (!base_child)
1690 			return -1;
1691 
1692 		if (dt_fixup_locals(base_child, fixup_child, base) < 0)
1693 			return -1;
1694 	}
1695 
1696 	return 0;
1697 }
1698 
1699 /*
1700  * Update all /__symbols__ properties in an overlay that start with
1701  * "/fragment@X/__overlay__" with corresponding path prefix in the base tree.
1702  *
1703  * @param symbols	/__symbols__ done to update.
1704  * @param fragment	/fragment@X node that references to should be updated.
1705  * @param base_path	Path of base tree node that the fragment overlaid.
1706  */
dt_fix_symbols(struct device_tree_node * symbols,struct device_tree_node * fragment,const char * base_path)1707 static void dt_fix_symbols(struct device_tree_node *symbols,
1708 			   struct device_tree_node *fragment,
1709 			   const char *base_path)
1710 {
1711 	struct device_tree_property *prop;
1712 	char buf[512]; /* Should be enough for maximum DT path length? */
1713 	char node_path[64]; /* easily enough for /fragment@XXXX/__overlay__ */
1714 
1715 	if (!symbols) /* If the overlay has no /__symbols__ node, we're done! */
1716 		return;
1717 
1718 	int len = snprintf(node_path, sizeof(node_path), "/%s/__overlay__",
1719 			   fragment->name);
1720 
1721 	list_for_each(prop, symbols->properties, list_node)
1722 		if (!strncmp(prop->prop.data, node_path, len)) {
1723 			prop->prop.size = snprintf(buf, sizeof(buf), "%s%s",
1724 				base_path, (char *)prop->prop.data + len) + 1;
1725 			free(prop->prop.data);
1726 			prop->prop.data = strdup(buf);
1727 		}
1728 }
1729 
1730 /*
1731  * Fix up overlay according to a property in /__fixup__. If the fixed property
1732  * is a /fragment@X:target, also update /__symbols__ references to fragment.
1733  *
1734  * @params overlay	Overlay to fix up.
1735  * @params fixup	/__fixup__ property.
1736  * @params phandle	phandle value to insert where the fixup points to.
1737  * @params base_path	Path to the base DT node that the fixup points to.
1738  * @params overlay_symbols /__symbols__ node of the overlay.
1739  *
1740  * @return		0 on success, -1 on error.
1741  */
dt_fixup_external(struct device_tree * overlay,struct device_tree_property * fixup,uint32_t phandle,const char * base_path,struct device_tree_node * overlay_symbols)1742 static int dt_fixup_external(struct device_tree *overlay,
1743 			     struct device_tree_property *fixup,
1744 			     uint32_t phandle, const char *base_path,
1745 			     struct device_tree_node *overlay_symbols)
1746 {
1747 	struct device_tree_property *prop;
1748 
1749 	/* External fixup properties are encoded as "<path>:<prop>:<offset>". */
1750 	char *entry = fixup->prop.data;
1751 	while ((void *)entry < fixup->prop.data + fixup->prop.size) {
1752 		/* okay to destroy fixup property value, won't need it again */
1753 		char *node_path = entry;
1754 		entry = strchr(node_path, ':');
1755 		if (!entry)
1756 			return -1;
1757 		*entry++ = '\0';
1758 
1759 		char *prop_name = entry;
1760 		entry = strchr(prop_name, ':');
1761 		if (!entry)
1762 			return -1;
1763 		*entry++ = '\0';
1764 
1765 		struct device_tree_node *ovl_node = dt_find_node_by_path(
1766 			overlay, node_path, NULL, NULL, 0);
1767 		if (!ovl_node || !isdigit(*entry))
1768 			return -1;
1769 
1770 		struct device_tree_property *ovl_prop = NULL;
1771 		list_for_each(prop, ovl_node->properties, list_node)
1772 			if (!strcmp(prop->prop.name, prop_name)) {
1773 				ovl_prop = prop;
1774 				break;
1775 			}
1776 
1777 		/* Move entry to first char after number, must be a '\0'. */
1778 		uint32_t offset = skip_atoi(&entry);
1779 		if (!ovl_prop || offset + 4 > ovl_prop->prop.size || entry[0])
1780 			return -1;
1781 		entry++;  /* jump over '\0' to potential next fixup */
1782 
1783 		be32enc(ovl_prop->prop.data + offset, phandle);
1784 
1785 		/* If this is a /fragment@X:target property, update references
1786 		   to this fragment in the overlay __symbols__ now. */
1787 		if (offset == 0 && !strcmp(prop_name, "target") &&
1788 		    !strchr(node_path + 1, '/')) /* only toplevel nodes */
1789 			dt_fix_symbols(overlay_symbols, ovl_node, base_path);
1790 	}
1791 
1792 	return 0;
1793 }
1794 
1795 /*
1796  * Apply all /__fixup__ properties in the overlay. This will destroy the
1797  * property data in /__fixup__ and it should not be accessed again.
1798  *
1799  * @params tree		Base device tree that the overlay updates.
1800  * @params symbols	/__symbols__ node of the base device tree.
1801  * @params overlay	Overlay to fix up.
1802  * @params fixups	/__fixup__ node in the overlay.
1803  * @params overlay_symbols /__symbols__ node of the overlay.
1804  *
1805  * @return		0 on success, -1 on error.
1806  */
dt_fixup_all_externals(struct device_tree * tree,struct device_tree_node * symbols,struct device_tree * overlay,struct device_tree_node * fixups,struct device_tree_node * overlay_symbols)1807 static int dt_fixup_all_externals(struct device_tree *tree,
1808 				  struct device_tree_node *symbols,
1809 				  struct device_tree *overlay,
1810 				  struct device_tree_node *fixups,
1811 				  struct device_tree_node *overlay_symbols)
1812 {
1813 	struct device_tree_property *fix;
1814 
1815 	/* If we have any external fixups, base tree must have /__symbols__. */
1816 	if (!symbols)
1817 		return -1;
1818 
1819 	/*
1820 	 * Unlike /__local_fixups__, /__fixups__ is not a whole subtree that
1821 	 * mirrors the node hierarchy. It's just a directory of fixup properties
1822 	 * that each directly contain all information necessary to apply them.
1823 	 */
1824 	list_for_each(fix, fixups->properties, list_node) {
1825 		/* The name of a fixup property is the label of the node we want
1826 		   a property to phandle-reference. Look up in /__symbols__. */
1827 		const char *path = dt_find_string_prop(symbols, fix->prop.name);
1828 		if (!path)
1829 			return -1;
1830 
1831 		/* Find node the label pointed to figure out its phandle. */
1832 		struct device_tree_node *node = dt_find_node_by_path(tree, path,
1833 			NULL, NULL, 0);
1834 		if (!node)
1835 			return -1;
1836 
1837 		/* Write into the overlay property(s) pointing to that node. */
1838 		if (dt_fixup_external(overlay, fix, node->phandle,
1839 				      path, overlay_symbols) < 0)
1840 			return -1;
1841 	}
1842 
1843 	return 0;
1844 }
1845 
1846 /*
1847  * Copy all nodes and properties from one DT subtree into another. This is a
1848  * shallow copy so both trees will point to the same property data afterwards.
1849  *
1850  * @params dst		Destination subtree to copy into.
1851  * @params src		Source subtree to copy from.
1852  * @params upd		1 to overwrite same-name properties, 0 to discard them.
1853  */
dt_copy_subtree(struct device_tree_node * dst,struct device_tree_node * src,int upd)1854 static void dt_copy_subtree(struct device_tree_node *dst,
1855 			    struct device_tree_node *src, int upd)
1856 {
1857 	struct device_tree_property *prop;
1858 	struct device_tree_property *src_prop;
1859 	list_for_each(src_prop, src->properties, list_node) {
1860 		if (dt_prop_is_phandle(src_prop) ||
1861 		    !strcmp(src_prop->prop.name, "name")) {
1862 			printk(BIOS_DEBUG,
1863 			       "WARNING: ignoring illegal overlay prop '%s'\n",
1864 			       src_prop->prop.name);
1865 			continue;
1866 		}
1867 
1868 		struct device_tree_property *dst_prop = NULL;
1869 		list_for_each(prop, dst->properties, list_node)
1870 			if (!strcmp(prop->prop.name, src_prop->prop.name)) {
1871 				dst_prop = prop;
1872 				break;
1873 			}
1874 
1875 		if (dst_prop) {
1876 			if (!upd) {
1877 				printk(BIOS_DEBUG,
1878 				       "WARNING: ignoring prop update '%s'\n",
1879 				       src_prop->prop.name);
1880 				continue;
1881 			}
1882 		} else {
1883 			dst_prop = alloc_prop();
1884 			list_insert_after(&dst_prop->list_node,
1885 					  &dst->properties);
1886 		}
1887 
1888 		dst_prop->prop = src_prop->prop;
1889 	}
1890 
1891 	struct device_tree_node *node;
1892 	struct device_tree_node *src_node;
1893 	list_for_each(src_node, src->children, list_node) {
1894 		struct device_tree_node *dst_node = NULL;
1895 		list_for_each(node, dst->children, list_node)
1896 			if (!strcmp(node->name, src_node->name)) {
1897 				dst_node = node;
1898 				break;
1899 			}
1900 
1901 		if (!dst_node) {
1902 			dst_node = alloc_node();
1903 			*dst_node = *src_node;
1904 			list_insert_after(&dst_node->list_node, &dst->children);
1905 		} else {
1906 			dt_copy_subtree(dst_node, src_node, upd);
1907 		}
1908 	}
1909 }
1910 
1911 /*
1912  * Apply an overlay /fragment@X node to a base device tree.
1913  *
1914  * @param tree		Base device tree.
1915  * @param fragment	/fragment@X node.
1916  * @params overlay_symbols /__symbols__ node of the overlay.
1917  *
1918  * @return		0 on success, -1 on error.
1919  */
dt_import_fragment(struct device_tree * tree,struct device_tree_node * fragment,struct device_tree_node * overlay_symbols)1920 static int dt_import_fragment(struct device_tree *tree,
1921 			      struct device_tree_node *fragment,
1922 			      struct device_tree_node *overlay_symbols)
1923 {
1924 	/* The actual overlaid nodes/props are in an __overlay__ child node. */
1925 	static const char *overlay_path[] = { "__overlay__", NULL };
1926 	struct device_tree_node *overlay = dt_find_node(fragment, overlay_path,
1927 							NULL, NULL, 0);
1928 
1929 	/* If it doesn't have an __overlay__ child, it's not a fragment. */
1930 	if (!overlay)
1931 		return 0;
1932 
1933 	/* Target node of the fragment can be given by path or by phandle. */
1934 	struct device_tree_property *prop;
1935 	struct device_tree_property *phandle = NULL;
1936 	struct device_tree_property *path = NULL;
1937 	list_for_each(prop, fragment->properties, list_node) {
1938 		if (!strcmp(prop->prop.name, "target")) {
1939 			phandle = prop;
1940 			break; /* phandle target has priority, stop looking */
1941 		}
1942 		if (!strcmp(prop->prop.name, "target-path"))
1943 			path = prop;
1944 	}
1945 
1946 	struct device_tree_node *target = NULL;
1947 	if (phandle) {
1948 		if (phandle->prop.size != sizeof(uint32_t))
1949 			return -1;
1950 		target = dt_find_node_by_phandle(tree->root,
1951 						 be32dec(phandle->prop.data));
1952 		/* Symbols already updated as part of dt_fixup_external(). */
1953 	} else if (path) {
1954 		target = dt_find_node_by_path(tree, path->prop.data,
1955 					      NULL, NULL, 0);
1956 		dt_fix_symbols(overlay_symbols, fragment, path->prop.data);
1957 	}
1958 	if (!target)
1959 		return -1;
1960 
1961 	dt_copy_subtree(target, overlay, 1);
1962 	return 0;
1963 }
1964 
1965 /*
1966  * Apply a device tree overlay to a base device tree. This will
1967  * destroy/incorporate the overlay data, so it should not be freed or reused.
1968  * See dtc.git/Documentation/dt-object-internal.txt for overlay format details.
1969  *
1970  * @param tree		Unflattened base device tree to add the overlay into.
1971  * @param overlay	Unflattened overlay device tree to apply to the base.
1972  *
1973  * @return		0 on success, -1 on error.
1974  */
dt_apply_overlay(struct device_tree * tree,struct device_tree * overlay)1975 int dt_apply_overlay(struct device_tree *tree, struct device_tree *overlay)
1976 {
1977 	/*
1978 	 * First, we need to make sure phandles inside the overlay don't clash
1979 	 * with those in the base tree. We just define the highest phandle value
1980 	 * in the base tree as the "phandle offset" for this overlay and
1981 	 * increment all phandles in it by that value.
1982 	 */
1983 	uint32_t phandle_base = tree->max_phandle;
1984 	uint32_t new_max = dt_adjust_all_phandles(overlay->root, phandle_base);
1985 	if (!new_max) {
1986 		printk(BIOS_ERR, "invalid phandles in overlay\n");
1987 		return -1;
1988 	}
1989 	tree->max_phandle = new_max;
1990 
1991 	/* Now that we changed phandles in the overlay, we need to update any
1992 	   nodes referring to them. Those are listed in /__local_fixups__. */
1993 	struct device_tree_node *local_fixups = dt_find_node_by_path(overlay,
1994 					"/__local_fixups__", NULL, NULL, 0);
1995 	if (local_fixups && dt_fixup_locals(overlay->root, local_fixups,
1996 					    phandle_base) < 0) {
1997 		printk(BIOS_ERR, "invalid local fixups in overlay\n");
1998 		return -1;
1999 	}
2000 
2001 	/*
2002 	 * Besides local phandle references (from nodes within the overlay to
2003 	 * other nodes within the overlay), the overlay may also contain phandle
2004 	 * references to the base tree. These are stored with invalid values and
2005 	 * must be updated now. /__symbols__ contains a list of all labels in
2006 	 * the base tree, and /__fixups__ describes all nodes in the overlay
2007 	 * that contain external phandle references.
2008 	 * We also take this opportunity to update all /fragment@X/__overlay__/
2009 	 * prefixes in the overlay's /__symbols__ node to the correct path that
2010 	 * the fragment will be placed in later, since this is the only step
2011 	 * where we have all necessary information for that easily available.
2012 	 */
2013 	struct device_tree_node *symbols = dt_find_node_by_path(tree,
2014 		"/__symbols__", NULL, NULL, 0);
2015 	struct device_tree_node *fixups = dt_find_node_by_path(overlay,
2016 		"/__fixups__", NULL, NULL, 0);
2017 	struct device_tree_node *overlay_symbols = dt_find_node_by_path(overlay,
2018 		"/__symbols__", NULL, NULL, 0);
2019 	if (fixups && dt_fixup_all_externals(tree, symbols, overlay,
2020 					     fixups, overlay_symbols) < 0) {
2021 		printk(BIOS_ERR, "cannot match external fixups from overlay\n");
2022 		return -1;
2023 	}
2024 
2025 	/* After all this fixing up, we can finally merge overlay into the tree
2026 	   (one fragment at a time, because for some reason it's split up). */
2027 	struct device_tree_node *fragment;
2028 	list_for_each(fragment, overlay->root->children, list_node)
2029 		if (dt_import_fragment(tree, fragment, overlay_symbols) < 0) {
2030 			printk(BIOS_ERR, "bad DT fragment '%s'\n",
2031 			       fragment->name);
2032 			return -1;
2033 		}
2034 
2035 	/*
2036 	 * We need to also update /__symbols__ to include labels from this
2037 	 * overlay, in case we want to load further overlays with external
2038 	 * phandle references to it. If the base tree already has a /__symbols__
2039 	 * we merge them together, otherwise we just insert the overlay's
2040 	 * /__symbols__ node into the base tree root.
2041 	 */
2042 	if (overlay_symbols) {
2043 		if (symbols)
2044 			dt_copy_subtree(symbols, overlay_symbols, 0);
2045 		else
2046 			list_insert_after(&overlay_symbols->list_node,
2047 					  &tree->root->children);
2048 	}
2049 
2050 	return 0;
2051 }
2052