xref: /openbmc/u-boot/lib/fdtdec.c (revision 0dfe3ffe)
1 /*
2  * Copyright (c) 2011 The Chromium OS Authors.
3  * SPDX-License-Identifier:	GPL-2.0+
4  */
5 
6 #ifndef USE_HOSTCC
7 #include <boot_fit.h>
8 #include <common.h>
9 #include <dm.h>
10 #include <errno.h>
11 #include <serial.h>
12 #include <libfdt.h>
13 #include <fdt_support.h>
14 #include <fdtdec.h>
15 #include <asm/sections.h>
16 #include <dm/of_extra.h>
17 #include <linux/ctype.h>
18 
19 DECLARE_GLOBAL_DATA_PTR;
20 
21 /*
22  * Here are the type we know about. One day we might allow drivers to
23  * register. For now we just put them here. The COMPAT macro allows us to
24  * turn this into a sparse list later, and keeps the ID with the name.
25  *
26  * NOTE: This list is basically a TODO list for things that need to be
27  * converted to driver model. So don't add new things here unless there is a
28  * good reason why driver-model conversion is infeasible. Examples include
29  * things which are used before driver model is available.
30  */
31 #define COMPAT(id, name) name
32 static const char * const compat_names[COMPAT_COUNT] = {
33 	COMPAT(UNKNOWN, "<none>"),
34 	COMPAT(NVIDIA_TEGRA20_EMC, "nvidia,tegra20-emc"),
35 	COMPAT(NVIDIA_TEGRA20_EMC_TABLE, "nvidia,tegra20-emc-table"),
36 	COMPAT(NVIDIA_TEGRA20_NAND, "nvidia,tegra20-nand"),
37 	COMPAT(NVIDIA_TEGRA124_XUSB_PADCTL, "nvidia,tegra124-xusb-padctl"),
38 	COMPAT(NVIDIA_TEGRA210_XUSB_PADCTL, "nvidia,tegra210-xusb-padctl"),
39 	COMPAT(SMSC_LAN9215, "smsc,lan9215"),
40 	COMPAT(SAMSUNG_EXYNOS5_SROMC, "samsung,exynos-sromc"),
41 	COMPAT(SAMSUNG_S3C2440_I2C, "samsung,s3c2440-i2c"),
42 	COMPAT(SAMSUNG_EXYNOS5_SOUND, "samsung,exynos-sound"),
43 	COMPAT(WOLFSON_WM8994_CODEC, "wolfson,wm8994-codec"),
44 	COMPAT(SAMSUNG_EXYNOS_USB_PHY, "samsung,exynos-usb-phy"),
45 	COMPAT(SAMSUNG_EXYNOS5_USB3_PHY, "samsung,exynos5250-usb3-phy"),
46 	COMPAT(SAMSUNG_EXYNOS_TMU, "samsung,exynos-tmu"),
47 	COMPAT(SAMSUNG_EXYNOS_MIPI_DSI, "samsung,exynos-mipi-dsi"),
48 	COMPAT(SAMSUNG_EXYNOS_DWMMC, "samsung,exynos-dwmmc"),
49 	COMPAT(SAMSUNG_EXYNOS_MMC, "samsung,exynos-mmc"),
50 	COMPAT(MAXIM_MAX77686_PMIC, "maxim,max77686"),
51 	COMPAT(GENERIC_SPI_FLASH, "spi-flash"),
52 	COMPAT(MAXIM_98095_CODEC, "maxim,max98095-codec"),
53 	COMPAT(SAMSUNG_EXYNOS5_I2C, "samsung,exynos5-hsi2c"),
54 	COMPAT(SAMSUNG_EXYNOS_SYSMMU, "samsung,sysmmu-v3.3"),
55 	COMPAT(INTEL_MICROCODE, "intel,microcode"),
56 	COMPAT(AMS_AS3722, "ams,as3722"),
57 	COMPAT(INTEL_QRK_MRC, "intel,quark-mrc"),
58 	COMPAT(ALTERA_SOCFPGA_DWMAC, "altr,socfpga-stmmac"),
59 	COMPAT(ALTERA_SOCFPGA_DWMMC, "altr,socfpga-dw-mshc"),
60 	COMPAT(ALTERA_SOCFPGA_DWC2USB, "snps,dwc2"),
61 	COMPAT(INTEL_BAYTRAIL_FSP, "intel,baytrail-fsp"),
62 	COMPAT(INTEL_BAYTRAIL_FSP_MDP, "intel,baytrail-fsp-mdp"),
63 	COMPAT(INTEL_IVYBRIDGE_FSP, "intel,ivybridge-fsp"),
64 	COMPAT(COMPAT_SUNXI_NAND, "allwinner,sun4i-a10-nand"),
65 	COMPAT(ALTERA_SOCFPGA_CLK, "altr,clk-mgr"),
66 	COMPAT(ALTERA_SOCFPGA_PINCTRL_SINGLE, "pinctrl-single"),
67 	COMPAT(ALTERA_SOCFPGA_H2F_BRG, "altr,socfpga-hps2fpga-bridge"),
68 	COMPAT(ALTERA_SOCFPGA_LWH2F_BRG, "altr,socfpga-lwhps2fpga-bridge"),
69 	COMPAT(ALTERA_SOCFPGA_F2H_BRG, "altr,socfpga-fpga2hps-bridge"),
70 	COMPAT(ALTERA_SOCFPGA_F2SDR0, "altr,socfpga-fpga2sdram0-bridge"),
71 	COMPAT(ALTERA_SOCFPGA_F2SDR1, "altr,socfpga-fpga2sdram1-bridge"),
72 	COMPAT(ALTERA_SOCFPGA_F2SDR2, "altr,socfpga-fpga2sdram2-bridge"),
73 };
74 
75 const char *fdtdec_get_compatible(enum fdt_compat_id id)
76 {
77 	/* We allow reading of the 'unknown' ID for testing purposes */
78 	assert(id >= 0 && id < COMPAT_COUNT);
79 	return compat_names[id];
80 }
81 
82 fdt_addr_t fdtdec_get_addr_size_fixed(const void *blob, int node,
83 		const char *prop_name, int index, int na, int ns,
84 		fdt_size_t *sizep, bool translate)
85 {
86 	const fdt32_t *prop, *prop_end;
87 	const fdt32_t *prop_addr, *prop_size, *prop_after_size;
88 	int len;
89 	fdt_addr_t addr;
90 
91 	debug("%s: %s: ", __func__, prop_name);
92 
93 	if (na > (sizeof(fdt_addr_t) / sizeof(fdt32_t))) {
94 		debug("(na too large for fdt_addr_t type)\n");
95 		return FDT_ADDR_T_NONE;
96 	}
97 
98 	if (ns > (sizeof(fdt_size_t) / sizeof(fdt32_t))) {
99 		debug("(ns too large for fdt_size_t type)\n");
100 		return FDT_ADDR_T_NONE;
101 	}
102 
103 	prop = fdt_getprop(blob, node, prop_name, &len);
104 	if (!prop) {
105 		debug("(not found)\n");
106 		return FDT_ADDR_T_NONE;
107 	}
108 	prop_end = prop + (len / sizeof(*prop));
109 
110 	prop_addr = prop + (index * (na + ns));
111 	prop_size = prop_addr + na;
112 	prop_after_size = prop_size + ns;
113 	if (prop_after_size > prop_end) {
114 		debug("(not enough data: expected >= %d cells, got %d cells)\n",
115 		      (u32)(prop_after_size - prop), ((u32)(prop_end - prop)));
116 		return FDT_ADDR_T_NONE;
117 	}
118 
119 #if CONFIG_IS_ENABLED(OF_TRANSLATE)
120 	if (translate)
121 		addr = fdt_translate_address(blob, node, prop_addr);
122 	else
123 #endif
124 		addr = fdtdec_get_number(prop_addr, na);
125 
126 	if (sizep) {
127 		*sizep = fdtdec_get_number(prop_size, ns);
128 		debug("addr=%08llx, size=%llx\n", (unsigned long long)addr,
129 		      (unsigned long long)*sizep);
130 	} else {
131 		debug("addr=%08llx\n", (unsigned long long)addr);
132 	}
133 
134 	return addr;
135 }
136 
137 fdt_addr_t fdtdec_get_addr_size_auto_parent(const void *blob, int parent,
138 		int node, const char *prop_name, int index, fdt_size_t *sizep,
139 		bool translate)
140 {
141 	int na, ns;
142 
143 	debug("%s: ", __func__);
144 
145 	na = fdt_address_cells(blob, parent);
146 	if (na < 1) {
147 		debug("(bad #address-cells)\n");
148 		return FDT_ADDR_T_NONE;
149 	}
150 
151 	ns = fdt_size_cells(blob, parent);
152 	if (ns < 0) {
153 		debug("(bad #size-cells)\n");
154 		return FDT_ADDR_T_NONE;
155 	}
156 
157 	debug("na=%d, ns=%d, ", na, ns);
158 
159 	return fdtdec_get_addr_size_fixed(blob, node, prop_name, index, na,
160 					  ns, sizep, translate);
161 }
162 
163 fdt_addr_t fdtdec_get_addr_size_auto_noparent(const void *blob, int node,
164 		const char *prop_name, int index, fdt_size_t *sizep,
165 		bool translate)
166 {
167 	int parent;
168 
169 	debug("%s: ", __func__);
170 
171 	parent = fdt_parent_offset(blob, node);
172 	if (parent < 0) {
173 		debug("(no parent found)\n");
174 		return FDT_ADDR_T_NONE;
175 	}
176 
177 	return fdtdec_get_addr_size_auto_parent(blob, parent, node, prop_name,
178 						index, sizep, translate);
179 }
180 
181 fdt_addr_t fdtdec_get_addr_size(const void *blob, int node,
182 		const char *prop_name, fdt_size_t *sizep)
183 {
184 	int ns = sizep ? (sizeof(fdt_size_t) / sizeof(fdt32_t)) : 0;
185 
186 	return fdtdec_get_addr_size_fixed(blob, node, prop_name, 0,
187 					  sizeof(fdt_addr_t) / sizeof(fdt32_t),
188 					  ns, sizep, false);
189 }
190 
191 fdt_addr_t fdtdec_get_addr(const void *blob, int node,
192 		const char *prop_name)
193 {
194 	return fdtdec_get_addr_size(blob, node, prop_name, NULL);
195 }
196 
197 #if defined(CONFIG_PCI) && defined(CONFIG_DM_PCI)
198 int fdtdec_get_pci_addr(const void *blob, int node, enum fdt_pci_space type,
199 		const char *prop_name, struct fdt_pci_addr *addr)
200 {
201 	const u32 *cell;
202 	int len;
203 	int ret = -ENOENT;
204 
205 	debug("%s: %s: ", __func__, prop_name);
206 
207 	/*
208 	 * If we follow the pci bus bindings strictly, we should check
209 	 * the value of the node's parent node's #address-cells and
210 	 * #size-cells. They need to be 3 and 2 accordingly. However,
211 	 * for simplicity we skip the check here.
212 	 */
213 	cell = fdt_getprop(blob, node, prop_name, &len);
214 	if (!cell)
215 		goto fail;
216 
217 	if ((len % FDT_PCI_REG_SIZE) == 0) {
218 		int num = len / FDT_PCI_REG_SIZE;
219 		int i;
220 
221 		for (i = 0; i < num; i++) {
222 			debug("pci address #%d: %08lx %08lx %08lx\n", i,
223 			      (ulong)fdt32_to_cpu(cell[0]),
224 			      (ulong)fdt32_to_cpu(cell[1]),
225 			      (ulong)fdt32_to_cpu(cell[2]));
226 			if ((fdt32_to_cpu(*cell) & type) == type) {
227 				addr->phys_hi = fdt32_to_cpu(cell[0]);
228 				addr->phys_mid = fdt32_to_cpu(cell[1]);
229 				addr->phys_lo = fdt32_to_cpu(cell[1]);
230 				break;
231 			} else {
232 				cell += (FDT_PCI_ADDR_CELLS +
233 					 FDT_PCI_SIZE_CELLS);
234 			}
235 		}
236 
237 		if (i == num) {
238 			ret = -ENXIO;
239 			goto fail;
240 		}
241 
242 		return 0;
243 	} else {
244 		ret = -EINVAL;
245 	}
246 
247 fail:
248 	debug("(not found)\n");
249 	return ret;
250 }
251 
252 int fdtdec_get_pci_vendev(const void *blob, int node, u16 *vendor, u16 *device)
253 {
254 	const char *list, *end;
255 	int len;
256 
257 	list = fdt_getprop(blob, node, "compatible", &len);
258 	if (!list)
259 		return -ENOENT;
260 
261 	end = list + len;
262 	while (list < end) {
263 		char *s;
264 
265 		len = strlen(list);
266 		if (len >= strlen("pciVVVV,DDDD")) {
267 			s = strstr(list, "pci");
268 
269 			/*
270 			 * check if the string is something like pciVVVV,DDDD.RR
271 			 * or just pciVVVV,DDDD
272 			 */
273 			if (s && s[7] == ',' &&
274 			    (s[12] == '.' || s[12] == 0)) {
275 				s += 3;
276 				*vendor = simple_strtol(s, NULL, 16);
277 
278 				s += 5;
279 				*device = simple_strtol(s, NULL, 16);
280 
281 				return 0;
282 			}
283 		}
284 		list += (len + 1);
285 	}
286 
287 	return -ENOENT;
288 }
289 
290 int fdtdec_get_pci_bar32(struct udevice *dev, struct fdt_pci_addr *addr,
291 			 u32 *bar)
292 {
293 	int barnum;
294 
295 	/* extract the bar number from fdt_pci_addr */
296 	barnum = addr->phys_hi & 0xff;
297 	if ((barnum < PCI_BASE_ADDRESS_0) || (barnum > PCI_CARDBUS_CIS))
298 		return -EINVAL;
299 
300 	barnum = (barnum - PCI_BASE_ADDRESS_0) / 4;
301 	*bar = dm_pci_read_bar32(dev, barnum);
302 
303 	return 0;
304 }
305 #endif
306 
307 uint64_t fdtdec_get_uint64(const void *blob, int node, const char *prop_name,
308 		uint64_t default_val)
309 {
310 	const uint64_t *cell64;
311 	int length;
312 
313 	cell64 = fdt_getprop(blob, node, prop_name, &length);
314 	if (!cell64 || length < sizeof(*cell64))
315 		return default_val;
316 
317 	return fdt64_to_cpu(*cell64);
318 }
319 
320 int fdtdec_get_is_enabled(const void *blob, int node)
321 {
322 	const char *cell;
323 
324 	/*
325 	 * It should say "okay", so only allow that. Some fdts use "ok" but
326 	 * this is a bug. Please fix your device tree source file. See here
327 	 * for discussion:
328 	 *
329 	 * http://www.mail-archive.com/u-boot@lists.denx.de/msg71598.html
330 	 */
331 	cell = fdt_getprop(blob, node, "status", NULL);
332 	if (cell)
333 		return 0 == strcmp(cell, "okay");
334 	return 1;
335 }
336 
337 enum fdt_compat_id fdtdec_lookup(const void *blob, int node)
338 {
339 	enum fdt_compat_id id;
340 
341 	/* Search our drivers */
342 	for (id = COMPAT_UNKNOWN; id < COMPAT_COUNT; id++)
343 		if (0 == fdt_node_check_compatible(blob, node,
344 				compat_names[id]))
345 			return id;
346 	return COMPAT_UNKNOWN;
347 }
348 
349 int fdtdec_next_compatible(const void *blob, int node,
350 		enum fdt_compat_id id)
351 {
352 	return fdt_node_offset_by_compatible(blob, node, compat_names[id]);
353 }
354 
355 int fdtdec_next_compatible_subnode(const void *blob, int node,
356 		enum fdt_compat_id id, int *depthp)
357 {
358 	do {
359 		node = fdt_next_node(blob, node, depthp);
360 	} while (*depthp > 1);
361 
362 	/* If this is a direct subnode, and compatible, return it */
363 	if (*depthp == 1 && 0 == fdt_node_check_compatible(
364 						blob, node, compat_names[id]))
365 		return node;
366 
367 	return -FDT_ERR_NOTFOUND;
368 }
369 
370 int fdtdec_next_alias(const void *blob, const char *name,
371 		enum fdt_compat_id id, int *upto)
372 {
373 #define MAX_STR_LEN 20
374 	char str[MAX_STR_LEN + 20];
375 	int node, err;
376 
377 	/* snprintf() is not available */
378 	assert(strlen(name) < MAX_STR_LEN);
379 	sprintf(str, "%.*s%d", MAX_STR_LEN, name, *upto);
380 	node = fdt_path_offset(blob, str);
381 	if (node < 0)
382 		return node;
383 	err = fdt_node_check_compatible(blob, node, compat_names[id]);
384 	if (err < 0)
385 		return err;
386 	if (err)
387 		return -FDT_ERR_NOTFOUND;
388 	(*upto)++;
389 	return node;
390 }
391 
392 int fdtdec_find_aliases_for_id(const void *blob, const char *name,
393 			enum fdt_compat_id id, int *node_list, int maxcount)
394 {
395 	memset(node_list, '\0', sizeof(*node_list) * maxcount);
396 
397 	return fdtdec_add_aliases_for_id(blob, name, id, node_list, maxcount);
398 }
399 
400 /* TODO: Can we tighten this code up a little? */
401 int fdtdec_add_aliases_for_id(const void *blob, const char *name,
402 			enum fdt_compat_id id, int *node_list, int maxcount)
403 {
404 	int name_len = strlen(name);
405 	int nodes[maxcount];
406 	int num_found = 0;
407 	int offset, node;
408 	int alias_node;
409 	int count;
410 	int i, j;
411 
412 	/* find the alias node if present */
413 	alias_node = fdt_path_offset(blob, "/aliases");
414 
415 	/*
416 	 * start with nothing, and we can assume that the root node can't
417 	 * match
418 	 */
419 	memset(nodes, '\0', sizeof(nodes));
420 
421 	/* First find all the compatible nodes */
422 	for (node = count = 0; node >= 0 && count < maxcount;) {
423 		node = fdtdec_next_compatible(blob, node, id);
424 		if (node >= 0)
425 			nodes[count++] = node;
426 	}
427 	if (node >= 0)
428 		debug("%s: warning: maxcount exceeded with alias '%s'\n",
429 		       __func__, name);
430 
431 	/* Now find all the aliases */
432 	for (offset = fdt_first_property_offset(blob, alias_node);
433 			offset > 0;
434 			offset = fdt_next_property_offset(blob, offset)) {
435 		const struct fdt_property *prop;
436 		const char *path;
437 		int number;
438 		int found;
439 
440 		node = 0;
441 		prop = fdt_get_property_by_offset(blob, offset, NULL);
442 		path = fdt_string(blob, fdt32_to_cpu(prop->nameoff));
443 		if (prop->len && 0 == strncmp(path, name, name_len))
444 			node = fdt_path_offset(blob, prop->data);
445 		if (node <= 0)
446 			continue;
447 
448 		/* Get the alias number */
449 		number = simple_strtoul(path + name_len, NULL, 10);
450 		if (number < 0 || number >= maxcount) {
451 			debug("%s: warning: alias '%s' is out of range\n",
452 			       __func__, path);
453 			continue;
454 		}
455 
456 		/* Make sure the node we found is actually in our list! */
457 		found = -1;
458 		for (j = 0; j < count; j++)
459 			if (nodes[j] == node) {
460 				found = j;
461 				break;
462 			}
463 
464 		if (found == -1) {
465 			debug("%s: warning: alias '%s' points to a node "
466 				"'%s' that is missing or is not compatible "
467 				" with '%s'\n", __func__, path,
468 				fdt_get_name(blob, node, NULL),
469 			       compat_names[id]);
470 			continue;
471 		}
472 
473 		/*
474 		 * Add this node to our list in the right place, and mark
475 		 * it as done.
476 		 */
477 		if (fdtdec_get_is_enabled(blob, node)) {
478 			if (node_list[number]) {
479 				debug("%s: warning: alias '%s' requires that "
480 				      "a node be placed in the list in a "
481 				      "position which is already filled by "
482 				      "node '%s'\n", __func__, path,
483 				      fdt_get_name(blob, node, NULL));
484 				continue;
485 			}
486 			node_list[number] = node;
487 			if (number >= num_found)
488 				num_found = number + 1;
489 		}
490 		nodes[found] = 0;
491 	}
492 
493 	/* Add any nodes not mentioned by an alias */
494 	for (i = j = 0; i < maxcount; i++) {
495 		if (!node_list[i]) {
496 			for (; j < maxcount; j++)
497 				if (nodes[j] &&
498 					fdtdec_get_is_enabled(blob, nodes[j]))
499 					break;
500 
501 			/* Have we run out of nodes to add? */
502 			if (j == maxcount)
503 				break;
504 
505 			assert(!node_list[i]);
506 			node_list[i] = nodes[j++];
507 			if (i >= num_found)
508 				num_found = i + 1;
509 		}
510 	}
511 
512 	return num_found;
513 }
514 
515 int fdtdec_get_alias_seq(const void *blob, const char *base, int offset,
516 			 int *seqp)
517 {
518 	int base_len = strlen(base);
519 	const char *find_name;
520 	int find_namelen;
521 	int prop_offset;
522 	int aliases;
523 
524 	find_name = fdt_get_name(blob, offset, &find_namelen);
525 	debug("Looking for '%s' at %d, name %s\n", base, offset, find_name);
526 
527 	aliases = fdt_path_offset(blob, "/aliases");
528 	for (prop_offset = fdt_first_property_offset(blob, aliases);
529 	     prop_offset > 0;
530 	     prop_offset = fdt_next_property_offset(blob, prop_offset)) {
531 		const char *prop;
532 		const char *name;
533 		const char *slash;
534 		int len, val;
535 
536 		prop = fdt_getprop_by_offset(blob, prop_offset, &name, &len);
537 		debug("   - %s, %s\n", name, prop);
538 		if (len < find_namelen || *prop != '/' || prop[len - 1] ||
539 		    strncmp(name, base, base_len))
540 			continue;
541 
542 		slash = strrchr(prop, '/');
543 		if (strcmp(slash + 1, find_name))
544 			continue;
545 		val = trailing_strtol(name);
546 		if (val != -1) {
547 			*seqp = val;
548 			debug("Found seq %d\n", *seqp);
549 			return 0;
550 		}
551 	}
552 
553 	debug("Not found\n");
554 	return -ENOENT;
555 }
556 
557 const char *fdtdec_get_chosen_prop(const void *blob, const char *name)
558 {
559 	int chosen_node;
560 
561 	if (!blob)
562 		return NULL;
563 	chosen_node = fdt_path_offset(blob, "/chosen");
564 	return fdt_getprop(blob, chosen_node, name, NULL);
565 }
566 
567 int fdtdec_get_chosen_node(const void *blob, const char *name)
568 {
569 	const char *prop;
570 
571 	prop = fdtdec_get_chosen_prop(blob, name);
572 	if (!prop)
573 		return -FDT_ERR_NOTFOUND;
574 	return fdt_path_offset(blob, prop);
575 }
576 
577 int fdtdec_check_fdt(void)
578 {
579 	/*
580 	 * We must have an FDT, but we cannot panic() yet since the console
581 	 * is not ready. So for now, just assert(). Boards which need an early
582 	 * FDT (prior to console ready) will need to make their own
583 	 * arrangements and do their own checks.
584 	 */
585 	assert(!fdtdec_prepare_fdt());
586 	return 0;
587 }
588 
589 /*
590  * This function is a little odd in that it accesses global data. At some
591  * point if the architecture board.c files merge this will make more sense.
592  * Even now, it is common code.
593  */
594 int fdtdec_prepare_fdt(void)
595 {
596 	if (!gd->fdt_blob || ((uintptr_t)gd->fdt_blob & 3) ||
597 	    fdt_check_header(gd->fdt_blob)) {
598 #ifdef CONFIG_SPL_BUILD
599 		puts("Missing DTB\n");
600 #else
601 		puts("No valid device tree binary found - please append one to U-Boot binary, use u-boot-dtb.bin or define CONFIG_OF_EMBED. For sandbox, use -d <file.dtb>\n");
602 # ifdef DEBUG
603 		if (gd->fdt_blob) {
604 			printf("fdt_blob=%p\n", gd->fdt_blob);
605 			print_buffer((ulong)gd->fdt_blob, gd->fdt_blob, 4,
606 				     32, 0);
607 		}
608 # endif
609 #endif
610 		return -1;
611 	}
612 	return 0;
613 }
614 
615 int fdtdec_lookup_phandle(const void *blob, int node, const char *prop_name)
616 {
617 	const u32 *phandle;
618 	int lookup;
619 
620 	debug("%s: %s\n", __func__, prop_name);
621 	phandle = fdt_getprop(blob, node, prop_name, NULL);
622 	if (!phandle)
623 		return -FDT_ERR_NOTFOUND;
624 
625 	lookup = fdt_node_offset_by_phandle(blob, fdt32_to_cpu(*phandle));
626 	return lookup;
627 }
628 
629 /**
630  * Look up a property in a node and check that it has a minimum length.
631  *
632  * @param blob		FDT blob
633  * @param node		node to examine
634  * @param prop_name	name of property to find
635  * @param min_len	minimum property length in bytes
636  * @param err		0 if ok, or -FDT_ERR_NOTFOUND if the property is not
637 			found, or -FDT_ERR_BADLAYOUT if not enough data
638  * @return pointer to cell, which is only valid if err == 0
639  */
640 static const void *get_prop_check_min_len(const void *blob, int node,
641 		const char *prop_name, int min_len, int *err)
642 {
643 	const void *cell;
644 	int len;
645 
646 	debug("%s: %s\n", __func__, prop_name);
647 	cell = fdt_getprop(blob, node, prop_name, &len);
648 	if (!cell)
649 		*err = -FDT_ERR_NOTFOUND;
650 	else if (len < min_len)
651 		*err = -FDT_ERR_BADLAYOUT;
652 	else
653 		*err = 0;
654 	return cell;
655 }
656 
657 int fdtdec_get_int_array(const void *blob, int node, const char *prop_name,
658 		u32 *array, int count)
659 {
660 	const u32 *cell;
661 	int i, err = 0;
662 
663 	debug("%s: %s\n", __func__, prop_name);
664 	cell = get_prop_check_min_len(blob, node, prop_name,
665 				      sizeof(u32) * count, &err);
666 	if (!err) {
667 		for (i = 0; i < count; i++)
668 			array[i] = fdt32_to_cpu(cell[i]);
669 	}
670 	return err;
671 }
672 
673 int fdtdec_get_int_array_count(const void *blob, int node,
674 			       const char *prop_name, u32 *array, int count)
675 {
676 	const u32 *cell;
677 	int len, elems;
678 	int i;
679 
680 	debug("%s: %s\n", __func__, prop_name);
681 	cell = fdt_getprop(blob, node, prop_name, &len);
682 	if (!cell)
683 		return -FDT_ERR_NOTFOUND;
684 	elems = len / sizeof(u32);
685 	if (count > elems)
686 		count = elems;
687 	for (i = 0; i < count; i++)
688 		array[i] = fdt32_to_cpu(cell[i]);
689 
690 	return count;
691 }
692 
693 const u32 *fdtdec_locate_array(const void *blob, int node,
694 			       const char *prop_name, int count)
695 {
696 	const u32 *cell;
697 	int err;
698 
699 	cell = get_prop_check_min_len(blob, node, prop_name,
700 				      sizeof(u32) * count, &err);
701 	return err ? NULL : cell;
702 }
703 
704 int fdtdec_get_bool(const void *blob, int node, const char *prop_name)
705 {
706 	const s32 *cell;
707 	int len;
708 
709 	debug("%s: %s\n", __func__, prop_name);
710 	cell = fdt_getprop(blob, node, prop_name, &len);
711 	return cell != NULL;
712 }
713 
714 int fdtdec_parse_phandle_with_args(const void *blob, int src_node,
715 				   const char *list_name,
716 				   const char *cells_name,
717 				   int cell_count, int index,
718 				   struct fdtdec_phandle_args *out_args)
719 {
720 	const __be32 *list, *list_end;
721 	int rc = 0, size, cur_index = 0;
722 	uint32_t count = 0;
723 	int node = -1;
724 	int phandle;
725 
726 	/* Retrieve the phandle list property */
727 	list = fdt_getprop(blob, src_node, list_name, &size);
728 	if (!list)
729 		return -ENOENT;
730 	list_end = list + size / sizeof(*list);
731 
732 	/* Loop over the phandles until all the requested entry is found */
733 	while (list < list_end) {
734 		rc = -EINVAL;
735 		count = 0;
736 
737 		/*
738 		 * If phandle is 0, then it is an empty entry with no
739 		 * arguments.  Skip forward to the next entry.
740 		 */
741 		phandle = be32_to_cpup(list++);
742 		if (phandle) {
743 			/*
744 			 * Find the provider node and parse the #*-cells
745 			 * property to determine the argument length.
746 			 *
747 			 * This is not needed if the cell count is hard-coded
748 			 * (i.e. cells_name not set, but cell_count is set),
749 			 * except when we're going to return the found node
750 			 * below.
751 			 */
752 			if (cells_name || cur_index == index) {
753 				node = fdt_node_offset_by_phandle(blob,
754 								  phandle);
755 				if (!node) {
756 					debug("%s: could not find phandle\n",
757 					      fdt_get_name(blob, src_node,
758 							   NULL));
759 					goto err;
760 				}
761 			}
762 
763 			if (cells_name) {
764 				count = fdtdec_get_int(blob, node, cells_name,
765 						       -1);
766 				if (count == -1) {
767 					debug("%s: could not get %s for %s\n",
768 					      fdt_get_name(blob, src_node,
769 							   NULL),
770 					      cells_name,
771 					      fdt_get_name(blob, node,
772 							   NULL));
773 					goto err;
774 				}
775 			} else {
776 				count = cell_count;
777 			}
778 
779 			/*
780 			 * Make sure that the arguments actually fit in the
781 			 * remaining property data length
782 			 */
783 			if (list + count > list_end) {
784 				debug("%s: arguments longer than property\n",
785 				      fdt_get_name(blob, src_node, NULL));
786 				goto err;
787 			}
788 		}
789 
790 		/*
791 		 * All of the error cases above bail out of the loop, so at
792 		 * this point, the parsing is successful. If the requested
793 		 * index matches, then fill the out_args structure and return,
794 		 * or return -ENOENT for an empty entry.
795 		 */
796 		rc = -ENOENT;
797 		if (cur_index == index) {
798 			if (!phandle)
799 				goto err;
800 
801 			if (out_args) {
802 				int i;
803 
804 				if (count > MAX_PHANDLE_ARGS) {
805 					debug("%s: too many arguments %d\n",
806 					      fdt_get_name(blob, src_node,
807 							   NULL), count);
808 					count = MAX_PHANDLE_ARGS;
809 				}
810 				out_args->node = node;
811 				out_args->args_count = count;
812 				for (i = 0; i < count; i++) {
813 					out_args->args[i] =
814 							be32_to_cpup(list++);
815 				}
816 			}
817 
818 			/* Found it! return success */
819 			return 0;
820 		}
821 
822 		node = -1;
823 		list += count;
824 		cur_index++;
825 	}
826 
827 	/*
828 	 * Result will be one of:
829 	 * -ENOENT : index is for empty phandle
830 	 * -EINVAL : parsing error on data
831 	 * [1..n]  : Number of phandle (count mode; when index = -1)
832 	 */
833 	rc = index < 0 ? cur_index : -ENOENT;
834  err:
835 	return rc;
836 }
837 
838 int fdtdec_get_child_count(const void *blob, int node)
839 {
840 	int subnode;
841 	int num = 0;
842 
843 	fdt_for_each_subnode(subnode, blob, node)
844 		num++;
845 
846 	return num;
847 }
848 
849 int fdtdec_get_byte_array(const void *blob, int node, const char *prop_name,
850 		u8 *array, int count)
851 {
852 	const u8 *cell;
853 	int err;
854 
855 	cell = get_prop_check_min_len(blob, node, prop_name, count, &err);
856 	if (!err)
857 		memcpy(array, cell, count);
858 	return err;
859 }
860 
861 const u8 *fdtdec_locate_byte_array(const void *blob, int node,
862 			     const char *prop_name, int count)
863 {
864 	const u8 *cell;
865 	int err;
866 
867 	cell = get_prop_check_min_len(blob, node, prop_name, count, &err);
868 	if (err)
869 		return NULL;
870 	return cell;
871 }
872 
873 int fdtdec_get_config_int(const void *blob, const char *prop_name,
874 		int default_val)
875 {
876 	int config_node;
877 
878 	debug("%s: %s\n", __func__, prop_name);
879 	config_node = fdt_path_offset(blob, "/config");
880 	if (config_node < 0)
881 		return default_val;
882 	return fdtdec_get_int(blob, config_node, prop_name, default_val);
883 }
884 
885 int fdtdec_get_config_bool(const void *blob, const char *prop_name)
886 {
887 	int config_node;
888 	const void *prop;
889 
890 	debug("%s: %s\n", __func__, prop_name);
891 	config_node = fdt_path_offset(blob, "/config");
892 	if (config_node < 0)
893 		return 0;
894 	prop = fdt_get_property(blob, config_node, prop_name, NULL);
895 
896 	return prop != NULL;
897 }
898 
899 char *fdtdec_get_config_string(const void *blob, const char *prop_name)
900 {
901 	const char *nodep;
902 	int nodeoffset;
903 	int len;
904 
905 	debug("%s: %s\n", __func__, prop_name);
906 	nodeoffset = fdt_path_offset(blob, "/config");
907 	if (nodeoffset < 0)
908 		return NULL;
909 
910 	nodep = fdt_getprop(blob, nodeoffset, prop_name, &len);
911 	if (!nodep)
912 		return NULL;
913 
914 	return (char *)nodep;
915 }
916 
917 int fdtdec_decode_region(const void *blob, int node, const char *prop_name,
918 			 fdt_addr_t *basep, fdt_size_t *sizep)
919 {
920 	const fdt_addr_t *cell;
921 	int len;
922 
923 	debug("%s: %s: %s\n", __func__, fdt_get_name(blob, node, NULL),
924 	      prop_name);
925 	cell = fdt_getprop(blob, node, prop_name, &len);
926 	if (!cell || (len < sizeof(fdt_addr_t) * 2)) {
927 		debug("cell=%p, len=%d\n", cell, len);
928 		return -1;
929 	}
930 
931 	*basep = fdt_addr_to_cpu(*cell);
932 	*sizep = fdt_size_to_cpu(cell[1]);
933 	debug("%s: base=%08lx, size=%lx\n", __func__, (ulong)*basep,
934 	      (ulong)*sizep);
935 
936 	return 0;
937 }
938 
939 u64 fdtdec_get_number(const fdt32_t *ptr, unsigned int cells)
940 {
941 	u64 number = 0;
942 
943 	while (cells--)
944 		number = (number << 32) | fdt32_to_cpu(*ptr++);
945 
946 	return number;
947 }
948 
949 int fdt_get_resource(const void *fdt, int node, const char *property,
950 		     unsigned int index, struct fdt_resource *res)
951 {
952 	const fdt32_t *ptr, *end;
953 	int na, ns, len, parent;
954 	unsigned int i = 0;
955 
956 	parent = fdt_parent_offset(fdt, node);
957 	if (parent < 0)
958 		return parent;
959 
960 	na = fdt_address_cells(fdt, parent);
961 	ns = fdt_size_cells(fdt, parent);
962 
963 	ptr = fdt_getprop(fdt, node, property, &len);
964 	if (!ptr)
965 		return len;
966 
967 	end = ptr + len / sizeof(*ptr);
968 
969 	while (ptr + na + ns <= end) {
970 		if (i == index) {
971 			res->start = res->end = fdtdec_get_number(ptr, na);
972 			res->end += fdtdec_get_number(&ptr[na], ns) - 1;
973 			return 0;
974 		}
975 
976 		ptr += na + ns;
977 		i++;
978 	}
979 
980 	return -FDT_ERR_NOTFOUND;
981 }
982 
983 int fdt_get_named_resource(const void *fdt, int node, const char *property,
984 			   const char *prop_names, const char *name,
985 			   struct fdt_resource *res)
986 {
987 	int index;
988 
989 	index = fdt_stringlist_search(fdt, node, prop_names, name);
990 	if (index < 0)
991 		return index;
992 
993 	return fdt_get_resource(fdt, node, property, index, res);
994 }
995 
996 int fdtdec_decode_memory_region(const void *blob, int config_node,
997 				const char *mem_type, const char *suffix,
998 				fdt_addr_t *basep, fdt_size_t *sizep)
999 {
1000 	char prop_name[50];
1001 	const char *mem;
1002 	fdt_size_t size, offset_size;
1003 	fdt_addr_t base, offset;
1004 	int node;
1005 
1006 	if (config_node == -1) {
1007 		config_node = fdt_path_offset(blob, "/config");
1008 		if (config_node < 0) {
1009 			debug("%s: Cannot find /config node\n", __func__);
1010 			return -ENOENT;
1011 		}
1012 	}
1013 	if (!suffix)
1014 		suffix = "";
1015 
1016 	snprintf(prop_name, sizeof(prop_name), "%s-memory%s", mem_type,
1017 		 suffix);
1018 	mem = fdt_getprop(blob, config_node, prop_name, NULL);
1019 	if (!mem) {
1020 		debug("%s: No memory type for '%s', using /memory\n", __func__,
1021 		      prop_name);
1022 		mem = "/memory";
1023 	}
1024 
1025 	node = fdt_path_offset(blob, mem);
1026 	if (node < 0) {
1027 		debug("%s: Failed to find node '%s': %s\n", __func__, mem,
1028 		      fdt_strerror(node));
1029 		return -ENOENT;
1030 	}
1031 
1032 	/*
1033 	 * Not strictly correct - the memory may have multiple banks. We just
1034 	 * use the first
1035 	 */
1036 	if (fdtdec_decode_region(blob, node, "reg", &base, &size)) {
1037 		debug("%s: Failed to decode memory region %s\n", __func__,
1038 		      mem);
1039 		return -EINVAL;
1040 	}
1041 
1042 	snprintf(prop_name, sizeof(prop_name), "%s-offset%s", mem_type,
1043 		 suffix);
1044 	if (fdtdec_decode_region(blob, config_node, prop_name, &offset,
1045 				 &offset_size)) {
1046 		debug("%s: Failed to decode memory region '%s'\n", __func__,
1047 		      prop_name);
1048 		return -EINVAL;
1049 	}
1050 
1051 	*basep = base + offset;
1052 	*sizep = offset_size;
1053 
1054 	return 0;
1055 }
1056 
1057 static int decode_timing_property(const void *blob, int node, const char *name,
1058 				  struct timing_entry *result)
1059 {
1060 	int length, ret = 0;
1061 	const u32 *prop;
1062 
1063 	prop = fdt_getprop(blob, node, name, &length);
1064 	if (!prop) {
1065 		debug("%s: could not find property %s\n",
1066 		      fdt_get_name(blob, node, NULL), name);
1067 		return length;
1068 	}
1069 
1070 	if (length == sizeof(u32)) {
1071 		result->typ = fdtdec_get_int(blob, node, name, 0);
1072 		result->min = result->typ;
1073 		result->max = result->typ;
1074 	} else {
1075 		ret = fdtdec_get_int_array(blob, node, name, &result->min, 3);
1076 	}
1077 
1078 	return ret;
1079 }
1080 
1081 int fdtdec_decode_display_timing(const void *blob, int parent, int index,
1082 				 struct display_timing *dt)
1083 {
1084 	int i, node, timings_node;
1085 	u32 val = 0;
1086 	int ret = 0;
1087 
1088 	timings_node = fdt_subnode_offset(blob, parent, "display-timings");
1089 	if (timings_node < 0)
1090 		return timings_node;
1091 
1092 	for (i = 0, node = fdt_first_subnode(blob, timings_node);
1093 	     node > 0 && i != index;
1094 	     node = fdt_next_subnode(blob, node))
1095 		i++;
1096 
1097 	if (node < 0)
1098 		return node;
1099 
1100 	memset(dt, 0, sizeof(*dt));
1101 
1102 	ret |= decode_timing_property(blob, node, "hback-porch",
1103 				      &dt->hback_porch);
1104 	ret |= decode_timing_property(blob, node, "hfront-porch",
1105 				      &dt->hfront_porch);
1106 	ret |= decode_timing_property(blob, node, "hactive", &dt->hactive);
1107 	ret |= decode_timing_property(blob, node, "hsync-len", &dt->hsync_len);
1108 	ret |= decode_timing_property(blob, node, "vback-porch",
1109 				      &dt->vback_porch);
1110 	ret |= decode_timing_property(blob, node, "vfront-porch",
1111 				      &dt->vfront_porch);
1112 	ret |= decode_timing_property(blob, node, "vactive", &dt->vactive);
1113 	ret |= decode_timing_property(blob, node, "vsync-len", &dt->vsync_len);
1114 	ret |= decode_timing_property(blob, node, "clock-frequency",
1115 				      &dt->pixelclock);
1116 
1117 	dt->flags = 0;
1118 	val = fdtdec_get_int(blob, node, "vsync-active", -1);
1119 	if (val != -1) {
1120 		dt->flags |= val ? DISPLAY_FLAGS_VSYNC_HIGH :
1121 				DISPLAY_FLAGS_VSYNC_LOW;
1122 	}
1123 	val = fdtdec_get_int(blob, node, "hsync-active", -1);
1124 	if (val != -1) {
1125 		dt->flags |= val ? DISPLAY_FLAGS_HSYNC_HIGH :
1126 				DISPLAY_FLAGS_HSYNC_LOW;
1127 	}
1128 	val = fdtdec_get_int(blob, node, "de-active", -1);
1129 	if (val != -1) {
1130 		dt->flags |= val ? DISPLAY_FLAGS_DE_HIGH :
1131 				DISPLAY_FLAGS_DE_LOW;
1132 	}
1133 	val = fdtdec_get_int(blob, node, "pixelclk-active", -1);
1134 	if (val != -1) {
1135 		dt->flags |= val ? DISPLAY_FLAGS_PIXDATA_POSEDGE :
1136 				DISPLAY_FLAGS_PIXDATA_NEGEDGE;
1137 	}
1138 
1139 	if (fdtdec_get_bool(blob, node, "interlaced"))
1140 		dt->flags |= DISPLAY_FLAGS_INTERLACED;
1141 	if (fdtdec_get_bool(blob, node, "doublescan"))
1142 		dt->flags |= DISPLAY_FLAGS_DOUBLESCAN;
1143 	if (fdtdec_get_bool(blob, node, "doubleclk"))
1144 		dt->flags |= DISPLAY_FLAGS_DOUBLECLK;
1145 
1146 	return ret;
1147 }
1148 
1149 int fdtdec_setup_memory_size(void)
1150 {
1151 	int ret, mem;
1152 	struct fdt_resource res;
1153 
1154 	mem = fdt_path_offset(gd->fdt_blob, "/memory");
1155 	if (mem < 0) {
1156 		debug("%s: Missing /memory node\n", __func__);
1157 		return -EINVAL;
1158 	}
1159 
1160 	ret = fdt_get_resource(gd->fdt_blob, mem, "reg", 0, &res);
1161 	if (ret != 0) {
1162 		debug("%s: Unable to decode first memory bank\n", __func__);
1163 		return -EINVAL;
1164 	}
1165 
1166 	gd->ram_size = (phys_size_t)(res.end - res.start + 1);
1167 	debug("%s: Initial DRAM size %llx\n", __func__,
1168 	      (unsigned long long)gd->ram_size);
1169 
1170 	return 0;
1171 }
1172 
1173 #if defined(CONFIG_NR_DRAM_BANKS)
1174 int fdtdec_setup_memory_banksize(void)
1175 {
1176 	int bank, ret, mem;
1177 	struct fdt_resource res;
1178 
1179 	mem = fdt_path_offset(gd->fdt_blob, "/memory");
1180 	if (mem < 0) {
1181 		debug("%s: Missing /memory node\n", __func__);
1182 		return -EINVAL;
1183 	}
1184 
1185 	for (bank = 0; bank < CONFIG_NR_DRAM_BANKS; bank++) {
1186 		ret = fdt_get_resource(gd->fdt_blob, mem, "reg", bank, &res);
1187 		if (ret == -FDT_ERR_NOTFOUND)
1188 			break;
1189 		if (ret != 0)
1190 			return -EINVAL;
1191 
1192 		gd->bd->bi_dram[bank].start = (phys_addr_t)res.start;
1193 		gd->bd->bi_dram[bank].size =
1194 			(phys_size_t)(res.end - res.start + 1);
1195 
1196 		debug("%s: DRAM Bank #%d: start = 0x%llx, size = 0x%llx\n",
1197 		      __func__, bank,
1198 		      (unsigned long long)gd->bd->bi_dram[bank].start,
1199 		      (unsigned long long)gd->bd->bi_dram[bank].size);
1200 	}
1201 
1202 	return 0;
1203 }
1204 #endif
1205 
1206 int fdtdec_setup(void)
1207 {
1208 #if CONFIG_IS_ENABLED(OF_CONTROL)
1209 # ifdef CONFIG_OF_EMBED
1210 	/* Get a pointer to the FDT */
1211 	gd->fdt_blob = __dtb_dt_begin;
1212 # elif defined CONFIG_OF_SEPARATE
1213 #  ifdef CONFIG_SPL_BUILD
1214 	/* FDT is at end of BSS unless it is in a different memory region */
1215 	if (IS_ENABLED(CONFIG_SPL_SEPARATE_BSS))
1216 		gd->fdt_blob = (ulong *)&_image_binary_end;
1217 	else
1218 		gd->fdt_blob = (ulong *)&__bss_end;
1219 
1220 #  elif defined CONFIG_FIT_EMBED
1221 	gd->fdt_blob = locate_dtb_in_fit(&_end);
1222 
1223 	if (gd->fdt_blob == NULL || gd->fdt_blob <= ((void *)&_end)) {
1224 		puts("Failed to find proper dtb in embedded FIT Image\n");
1225 		return -1;
1226 	}
1227 
1228 #  else
1229 	/* FDT is at end of image */
1230 	gd->fdt_blob = (ulong *)&_end;
1231 #  endif
1232 # elif defined(CONFIG_OF_BOARD)
1233 	/* Allow the board to override the fdt address. */
1234 	gd->fdt_blob = board_fdt_blob_setup();
1235 # elif defined(CONFIG_OF_HOSTFILE)
1236 	if (sandbox_read_fdt_from_file()) {
1237 		puts("Failed to read control FDT\n");
1238 		return -1;
1239 	}
1240 # endif
1241 # ifndef CONFIG_SPL_BUILD
1242 	/* Allow the early environment to override the fdt address */
1243 	gd->fdt_blob = (void *)getenv_ulong("fdtcontroladdr", 16,
1244 						(uintptr_t)gd->fdt_blob);
1245 # endif
1246 #endif
1247 	return fdtdec_prepare_fdt();
1248 }
1249 
1250 #endif /* !USE_HOSTCC */
1251