xref: /rk3399_rockchip-uboot/common/fdt_support.c (revision d156c9ff6fddc6358d6746127b8dc4e9ca224857)
1 /*
2  * (C) Copyright 2007
3  * Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com
4  *
5  * Copyright 2010-2011 Freescale Semiconductor, Inc.
6  *
7  * SPDX-License-Identifier:	GPL-2.0+
8  */
9 
10 #include <common.h>
11 #include <inttypes.h>
12 #include <stdio_dev.h>
13 #include <linux/ctype.h>
14 #include <linux/types.h>
15 #include <asm/global_data.h>
16 #include <libfdt.h>
17 #include <fdt_support.h>
18 #include <exports.h>
19 #include <fdtdec.h>
20 
21 /**
22  * fdt_getprop_u32_default_node - Return a node's property or a default
23  *
24  * @fdt: ptr to device tree
25  * @off: offset of node
26  * @cell: cell offset in property
27  * @prop: property name
28  * @dflt: default value if the property isn't found
29  *
30  * Convenience function to return a node's property or a default value if
31  * the property doesn't exist.
32  */
33 u32 fdt_getprop_u32_default_node(const void *fdt, int off, int cell,
34 				const char *prop, const u32 dflt)
35 {
36 	const fdt32_t *val;
37 	int len;
38 
39 	val = fdt_getprop(fdt, off, prop, &len);
40 
41 	/* Check if property exists */
42 	if (!val)
43 		return dflt;
44 
45 	/* Check if property is long enough */
46 	if (len < ((cell + 1) * sizeof(uint32_t)))
47 		return dflt;
48 
49 	return fdt32_to_cpu(*val);
50 }
51 
52 /**
53  * fdt_getprop_u32_default - Find a node and return it's property or a default
54  *
55  * @fdt: ptr to device tree
56  * @path: path of node
57  * @prop: property name
58  * @dflt: default value if the property isn't found
59  *
60  * Convenience function to find a node and return it's property or a
61  * default value if it doesn't exist.
62  */
63 u32 fdt_getprop_u32_default(const void *fdt, const char *path,
64 				const char *prop, const u32 dflt)
65 {
66 	int off;
67 
68 	off = fdt_path_offset(fdt, path);
69 	if (off < 0)
70 		return dflt;
71 
72 	return fdt_getprop_u32_default_node(fdt, off, 0, prop, dflt);
73 }
74 
75 /**
76  * fdt_find_and_setprop: Find a node and set it's property
77  *
78  * @fdt: ptr to device tree
79  * @node: path of node
80  * @prop: property name
81  * @val: ptr to new value
82  * @len: length of new property value
83  * @create: flag to create the property if it doesn't exist
84  *
85  * Convenience function to directly set a property given the path to the node.
86  */
87 int fdt_find_and_setprop(void *fdt, const char *node, const char *prop,
88 			 const void *val, int len, int create)
89 {
90 	int nodeoff = fdt_path_offset(fdt, node);
91 
92 	if (nodeoff < 0)
93 		return nodeoff;
94 
95 	if ((!create) && (fdt_get_property(fdt, nodeoff, prop, NULL) == NULL))
96 		return 0; /* create flag not set; so exit quietly */
97 
98 	return fdt_setprop(fdt, nodeoff, prop, val, len);
99 }
100 
101 /**
102  * fdt_find_or_add_subnode() - find or possibly add a subnode of a given node
103  *
104  * @fdt: pointer to the device tree blob
105  * @parentoffset: structure block offset of a node
106  * @name: name of the subnode to locate
107  *
108  * fdt_subnode_offset() finds a subnode of the node with a given name.
109  * If the subnode does not exist, it will be created.
110  */
111 int fdt_find_or_add_subnode(void *fdt, int parentoffset, const char *name)
112 {
113 	int offset;
114 
115 	offset = fdt_subnode_offset(fdt, parentoffset, name);
116 
117 	if (offset == -FDT_ERR_NOTFOUND)
118 		offset = fdt_add_subnode(fdt, parentoffset, name);
119 
120 	if (offset < 0)
121 		printf("%s: %s: %s\n", __func__, name, fdt_strerror(offset));
122 
123 	return offset;
124 }
125 
126 /* rename to CONFIG_OF_STDOUT_PATH ? */
127 #if defined(OF_STDOUT_PATH)
128 static int fdt_fixup_stdout(void *fdt, int chosenoff)
129 {
130 	return fdt_setprop(fdt, chosenoff, "linux,stdout-path",
131 			      OF_STDOUT_PATH, strlen(OF_STDOUT_PATH) + 1);
132 }
133 #elif defined(CONFIG_OF_STDOUT_VIA_ALIAS) && defined(CONFIG_CONS_INDEX)
134 static int fdt_fixup_stdout(void *fdt, int chosenoff)
135 {
136 	int err;
137 	int aliasoff;
138 	char sername[9] = { 0 };
139 	const void *path;
140 	int len;
141 	char tmp[256]; /* long enough */
142 
143 	sprintf(sername, "serial%d", CONFIG_CONS_INDEX - 1);
144 
145 	aliasoff = fdt_path_offset(fdt, "/aliases");
146 	if (aliasoff < 0) {
147 		err = aliasoff;
148 		goto noalias;
149 	}
150 
151 	path = fdt_getprop(fdt, aliasoff, sername, &len);
152 	if (!path) {
153 		err = len;
154 		goto noalias;
155 	}
156 
157 	/* fdt_setprop may break "path" so we copy it to tmp buffer */
158 	memcpy(tmp, path, len);
159 
160 	err = fdt_setprop(fdt, chosenoff, "linux,stdout-path", tmp, len);
161 	if (err < 0)
162 		printf("WARNING: could not set linux,stdout-path %s.\n",
163 		       fdt_strerror(err));
164 
165 	return err;
166 
167 noalias:
168 	printf("WARNING: %s: could not read %s alias: %s\n",
169 	       __func__, sername, fdt_strerror(err));
170 
171 	return 0;
172 }
173 #else
174 static int fdt_fixup_stdout(void *fdt, int chosenoff)
175 {
176 	return 0;
177 }
178 #endif
179 
180 static inline int fdt_setprop_uxx(void *fdt, int nodeoffset, const char *name,
181 				  uint64_t val, int is_u64)
182 {
183 	if (is_u64)
184 		return fdt_setprop_u64(fdt, nodeoffset, name, val);
185 	else
186 		return fdt_setprop_u32(fdt, nodeoffset, name, (uint32_t)val);
187 }
188 
189 int fdt_root(void *fdt)
190 {
191 	char *serial;
192 	int err;
193 
194 	err = fdt_check_header(fdt);
195 	if (err < 0) {
196 		printf("fdt_root: %s\n", fdt_strerror(err));
197 		return err;
198 	}
199 
200 	serial = env_get("serial#");
201 	if (serial) {
202 		err = fdt_setprop(fdt, 0, "serial-number", serial,
203 				  strlen(serial) + 1);
204 
205 		if (err < 0) {
206 			printf("WARNING: could not set serial-number %s.\n",
207 			       fdt_strerror(err));
208 			return err;
209 		}
210 	}
211 
212 	return 0;
213 }
214 
215 int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end)
216 {
217 	int   nodeoffset;
218 	int   err, j, total;
219 	int is_u64;
220 	uint64_t addr, size;
221 
222 	/* just return if the size of initrd is zero */
223 	if (initrd_start == initrd_end)
224 		return 0;
225 
226 	/* find or create "/chosen" node. */
227 	nodeoffset = fdt_find_or_add_subnode(fdt, 0, "chosen");
228 	if (nodeoffset < 0)
229 		return nodeoffset;
230 
231 	total = fdt_num_mem_rsv(fdt);
232 
233 	/*
234 	 * Look for an existing entry and update it.  If we don't find
235 	 * the entry, we will j be the next available slot.
236 	 */
237 	for (j = 0; j < total; j++) {
238 		err = fdt_get_mem_rsv(fdt, j, &addr, &size);
239 		if (addr == initrd_start) {
240 			fdt_del_mem_rsv(fdt, j);
241 			break;
242 		}
243 	}
244 
245 	err = fdt_add_mem_rsv(fdt, initrd_start, initrd_end - initrd_start);
246 	if (err < 0) {
247 		printf("fdt_initrd: %s\n", fdt_strerror(err));
248 		return err;
249 	}
250 
251 	is_u64 = (fdt_address_cells(fdt, 0) == 2);
252 
253 	err = fdt_setprop_uxx(fdt, nodeoffset, "linux,initrd-start",
254 			      (uint64_t)initrd_start, is_u64);
255 
256 	if (err < 0) {
257 		printf("WARNING: could not set linux,initrd-start %s.\n",
258 		       fdt_strerror(err));
259 		return err;
260 	}
261 
262 	err = fdt_setprop_uxx(fdt, nodeoffset, "linux,initrd-end",
263 			      (uint64_t)initrd_end, is_u64);
264 
265 	if (err < 0) {
266 		printf("WARNING: could not set linux,initrd-end %s.\n",
267 		       fdt_strerror(err));
268 
269 		return err;
270 	}
271 
272 	return 0;
273 }
274 
275 int fdt_chosen(void *fdt)
276 {
277 	/*
278 	 * "bootargs_ext" is used when dtbo is applied.
279 	 */
280 	const char *arr_bootargs[] = { "bootargs", "bootargs_ext" };
281 	int   nodeoffset;
282 	int   err;
283 	int   i;
284 	char  *str;		/* used to set string properties */
285 
286 	err = fdt_check_header(fdt);
287 	if (err < 0) {
288 		printf("fdt_chosen: %s\n", fdt_strerror(err));
289 		return err;
290 	}
291 
292 	/* find or create "/chosen" node. */
293 	nodeoffset = fdt_find_or_add_subnode(fdt, 0, "chosen");
294 	if (nodeoffset < 0)
295 		return nodeoffset;
296 
297 	str = env_get("bootargs");
298 	if (str) {
299 #ifdef CONFIG_ARCH_ROCKCHIP
300 		const char *bootargs;
301 
302 		for (i = 0; i < ARRAY_SIZE(arr_bootargs); i++) {
303 			bootargs = fdt_getprop(fdt, nodeoffset,
304 					       arr_bootargs[i], NULL);
305 			if (bootargs) {
306 				/*
307 				 * Append kernel bootargs
308 				 * If use AB system, delete default "root=" which route
309 				 * to rootfs. Then the ab bootctl will choose the
310 				 * high priority system to boot and add its UUID
311 				 * to cmdline. The format is "roo=PARTUUID=xxxx...".
312 				 */
313 #ifdef CONFIG_ANDROID_AB
314 				env_update_filter("bootargs", bootargs, "root=");
315 #else
316 				/*
317 				 * Initrd fixup: remove unused "initrd=0x...,0x...",
318 				 * this for compatible with legacy parameter.txt
319 				 */
320 				env_update_filter("bootargs", bootargs, "initrd=");
321 #endif
322 			}
323 #endif
324 		}
325 
326 		str = env_get("bootargs");
327 		err = fdt_setprop(fdt, nodeoffset, "bootargs", str,
328 				  strlen(str) + 1);
329 		if (err < 0) {
330 			printf("WARNING: could not set bootargs %s.\n",
331 			       fdt_strerror(err));
332 			return err;
333 		}
334 	}
335 
336 	debug("bootargs = %s\n", env_get("bootargs"));
337 
338 	return fdt_fixup_stdout(fdt, nodeoffset);
339 }
340 
341 void do_fixup_by_path(void *fdt, const char *path, const char *prop,
342 		      const void *val, int len, int create)
343 {
344 #if defined(DEBUG)
345 	int i;
346 	debug("Updating property '%s/%s' = ", path, prop);
347 	for (i = 0; i < len; i++)
348 		debug(" %.2x", *(u8*)(val+i));
349 	debug("\n");
350 #endif
351 	int rc = fdt_find_and_setprop(fdt, path, prop, val, len, create);
352 	if (rc)
353 		printf("Unable to update property %s:%s, err=%s\n",
354 			path, prop, fdt_strerror(rc));
355 }
356 
357 void do_fixup_by_path_u32(void *fdt, const char *path, const char *prop,
358 			  u32 val, int create)
359 {
360 	fdt32_t tmp = cpu_to_fdt32(val);
361 	do_fixup_by_path(fdt, path, prop, &tmp, sizeof(tmp), create);
362 }
363 
364 void do_fixup_by_prop(void *fdt,
365 		      const char *pname, const void *pval, int plen,
366 		      const char *prop, const void *val, int len,
367 		      int create)
368 {
369 	int off;
370 #if defined(DEBUG)
371 	int i;
372 	debug("Updating property '%s' = ", prop);
373 	for (i = 0; i < len; i++)
374 		debug(" %.2x", *(u8*)(val+i));
375 	debug("\n");
376 #endif
377 	off = fdt_node_offset_by_prop_value(fdt, -1, pname, pval, plen);
378 	while (off != -FDT_ERR_NOTFOUND) {
379 		if (create || (fdt_get_property(fdt, off, prop, NULL) != NULL))
380 			fdt_setprop(fdt, off, prop, val, len);
381 		off = fdt_node_offset_by_prop_value(fdt, off, pname, pval, plen);
382 	}
383 }
384 
385 void do_fixup_by_prop_u32(void *fdt,
386 			  const char *pname, const void *pval, int plen,
387 			  const char *prop, u32 val, int create)
388 {
389 	fdt32_t tmp = cpu_to_fdt32(val);
390 	do_fixup_by_prop(fdt, pname, pval, plen, prop, &tmp, 4, create);
391 }
392 
393 void do_fixup_by_compat(void *fdt, const char *compat,
394 			const char *prop, const void *val, int len, int create)
395 {
396 	int off = -1;
397 #if defined(DEBUG)
398 	int i;
399 	debug("Updating property '%s' = ", prop);
400 	for (i = 0; i < len; i++)
401 		debug(" %.2x", *(u8*)(val+i));
402 	debug("\n");
403 #endif
404 	off = fdt_node_offset_by_compatible(fdt, -1, compat);
405 	while (off != -FDT_ERR_NOTFOUND) {
406 		if (create || (fdt_get_property(fdt, off, prop, NULL) != NULL))
407 			fdt_setprop(fdt, off, prop, val, len);
408 		off = fdt_node_offset_by_compatible(fdt, off, compat);
409 	}
410 }
411 
412 void do_fixup_by_compat_u32(void *fdt, const char *compat,
413 			    const char *prop, u32 val, int create)
414 {
415 	fdt32_t tmp = cpu_to_fdt32(val);
416 	do_fixup_by_compat(fdt, compat, prop, &tmp, 4, create);
417 }
418 
419 #ifdef CONFIG_ARCH_FIXUP_FDT_MEMORY
420 /*
421  * fdt_pack_reg - pack address and size array into the "reg"-suitable stream
422  */
423 static int fdt_pack_reg(const void *fdt, void *buf, u64 *address, u64 *size,
424 			int n)
425 {
426 	int i;
427 	int address_cells = fdt_address_cells(fdt, 0);
428 	int size_cells = fdt_size_cells(fdt, 0);
429 	char *p = buf;
430 
431 	for (i = 0; i < n; i++) {
432 		if (address_cells == 2)
433 			*(fdt64_t *)p = cpu_to_fdt64(address[i]);
434 		else
435 			*(fdt32_t *)p = cpu_to_fdt32(address[i]);
436 		p += 4 * address_cells;
437 
438 		if (size_cells == 2)
439 			*(fdt64_t *)p = cpu_to_fdt64(size[i]);
440 		else
441 			*(fdt32_t *)p = cpu_to_fdt32(size[i]);
442 		p += 4 * size_cells;
443 	}
444 
445 	return p - (char *)buf;
446 }
447 
448 int fdt_record_loadable(void *blob, u32 index, const char *name,
449 			uintptr_t load_addr, u32 size, uintptr_t entry_point,
450 			const char *type, const char *os)
451 {
452 	int err, node;
453 
454 	err = fdt_check_header(blob);
455 	if (err < 0) {
456 		printf("%s: %s\n", __func__, fdt_strerror(err));
457 		return err;
458 	}
459 
460 	/* find or create "/fit-images" node */
461 	node = fdt_find_or_add_subnode(blob, 0, "fit-images");
462 	if (node < 0)
463 			return node;
464 
465 	/* find or create "/fit-images/<name>" node */
466 	node = fdt_find_or_add_subnode(blob, node, name);
467 	if (node < 0)
468 		return node;
469 
470 	/*
471 	 * We record these as 32bit entities, possibly truncating addresses.
472 	 * However, spl_fit.c is not 64bit safe either: i.e. we should not
473 	 * have an issue here.
474 	 */
475 	fdt_setprop_u32(blob, node, "load-addr", load_addr);
476 	if (entry_point != -1)
477 		fdt_setprop_u32(blob, node, "entry-point", entry_point);
478 	fdt_setprop_u32(blob, node, "size", size);
479 	if (type)
480 		fdt_setprop_string(blob, node, "type", type);
481 	if (os)
482 		fdt_setprop_string(blob, node, "os", os);
483 
484 	return node;
485 }
486 
487 #ifdef CONFIG_NR_DRAM_BANKS
488 #define MEMORY_BANKS_MAX CONFIG_NR_DRAM_BANKS
489 #else
490 #define MEMORY_BANKS_MAX 4
491 #endif
492 int fdt_fixup_memory_banks(void *blob, u64 start[], u64 size[], int banks)
493 {
494 	int err, nodeoffset;
495 	int len;
496 	u8 tmp[MEMORY_BANKS_MAX * 16]; /* Up to 64-bit address + 64-bit size */
497 
498 	if (banks > MEMORY_BANKS_MAX) {
499 		printf("%s: num banks %d exceeds hardcoded limit %d."
500 		       " Recompile with higher MEMORY_BANKS_MAX?\n",
501 		       __FUNCTION__, banks, MEMORY_BANKS_MAX);
502 		return -1;
503 	}
504 
505 	err = fdt_check_header(blob);
506 	if (err < 0) {
507 		printf("%s: %s\n", __FUNCTION__, fdt_strerror(err));
508 		return err;
509 	}
510 
511 	/* find or create "/memory" node. */
512 	nodeoffset = fdt_find_or_add_subnode(blob, 0, "memory");
513 	if (nodeoffset < 0)
514 			return nodeoffset;
515 
516 	err = fdt_setprop(blob, nodeoffset, "device_type", "memory",
517 			sizeof("memory"));
518 	if (err < 0) {
519 		printf("WARNING: could not set %s %s.\n", "device_type",
520 				fdt_strerror(err));
521 		return err;
522 	}
523 
524 	if (!banks)
525 		return 0;
526 
527 	len = fdt_pack_reg(blob, tmp, start, size, banks);
528 
529 	err = fdt_setprop(blob, nodeoffset, "reg", tmp, len);
530 	if (err < 0) {
531 		printf("WARNING: could not set %s %s.\n",
532 				"reg", fdt_strerror(err));
533 		return err;
534 	}
535 	return 0;
536 }
537 #endif
538 
539 int fdt_fixup_memory(void *blob, u64 start, u64 size)
540 {
541 	return fdt_fixup_memory_banks(blob, &start, &size, 1);
542 }
543 
544 int fdt_update_reserved_memory(void *blob, char *name, u64 start, u64 size)
545 {
546 	int nodeoffset, len, err;
547 	u8 tmp[16]; /* Up to 64-bit address + 64-bit size */
548 
549 #if 0
550 	/*name is rockchip_logo*/
551 	nodeoffset = fdt_find_or_add_subnode(blob, 0, "reserved-memory");
552 	if (nodeoffset < 0)
553 		return nodeoffset;
554 	printf("hjc>>reserved-memory>>%s, nodeoffset:%d\n", __func__, nodeoffset);
555 	nodeoffset = fdt_find_or_add_subnode(blob, nodeoffset, name);
556 	if (nodeoffset < 0)
557 		return nodeoffset;
558 #else
559 	nodeoffset = fdt_node_offset_by_compatible(blob, 0, name);
560 	if (nodeoffset < 0)
561 		debug("Can't find nodeoffset: %d\n", nodeoffset);
562 #endif
563 	len = fdt_pack_reg(blob, tmp, &start, &size, 1);
564 	err = fdt_setprop(blob, nodeoffset, "reg", tmp, len);
565 	if (err < 0) {
566 		printf("WARNING: could not set %s %s.\n",
567 				"reg", fdt_strerror(err));
568 		return err;
569 	}
570 
571 	return nodeoffset;
572 }
573 
574 void fdt_fixup_ethernet(void *fdt)
575 {
576 	int i = 0, j, prop;
577 	char *tmp, *end;
578 	char mac[16];
579 	const char *path;
580 	unsigned char mac_addr[ARP_HLEN];
581 	int offset;
582 #ifdef FDT_SEQ_MACADDR_FROM_ENV
583 	int nodeoff;
584 	const struct fdt_property *fdt_prop;
585 #endif
586 
587 	if (fdt_path_offset(fdt, "/aliases") < 0)
588 		return;
589 
590 	/* Cycle through all aliases */
591 	for (prop = 0; ; prop++) {
592 		const char *name;
593 
594 		/* FDT might have been edited, recompute the offset */
595 		offset = fdt_first_property_offset(fdt,
596 			fdt_path_offset(fdt, "/aliases"));
597 		/* Select property number 'prop' */
598 		for (j = 0; j < prop; j++)
599 			offset = fdt_next_property_offset(fdt, offset);
600 
601 		if (offset < 0)
602 			break;
603 
604 		path = fdt_getprop_by_offset(fdt, offset, &name, NULL);
605 		if (!strncmp(name, "ethernet", 8)) {
606 			/* Treat plain "ethernet" same as "ethernet0". */
607 			if (!strcmp(name, "ethernet")
608 #ifdef FDT_SEQ_MACADDR_FROM_ENV
609 			 || !strcmp(name, "ethernet0")
610 #endif
611 			)
612 				i = 0;
613 #ifndef FDT_SEQ_MACADDR_FROM_ENV
614 			else
615 				i = trailing_strtol(name);
616 #endif
617 			if (i != -1) {
618 				if (i == 0)
619 					strcpy(mac, "ethaddr");
620 				else
621 					sprintf(mac, "eth%daddr", i);
622 			} else {
623 				continue;
624 			}
625 #ifdef FDT_SEQ_MACADDR_FROM_ENV
626 			nodeoff = fdt_path_offset(fdt, path);
627 			fdt_prop = fdt_get_property(fdt, nodeoff, "status",
628 						    NULL);
629 			if (fdt_prop && !strcmp(fdt_prop->data, "disabled"))
630 				continue;
631 			i++;
632 #endif
633 			tmp = env_get(mac);
634 			if (!tmp)
635 				continue;
636 
637 			for (j = 0; j < 6; j++) {
638 				mac_addr[j] = tmp ?
639 					      simple_strtoul(tmp, &end, 16) : 0;
640 				if (tmp)
641 					tmp = (*end) ? end + 1 : end;
642 			}
643 
644 			do_fixup_by_path(fdt, path, "mac-address",
645 					 &mac_addr, 6, 0);
646 			do_fixup_by_path(fdt, path, "local-mac-address",
647 					 &mac_addr, 6, 1);
648 		}
649 	}
650 }
651 
652 /* Resize the fdt to its actual size + a bit of padding */
653 int fdt_shrink_to_minimum(void *blob, uint extrasize)
654 {
655 	int i;
656 	uint64_t addr, size;
657 	int total, ret;
658 	uint actualsize;
659 
660 	if (!blob)
661 		return 0;
662 
663 	total = fdt_num_mem_rsv(blob);
664 	for (i = 0; i < total; i++) {
665 		fdt_get_mem_rsv(blob, i, &addr, &size);
666 		if (addr == (uintptr_t)blob) {
667 			fdt_del_mem_rsv(blob, i);
668 			break;
669 		}
670 	}
671 
672 	/*
673 	 * Calculate the actual size of the fdt
674 	 * plus the size needed for 5 fdt_add_mem_rsv, one
675 	 * for the fdt itself and 4 for a possible initrd
676 	 * ((initrd-start + initrd-end) * 2 (name & value))
677 	 */
678 	actualsize = fdt_off_dt_strings(blob) +
679 		fdt_size_dt_strings(blob) + 5 * sizeof(struct fdt_reserve_entry);
680 
681 	actualsize += extrasize;
682 	/* Make it so the fdt ends on a page boundary */
683 	actualsize = ALIGN(actualsize + ((uintptr_t)blob & 0xfff), 0x1000);
684 	actualsize = actualsize - ((uintptr_t)blob & 0xfff);
685 
686 	/* Change the fdt header to reflect the correct size */
687 	fdt_set_totalsize(blob, actualsize);
688 
689 	/* Add the new reservation */
690 	ret = fdt_add_mem_rsv(blob, (uintptr_t)blob, actualsize);
691 	if (ret < 0)
692 		return ret;
693 
694 	return actualsize;
695 }
696 
697 #ifdef CONFIG_PCI
698 #define CONFIG_SYS_PCI_NR_INBOUND_WIN 4
699 
700 #define FDT_PCI_PREFETCH	(0x40000000)
701 #define FDT_PCI_MEM32		(0x02000000)
702 #define FDT_PCI_IO		(0x01000000)
703 #define FDT_PCI_MEM64		(0x03000000)
704 
705 int fdt_pci_dma_ranges(void *blob, int phb_off, struct pci_controller *hose) {
706 
707 	int addrcell, sizecell, len, r;
708 	u32 *dma_range;
709 	/* sized based on pci addr cells, size-cells, & address-cells */
710 	u32 dma_ranges[(3 + 2 + 2) * CONFIG_SYS_PCI_NR_INBOUND_WIN];
711 
712 	addrcell = fdt_getprop_u32_default(blob, "/", "#address-cells", 1);
713 	sizecell = fdt_getprop_u32_default(blob, "/", "#size-cells", 1);
714 
715 	dma_range = &dma_ranges[0];
716 	for (r = 0; r < hose->region_count; r++) {
717 		u64 bus_start, phys_start, size;
718 
719 		/* skip if !PCI_REGION_SYS_MEMORY */
720 		if (!(hose->regions[r].flags & PCI_REGION_SYS_MEMORY))
721 			continue;
722 
723 		bus_start = (u64)hose->regions[r].bus_start;
724 		phys_start = (u64)hose->regions[r].phys_start;
725 		size = (u64)hose->regions[r].size;
726 
727 		dma_range[0] = 0;
728 		if (size >= 0x100000000ull)
729 			dma_range[0] |= FDT_PCI_MEM64;
730 		else
731 			dma_range[0] |= FDT_PCI_MEM32;
732 		if (hose->regions[r].flags & PCI_REGION_PREFETCH)
733 			dma_range[0] |= FDT_PCI_PREFETCH;
734 #ifdef CONFIG_SYS_PCI_64BIT
735 		dma_range[1] = bus_start >> 32;
736 #else
737 		dma_range[1] = 0;
738 #endif
739 		dma_range[2] = bus_start & 0xffffffff;
740 
741 		if (addrcell == 2) {
742 			dma_range[3] = phys_start >> 32;
743 			dma_range[4] = phys_start & 0xffffffff;
744 		} else {
745 			dma_range[3] = phys_start & 0xffffffff;
746 		}
747 
748 		if (sizecell == 2) {
749 			dma_range[3 + addrcell + 0] = size >> 32;
750 			dma_range[3 + addrcell + 1] = size & 0xffffffff;
751 		} else {
752 			dma_range[3 + addrcell + 0] = size & 0xffffffff;
753 		}
754 
755 		dma_range += (3 + addrcell + sizecell);
756 	}
757 
758 	len = dma_range - &dma_ranges[0];
759 	if (len)
760 		fdt_setprop(blob, phb_off, "dma-ranges", &dma_ranges[0], len*4);
761 
762 	return 0;
763 }
764 #endif
765 
766 int fdt_increase_size(void *fdt, int add_len)
767 {
768 	int newlen;
769 
770 	newlen = fdt_totalsize(fdt) + add_len;
771 
772 	/* Open in place with a new len */
773 	return fdt_open_into(fdt, fdt, newlen);
774 }
775 
776 #ifdef CONFIG_FDT_FIXUP_PARTITIONS
777 #include <jffs2/load_kernel.h>
778 #include <mtd_node.h>
779 
780 struct reg_cell {
781 	unsigned int r0;
782 	unsigned int r1;
783 };
784 
785 int fdt_del_subnodes(const void *blob, int parent_offset)
786 {
787 	int off, ndepth;
788 	int ret;
789 
790 	for (ndepth = 0, off = fdt_next_node(blob, parent_offset, &ndepth);
791 	     (off >= 0) && (ndepth > 0);
792 	     off = fdt_next_node(blob, off, &ndepth)) {
793 		if (ndepth == 1) {
794 			debug("delete %s: offset: %x\n",
795 				fdt_get_name(blob, off, 0), off);
796 			ret = fdt_del_node((void *)blob, off);
797 			if (ret < 0) {
798 				printf("Can't delete node: %s\n",
799 					fdt_strerror(ret));
800 				return ret;
801 			} else {
802 				ndepth = 0;
803 				off = parent_offset;
804 			}
805 		}
806 	}
807 	return 0;
808 }
809 
810 int fdt_del_partitions(void *blob, int parent_offset)
811 {
812 	const void *prop;
813 	int ndepth = 0;
814 	int off;
815 	int ret;
816 
817 	off = fdt_next_node(blob, parent_offset, &ndepth);
818 	if (off > 0 && ndepth == 1) {
819 		prop = fdt_getprop(blob, off, "label", NULL);
820 		if (prop == NULL) {
821 			/*
822 			 * Could not find label property, nand {}; node?
823 			 * Check subnode, delete partitions there if any.
824 			 */
825 			return fdt_del_partitions(blob, off);
826 		} else {
827 			ret = fdt_del_subnodes(blob, parent_offset);
828 			if (ret < 0) {
829 				printf("Can't remove subnodes: %s\n",
830 					fdt_strerror(ret));
831 				return ret;
832 			}
833 		}
834 	}
835 	return 0;
836 }
837 
838 int fdt_node_set_part_info(void *blob, int parent_offset,
839 			   struct mtd_device *dev)
840 {
841 	struct list_head *pentry;
842 	struct part_info *part;
843 	struct reg_cell cell;
844 	int off, ndepth = 0;
845 	int part_num, ret;
846 	char buf[64];
847 
848 	ret = fdt_del_partitions(blob, parent_offset);
849 	if (ret < 0)
850 		return ret;
851 
852 	/*
853 	 * Check if it is nand {}; subnode, adjust
854 	 * the offset in this case
855 	 */
856 	off = fdt_next_node(blob, parent_offset, &ndepth);
857 	if (off > 0 && ndepth == 1)
858 		parent_offset = off;
859 
860 	part_num = 0;
861 	list_for_each_prev(pentry, &dev->parts) {
862 		int newoff;
863 
864 		part = list_entry(pentry, struct part_info, link);
865 
866 		debug("%2d: %-20s0x%08llx\t0x%08llx\t%d\n",
867 			part_num, part->name, part->size,
868 			part->offset, part->mask_flags);
869 
870 		sprintf(buf, "partition@%llx", part->offset);
871 add_sub:
872 		ret = fdt_add_subnode(blob, parent_offset, buf);
873 		if (ret == -FDT_ERR_NOSPACE) {
874 			ret = fdt_increase_size(blob, 512);
875 			if (!ret)
876 				goto add_sub;
877 			else
878 				goto err_size;
879 		} else if (ret < 0) {
880 			printf("Can't add partition node: %s\n",
881 				fdt_strerror(ret));
882 			return ret;
883 		}
884 		newoff = ret;
885 
886 		/* Check MTD_WRITEABLE_CMD flag */
887 		if (part->mask_flags & 1) {
888 add_ro:
889 			ret = fdt_setprop(blob, newoff, "read_only", NULL, 0);
890 			if (ret == -FDT_ERR_NOSPACE) {
891 				ret = fdt_increase_size(blob, 512);
892 				if (!ret)
893 					goto add_ro;
894 				else
895 					goto err_size;
896 			} else if (ret < 0)
897 				goto err_prop;
898 		}
899 
900 		cell.r0 = cpu_to_fdt32(part->offset);
901 		cell.r1 = cpu_to_fdt32(part->size);
902 add_reg:
903 		ret = fdt_setprop(blob, newoff, "reg", &cell, sizeof(cell));
904 		if (ret == -FDT_ERR_NOSPACE) {
905 			ret = fdt_increase_size(blob, 512);
906 			if (!ret)
907 				goto add_reg;
908 			else
909 				goto err_size;
910 		} else if (ret < 0)
911 			goto err_prop;
912 
913 add_label:
914 		ret = fdt_setprop_string(blob, newoff, "label", part->name);
915 		if (ret == -FDT_ERR_NOSPACE) {
916 			ret = fdt_increase_size(blob, 512);
917 			if (!ret)
918 				goto add_label;
919 			else
920 				goto err_size;
921 		} else if (ret < 0)
922 			goto err_prop;
923 
924 		part_num++;
925 	}
926 	return 0;
927 err_size:
928 	printf("Can't increase blob size: %s\n", fdt_strerror(ret));
929 	return ret;
930 err_prop:
931 	printf("Can't add property: %s\n", fdt_strerror(ret));
932 	return ret;
933 }
934 
935 /*
936  * Update partitions in nor/nand nodes using info from
937  * mtdparts environment variable. The nodes to update are
938  * specified by node_info structure which contains mtd device
939  * type and compatible string: E. g. the board code in
940  * ft_board_setup() could use:
941  *
942  *	struct node_info nodes[] = {
943  *		{ "fsl,mpc5121-nfc",    MTD_DEV_TYPE_NAND, },
944  *		{ "cfi-flash",          MTD_DEV_TYPE_NOR,  },
945  *	};
946  *
947  *	fdt_fixup_mtdparts(blob, nodes, ARRAY_SIZE(nodes));
948  */
949 void fdt_fixup_mtdparts(void *blob, void *node_info, int node_info_size)
950 {
951 	struct node_info *ni = node_info;
952 	struct mtd_device *dev;
953 	int i, idx;
954 	int noff;
955 
956 	if (mtdparts_init() != 0)
957 		return;
958 
959 	for (i = 0; i < node_info_size; i++) {
960 		idx = 0;
961 		noff = fdt_node_offset_by_compatible(blob, -1, ni[i].compat);
962 		while (noff != -FDT_ERR_NOTFOUND) {
963 			debug("%s: %s, mtd dev type %d\n",
964 				fdt_get_name(blob, noff, 0),
965 				ni[i].compat, ni[i].type);
966 			dev = device_find(ni[i].type, idx++);
967 			if (dev) {
968 				if (fdt_node_set_part_info(blob, noff, dev))
969 					return; /* return on error */
970 			}
971 
972 			/* Jump to next flash node */
973 			noff = fdt_node_offset_by_compatible(blob, noff,
974 							     ni[i].compat);
975 		}
976 	}
977 }
978 #endif
979 
980 void fdt_del_node_and_alias(void *blob, const char *alias)
981 {
982 	int off = fdt_path_offset(blob, alias);
983 
984 	if (off < 0)
985 		return;
986 
987 	fdt_del_node(blob, off);
988 
989 	off = fdt_path_offset(blob, "/aliases");
990 	fdt_delprop(blob, off, alias);
991 }
992 
993 /* Max address size we deal with */
994 #define OF_MAX_ADDR_CELLS	4
995 #define OF_BAD_ADDR	FDT_ADDR_T_NONE
996 #define OF_CHECK_COUNTS(na, ns)	((na) > 0 && (na) <= OF_MAX_ADDR_CELLS && \
997 			(ns) > 0)
998 
999 /* Debug utility */
1000 #ifdef DEBUG
1001 static void of_dump_addr(const char *s, const fdt32_t *addr, int na)
1002 {
1003 	printf("%s", s);
1004 	while(na--)
1005 		printf(" %08x", *(addr++));
1006 	printf("\n");
1007 }
1008 #else
1009 static void of_dump_addr(const char *s, const fdt32_t *addr, int na) { }
1010 #endif
1011 
1012 /**
1013  * struct of_bus - Callbacks for bus specific translators
1014  * @name:	A string used to identify this bus in debug output.
1015  * @addresses:	The name of the DT property from which addresses are
1016  *		to be read, typically "reg".
1017  * @match:	Return non-zero if the node whose parent is at
1018  *		parentoffset in the FDT blob corresponds to a bus
1019  *		of this type, otherwise return zero. If NULL a match
1020  *		is assumed.
1021  * @count_cells:Count how many cells (be32 values) a node whose parent
1022  *		is at parentoffset in the FDT blob will require to
1023  *		represent its address (written to *addrc) & size
1024  *		(written to *sizec).
1025  * @map:	Map the address addr from the address space of this
1026  *		bus to that of its parent, making use of the ranges
1027  *		read from DT to an array at range. na and ns are the
1028  *		number of cells (be32 values) used to hold and address
1029  *		or size, respectively, for this bus. pna is the number
1030  *		of cells used to hold an address for the parent bus.
1031  *		Returns the address in the address space of the parent
1032  *		bus.
1033  * @translate:	Update the value of the address cells at addr within an
1034  *		FDT by adding offset to it. na specifies the number of
1035  *		cells used to hold the address being translated. Returns
1036  *		zero on success, non-zero on error.
1037  *
1038  * Each bus type will include a struct of_bus in the of_busses array,
1039  * providing implementations of some or all of the functions used to
1040  * match the bus & handle address translation for its children.
1041  */
1042 struct of_bus {
1043 	const char	*name;
1044 	const char	*addresses;
1045 	int		(*match)(const void *blob, int parentoffset);
1046 	void		(*count_cells)(const void *blob, int parentoffset,
1047 				int *addrc, int *sizec);
1048 	u64		(*map)(fdt32_t *addr, const fdt32_t *range,
1049 				int na, int ns, int pna);
1050 	int		(*translate)(fdt32_t *addr, u64 offset, int na);
1051 };
1052 
1053 /* Default translator (generic bus) */
1054 void fdt_support_default_count_cells(const void *blob, int parentoffset,
1055 					int *addrc, int *sizec)
1056 {
1057 	const fdt32_t *prop;
1058 
1059 	if (addrc)
1060 		*addrc = fdt_address_cells(blob, parentoffset);
1061 
1062 	if (sizec) {
1063 		prop = fdt_getprop(blob, parentoffset, "#size-cells", NULL);
1064 		if (prop)
1065 			*sizec = be32_to_cpup(prop);
1066 		else
1067 			*sizec = 1;
1068 	}
1069 }
1070 
1071 static u64 of_bus_default_map(fdt32_t *addr, const fdt32_t *range,
1072 		int na, int ns, int pna)
1073 {
1074 	u64 cp, s, da;
1075 
1076 	cp = fdt_read_number(range, na);
1077 	s  = fdt_read_number(range + na + pna, ns);
1078 	da = fdt_read_number(addr, na);
1079 
1080 	debug("OF: default map, cp=%" PRIu64 ", s=%" PRIu64
1081 	      ", da=%" PRIu64 "\n", cp, s, da);
1082 
1083 	if (da < cp || da >= (cp + s))
1084 		return OF_BAD_ADDR;
1085 	return da - cp;
1086 }
1087 
1088 static int of_bus_default_translate(fdt32_t *addr, u64 offset, int na)
1089 {
1090 	u64 a = fdt_read_number(addr, na);
1091 	memset(addr, 0, na * 4);
1092 	a += offset;
1093 	if (na > 1)
1094 		addr[na - 2] = cpu_to_fdt32(a >> 32);
1095 	addr[na - 1] = cpu_to_fdt32(a & 0xffffffffu);
1096 
1097 	return 0;
1098 }
1099 
1100 #ifdef CONFIG_OF_ISA_BUS
1101 
1102 /* ISA bus translator */
1103 static int of_bus_isa_match(const void *blob, int parentoffset)
1104 {
1105 	const char *name;
1106 
1107 	name = fdt_get_name(blob, parentoffset, NULL);
1108 	if (!name)
1109 		return 0;
1110 
1111 	return !strcmp(name, "isa");
1112 }
1113 
1114 static void of_bus_isa_count_cells(const void *blob, int parentoffset,
1115 				   int *addrc, int *sizec)
1116 {
1117 	if (addrc)
1118 		*addrc = 2;
1119 	if (sizec)
1120 		*sizec = 1;
1121 }
1122 
1123 static u64 of_bus_isa_map(fdt32_t *addr, const fdt32_t *range,
1124 			  int na, int ns, int pna)
1125 {
1126 	u64 cp, s, da;
1127 
1128 	/* Check address type match */
1129 	if ((addr[0] ^ range[0]) & cpu_to_be32(1))
1130 		return OF_BAD_ADDR;
1131 
1132 	cp = fdt_read_number(range + 1, na - 1);
1133 	s  = fdt_read_number(range + na + pna, ns);
1134 	da = fdt_read_number(addr + 1, na - 1);
1135 
1136 	debug("OF: ISA map, cp=%" PRIu64 ", s=%" PRIu64
1137 	      ", da=%" PRIu64 "\n", cp, s, da);
1138 
1139 	if (da < cp || da >= (cp + s))
1140 		return OF_BAD_ADDR;
1141 	return da - cp;
1142 }
1143 
1144 static int of_bus_isa_translate(fdt32_t *addr, u64 offset, int na)
1145 {
1146 	return of_bus_default_translate(addr + 1, offset, na - 1);
1147 }
1148 
1149 #endif /* CONFIG_OF_ISA_BUS */
1150 
1151 /* Array of bus specific translators */
1152 static struct of_bus of_busses[] = {
1153 #ifdef CONFIG_OF_ISA_BUS
1154 	/* ISA */
1155 	{
1156 		.name = "isa",
1157 		.addresses = "reg",
1158 		.match = of_bus_isa_match,
1159 		.count_cells = of_bus_isa_count_cells,
1160 		.map = of_bus_isa_map,
1161 		.translate = of_bus_isa_translate,
1162 	},
1163 #endif /* CONFIG_OF_ISA_BUS */
1164 	/* Default */
1165 	{
1166 		.name = "default",
1167 		.addresses = "reg",
1168 		.count_cells = fdt_support_default_count_cells,
1169 		.map = of_bus_default_map,
1170 		.translate = of_bus_default_translate,
1171 	},
1172 };
1173 
1174 static struct of_bus *of_match_bus(const void *blob, int parentoffset)
1175 {
1176 	struct of_bus *bus;
1177 
1178 	if (ARRAY_SIZE(of_busses) == 1)
1179 		return of_busses;
1180 
1181 	for (bus = of_busses; bus; bus++) {
1182 		if (!bus->match || bus->match(blob, parentoffset))
1183 			return bus;
1184 	}
1185 
1186 	/*
1187 	 * We should always have matched the default bus at least, since
1188 	 * it has a NULL match field. If we didn't then it somehow isn't
1189 	 * in the of_busses array or something equally catastrophic has
1190 	 * gone wrong.
1191 	 */
1192 	assert(0);
1193 	return NULL;
1194 }
1195 
1196 static int of_translate_one(const void *blob, int parent, struct of_bus *bus,
1197 			    struct of_bus *pbus, fdt32_t *addr,
1198 			    int na, int ns, int pna, const char *rprop)
1199 {
1200 	const fdt32_t *ranges;
1201 	int rlen;
1202 	int rone;
1203 	u64 offset = OF_BAD_ADDR;
1204 
1205 	/* Normally, an absence of a "ranges" property means we are
1206 	 * crossing a non-translatable boundary, and thus the addresses
1207 	 * below the current not cannot be converted to CPU physical ones.
1208 	 * Unfortunately, while this is very clear in the spec, it's not
1209 	 * what Apple understood, and they do have things like /uni-n or
1210 	 * /ht nodes with no "ranges" property and a lot of perfectly
1211 	 * useable mapped devices below them. Thus we treat the absence of
1212 	 * "ranges" as equivalent to an empty "ranges" property which means
1213 	 * a 1:1 translation at that level. It's up to the caller not to try
1214 	 * to translate addresses that aren't supposed to be translated in
1215 	 * the first place. --BenH.
1216 	 */
1217 	ranges = fdt_getprop(blob, parent, rprop, &rlen);
1218 	if (ranges == NULL || rlen == 0) {
1219 		offset = fdt_read_number(addr, na);
1220 		memset(addr, 0, pna * 4);
1221 		debug("OF: no ranges, 1:1 translation\n");
1222 		goto finish;
1223 	}
1224 
1225 	debug("OF: walking ranges...\n");
1226 
1227 	/* Now walk through the ranges */
1228 	rlen /= 4;
1229 	rone = na + pna + ns;
1230 	for (; rlen >= rone; rlen -= rone, ranges += rone) {
1231 		offset = bus->map(addr, ranges, na, ns, pna);
1232 		if (offset != OF_BAD_ADDR)
1233 			break;
1234 	}
1235 	if (offset == OF_BAD_ADDR) {
1236 		debug("OF: not found !\n");
1237 		return 1;
1238 	}
1239 	memcpy(addr, ranges + na, 4 * pna);
1240 
1241  finish:
1242 	of_dump_addr("OF: parent translation for:", addr, pna);
1243 	debug("OF: with offset: %" PRIu64 "\n", offset);
1244 
1245 	/* Translate it into parent bus space */
1246 	return pbus->translate(addr, offset, pna);
1247 }
1248 
1249 /*
1250  * Translate an address from the device-tree into a CPU physical address,
1251  * this walks up the tree and applies the various bus mappings on the
1252  * way.
1253  *
1254  * Note: We consider that crossing any level with #size-cells == 0 to mean
1255  * that translation is impossible (that is we are not dealing with a value
1256  * that can be mapped to a cpu physical address). This is not really specified
1257  * that way, but this is traditionally the way IBM at least do things
1258  */
1259 static u64 __of_translate_address(const void *blob, int node_offset,
1260 				  const fdt32_t *in_addr, const char *rprop)
1261 {
1262 	int parent;
1263 	struct of_bus *bus, *pbus;
1264 	fdt32_t addr[OF_MAX_ADDR_CELLS];
1265 	int na, ns, pna, pns;
1266 	u64 result = OF_BAD_ADDR;
1267 
1268 	debug("OF: ** translation for device %s **\n",
1269 		fdt_get_name(blob, node_offset, NULL));
1270 
1271 	/* Get parent & match bus type */
1272 	parent = fdt_parent_offset(blob, node_offset);
1273 	if (parent < 0)
1274 		goto bail;
1275 	bus = of_match_bus(blob, parent);
1276 
1277 	/* Cound address cells & copy address locally */
1278 	bus->count_cells(blob, parent, &na, &ns);
1279 	if (!OF_CHECK_COUNTS(na, ns)) {
1280 		printf("%s: Bad cell count for %s\n", __FUNCTION__,
1281 		       fdt_get_name(blob, node_offset, NULL));
1282 		goto bail;
1283 	}
1284 	memcpy(addr, in_addr, na * 4);
1285 
1286 	debug("OF: bus is %s (na=%d, ns=%d) on %s\n",
1287 	    bus->name, na, ns, fdt_get_name(blob, parent, NULL));
1288 	of_dump_addr("OF: translating address:", addr, na);
1289 
1290 	/* Translate */
1291 	for (;;) {
1292 		/* Switch to parent bus */
1293 		node_offset = parent;
1294 		parent = fdt_parent_offset(blob, node_offset);
1295 
1296 		/* If root, we have finished */
1297 		if (parent < 0) {
1298 			debug("OF: reached root node\n");
1299 			result = fdt_read_number(addr, na);
1300 			break;
1301 		}
1302 
1303 		/* Get new parent bus and counts */
1304 		pbus = of_match_bus(blob, parent);
1305 		pbus->count_cells(blob, parent, &pna, &pns);
1306 		if (!OF_CHECK_COUNTS(pna, pns)) {
1307 			printf("%s: Bad cell count for %s\n", __FUNCTION__,
1308 				fdt_get_name(blob, node_offset, NULL));
1309 			break;
1310 		}
1311 
1312 		debug("OF: parent bus is %s (na=%d, ns=%d) on %s\n",
1313 		    pbus->name, pna, pns, fdt_get_name(blob, parent, NULL));
1314 
1315 		/* Apply bus translation */
1316 		if (of_translate_one(blob, node_offset, bus, pbus,
1317 					addr, na, ns, pna, rprop))
1318 			break;
1319 
1320 		/* Complete the move up one level */
1321 		na = pna;
1322 		ns = pns;
1323 		bus = pbus;
1324 
1325 		of_dump_addr("OF: one level translation:", addr, na);
1326 	}
1327  bail:
1328 
1329 	return result;
1330 }
1331 
1332 u64 fdt_translate_address(const void *blob, int node_offset,
1333 			  const fdt32_t *in_addr)
1334 {
1335 	return __of_translate_address(blob, node_offset, in_addr, "ranges");
1336 }
1337 
1338 /**
1339  * fdt_node_offset_by_compat_reg: Find a node that matches compatiable and
1340  * who's reg property matches a physical cpu address
1341  *
1342  * @blob: ptr to device tree
1343  * @compat: compatiable string to match
1344  * @compat_off: property name
1345  *
1346  */
1347 int fdt_node_offset_by_compat_reg(void *blob, const char *compat,
1348 					phys_addr_t compat_off)
1349 {
1350 	int len, off = fdt_node_offset_by_compatible(blob, -1, compat);
1351 	while (off != -FDT_ERR_NOTFOUND) {
1352 		const fdt32_t *reg = fdt_getprop(blob, off, "reg", &len);
1353 		if (reg) {
1354 			if (compat_off == fdt_translate_address(blob, off, reg))
1355 				return off;
1356 		}
1357 		off = fdt_node_offset_by_compatible(blob, off, compat);
1358 	}
1359 
1360 	return -FDT_ERR_NOTFOUND;
1361 }
1362 
1363 /**
1364  * fdt_alloc_phandle: Return next free phandle value
1365  *
1366  * @blob: ptr to device tree
1367  */
1368 int fdt_alloc_phandle(void *blob)
1369 {
1370 	int offset;
1371 	uint32_t phandle = 0;
1372 
1373 	for (offset = fdt_next_node(blob, -1, NULL); offset >= 0;
1374 	     offset = fdt_next_node(blob, offset, NULL)) {
1375 		phandle = max(phandle, fdt_get_phandle(blob, offset));
1376 	}
1377 
1378 	return phandle + 1;
1379 }
1380 
1381 /*
1382  * fdt_set_phandle: Create a phandle property for the given node
1383  *
1384  * @fdt: ptr to device tree
1385  * @nodeoffset: node to update
1386  * @phandle: phandle value to set (must be unique)
1387  */
1388 int fdt_set_phandle(void *fdt, int nodeoffset, uint32_t phandle)
1389 {
1390 	int ret;
1391 
1392 #ifdef DEBUG
1393 	int off = fdt_node_offset_by_phandle(fdt, phandle);
1394 
1395 	if ((off >= 0) && (off != nodeoffset)) {
1396 		char buf[64];
1397 
1398 		fdt_get_path(fdt, nodeoffset, buf, sizeof(buf));
1399 		printf("Trying to update node %s with phandle %u ",
1400 		       buf, phandle);
1401 
1402 		fdt_get_path(fdt, off, buf, sizeof(buf));
1403 		printf("that already exists in node %s.\n", buf);
1404 		return -FDT_ERR_BADPHANDLE;
1405 	}
1406 #endif
1407 
1408 	ret = fdt_setprop_cell(fdt, nodeoffset, "phandle", phandle);
1409 	if (ret < 0)
1410 		return ret;
1411 
1412 	/*
1413 	 * For now, also set the deprecated "linux,phandle" property, so that we
1414 	 * don't break older kernels.
1415 	 */
1416 	ret = fdt_setprop_cell(fdt, nodeoffset, "linux,phandle", phandle);
1417 
1418 	return ret;
1419 }
1420 
1421 /*
1422  * fdt_create_phandle: Create a phandle property for the given node
1423  *
1424  * @fdt: ptr to device tree
1425  * @nodeoffset: node to update
1426  */
1427 unsigned int fdt_create_phandle(void *fdt, int nodeoffset)
1428 {
1429 	/* see if there is a phandle already */
1430 	int phandle = fdt_get_phandle(fdt, nodeoffset);
1431 
1432 	/* if we got 0, means no phandle so create one */
1433 	if (phandle == 0) {
1434 		int ret;
1435 
1436 		phandle = fdt_alloc_phandle(fdt);
1437 		ret = fdt_set_phandle(fdt, nodeoffset, phandle);
1438 		if (ret < 0) {
1439 			printf("Can't set phandle %u: %s\n", phandle,
1440 			       fdt_strerror(ret));
1441 			return 0;
1442 		}
1443 	}
1444 
1445 	return phandle;
1446 }
1447 
1448 /*
1449  * fdt_set_node_status: Set status for the given node
1450  *
1451  * @fdt: ptr to device tree
1452  * @nodeoffset: node to update
1453  * @status: FDT_STATUS_OKAY, FDT_STATUS_DISABLED,
1454  *	    FDT_STATUS_FAIL, FDT_STATUS_FAIL_ERROR_CODE
1455  * @error_code: optional, only used if status is FDT_STATUS_FAIL_ERROR_CODE
1456  */
1457 int fdt_set_node_status(void *fdt, int nodeoffset,
1458 			enum fdt_status status, unsigned int error_code)
1459 {
1460 	char buf[16];
1461 	int ret = 0;
1462 
1463 	if (nodeoffset < 0)
1464 		return nodeoffset;
1465 
1466 	switch (status) {
1467 	case FDT_STATUS_OKAY:
1468 		ret = fdt_setprop_string(fdt, nodeoffset, "status", "okay");
1469 		break;
1470 	case FDT_STATUS_DISABLED:
1471 		ret = fdt_setprop_string(fdt, nodeoffset, "status", "disabled");
1472 		break;
1473 	case FDT_STATUS_FAIL:
1474 		ret = fdt_setprop_string(fdt, nodeoffset, "status", "fail");
1475 		break;
1476 	case FDT_STATUS_FAIL_ERROR_CODE:
1477 		sprintf(buf, "fail-%d", error_code);
1478 		ret = fdt_setprop_string(fdt, nodeoffset, "status", buf);
1479 		break;
1480 	default:
1481 		printf("Invalid fdt status: %x\n", status);
1482 		ret = -1;
1483 		break;
1484 	}
1485 
1486 	return ret;
1487 }
1488 
1489 /*
1490  * fdt_set_status_by_alias: Set status for the given node given an alias
1491  *
1492  * @fdt: ptr to device tree
1493  * @alias: alias of node to update
1494  * @status: FDT_STATUS_OKAY, FDT_STATUS_DISABLED,
1495  *	    FDT_STATUS_FAIL, FDT_STATUS_FAIL_ERROR_CODE
1496  * @error_code: optional, only used if status is FDT_STATUS_FAIL_ERROR_CODE
1497  */
1498 int fdt_set_status_by_alias(void *fdt, const char* alias,
1499 			    enum fdt_status status, unsigned int error_code)
1500 {
1501 	int offset = fdt_path_offset(fdt, alias);
1502 
1503 	return fdt_set_node_status(fdt, offset, status, error_code);
1504 }
1505 
1506 #if defined(CONFIG_VIDEO) || defined(CONFIG_LCD)
1507 int fdt_add_edid(void *blob, const char *compat, unsigned char *edid_buf)
1508 {
1509 	int noff;
1510 	int ret;
1511 
1512 	noff = fdt_node_offset_by_compatible(blob, -1, compat);
1513 	if (noff != -FDT_ERR_NOTFOUND) {
1514 		debug("%s: %s\n", fdt_get_name(blob, noff, 0), compat);
1515 add_edid:
1516 		ret = fdt_setprop(blob, noff, "edid", edid_buf, 128);
1517 		if (ret == -FDT_ERR_NOSPACE) {
1518 			ret = fdt_increase_size(blob, 512);
1519 			if (!ret)
1520 				goto add_edid;
1521 			else
1522 				goto err_size;
1523 		} else if (ret < 0) {
1524 			printf("Can't add property: %s\n", fdt_strerror(ret));
1525 			return ret;
1526 		}
1527 	}
1528 	return 0;
1529 err_size:
1530 	printf("Can't increase blob size: %s\n", fdt_strerror(ret));
1531 	return ret;
1532 }
1533 #endif
1534 
1535 /*
1536  * Verify the physical address of device tree node for a given alias
1537  *
1538  * This function locates the device tree node of a given alias, and then
1539  * verifies that the physical address of that device matches the given
1540  * parameter.  It displays a message if there is a mismatch.
1541  *
1542  * Returns 1 on success, 0 on failure
1543  */
1544 int fdt_verify_alias_address(void *fdt, int anode, const char *alias, u64 addr)
1545 {
1546 	const char *path;
1547 	const fdt32_t *reg;
1548 	int node, len;
1549 	u64 dt_addr;
1550 
1551 	path = fdt_getprop(fdt, anode, alias, NULL);
1552 	if (!path) {
1553 		/* If there's no such alias, then it's not a failure */
1554 		return 1;
1555 	}
1556 
1557 	node = fdt_path_offset(fdt, path);
1558 	if (node < 0) {
1559 		printf("Warning: device tree alias '%s' points to invalid "
1560 		       "node %s.\n", alias, path);
1561 		return 0;
1562 	}
1563 
1564 	reg = fdt_getprop(fdt, node, "reg", &len);
1565 	if (!reg) {
1566 		printf("Warning: device tree node '%s' has no address.\n",
1567 		       path);
1568 		return 0;
1569 	}
1570 
1571 	dt_addr = fdt_translate_address(fdt, node, reg);
1572 	if (addr != dt_addr) {
1573 		printf("Warning: U-Boot configured device %s at address %"
1574 		       PRIx64 ",\n but the device tree has it address %"
1575 		       PRIx64 ".\n", alias, addr, dt_addr);
1576 		return 0;
1577 	}
1578 
1579 	return 1;
1580 }
1581 
1582 /*
1583  * Returns the base address of an SOC or PCI node
1584  */
1585 u64 fdt_get_base_address(const void *fdt, int node)
1586 {
1587 	int size;
1588 	const fdt32_t *prop;
1589 
1590 	prop = fdt_getprop(fdt, node, "reg", &size);
1591 
1592 	return prop ? fdt_translate_address(fdt, node, prop) : 0;
1593 }
1594 
1595 /*
1596  * Read a property of size <prop_len>. Currently only supports 1 or 2 cells.
1597  */
1598 static int fdt_read_prop(const fdt32_t *prop, int prop_len, int cell_off,
1599 			 uint64_t *val, int cells)
1600 {
1601 	const fdt32_t *prop32 = &prop[cell_off];
1602 	const fdt64_t *prop64 = (const fdt64_t *)&prop[cell_off];
1603 
1604 	if ((cell_off + cells) > prop_len)
1605 		return -FDT_ERR_NOSPACE;
1606 
1607 	switch (cells) {
1608 	case 1:
1609 		*val = fdt32_to_cpu(*prop32);
1610 		break;
1611 	case 2:
1612 		*val = fdt64_to_cpu(*prop64);
1613 		break;
1614 	default:
1615 		return -FDT_ERR_NOSPACE;
1616 	}
1617 
1618 	return 0;
1619 }
1620 
1621 /**
1622  * fdt_read_range - Read a node's n'th range property
1623  *
1624  * @fdt: ptr to device tree
1625  * @node: offset of node
1626  * @n: range index
1627  * @child_addr: pointer to storage for the "child address" field
1628  * @addr: pointer to storage for the CPU view translated physical start
1629  * @len: pointer to storage for the range length
1630  *
1631  * Convenience function that reads and interprets a specific range out of
1632  * a number of the "ranges" property array.
1633  */
1634 int fdt_read_range(void *fdt, int node, int n, uint64_t *child_addr,
1635 		   uint64_t *addr, uint64_t *len)
1636 {
1637 	int pnode = fdt_parent_offset(fdt, node);
1638 	const fdt32_t *ranges;
1639 	int pacells;
1640 	int acells;
1641 	int scells;
1642 	int ranges_len;
1643 	int cell = 0;
1644 	int r = 0;
1645 
1646 	/*
1647 	 * The "ranges" property is an array of
1648 	 * { <child address> <parent address> <size in child address space> }
1649 	 *
1650 	 * All 3 elements can span a diffent number of cells. Fetch their size.
1651 	 */
1652 	pacells = fdt_getprop_u32_default_node(fdt, pnode, 0, "#address-cells", 1);
1653 	acells = fdt_getprop_u32_default_node(fdt, node, 0, "#address-cells", 1);
1654 	scells = fdt_getprop_u32_default_node(fdt, node, 0, "#size-cells", 1);
1655 
1656 	/* Now try to get the ranges property */
1657 	ranges = fdt_getprop(fdt, node, "ranges", &ranges_len);
1658 	if (!ranges)
1659 		return -FDT_ERR_NOTFOUND;
1660 	ranges_len /= sizeof(uint32_t);
1661 
1662 	/* Jump to the n'th entry */
1663 	cell = n * (pacells + acells + scells);
1664 
1665 	/* Read <child address> */
1666 	if (child_addr) {
1667 		r = fdt_read_prop(ranges, ranges_len, cell, child_addr,
1668 				  acells);
1669 		if (r)
1670 			return r;
1671 	}
1672 	cell += acells;
1673 
1674 	/* Read <parent address> */
1675 	if (addr)
1676 		*addr = fdt_translate_address(fdt, node, ranges + cell);
1677 	cell += pacells;
1678 
1679 	/* Read <size in child address space> */
1680 	if (len) {
1681 		r = fdt_read_prop(ranges, ranges_len, cell, len, scells);
1682 		if (r)
1683 			return r;
1684 	}
1685 
1686 	return 0;
1687 }
1688 
1689 /**
1690  * fdt_setup_simplefb_node - Fill and enable a simplefb node
1691  *
1692  * @fdt: ptr to device tree
1693  * @node: offset of the simplefb node
1694  * @base_address: framebuffer base address
1695  * @width: width in pixels
1696  * @height: height in pixels
1697  * @stride: bytes per line
1698  * @format: pixel format string
1699  *
1700  * Convenience function to fill and enable a simplefb node.
1701  */
1702 int fdt_setup_simplefb_node(void *fdt, int node, u64 base_address, u32 width,
1703 			    u32 height, u32 stride, const char *format)
1704 {
1705 	char name[32];
1706 	fdt32_t cells[4];
1707 	int i, addrc, sizec, ret;
1708 
1709 	fdt_support_default_count_cells(fdt, fdt_parent_offset(fdt, node),
1710 					&addrc, &sizec);
1711 	i = 0;
1712 	if (addrc == 2)
1713 		cells[i++] = cpu_to_fdt32(base_address >> 32);
1714 	cells[i++] = cpu_to_fdt32(base_address);
1715 	if (sizec == 2)
1716 		cells[i++] = 0;
1717 	cells[i++] = cpu_to_fdt32(height * stride);
1718 
1719 	ret = fdt_setprop(fdt, node, "reg", cells, sizeof(cells[0]) * i);
1720 	if (ret < 0)
1721 		return ret;
1722 
1723 	snprintf(name, sizeof(name), "framebuffer@%" PRIx64, base_address);
1724 	ret = fdt_set_name(fdt, node, name);
1725 	if (ret < 0)
1726 		return ret;
1727 
1728 	ret = fdt_setprop_u32(fdt, node, "width", width);
1729 	if (ret < 0)
1730 		return ret;
1731 
1732 	ret = fdt_setprop_u32(fdt, node, "height", height);
1733 	if (ret < 0)
1734 		return ret;
1735 
1736 	ret = fdt_setprop_u32(fdt, node, "stride", stride);
1737 	if (ret < 0)
1738 		return ret;
1739 
1740 	ret = fdt_setprop_string(fdt, node, "format", format);
1741 	if (ret < 0)
1742 		return ret;
1743 
1744 	ret = fdt_setprop_string(fdt, node, "status", "okay");
1745 	if (ret < 0)
1746 		return ret;
1747 
1748 	return 0;
1749 }
1750 
1751 /*
1752  * Update native-mode in display-timings from display environment variable.
1753  * The node to update are specified by path.
1754  */
1755 int fdt_fixup_display(void *blob, const char *path, const char *display)
1756 {
1757 	int off, toff;
1758 
1759 	if (!display || !path)
1760 		return -FDT_ERR_NOTFOUND;
1761 
1762 	toff = fdt_path_offset(blob, path);
1763 	if (toff >= 0)
1764 		toff = fdt_subnode_offset(blob, toff, "display-timings");
1765 	if (toff < 0)
1766 		return toff;
1767 
1768 	for (off = fdt_first_subnode(blob, toff);
1769 	     off >= 0;
1770 	     off = fdt_next_subnode(blob, off)) {
1771 		uint32_t h = fdt_get_phandle(blob, off);
1772 		debug("%s:0x%x\n", fdt_get_name(blob, off, NULL),
1773 		      fdt32_to_cpu(h));
1774 		if (strcasecmp(fdt_get_name(blob, off, NULL), display) == 0)
1775 			return fdt_setprop_u32(blob, toff, "native-mode", h);
1776 	}
1777 	return toff;
1778 }
1779 
1780 #ifdef CONFIG_OF_LIBFDT_OVERLAY
1781 /**
1782  * fdt_overlay_apply_verbose - Apply an overlay with verbose error reporting
1783  *
1784  * @fdt: ptr to device tree
1785  * @fdto: ptr to device tree overlay
1786  *
1787  * Convenience function to apply an overlay and display helpful messages
1788  * in the case of an error
1789  */
1790 int fdt_overlay_apply_verbose(void *fdt, void *fdto)
1791 {
1792 	int err;
1793 	bool has_symbols;
1794 
1795 	err = fdt_path_offset(fdt, "/__symbols__");
1796 	has_symbols = err >= 0;
1797 
1798 	err = fdt_overlay_apply(fdt, fdto);
1799 	if (err < 0) {
1800 		printf("failed on fdt_overlay_apply(): %s\n",
1801 				fdt_strerror(err));
1802 		if (!has_symbols) {
1803 			printf("base fdt does did not have a /__symbols__ node\n");
1804 			printf("make sure you've compiled with -@\n");
1805 		}
1806 	}
1807 	return err;
1808 }
1809 #endif
1810