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