1 /*
2  * Copyright (c) 2018-2020, ARM Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 /* Helper functions to offer easier navigation of Device Tree Blob */
8 
9 #include <assert.h>
10 #include <string.h>
11 
12 #include <libfdt.h>
13 
14 #include <common/debug.h>
15 #include <common/fdt_wrappers.h>
16 
17 /*
18  * Read cells from a given property of the given node. Any number of 32-bit
19  * cells of the property can be read. Returns 0 on success, or a negative
20  * FDT error value otherwise.
21  */
fdt_read_uint32_array(const void * dtb,int node,const char * prop_name,unsigned int cells,uint32_t * value)22 int fdt_read_uint32_array(const void *dtb, int node, const char *prop_name,
23 			  unsigned int cells, uint32_t *value)
24 {
25 	const fdt32_t *prop;
26 	int value_len;
27 
28 	assert(dtb != NULL);
29 	assert(prop_name != NULL);
30 	assert(value != NULL);
31 	assert(node >= 0);
32 
33 	/* Access property and obtain its length (in bytes) */
34 	prop = fdt_getprop(dtb, node, prop_name, &value_len);
35 	if (prop == NULL) {
36 		WARN("Couldn't find property %s in dtb\n", prop_name);
37 		return -FDT_ERR_NOTFOUND;
38 	}
39 
40 	/* Verify that property length can fill the entire array. */
41 	if (NCELLS((unsigned int)value_len) < cells) {
42 		WARN("Property length mismatch\n");
43 		return -FDT_ERR_BADVALUE;
44 	}
45 
46 	for (unsigned int i = 0U; i < cells; i++) {
47 		value[i] = fdt32_to_cpu(prop[i]);
48 	}
49 
50 	return 0;
51 }
52 
fdt_read_uint32(const void * dtb,int node,const char * prop_name,uint32_t * value)53 int fdt_read_uint32(const void *dtb, int node, const char *prop_name,
54 		    uint32_t *value)
55 {
56 	return fdt_read_uint32_array(dtb, node, prop_name, 1, value);
57 }
58 
fdt_read_uint32_default(const void * dtb,int node,const char * prop_name,uint32_t dflt_value)59 uint32_t fdt_read_uint32_default(const void *dtb, int node,
60 				 const char *prop_name, uint32_t dflt_value)
61 {
62 	uint32_t ret = dflt_value;
63 	int err = fdt_read_uint32(dtb, node, prop_name, &ret);
64 
65 	if (err < 0) {
66 		return dflt_value;
67 	}
68 
69 	return ret;
70 }
71 
fdt_read_uint64(const void * dtb,int node,const char * prop_name,uint64_t * value)72 int fdt_read_uint64(const void *dtb, int node, const char *prop_name,
73 		    uint64_t *value)
74 {
75 	uint32_t array[2] = {0, 0};
76 	int ret;
77 
78 	ret = fdt_read_uint32_array(dtb, node, prop_name, 2, array);
79 	if (ret < 0) {
80 		return ret;
81 	}
82 
83 	*value = ((uint64_t)array[0] << 32) | array[1];
84 	return 0;
85 }
86 
87 /*
88  * Read bytes from a given property of the given node. Any number of
89  * bytes of the property can be read. The fdt pointer is updated.
90  * Returns 0 on success, and -1 on error.
91  */
fdtw_read_bytes(const void * dtb,int node,const char * prop,unsigned int length,void * value)92 int fdtw_read_bytes(const void *dtb, int node, const char *prop,
93 		    unsigned int length, void *value)
94 {
95 	const void *ptr;
96 	int value_len;
97 
98 	assert(dtb != NULL);
99 	assert(prop != NULL);
100 	assert(value != NULL);
101 	assert(node >= 0);
102 
103 	/* Access property and obtain its length (in bytes) */
104 	ptr = fdt_getprop_namelen(dtb, node, prop, (int)strlen(prop),
105 					&value_len);
106 	if (ptr == NULL) {
107 		WARN("Couldn't find property %s in dtb\n", prop);
108 		return -1;
109 	}
110 
111 	/* Verify that property length is not less than number of bytes */
112 	if ((unsigned int)value_len < length) {
113 		WARN("Property length mismatch\n");
114 		return -1;
115 	}
116 
117 	(void)memcpy(value, ptr, length);
118 
119 	return 0;
120 }
121 
122 /*
123  * Read string from a given property of the given node. Up to 'size - 1'
124  * characters are read, and a NUL terminator is added. Returns 0 on success,
125  * and -1 upon error.
126  */
fdtw_read_string(const void * dtb,int node,const char * prop,char * str,size_t size)127 int fdtw_read_string(const void *dtb, int node, const char *prop,
128 		char *str, size_t size)
129 {
130 	const char *ptr;
131 	size_t len;
132 
133 	assert(dtb != NULL);
134 	assert(node >= 0);
135 	assert(prop != NULL);
136 	assert(str != NULL);
137 	assert(size > 0U);
138 
139 	ptr = fdt_getprop_namelen(dtb, node, prop, (int)strlen(prop), NULL);
140 	if (ptr == NULL) {
141 		WARN("Couldn't find property %s in dtb\n", prop);
142 		return -1;
143 	}
144 
145 	len = strlcpy(str, ptr, size);
146 	if (len >= size) {
147 		WARN("String of property %s in dtb has been truncated\n", prop);
148 		return -1;
149 	}
150 
151 	return 0;
152 }
153 
154 /*
155  * Write cells in place to a given property of the given node. At most 2 cells
156  * of the property are written. Returns 0 on success, and -1 upon error.
157  */
fdtw_write_inplace_cells(void * dtb,int node,const char * prop,unsigned int cells,void * value)158 int fdtw_write_inplace_cells(void *dtb, int node, const char *prop,
159 		unsigned int cells, void *value)
160 {
161 	int err, len;
162 
163 	assert(dtb != NULL);
164 	assert(prop != NULL);
165 	assert(value != NULL);
166 	assert(node >= 0);
167 
168 	/* We expect either 1 or 2 cell property */
169 	assert(cells <= 2U);
170 
171 	if (cells == 2U)
172 		*(uint64_t *)value = cpu_to_fdt64(*(uint64_t *)value);
173 	else
174 		*(uint32_t *)value = cpu_to_fdt32(*(uint32_t *)value);
175 
176 	len = (int)cells * 4;
177 
178 	/* Set property value in place */
179 	err = fdt_setprop_inplace(dtb, node, prop, value, len);
180 	if (err != 0) {
181 		WARN("Modify property %s failed with error %d\n", prop, err);
182 		return -1;
183 	}
184 
185 	return 0;
186 }
187 
188 /*
189  * Write bytes in place to a given property of the given node.
190  * Any number of bytes of the property can be written.
191  * Returns 0 on success, and < 0 on error.
192  */
fdtw_write_inplace_bytes(void * dtb,int node,const char * prop,unsigned int length,const void * data)193 int fdtw_write_inplace_bytes(void *dtb, int node, const char *prop,
194 			     unsigned int length, const void *data)
195 {
196 	const void *ptr;
197 	int namelen, value_len, err;
198 
199 	assert(dtb != NULL);
200 	assert(prop != NULL);
201 	assert(data != NULL);
202 	assert(node >= 0);
203 
204 	namelen = (int)strlen(prop);
205 
206 	/* Access property and obtain its length in bytes */
207 	ptr = fdt_getprop_namelen(dtb, node, prop, namelen, &value_len);
208 	if (ptr == NULL) {
209 		WARN("Couldn't find property %s in dtb\n", prop);
210 		return -1;
211 	}
212 
213 	/* Verify that property length is not less than number of bytes */
214 	if ((unsigned int)value_len < length) {
215 		WARN("Property length mismatch\n");
216 		return -1;
217 	}
218 
219 	/* Set property value in place */
220 	err = fdt_setprop_inplace_namelen_partial(dtb, node, prop,
221 						  namelen, 0,
222 						  data, (int)length);
223 	if (err != 0) {
224 		WARN("Set property %s failed with error %d\n", prop, err);
225 	}
226 
227 	return err;
228 }
229 
fdt_read_prop_cells(const fdt32_t * prop,int nr_cells)230 static uint64_t fdt_read_prop_cells(const fdt32_t *prop, int nr_cells)
231 {
232 	uint64_t reg = fdt32_to_cpu(prop[0]);
233 
234 	if (nr_cells > 1) {
235 		reg = (reg << 32) | fdt32_to_cpu(prop[1]);
236 	}
237 
238 	return reg;
239 }
240 
fdt_get_reg_props_by_index(const void * dtb,int node,int index,uintptr_t * base,size_t * size)241 int fdt_get_reg_props_by_index(const void *dtb, int node, int index,
242 			       uintptr_t *base, size_t *size)
243 {
244 	const fdt32_t *prop;
245 	int parent, len;
246 	int ac, sc;
247 	int cell;
248 
249 	parent = fdt_parent_offset(dtb, node);
250 	if (parent < 0) {
251 		return -FDT_ERR_BADOFFSET;
252 	}
253 
254 	ac = fdt_address_cells(dtb, parent);
255 	sc = fdt_size_cells(dtb, parent);
256 
257 	cell = index * (ac + sc);
258 
259 	prop = fdt_getprop(dtb, node, "reg", &len);
260 	if (prop == NULL) {
261 		WARN("Couldn't find \"reg\" property in dtb\n");
262 		return -FDT_ERR_NOTFOUND;
263 	}
264 
265 	if (((cell + ac + sc) * (int)sizeof(uint32_t)) > len) {
266 		return -FDT_ERR_BADVALUE;
267 	}
268 
269 	if (base != NULL) {
270 		*base = (uintptr_t)fdt_read_prop_cells(&prop[cell], ac);
271 	}
272 
273 	if (size != NULL) {
274 		*size = (size_t)fdt_read_prop_cells(&prop[cell + ac], sc);
275 	}
276 
277 	return 0;
278 }
279 
280 /*******************************************************************************
281  * This function fills reg node info (base & size) with an index found by
282  * checking the reg-names node.
283  * Returns 0 on success and a negative FDT error code on failure.
284  ******************************************************************************/
fdt_get_reg_props_by_name(const void * dtb,int node,const char * name,uintptr_t * base,size_t * size)285 int fdt_get_reg_props_by_name(const void *dtb, int node, const char *name,
286 			      uintptr_t *base, size_t *size)
287 {
288 	int index;
289 
290 	index = fdt_stringlist_search(dtb, node, "reg-names", name);
291 	if (index < 0) {
292 		return index;
293 	}
294 
295 	return fdt_get_reg_props_by_index(dtb, node, index, base, size);
296 }
297 
298 /*******************************************************************************
299  * This function gets the stdout path node.
300  * It reads the value indicated inside the device tree.
301  * Returns node offset on success and a negative FDT error code on failure.
302  ******************************************************************************/
fdt_get_stdout_node_offset(const void * dtb)303 int fdt_get_stdout_node_offset(const void *dtb)
304 {
305 	int node;
306 	const char *prop, *path;
307 	int len;
308 
309 	/* The /secure-chosen node takes precedence over the standard one. */
310 	node = fdt_path_offset(dtb, "/secure-chosen");
311 	if (node < 0) {
312 		node = fdt_path_offset(dtb, "/chosen");
313 		if (node < 0) {
314 			return -FDT_ERR_NOTFOUND;
315 		}
316 	}
317 
318 	prop = fdt_getprop(dtb, node, "stdout-path", NULL);
319 	if (prop == NULL) {
320 		return -FDT_ERR_NOTFOUND;
321 	}
322 
323 	/* Determine the actual path length, as a colon terminates the path. */
324 	path = strchr(prop, ':');
325 	if (path == NULL) {
326 		len = strlen(prop);
327 	} else {
328 		len = path - prop;
329 	}
330 
331 	/* Aliases cannot start with a '/', so it must be the actual path. */
332 	if (prop[0] == '/') {
333 		return fdt_path_offset_namelen(dtb, prop, len);
334 	}
335 
336 	/* Lookup the alias, as this contains the actual path. */
337 	path = fdt_get_alias_namelen(dtb, prop, len);
338 	if (path == NULL) {
339 		return -FDT_ERR_NOTFOUND;
340 	}
341 
342 	return fdt_path_offset(dtb, path);
343 }
344 
345 
346 /*******************************************************************************
347  * Only devices which are direct children of root node use CPU address domain.
348  * All other devices use addresses that are local to the device node and cannot
349  * directly used by CPU. Device tree provides an address translation mechanism
350  * through "ranges" property which provides mappings from local address space to
351  * parent address space. Since a device could be a child of a child node to the
352  * root node, there can be more than one level of address translation needed to
353  * map the device local address space to CPU address space.
354  * fdtw_translate_address() API performs address translation of a local address
355  * to a global address with help of various helper functions.
356  ******************************************************************************/
357 
fdtw_xlat_hit(const uint32_t * value,int child_addr_size,int parent_addr_size,int range_size,uint64_t base_address,uint64_t * translated_addr)358 static bool fdtw_xlat_hit(const uint32_t *value, int child_addr_size,
359 		int parent_addr_size, int range_size, uint64_t base_address,
360 		uint64_t *translated_addr)
361 {
362 	uint64_t local_address, parent_address, addr_range;
363 
364 	local_address = fdt_read_prop_cells(value, child_addr_size);
365 	parent_address = fdt_read_prop_cells(value + child_addr_size,
366 				parent_addr_size);
367 	addr_range = fdt_read_prop_cells(value + child_addr_size +
368 				parent_addr_size,
369 				range_size);
370 	VERBOSE("DT: Address %llx mapped to %llx with range %llx\n",
371 		local_address, parent_address, addr_range);
372 
373 	/* Perform range check */
374 	if ((base_address < local_address) ||
375 		(base_address >= local_address + addr_range)) {
376 		return false;
377 	}
378 
379 	/* Found hit for the addr range that needs to be translated */
380 	*translated_addr = parent_address + (base_address - local_address);
381 	VERBOSE("DT: child address %llx mapped to %llx in parent bus\n",
382 			local_address, parent_address);
383 	return true;
384 }
385 
386 #define ILLEGAL_ADDR	ULL(~0)
387 
fdtw_search_all_xlat_entries(const void * dtb,const struct fdt_property * ranges_prop,int local_bus,uint64_t base_address)388 static uint64_t fdtw_search_all_xlat_entries(const void *dtb,
389 				const struct fdt_property *ranges_prop,
390 				int local_bus, uint64_t base_address)
391 {
392 	uint64_t translated_addr;
393 	const uint32_t *next_entry;
394 	int parent_bus_node, nxlat_entries, length;
395 	int self_addr_cells, parent_addr_cells, self_size_cells, ncells_xlat;
396 
397 	/*
398 	 * The number of cells in one translation entry in ranges is the sum of
399 	 * the following values:
400 	 * self#address-cells + parent#address-cells + self#size-cells
401 	 * Ex: the iofpga ranges property has one translation entry with 4 cells
402 	 * They represent iofpga#addr-cells + motherboard#addr-cells + iofpga#size-cells
403 	 *              = 1                 + 2                      + 1
404 	 */
405 
406 	parent_bus_node = fdt_parent_offset(dtb, local_bus);
407 	self_addr_cells = fdt_address_cells(dtb, local_bus);
408 	self_size_cells = fdt_size_cells(dtb, local_bus);
409 	parent_addr_cells = fdt_address_cells(dtb, parent_bus_node);
410 
411 	/* Number of cells per translation entry i.e., mapping */
412 	ncells_xlat = self_addr_cells + parent_addr_cells + self_size_cells;
413 
414 	assert(ncells_xlat > 0);
415 
416 	/*
417 	 * Find the number of translations(mappings) specified in the current
418 	 * `ranges` property. Note that length represents number of bytes and
419 	 * is stored in big endian mode.
420 	 */
421 	length = fdt32_to_cpu(ranges_prop->len);
422 	nxlat_entries = (length/sizeof(uint32_t))/ncells_xlat;
423 
424 	assert(nxlat_entries > 0);
425 
426 	next_entry = (const uint32_t *)ranges_prop->data;
427 
428 	/* Iterate over the entries in the "ranges" */
429 	for (int i = 0; i < nxlat_entries; i++) {
430 		if (fdtw_xlat_hit(next_entry, self_addr_cells,
431 				parent_addr_cells, self_size_cells, base_address,
432 				&translated_addr)){
433 			return translated_addr;
434 		}
435 		next_entry = next_entry + ncells_xlat;
436 	}
437 
438 	INFO("DT: No translation found for address %llx in node %s\n",
439 		base_address, fdt_get_name(dtb, local_bus, NULL));
440 	return ILLEGAL_ADDR;
441 }
442 
443 
444 /*******************************************************************************
445  * address mapping needs to be done recursively starting from current node to
446  * root node through all intermediate parent nodes.
447  * Sample device tree is shown here:
448 
449 smb@0,0 {
450 	compatible = "simple-bus";
451 
452 	#address-cells = <2>;
453 	#size-cells = <1>;
454 	ranges = <0 0 0 0x08000000 0x04000000>,
455 		 <1 0 0 0x14000000 0x04000000>,
456 		 <2 0 0 0x18000000 0x04000000>,
457 		 <3 0 0 0x1c000000 0x04000000>,
458 		 <4 0 0 0x0c000000 0x04000000>,
459 		 <5 0 0 0x10000000 0x04000000>;
460 
461 	motherboard {
462 		arm,v2m-memory-map = "rs1";
463 		compatible = "arm,vexpress,v2m-p1", "simple-bus";
464 		#address-cells = <2>;
465 		#size-cells = <1>;
466 		ranges;
467 
468 		iofpga@3,00000000 {
469 			compatible = "arm,amba-bus", "simple-bus";
470 			#address-cells = <1>;
471 			#size-cells = <1>;
472 			ranges = <0 3 0 0x200000>;
473 			v2m_serial1: uart@a0000 {
474 				compatible = "arm,pl011", "arm,primecell";
475 				reg = <0x0a0000 0x1000>;
476 				interrupts = <0 6 4>;
477 				clocks = <&v2m_clk24mhz>, <&v2m_clk24mhz>;
478 				clock-names = "uartclk", "apb_pclk";
479 		};
480 	};
481 };
482 
483  * As seen above, there are 3 levels of address translations needed. An empty
484  * `ranges` property denotes identity mapping (as seen in `motherboard` node).
485  * Each ranges property can map a set of child addresses to parent bus. Hence
486  * there can be more than 1 (translation) entry in the ranges property as seen
487  * in the `smb` node which has 6 translation entries.
488  ******************************************************************************/
489 
490 /* Recursive implementation */
fdtw_translate_address(const void * dtb,int node,uint64_t base_address)491 uint64_t fdtw_translate_address(const void *dtb, int node,
492 				uint64_t base_address)
493 {
494 	int length, local_bus_node;
495 	const char *node_name;
496 	uint64_t global_address;
497 
498 	local_bus_node = fdt_parent_offset(dtb, node);
499 	node_name = fdt_get_name(dtb, local_bus_node, NULL);
500 
501 	/*
502 	 * In the example given above, starting from the leaf node:
503 	 * uart@a000 represents the current node
504 	 * iofpga@3,00000000 represents the local bus
505 	 * motherboard represents the parent bus
506 	 */
507 
508 	/* Read the ranges property */
509 	const struct fdt_property *property = fdt_get_property(dtb,
510 					local_bus_node, "ranges", &length);
511 
512 	if (property == NULL) {
513 		if (local_bus_node == 0) {
514 			/*
515 			 * root node doesn't have range property as addresses
516 			 * are in CPU address space.
517 			 */
518 			return base_address;
519 		}
520 		INFO("DT: Couldn't find ranges property in node %s\n",
521 			node_name);
522 		return ILLEGAL_ADDR;
523 	} else if (length == 0) {
524 		/* empty ranges indicates identity map to parent bus */
525 		return fdtw_translate_address(dtb, local_bus_node, base_address);
526 	}
527 
528 	VERBOSE("DT: Translation lookup in node %s at offset %d\n", node_name,
529 		local_bus_node);
530 	global_address = fdtw_search_all_xlat_entries(dtb, property,
531 				local_bus_node, base_address);
532 
533 	if (global_address == ILLEGAL_ADDR) {
534 		return ILLEGAL_ADDR;
535 	}
536 
537 	/* Translate the local device address recursively */
538 	return fdtw_translate_address(dtb, local_bus_node, global_address);
539 }
540