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