xref: /rk3399_rockchip-uboot/common/fdt_support.c (revision 754ae3fbb76dc429ef932bbd04b432196efe45ff)
1 /*
2  * (C) Copyright 2007
3  * Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com
4  *
5  * Copyright 2010 Freescale Semiconductor, Inc.
6  *
7  * See file CREDITS for list of people who contributed to this
8  * project.
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License as
12  * published by the Free Software Foundation; either version 2 of
13  * the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
23  * MA 02111-1307 USA
24  */
25 
26 #include <common.h>
27 #include <stdio_dev.h>
28 #include <linux/ctype.h>
29 #include <linux/types.h>
30 #include <asm/global_data.h>
31 #include <fdt.h>
32 #include <libfdt.h>
33 #include <fdt_support.h>
34 #include <exports.h>
35 
36 /*
37  * Global data (for the gd->bd)
38  */
39 DECLARE_GLOBAL_DATA_PTR;
40 
41 /**
42  * fdt_getprop_u32_default - Find a node and return it's property or a default
43  *
44  * @fdt: ptr to device tree
45  * @path: path of node
46  * @prop: property name
47  * @dflt: default value if the property isn't found
48  *
49  * Convenience function to find a node and return it's property or a
50  * default value if it doesn't exist.
51  */
52 u32 fdt_getprop_u32_default(void *fdt, const char *path, const char *prop,
53 				const u32 dflt)
54 {
55 	const u32 *val;
56 	int off;
57 
58 	off = fdt_path_offset(fdt, path);
59 	if (off < 0)
60 		return dflt;
61 
62 	val = fdt_getprop(fdt, off, prop, NULL);
63 	if (val)
64 		return *val;
65 	else
66 		return dflt;
67 }
68 
69 /**
70  * fdt_find_and_setprop: Find a node and set it's property
71  *
72  * @fdt: ptr to device tree
73  * @node: path of node
74  * @prop: property name
75  * @val: ptr to new value
76  * @len: length of new property value
77  * @create: flag to create the property if it doesn't exist
78  *
79  * Convenience function to directly set a property given the path to the node.
80  */
81 int fdt_find_and_setprop(void *fdt, const char *node, const char *prop,
82 			 const void *val, int len, int create)
83 {
84 	int nodeoff = fdt_path_offset(fdt, node);
85 
86 	if (nodeoff < 0)
87 		return nodeoff;
88 
89 	if ((!create) && (fdt_get_property(fdt, nodeoff, prop, 0) == NULL))
90 		return 0; /* create flag not set; so exit quietly */
91 
92 	return fdt_setprop(fdt, nodeoff, prop, val, len);
93 }
94 
95 #ifdef CONFIG_OF_STDOUT_VIA_ALIAS
96 
97 #ifdef CONFIG_SERIAL_MULTI
98 static void fdt_fill_multisername(char *sername, size_t maxlen)
99 {
100 	const char *outname = stdio_devices[stdout]->name;
101 
102 	if (strcmp(outname, "serial") > 0)
103 		strncpy(sername, outname, maxlen);
104 
105 	/* eserial? */
106 	if (strcmp(outname + 1, "serial") > 0)
107 		strncpy(sername, outname + 1, maxlen);
108 }
109 #else
110 static inline void fdt_fill_multisername(char *sername, size_t maxlen) {}
111 #endif /* CONFIG_SERIAL_MULTI */
112 
113 static int fdt_fixup_stdout(void *fdt, int chosenoff)
114 {
115 	int err = 0;
116 #ifdef CONFIG_CONS_INDEX
117 	int node;
118 	char sername[9] = { 0 };
119 	const char *path;
120 
121 	fdt_fill_multisername(sername, sizeof(sername) - 1);
122 	if (!sername[0])
123 		sprintf(sername, "serial%d", CONFIG_CONS_INDEX - 1);
124 
125 	err = node = fdt_path_offset(fdt, "/aliases");
126 	if (node >= 0) {
127 		int len;
128 		path = fdt_getprop(fdt, node, sername, &len);
129 		if (path) {
130 			char *p = malloc(len);
131 			err = -FDT_ERR_NOSPACE;
132 			if (p) {
133 				memcpy(p, path, len);
134 				err = fdt_setprop(fdt, chosenoff,
135 					"linux,stdout-path", p, len);
136 				free(p);
137 			}
138 		} else {
139 			err = len;
140 		}
141 	}
142 #endif
143 	if (err < 0)
144 		printf("WARNING: could not set linux,stdout-path %s.\n",
145 				fdt_strerror(err));
146 
147 	return err;
148 }
149 #endif
150 
151 int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end, int force)
152 {
153 	int   nodeoffset;
154 	int   err, j, total;
155 	u32   tmp;
156 	const char *path;
157 	uint64_t addr, size;
158 
159 	/* Find the "chosen" node.  */
160 	nodeoffset = fdt_path_offset (fdt, "/chosen");
161 
162 	/* If there is no "chosen" node in the blob return */
163 	if (nodeoffset < 0) {
164 		printf("fdt_initrd: %s\n", fdt_strerror(nodeoffset));
165 		return nodeoffset;
166 	}
167 
168 	/* just return if initrd_start/end aren't valid */
169 	if ((initrd_start == 0) || (initrd_end == 0))
170 		return 0;
171 
172 	total = fdt_num_mem_rsv(fdt);
173 
174 	/*
175 	 * Look for an existing entry and update it.  If we don't find
176 	 * the entry, we will j be the next available slot.
177 	 */
178 	for (j = 0; j < total; j++) {
179 		err = fdt_get_mem_rsv(fdt, j, &addr, &size);
180 		if (addr == initrd_start) {
181 			fdt_del_mem_rsv(fdt, j);
182 			break;
183 		}
184 	}
185 
186 	err = fdt_add_mem_rsv(fdt, initrd_start, initrd_end - initrd_start + 1);
187 	if (err < 0) {
188 		printf("fdt_initrd: %s\n", fdt_strerror(err));
189 		return err;
190 	}
191 
192 	path = fdt_getprop(fdt, nodeoffset, "linux,initrd-start", NULL);
193 	if ((path == NULL) || force) {
194 		tmp = __cpu_to_be32(initrd_start);
195 		err = fdt_setprop(fdt, nodeoffset,
196 			"linux,initrd-start", &tmp, sizeof(tmp));
197 		if (err < 0) {
198 			printf("WARNING: "
199 				"could not set linux,initrd-start %s.\n",
200 				fdt_strerror(err));
201 			return err;
202 		}
203 		tmp = __cpu_to_be32(initrd_end);
204 		err = fdt_setprop(fdt, nodeoffset,
205 			"linux,initrd-end", &tmp, sizeof(tmp));
206 		if (err < 0) {
207 			printf("WARNING: could not set linux,initrd-end %s.\n",
208 				fdt_strerror(err));
209 
210 			return err;
211 		}
212 	}
213 
214 	return 0;
215 }
216 
217 int fdt_chosen(void *fdt, int force)
218 {
219 	int   nodeoffset;
220 	int   err;
221 	char  *str;		/* used to set string properties */
222 	const char *path;
223 
224 	err = fdt_check_header(fdt);
225 	if (err < 0) {
226 		printf("fdt_chosen: %s\n", fdt_strerror(err));
227 		return err;
228 	}
229 
230 	/*
231 	 * Find the "chosen" node.
232 	 */
233 	nodeoffset = fdt_path_offset (fdt, "/chosen");
234 
235 	/*
236 	 * If there is no "chosen" node in the blob, create it.
237 	 */
238 	if (nodeoffset < 0) {
239 		/*
240 		 * Create a new node "/chosen" (offset 0 is root level)
241 		 */
242 		nodeoffset = fdt_add_subnode(fdt, 0, "chosen");
243 		if (nodeoffset < 0) {
244 			printf("WARNING: could not create /chosen %s.\n",
245 				fdt_strerror(nodeoffset));
246 			return nodeoffset;
247 		}
248 	}
249 
250 	/*
251 	 * Create /chosen properites that don't exist in the fdt.
252 	 * If the property exists, update it only if the "force" parameter
253 	 * is true.
254 	 */
255 	str = getenv("bootargs");
256 	if (str != NULL) {
257 		path = fdt_getprop(fdt, nodeoffset, "bootargs", NULL);
258 		if ((path == NULL) || force) {
259 			err = fdt_setprop(fdt, nodeoffset,
260 				"bootargs", str, strlen(str)+1);
261 			if (err < 0)
262 				printf("WARNING: could not set bootargs %s.\n",
263 					fdt_strerror(err));
264 		}
265 	}
266 
267 #ifdef CONFIG_OF_STDOUT_VIA_ALIAS
268 	path = fdt_getprop(fdt, nodeoffset, "linux,stdout-path", NULL);
269 	if ((path == NULL) || force)
270 		err = fdt_fixup_stdout(fdt, nodeoffset);
271 #endif
272 
273 #ifdef OF_STDOUT_PATH
274 	path = fdt_getprop(fdt, nodeoffset, "linux,stdout-path", NULL);
275 	if ((path == NULL) || force) {
276 		err = fdt_setprop(fdt, nodeoffset,
277 			"linux,stdout-path", OF_STDOUT_PATH, strlen(OF_STDOUT_PATH)+1);
278 		if (err < 0)
279 			printf("WARNING: could not set linux,stdout-path %s.\n",
280 				fdt_strerror(err));
281 	}
282 #endif
283 
284 	return err;
285 }
286 
287 void do_fixup_by_path(void *fdt, const char *path, const char *prop,
288 		      const void *val, int len, int create)
289 {
290 #if defined(DEBUG)
291 	int i;
292 	debug("Updating property '%s/%s' = ", path, prop);
293 	for (i = 0; i < len; i++)
294 		debug(" %.2x", *(u8*)(val+i));
295 	debug("\n");
296 #endif
297 	int rc = fdt_find_and_setprop(fdt, path, prop, val, len, create);
298 	if (rc)
299 		printf("Unable to update property %s:%s, err=%s\n",
300 			path, prop, fdt_strerror(rc));
301 }
302 
303 void do_fixup_by_path_u32(void *fdt, const char *path, const char *prop,
304 			  u32 val, int create)
305 {
306 	val = cpu_to_fdt32(val);
307 	do_fixup_by_path(fdt, path, prop, &val, sizeof(val), create);
308 }
309 
310 void do_fixup_by_prop(void *fdt,
311 		      const char *pname, const void *pval, int plen,
312 		      const char *prop, const void *val, int len,
313 		      int create)
314 {
315 	int off;
316 #if defined(DEBUG)
317 	int i;
318 	debug("Updating property '%s' = ", prop);
319 	for (i = 0; i < len; i++)
320 		debug(" %.2x", *(u8*)(val+i));
321 	debug("\n");
322 #endif
323 	off = fdt_node_offset_by_prop_value(fdt, -1, pname, pval, plen);
324 	while (off != -FDT_ERR_NOTFOUND) {
325 		if (create || (fdt_get_property(fdt, off, prop, 0) != NULL))
326 			fdt_setprop(fdt, off, prop, val, len);
327 		off = fdt_node_offset_by_prop_value(fdt, off, pname, pval, plen);
328 	}
329 }
330 
331 void do_fixup_by_prop_u32(void *fdt,
332 			  const char *pname, const void *pval, int plen,
333 			  const char *prop, u32 val, int create)
334 {
335 	val = cpu_to_fdt32(val);
336 	do_fixup_by_prop(fdt, pname, pval, plen, prop, &val, 4, create);
337 }
338 
339 void do_fixup_by_compat(void *fdt, const char *compat,
340 			const char *prop, const void *val, int len, int create)
341 {
342 	int off = -1;
343 #if defined(DEBUG)
344 	int i;
345 	debug("Updating property '%s' = ", prop);
346 	for (i = 0; i < len; i++)
347 		debug(" %.2x", *(u8*)(val+i));
348 	debug("\n");
349 #endif
350 	off = fdt_node_offset_by_compatible(fdt, -1, compat);
351 	while (off != -FDT_ERR_NOTFOUND) {
352 		if (create || (fdt_get_property(fdt, off, prop, 0) != NULL))
353 			fdt_setprop(fdt, off, prop, val, len);
354 		off = fdt_node_offset_by_compatible(fdt, off, compat);
355 	}
356 }
357 
358 void do_fixup_by_compat_u32(void *fdt, const char *compat,
359 			    const char *prop, u32 val, int create)
360 {
361 	val = cpu_to_fdt32(val);
362 	do_fixup_by_compat(fdt, compat, prop, &val, 4, create);
363 }
364 
365 /*
366  * Get cells len in bytes
367  *     if #NNNN-cells property is 2 then len is 8
368  *     otherwise len is 4
369  */
370 static int get_cells_len(void *blob, char *nr_cells_name)
371 {
372 	const u32 *cell;
373 
374 	cell = fdt_getprop(blob, 0, nr_cells_name, NULL);
375 	if (cell && *cell == 2)
376 		return 8;
377 
378 	return 4;
379 }
380 
381 /*
382  * Write a 4 or 8 byte big endian cell
383  */
384 static void write_cell(u8 *addr, u64 val, int size)
385 {
386 	int shift = (size - 1) * 8;
387 	while (size-- > 0) {
388 		*addr++ = (val >> shift) & 0xff;
389 		shift -= 8;
390 	}
391 }
392 
393 int fdt_fixup_memory_banks(void *blob, u64 start[], u64 size[], int banks)
394 {
395 	int err, nodeoffset;
396 	int addr_cell_len, size_cell_len, len;
397 	u8 tmp[banks * 8];
398 	int bank;
399 	const u32 *addrcell, *sizecell;
400 
401 	err = fdt_check_header(blob);
402 	if (err < 0) {
403 		printf("%s: %s\n", __FUNCTION__, fdt_strerror(err));
404 		return err;
405 	}
406 
407 	/* update, or add and update /memory node */
408 	nodeoffset = fdt_path_offset(blob, "/memory");
409 	if (nodeoffset < 0) {
410 		nodeoffset = fdt_add_subnode(blob, 0, "memory");
411 		if (nodeoffset < 0)
412 			printf("WARNING: could not create /memory: %s.\n",
413 					fdt_strerror(nodeoffset));
414 		return nodeoffset;
415 	}
416 	err = fdt_setprop(blob, nodeoffset, "device_type", "memory",
417 			sizeof("memory"));
418 	if (err < 0) {
419 		printf("WARNING: could not set %s %s.\n", "device_type",
420 				fdt_strerror(err));
421 		return err;
422 	}
423 
424 	addr_cell_len = get_cells_len(blob, "#address-cells");
425 	size_cell_len = get_cells_len(blob, "#size-cells");
426 
427 	for (bank = 0, len = 0; bank < banks; bank++) {
428 		write_cell(tmp + len, start[bank], addr_cell_len);
429 		len += addr_cell_len;
430 
431 		write_cell(tmp + len, size[bank], size_cell_len);
432 		len += size_cell_len;
433 	}
434 
435 	err = fdt_setprop(blob, nodeoffset, "reg", tmp, len);
436 	if (err < 0) {
437 		printf("WARNING: could not set %s %s.\n",
438 				"reg", fdt_strerror(err));
439 		return err;
440 	}
441 	return 0;
442 }
443 
444 int fdt_fixup_memory(void *blob, u64 start, u64 size)
445 {
446 	return fdt_fixup_memory_banks(blob, &start, &size, 1);
447 }
448 
449 void fdt_fixup_ethernet(void *fdt)
450 {
451 	int node, i, j;
452 	char enet[16], *tmp, *end;
453 	char mac[16] = "ethaddr";
454 	const char *path;
455 	unsigned char mac_addr[6];
456 
457 	node = fdt_path_offset(fdt, "/aliases");
458 	if (node < 0)
459 		return;
460 
461 	i = 0;
462 	while ((tmp = getenv(mac)) != NULL) {
463 		sprintf(enet, "ethernet%d", i);
464 		path = fdt_getprop(fdt, node, enet, NULL);
465 		if (!path) {
466 			debug("No alias for %s\n", enet);
467 			sprintf(mac, "eth%daddr", ++i);
468 			continue;
469 		}
470 
471 		for (j = 0; j < 6; j++) {
472 			mac_addr[j] = tmp ? simple_strtoul(tmp, &end, 16) : 0;
473 			if (tmp)
474 				tmp = (*end) ? end+1 : end;
475 		}
476 
477 		do_fixup_by_path(fdt, path, "mac-address", &mac_addr, 6, 0);
478 		do_fixup_by_path(fdt, path, "local-mac-address",
479 				&mac_addr, 6, 1);
480 
481 		sprintf(mac, "eth%daddr", ++i);
482 	}
483 }
484 
485 /* Resize the fdt to its actual size + a bit of padding */
486 int fdt_resize(void *blob)
487 {
488 	int i;
489 	uint64_t addr, size;
490 	int total, ret;
491 	uint actualsize;
492 
493 	if (!blob)
494 		return 0;
495 
496 	total = fdt_num_mem_rsv(blob);
497 	for (i = 0; i < total; i++) {
498 		fdt_get_mem_rsv(blob, i, &addr, &size);
499 		if (addr == (uint64_t)(u32)blob) {
500 			fdt_del_mem_rsv(blob, i);
501 			break;
502 		}
503 	}
504 
505 	/*
506 	 * Calculate the actual size of the fdt
507 	 * plus the size needed for 5 fdt_add_mem_rsv, one
508 	 * for the fdt itself and 4 for a possible initrd
509 	 * ((initrd-start + initrd-end) * 2 (name & value))
510 	 */
511 	actualsize = fdt_off_dt_strings(blob) +
512 		fdt_size_dt_strings(blob) + 5 * sizeof(struct fdt_reserve_entry);
513 
514 	/* Make it so the fdt ends on a page boundary */
515 	actualsize = ALIGN(actualsize + ((uint)blob & 0xfff), 0x1000);
516 	actualsize = actualsize - ((uint)blob & 0xfff);
517 
518 	/* Change the fdt header to reflect the correct size */
519 	fdt_set_totalsize(blob, actualsize);
520 
521 	/* Add the new reservation */
522 	ret = fdt_add_mem_rsv(blob, (uint)blob, actualsize);
523 	if (ret < 0)
524 		return ret;
525 
526 	return actualsize;
527 }
528 
529 #ifdef CONFIG_PCI
530 #define CONFIG_SYS_PCI_NR_INBOUND_WIN 4
531 
532 #define FDT_PCI_PREFETCH	(0x40000000)
533 #define FDT_PCI_MEM32		(0x02000000)
534 #define FDT_PCI_IO		(0x01000000)
535 #define FDT_PCI_MEM64		(0x03000000)
536 
537 int fdt_pci_dma_ranges(void *blob, int phb_off, struct pci_controller *hose) {
538 
539 	int addrcell, sizecell, len, r;
540 	u32 *dma_range;
541 	/* sized based on pci addr cells, size-cells, & address-cells */
542 	u32 dma_ranges[(3 + 2 + 2) * CONFIG_SYS_PCI_NR_INBOUND_WIN];
543 
544 	addrcell = fdt_getprop_u32_default(blob, "/", "#address-cells", 1);
545 	sizecell = fdt_getprop_u32_default(blob, "/", "#size-cells", 1);
546 
547 	dma_range = &dma_ranges[0];
548 	for (r = 0; r < hose->region_count; r++) {
549 		u64 bus_start, phys_start, size;
550 
551 		/* skip if !PCI_REGION_SYS_MEMORY */
552 		if (!(hose->regions[r].flags & PCI_REGION_SYS_MEMORY))
553 			continue;
554 
555 		bus_start = (u64)hose->regions[r].bus_start;
556 		phys_start = (u64)hose->regions[r].phys_start;
557 		size = (u64)hose->regions[r].size;
558 
559 		dma_range[0] = 0;
560 		if (size >= 0x100000000ull)
561 			dma_range[0] |= FDT_PCI_MEM64;
562 		else
563 			dma_range[0] |= FDT_PCI_MEM32;
564 		if (hose->regions[r].flags & PCI_REGION_PREFETCH)
565 			dma_range[0] |= FDT_PCI_PREFETCH;
566 #ifdef CONFIG_SYS_PCI_64BIT
567 		dma_range[1] = bus_start >> 32;
568 #else
569 		dma_range[1] = 0;
570 #endif
571 		dma_range[2] = bus_start & 0xffffffff;
572 
573 		if (addrcell == 2) {
574 			dma_range[3] = phys_start >> 32;
575 			dma_range[4] = phys_start & 0xffffffff;
576 		} else {
577 			dma_range[3] = phys_start & 0xffffffff;
578 		}
579 
580 		if (sizecell == 2) {
581 			dma_range[3 + addrcell + 0] = size >> 32;
582 			dma_range[3 + addrcell + 1] = size & 0xffffffff;
583 		} else {
584 			dma_range[3 + addrcell + 0] = size & 0xffffffff;
585 		}
586 
587 		dma_range += (3 + addrcell + sizecell);
588 	}
589 
590 	len = dma_range - &dma_ranges[0];
591 	if (len)
592 		fdt_setprop(blob, phb_off, "dma-ranges", &dma_ranges[0], len*4);
593 
594 	return 0;
595 }
596 #endif
597 
598 #ifdef CONFIG_FDT_FIXUP_NOR_FLASH_SIZE
599 /*
600  * Provide a weak default function to return the flash bank size.
601  * There might be multiple non-identical flash chips connected to one
602  * chip-select, so we need to pass an index as well.
603  */
604 u32 __flash_get_bank_size(int cs, int idx)
605 {
606 	extern flash_info_t flash_info[];
607 
608 	/*
609 	 * As default, a simple 1:1 mapping is provided. Boards with
610 	 * a different mapping need to supply a board specific mapping
611 	 * routine.
612 	 */
613 	return flash_info[cs].size;
614 }
615 u32 flash_get_bank_size(int cs, int idx)
616 	__attribute__((weak, alias("__flash_get_bank_size")));
617 
618 /*
619  * This function can be used to update the size in the "reg" property
620  * of all NOR FLASH device nodes. This is necessary for boards with
621  * non-fixed NOR FLASH sizes.
622  */
623 int fdt_fixup_nor_flash_size(void *blob)
624 {
625 	char compat[][16] = { "cfi-flash", "jedec-flash" };
626 	int off;
627 	int len;
628 	struct fdt_property *prop;
629 	u32 *reg, *reg2;
630 	int i;
631 
632 	for (i = 0; i < 2; i++) {
633 		off = fdt_node_offset_by_compatible(blob, -1, compat[i]);
634 		while (off != -FDT_ERR_NOTFOUND) {
635 			int idx;
636 
637 			/*
638 			 * Found one compatible node, so fixup the size
639 			 * int its reg properties
640 			 */
641 			prop = fdt_get_property_w(blob, off, "reg", &len);
642 			if (prop) {
643 				int tuple_size = 3 * sizeof(reg);
644 
645 				/*
646 				 * There might be multiple reg-tuples,
647 				 * so loop through them all
648 				 */
649 				reg = reg2 = (u32 *)&prop->data[0];
650 				for (idx = 0; idx < (len / tuple_size); idx++) {
651 					/*
652 					 * Update size in reg property
653 					 */
654 					reg[2] = flash_get_bank_size(reg[0],
655 								     idx);
656 
657 					/*
658 					 * Point to next reg tuple
659 					 */
660 					reg += 3;
661 				}
662 
663 				fdt_setprop(blob, off, "reg", reg2, len);
664 			}
665 
666 			/* Move to next compatible node */
667 			off = fdt_node_offset_by_compatible(blob, off,
668 							    compat[i]);
669 		}
670 	}
671 
672 	return 0;
673 }
674 #endif
675 
676 int fdt_increase_size(void *fdt, int add_len)
677 {
678 	int newlen;
679 
680 	newlen = fdt_totalsize(fdt) + add_len;
681 
682 	/* Open in place with a new len */
683 	return fdt_open_into(fdt, fdt, newlen);
684 }
685 
686 #ifdef CONFIG_FDT_FIXUP_PARTITIONS
687 #include <jffs2/load_kernel.h>
688 #include <mtd_node.h>
689 
690 struct reg_cell {
691 	unsigned int r0;
692 	unsigned int r1;
693 };
694 
695 int fdt_del_subnodes(const void *blob, int parent_offset)
696 {
697 	int off, ndepth;
698 	int ret;
699 
700 	for (ndepth = 0, off = fdt_next_node(blob, parent_offset, &ndepth);
701 	     (off >= 0) && (ndepth > 0);
702 	     off = fdt_next_node(blob, off, &ndepth)) {
703 		if (ndepth == 1) {
704 			debug("delete %s: offset: %x\n",
705 				fdt_get_name(blob, off, 0), off);
706 			ret = fdt_del_node((void *)blob, off);
707 			if (ret < 0) {
708 				printf("Can't delete node: %s\n",
709 					fdt_strerror(ret));
710 				return ret;
711 			} else {
712 				ndepth = 0;
713 				off = parent_offset;
714 			}
715 		}
716 	}
717 	return 0;
718 }
719 
720 int fdt_del_partitions(void *blob, int parent_offset)
721 {
722 	const void *prop;
723 	int ndepth = 0;
724 	int off;
725 	int ret;
726 
727 	off = fdt_next_node(blob, parent_offset, &ndepth);
728 	if (off > 0 && ndepth == 1) {
729 		prop = fdt_getprop(blob, off, "label", NULL);
730 		if (prop == NULL) {
731 			/*
732 			 * Could not find label property, nand {}; node?
733 			 * Check subnode, delete partitions there if any.
734 			 */
735 			return fdt_del_partitions(blob, off);
736 		} else {
737 			ret = fdt_del_subnodes(blob, parent_offset);
738 			if (ret < 0) {
739 				printf("Can't remove subnodes: %s\n",
740 					fdt_strerror(ret));
741 				return ret;
742 			}
743 		}
744 	}
745 	return 0;
746 }
747 
748 int fdt_node_set_part_info(void *blob, int parent_offset,
749 			   struct mtd_device *dev)
750 {
751 	struct list_head *pentry;
752 	struct part_info *part;
753 	struct reg_cell cell;
754 	int off, ndepth = 0;
755 	int part_num, ret;
756 	char buf[64];
757 
758 	ret = fdt_del_partitions(blob, parent_offset);
759 	if (ret < 0)
760 		return ret;
761 
762 	/*
763 	 * Check if it is nand {}; subnode, adjust
764 	 * the offset in this case
765 	 */
766 	off = fdt_next_node(blob, parent_offset, &ndepth);
767 	if (off > 0 && ndepth == 1)
768 		parent_offset = off;
769 
770 	part_num = 0;
771 	list_for_each_prev(pentry, &dev->parts) {
772 		int newoff;
773 
774 		part = list_entry(pentry, struct part_info, link);
775 
776 		debug("%2d: %-20s0x%08x\t0x%08x\t%d\n",
777 			part_num, part->name, part->size,
778 			part->offset, part->mask_flags);
779 
780 		sprintf(buf, "partition@%x", part->offset);
781 add_sub:
782 		ret = fdt_add_subnode(blob, parent_offset, buf);
783 		if (ret == -FDT_ERR_NOSPACE) {
784 			ret = fdt_increase_size(blob, 512);
785 			if (!ret)
786 				goto add_sub;
787 			else
788 				goto err_size;
789 		} else if (ret < 0) {
790 			printf("Can't add partition node: %s\n",
791 				fdt_strerror(ret));
792 			return ret;
793 		}
794 		newoff = ret;
795 
796 		/* Check MTD_WRITEABLE_CMD flag */
797 		if (part->mask_flags & 1) {
798 add_ro:
799 			ret = fdt_setprop(blob, newoff, "read_only", NULL, 0);
800 			if (ret == -FDT_ERR_NOSPACE) {
801 				ret = fdt_increase_size(blob, 512);
802 				if (!ret)
803 					goto add_ro;
804 				else
805 					goto err_size;
806 			} else if (ret < 0)
807 				goto err_prop;
808 		}
809 
810 		cell.r0 = cpu_to_fdt32(part->offset);
811 		cell.r1 = cpu_to_fdt32(part->size);
812 add_reg:
813 		ret = fdt_setprop(blob, newoff, "reg", &cell, sizeof(cell));
814 		if (ret == -FDT_ERR_NOSPACE) {
815 			ret = fdt_increase_size(blob, 512);
816 			if (!ret)
817 				goto add_reg;
818 			else
819 				goto err_size;
820 		} else if (ret < 0)
821 			goto err_prop;
822 
823 add_label:
824 		ret = fdt_setprop_string(blob, newoff, "label", part->name);
825 		if (ret == -FDT_ERR_NOSPACE) {
826 			ret = fdt_increase_size(blob, 512);
827 			if (!ret)
828 				goto add_label;
829 			else
830 				goto err_size;
831 		} else if (ret < 0)
832 			goto err_prop;
833 
834 		part_num++;
835 	}
836 	return 0;
837 err_size:
838 	printf("Can't increase blob size: %s\n", fdt_strerror(ret));
839 	return ret;
840 err_prop:
841 	printf("Can't add property: %s\n", fdt_strerror(ret));
842 	return ret;
843 }
844 
845 /*
846  * Update partitions in nor/nand nodes using info from
847  * mtdparts environment variable. The nodes to update are
848  * specified by node_info structure which contains mtd device
849  * type and compatible string: E. g. the board code in
850  * ft_board_setup() could use:
851  *
852  *	struct node_info nodes[] = {
853  *		{ "fsl,mpc5121-nfc",    MTD_DEV_TYPE_NAND, },
854  *		{ "cfi-flash",          MTD_DEV_TYPE_NOR,  },
855  *	};
856  *
857  *	fdt_fixup_mtdparts(blob, nodes, ARRAY_SIZE(nodes));
858  */
859 void fdt_fixup_mtdparts(void *blob, void *node_info, int node_info_size)
860 {
861 	struct node_info *ni = node_info;
862 	struct mtd_device *dev;
863 	char *parts;
864 	int i, idx;
865 	int noff;
866 
867 	parts = getenv("mtdparts");
868 	if (!parts)
869 		return;
870 
871 	if (mtdparts_init() != 0)
872 		return;
873 
874 	for (i = 0; i < node_info_size; i++) {
875 		idx = 0;
876 		noff = fdt_node_offset_by_compatible(blob, -1, ni[i].compat);
877 		while (noff != -FDT_ERR_NOTFOUND) {
878 			debug("%s: %s, mtd dev type %d\n",
879 				fdt_get_name(blob, noff, 0),
880 				ni[i].compat, ni[i].type);
881 			dev = device_find(ni[i].type, idx++);
882 			if (dev) {
883 				if (fdt_node_set_part_info(blob, noff, dev))
884 					return; /* return on error */
885 			}
886 
887 			/* Jump to next flash node */
888 			noff = fdt_node_offset_by_compatible(blob, noff,
889 							     ni[i].compat);
890 		}
891 	}
892 }
893 #endif
894 
895 void fdt_del_node_and_alias(void *blob, const char *alias)
896 {
897 	int off = fdt_path_offset(blob, alias);
898 
899 	if (off < 0)
900 		return;
901 
902 	fdt_del_node(blob, off);
903 
904 	off = fdt_path_offset(blob, "/aliases");
905 	fdt_delprop(blob, off, alias);
906 }
907 
908 /* Helper to read a big number; size is in cells (not bytes) */
909 static inline u64 of_read_number(const __be32 *cell, int size)
910 {
911 	u64 r = 0;
912 	while (size--)
913 		r = (r << 32) | be32_to_cpu(*(cell++));
914 	return r;
915 }
916 
917 #define PRu64	"%llx"
918 
919 /* Max address size we deal with */
920 #define OF_MAX_ADDR_CELLS	4
921 #define OF_BAD_ADDR	((u64)-1)
922 #define OF_CHECK_COUNTS(na, ns)	((na) > 0 && (na) <= OF_MAX_ADDR_CELLS && \
923 			(ns) > 0)
924 
925 /* Debug utility */
926 #ifdef DEBUG
927 static void of_dump_addr(const char *s, const u32 *addr, int na)
928 {
929 	printf("%s", s);
930 	while(na--)
931 		printf(" %08x", *(addr++));
932 	printf("\n");
933 }
934 #else
935 static void of_dump_addr(const char *s, const u32 *addr, int na) { }
936 #endif
937 
938 /* Callbacks for bus specific translators */
939 struct of_bus {
940 	const char	*name;
941 	const char	*addresses;
942 	void		(*count_cells)(void *blob, int parentoffset,
943 				int *addrc, int *sizec);
944 	u64		(*map)(u32 *addr, const u32 *range,
945 				int na, int ns, int pna);
946 	int		(*translate)(u32 *addr, u64 offset, int na);
947 };
948 
949 /* Default translator (generic bus) */
950 static void of_bus_default_count_cells(void *blob, int parentoffset,
951 					int *addrc, int *sizec)
952 {
953 	const u32 *prop;
954 
955 	if (addrc) {
956 		prop = fdt_getprop(blob, parentoffset, "#address-cells", NULL);
957 		if (prop)
958 			*addrc = be32_to_cpup(prop);
959 		else
960 			*addrc = 2;
961 	}
962 
963 	if (sizec) {
964 		prop = fdt_getprop(blob, parentoffset, "#size-cells", NULL);
965 		if (prop)
966 			*sizec = be32_to_cpup(prop);
967 		else
968 			*sizec = 1;
969 	}
970 }
971 
972 static u64 of_bus_default_map(u32 *addr, const u32 *range,
973 		int na, int ns, int pna)
974 {
975 	u64 cp, s, da;
976 
977 	cp = of_read_number(range, na);
978 	s  = of_read_number(range + na + pna, ns);
979 	da = of_read_number(addr, na);
980 
981 	debug("OF: default map, cp="PRu64", s="PRu64", da="PRu64"\n",
982 	    cp, s, da);
983 
984 	if (da < cp || da >= (cp + s))
985 		return OF_BAD_ADDR;
986 	return da - cp;
987 }
988 
989 static int of_bus_default_translate(u32 *addr, u64 offset, int na)
990 {
991 	u64 a = of_read_number(addr, na);
992 	memset(addr, 0, na * 4);
993 	a += offset;
994 	if (na > 1)
995 		addr[na - 2] = a >> 32;
996 	addr[na - 1] = a & 0xffffffffu;
997 
998 	return 0;
999 }
1000 
1001 /* Array of bus specific translators */
1002 static struct of_bus of_busses[] = {
1003 	/* Default */
1004 	{
1005 		.name = "default",
1006 		.addresses = "reg",
1007 		.count_cells = of_bus_default_count_cells,
1008 		.map = of_bus_default_map,
1009 		.translate = of_bus_default_translate,
1010 	},
1011 };
1012 
1013 static int of_translate_one(void * blob, int parent, struct of_bus *bus,
1014 			    struct of_bus *pbus, u32 *addr,
1015 			    int na, int ns, int pna, const char *rprop)
1016 {
1017 	const u32 *ranges;
1018 	int rlen;
1019 	int rone;
1020 	u64 offset = OF_BAD_ADDR;
1021 
1022 	/* Normally, an absence of a "ranges" property means we are
1023 	 * crossing a non-translatable boundary, and thus the addresses
1024 	 * below the current not cannot be converted to CPU physical ones.
1025 	 * Unfortunately, while this is very clear in the spec, it's not
1026 	 * what Apple understood, and they do have things like /uni-n or
1027 	 * /ht nodes with no "ranges" property and a lot of perfectly
1028 	 * useable mapped devices below them. Thus we treat the absence of
1029 	 * "ranges" as equivalent to an empty "ranges" property which means
1030 	 * a 1:1 translation at that level. It's up to the caller not to try
1031 	 * to translate addresses that aren't supposed to be translated in
1032 	 * the first place. --BenH.
1033 	 */
1034 	ranges = (u32 *)fdt_getprop(blob, parent, rprop, &rlen);
1035 	if (ranges == NULL || rlen == 0) {
1036 		offset = of_read_number(addr, na);
1037 		memset(addr, 0, pna * 4);
1038 		debug("OF: no ranges, 1:1 translation\n");
1039 		goto finish;
1040 	}
1041 
1042 	debug("OF: walking ranges...\n");
1043 
1044 	/* Now walk through the ranges */
1045 	rlen /= 4;
1046 	rone = na + pna + ns;
1047 	for (; rlen >= rone; rlen -= rone, ranges += rone) {
1048 		offset = bus->map(addr, ranges, na, ns, pna);
1049 		if (offset != OF_BAD_ADDR)
1050 			break;
1051 	}
1052 	if (offset == OF_BAD_ADDR) {
1053 		debug("OF: not found !\n");
1054 		return 1;
1055 	}
1056 	memcpy(addr, ranges + na, 4 * pna);
1057 
1058  finish:
1059 	of_dump_addr("OF: parent translation for:", addr, pna);
1060 	debug("OF: with offset: "PRu64"\n", offset);
1061 
1062 	/* Translate it into parent bus space */
1063 	return pbus->translate(addr, offset, pna);
1064 }
1065 
1066 /*
1067  * Translate an address from the device-tree into a CPU physical address,
1068  * this walks up the tree and applies the various bus mappings on the
1069  * way.
1070  *
1071  * Note: We consider that crossing any level with #size-cells == 0 to mean
1072  * that translation is impossible (that is we are not dealing with a value
1073  * that can be mapped to a cpu physical address). This is not really specified
1074  * that way, but this is traditionally the way IBM at least do things
1075  */
1076 u64 __of_translate_address(void *blob, int node_offset, const u32 *in_addr,
1077 			   const char *rprop)
1078 {
1079 	int parent;
1080 	struct of_bus *bus, *pbus;
1081 	u32 addr[OF_MAX_ADDR_CELLS];
1082 	int na, ns, pna, pns;
1083 	u64 result = OF_BAD_ADDR;
1084 
1085 	debug("OF: ** translation for device %s **\n",
1086 		fdt_get_name(blob, node_offset, NULL));
1087 
1088 	/* Get parent & match bus type */
1089 	parent = fdt_parent_offset(blob, node_offset);
1090 	if (parent < 0)
1091 		goto bail;
1092 	bus = &of_busses[0];
1093 
1094 	/* Cound address cells & copy address locally */
1095 	bus->count_cells(blob, parent, &na, &ns);
1096 	if (!OF_CHECK_COUNTS(na, ns)) {
1097 		printf("%s: Bad cell count for %s\n", __FUNCTION__,
1098 		       fdt_get_name(blob, node_offset, NULL));
1099 		goto bail;
1100 	}
1101 	memcpy(addr, in_addr, na * 4);
1102 
1103 	debug("OF: bus is %s (na=%d, ns=%d) on %s\n",
1104 	    bus->name, na, ns, fdt_get_name(blob, parent, NULL));
1105 	of_dump_addr("OF: translating address:", addr, na);
1106 
1107 	/* Translate */
1108 	for (;;) {
1109 		/* Switch to parent bus */
1110 		node_offset = parent;
1111 		parent = fdt_parent_offset(blob, node_offset);
1112 
1113 		/* If root, we have finished */
1114 		if (parent < 0) {
1115 			debug("OF: reached root node\n");
1116 			result = of_read_number(addr, na);
1117 			break;
1118 		}
1119 
1120 		/* Get new parent bus and counts */
1121 		pbus = &of_busses[0];
1122 		pbus->count_cells(blob, parent, &pna, &pns);
1123 		if (!OF_CHECK_COUNTS(pna, pns)) {
1124 			printf("%s: Bad cell count for %s\n", __FUNCTION__,
1125 				fdt_get_name(blob, node_offset, NULL));
1126 			break;
1127 		}
1128 
1129 		debug("OF: parent bus is %s (na=%d, ns=%d) on %s\n",
1130 		    pbus->name, pna, pns, fdt_get_name(blob, parent, NULL));
1131 
1132 		/* Apply bus translation */
1133 		if (of_translate_one(blob, node_offset, bus, pbus,
1134 					addr, na, ns, pna, rprop))
1135 			break;
1136 
1137 		/* Complete the move up one level */
1138 		na = pna;
1139 		ns = pns;
1140 		bus = pbus;
1141 
1142 		of_dump_addr("OF: one level translation:", addr, na);
1143 	}
1144  bail:
1145 
1146 	return result;
1147 }
1148 
1149 u64 fdt_translate_address(void *blob, int node_offset, const u32 *in_addr)
1150 {
1151 	return __of_translate_address(blob, node_offset, in_addr, "ranges");
1152 }
1153 
1154 /**
1155  * fdt_node_offset_by_compat_reg: Find a node that matches compatiable and
1156  * who's reg property matches a physical cpu address
1157  *
1158  * @blob: ptr to device tree
1159  * @compat: compatiable string to match
1160  * @compat_off: property name
1161  *
1162  */
1163 int fdt_node_offset_by_compat_reg(void *blob, const char *compat,
1164 					phys_addr_t compat_off)
1165 {
1166 	int len, off = fdt_node_offset_by_compatible(blob, -1, compat);
1167 	while (off != -FDT_ERR_NOTFOUND) {
1168 		u32 *reg = (u32 *)fdt_getprop(blob, off, "reg", &len);
1169 		if (reg) {
1170 			if (compat_off == fdt_translate_address(blob, off, reg))
1171 				return off;
1172 		}
1173 		off = fdt_node_offset_by_compatible(blob, off, compat);
1174 	}
1175 
1176 	return -FDT_ERR_NOTFOUND;
1177 }
1178 
1179 /**
1180  * fdt_alloc_phandle: Return next free phandle value
1181  *
1182  * @blob: ptr to device tree
1183  */
1184 int fdt_alloc_phandle(void *blob)
1185 {
1186 	int offset, len, phandle = 0;
1187 	const u32 *val;
1188 
1189 	for (offset = fdt_next_node(blob, -1, NULL); offset >= 0;
1190 	     offset = fdt_next_node(blob, offset, NULL)) {
1191 		val = fdt_getprop(blob, offset, "linux,phandle", &len);
1192 		if (val)
1193 			phandle = max(*val, phandle);
1194 	}
1195 
1196 	return phandle + 1;
1197 }
1198 
1199 #if defined(CONFIG_VIDEO)
1200 int fdt_add_edid(void *blob, const char *compat, unsigned char *edid_buf)
1201 {
1202 	int noff;
1203 	int ret;
1204 
1205 	noff = fdt_node_offset_by_compatible(blob, -1, compat);
1206 	if (noff != -FDT_ERR_NOTFOUND) {
1207 		debug("%s: %s\n", fdt_get_name(blob, noff, 0), compat);
1208 add_edid:
1209 		ret = fdt_setprop(blob, noff, "edid", edid_buf, 128);
1210 		if (ret == -FDT_ERR_NOSPACE) {
1211 			ret = fdt_increase_size(blob, 512);
1212 			if (!ret)
1213 				goto add_edid;
1214 			else
1215 				goto err_size;
1216 		} else if (ret < 0) {
1217 			printf("Can't add property: %s\n", fdt_strerror(ret));
1218 			return ret;
1219 		}
1220 	}
1221 	return 0;
1222 err_size:
1223 	printf("Can't increase blob size: %s\n", fdt_strerror(ret));
1224 	return ret;
1225 }
1226 #endif
1227