xref: /openbmc/u-boot/common/fdt_support.c (revision cdb749778aa3a8f8d2a41dd4ad811ef822aecfe6)
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 int fdt_fixup_memory(void *blob, u64 start, u64 size)
366 {
367 	int err, nodeoffset, len = 0;
368 	u8 tmp[16];
369 	const u32 *addrcell, *sizecell;
370 
371 	err = fdt_check_header(blob);
372 	if (err < 0) {
373 		printf("%s: %s\n", __FUNCTION__, fdt_strerror(err));
374 		return err;
375 	}
376 
377 	/* update, or add and update /memory node */
378 	nodeoffset = fdt_path_offset(blob, "/memory");
379 	if (nodeoffset < 0) {
380 		nodeoffset = fdt_add_subnode(blob, 0, "memory");
381 		if (nodeoffset < 0)
382 			printf("WARNING: could not create /memory: %s.\n",
383 					fdt_strerror(nodeoffset));
384 		return nodeoffset;
385 	}
386 	err = fdt_setprop(blob, nodeoffset, "device_type", "memory",
387 			sizeof("memory"));
388 	if (err < 0) {
389 		printf("WARNING: could not set %s %s.\n", "device_type",
390 				fdt_strerror(err));
391 		return err;
392 	}
393 
394 	addrcell = fdt_getprop(blob, 0, "#address-cells", NULL);
395 	/* use shifts and mask to ensure endianness */
396 	if ((addrcell) && (*addrcell == 2)) {
397 		tmp[0] = (start >> 56) & 0xff;
398 		tmp[1] = (start >> 48) & 0xff;
399 		tmp[2] = (start >> 40) & 0xff;
400 		tmp[3] = (start >> 32) & 0xff;
401 		tmp[4] = (start >> 24) & 0xff;
402 		tmp[5] = (start >> 16) & 0xff;
403 		tmp[6] = (start >>  8) & 0xff;
404 		tmp[7] = (start      ) & 0xff;
405 		len = 8;
406 	} else {
407 		tmp[0] = (start >> 24) & 0xff;
408 		tmp[1] = (start >> 16) & 0xff;
409 		tmp[2] = (start >>  8) & 0xff;
410 		tmp[3] = (start      ) & 0xff;
411 		len = 4;
412 	}
413 
414 	sizecell = fdt_getprop(blob, 0, "#size-cells", NULL);
415 	/* use shifts and mask to ensure endianness */
416 	if ((sizecell) && (*sizecell == 2)) {
417 		tmp[0+len] = (size >> 56) & 0xff;
418 		tmp[1+len] = (size >> 48) & 0xff;
419 		tmp[2+len] = (size >> 40) & 0xff;
420 		tmp[3+len] = (size >> 32) & 0xff;
421 		tmp[4+len] = (size >> 24) & 0xff;
422 		tmp[5+len] = (size >> 16) & 0xff;
423 		tmp[6+len] = (size >>  8) & 0xff;
424 		tmp[7+len] = (size      ) & 0xff;
425 		len += 8;
426 	} else {
427 		tmp[0+len] = (size >> 24) & 0xff;
428 		tmp[1+len] = (size >> 16) & 0xff;
429 		tmp[2+len] = (size >>  8) & 0xff;
430 		tmp[3+len] = (size      ) & 0xff;
431 		len += 4;
432 	}
433 
434 	err = fdt_setprop(blob, nodeoffset, "reg", tmp, len);
435 	if (err < 0) {
436 		printf("WARNING: could not set %s %s.\n",
437 				"reg", fdt_strerror(err));
438 		return err;
439 	}
440 	return 0;
441 }
442 
443 void fdt_fixup_ethernet(void *fdt)
444 {
445 	int node, i, j;
446 	char enet[16], *tmp, *end;
447 	char mac[16] = "ethaddr";
448 	const char *path;
449 	unsigned char mac_addr[6];
450 
451 	node = fdt_path_offset(fdt, "/aliases");
452 	if (node < 0)
453 		return;
454 
455 	i = 0;
456 	while ((tmp = getenv(mac)) != NULL) {
457 		sprintf(enet, "ethernet%d", i);
458 		path = fdt_getprop(fdt, node, enet, NULL);
459 		if (!path) {
460 			debug("No alias for %s\n", enet);
461 			sprintf(mac, "eth%daddr", ++i);
462 			continue;
463 		}
464 
465 		for (j = 0; j < 6; j++) {
466 			mac_addr[j] = tmp ? simple_strtoul(tmp, &end, 16) : 0;
467 			if (tmp)
468 				tmp = (*end) ? end+1 : end;
469 		}
470 
471 		do_fixup_by_path(fdt, path, "mac-address", &mac_addr, 6, 0);
472 		do_fixup_by_path(fdt, path, "local-mac-address",
473 				&mac_addr, 6, 1);
474 
475 		sprintf(mac, "eth%daddr", ++i);
476 	}
477 }
478 
479 /* Resize the fdt to its actual size + a bit of padding */
480 int fdt_resize(void *blob)
481 {
482 	int i;
483 	uint64_t addr, size;
484 	int total, ret;
485 	uint actualsize;
486 
487 	if (!blob)
488 		return 0;
489 
490 	total = fdt_num_mem_rsv(blob);
491 	for (i = 0; i < total; i++) {
492 		fdt_get_mem_rsv(blob, i, &addr, &size);
493 		if (addr == (uint64_t)(u32)blob) {
494 			fdt_del_mem_rsv(blob, i);
495 			break;
496 		}
497 	}
498 
499 	/*
500 	 * Calculate the actual size of the fdt
501 	 * plus the size needed for two fdt_add_mem_rsv, one
502 	 * for the fdt itself and one for a possible initrd
503 	 */
504 	actualsize = fdt_off_dt_strings(blob) +
505 		fdt_size_dt_strings(blob) + 2*sizeof(struct fdt_reserve_entry);
506 
507 	/* Make it so the fdt ends on a page boundary */
508 	actualsize = ALIGN(actualsize + ((uint)blob & 0xfff), 0x1000);
509 	actualsize = actualsize - ((uint)blob & 0xfff);
510 
511 	/* Change the fdt header to reflect the correct size */
512 	fdt_set_totalsize(blob, actualsize);
513 
514 	/* Add the new reservation */
515 	ret = fdt_add_mem_rsv(blob, (uint)blob, actualsize);
516 	if (ret < 0)
517 		return ret;
518 
519 	return actualsize;
520 }
521 
522 #ifdef CONFIG_PCI
523 #define CONFIG_SYS_PCI_NR_INBOUND_WIN 4
524 
525 #define FDT_PCI_PREFETCH	(0x40000000)
526 #define FDT_PCI_MEM32		(0x02000000)
527 #define FDT_PCI_IO		(0x01000000)
528 #define FDT_PCI_MEM64		(0x03000000)
529 
530 int fdt_pci_dma_ranges(void *blob, int phb_off, struct pci_controller *hose) {
531 
532 	int addrcell, sizecell, len, r;
533 	u32 *dma_range;
534 	/* sized based on pci addr cells, size-cells, & address-cells */
535 	u32 dma_ranges[(3 + 2 + 2) * CONFIG_SYS_PCI_NR_INBOUND_WIN];
536 
537 	addrcell = fdt_getprop_u32_default(blob, "/", "#address-cells", 1);
538 	sizecell = fdt_getprop_u32_default(blob, "/", "#size-cells", 1);
539 
540 	dma_range = &dma_ranges[0];
541 	for (r = 0; r < hose->region_count; r++) {
542 		u64 bus_start, phys_start, size;
543 
544 		/* skip if !PCI_REGION_SYS_MEMORY */
545 		if (!(hose->regions[r].flags & PCI_REGION_SYS_MEMORY))
546 			continue;
547 
548 		bus_start = (u64)hose->regions[r].bus_start;
549 		phys_start = (u64)hose->regions[r].phys_start;
550 		size = (u64)hose->regions[r].size;
551 
552 		dma_range[0] = 0;
553 		if (size >= 0x100000000ull)
554 			dma_range[0] |= FDT_PCI_MEM64;
555 		else
556 			dma_range[0] |= FDT_PCI_MEM32;
557 		if (hose->regions[r].flags & PCI_REGION_PREFETCH)
558 			dma_range[0] |= FDT_PCI_PREFETCH;
559 #ifdef CONFIG_SYS_PCI_64BIT
560 		dma_range[1] = bus_start >> 32;
561 #else
562 		dma_range[1] = 0;
563 #endif
564 		dma_range[2] = bus_start & 0xffffffff;
565 
566 		if (addrcell == 2) {
567 			dma_range[3] = phys_start >> 32;
568 			dma_range[4] = phys_start & 0xffffffff;
569 		} else {
570 			dma_range[3] = phys_start & 0xffffffff;
571 		}
572 
573 		if (sizecell == 2) {
574 			dma_range[3 + addrcell + 0] = size >> 32;
575 			dma_range[3 + addrcell + 1] = size & 0xffffffff;
576 		} else {
577 			dma_range[3 + addrcell + 0] = size & 0xffffffff;
578 		}
579 
580 		dma_range += (3 + addrcell + sizecell);
581 	}
582 
583 	len = dma_range - &dma_ranges[0];
584 	if (len)
585 		fdt_setprop(blob, phb_off, "dma-ranges", &dma_ranges[0], len*4);
586 
587 	return 0;
588 }
589 #endif
590 
591 #ifdef CONFIG_FDT_FIXUP_NOR_FLASH_SIZE
592 /*
593  * This function can be used to update the size in the "reg" property
594  * of the NOR FLASH device nodes. This is necessary for boards with
595  * non-fixed NOR FLASH sizes.
596  */
597 int fdt_fixup_nor_flash_size(void *blob, int cs, u32 size)
598 {
599 	char compat[][16] = { "cfi-flash", "jedec-flash" };
600 	int off;
601 	int len;
602 	struct fdt_property *prop;
603 	u32 *reg;
604 	int i;
605 
606 	for (i = 0; i < 2; i++) {
607 		off = fdt_node_offset_by_compatible(blob, -1, compat[i]);
608 		while (off != -FDT_ERR_NOTFOUND) {
609 			/*
610 			 * Found one compatible node, now check if this one
611 			 * has the correct CS
612 			 */
613 			prop = fdt_get_property_w(blob, off, "reg", &len);
614 			if (prop) {
615 				reg = (u32 *)&prop->data[0];
616 				if (reg[0] == cs) {
617 					reg[2] = size;
618 					fdt_setprop(blob, off, "reg", reg,
619 						    3 * sizeof(u32));
620 
621 					return 0;
622 				}
623 			}
624 
625 			/* Move to next compatible node */
626 			off = fdt_node_offset_by_compatible(blob, off,
627 							    compat[i]);
628 		}
629 	}
630 
631 	return -1;
632 }
633 #endif
634 
635 #ifdef CONFIG_FDT_FIXUP_PARTITIONS
636 #include <jffs2/load_kernel.h>
637 #include <mtd_node.h>
638 
639 struct reg_cell {
640 	unsigned int r0;
641 	unsigned int r1;
642 };
643 
644 int fdt_del_subnodes(const void *blob, int parent_offset)
645 {
646 	int off, ndepth;
647 	int ret;
648 
649 	for (ndepth = 0, off = fdt_next_node(blob, parent_offset, &ndepth);
650 	     (off >= 0) && (ndepth > 0);
651 	     off = fdt_next_node(blob, off, &ndepth)) {
652 		if (ndepth == 1) {
653 			debug("delete %s: offset: %x\n",
654 				fdt_get_name(blob, off, 0), off);
655 			ret = fdt_del_node((void *)blob, off);
656 			if (ret < 0) {
657 				printf("Can't delete node: %s\n",
658 					fdt_strerror(ret));
659 				return ret;
660 			} else {
661 				ndepth = 0;
662 				off = parent_offset;
663 			}
664 		}
665 	}
666 	return 0;
667 }
668 
669 int fdt_increase_size(void *fdt, int add_len)
670 {
671 	int newlen;
672 
673 	newlen = fdt_totalsize(fdt) + add_len;
674 
675 	/* Open in place with a new len */
676 	return fdt_open_into(fdt, fdt, newlen);
677 }
678 
679 int fdt_del_partitions(void *blob, int parent_offset)
680 {
681 	const void *prop;
682 	int ndepth = 0;
683 	int off;
684 	int ret;
685 
686 	off = fdt_next_node(blob, parent_offset, &ndepth);
687 	if (off > 0 && ndepth == 1) {
688 		prop = fdt_getprop(blob, off, "label", NULL);
689 		if (prop == NULL) {
690 			/*
691 			 * Could not find label property, nand {}; node?
692 			 * Check subnode, delete partitions there if any.
693 			 */
694 			return fdt_del_partitions(blob, off);
695 		} else {
696 			ret = fdt_del_subnodes(blob, parent_offset);
697 			if (ret < 0) {
698 				printf("Can't remove subnodes: %s\n",
699 					fdt_strerror(ret));
700 				return ret;
701 			}
702 		}
703 	}
704 	return 0;
705 }
706 
707 int fdt_node_set_part_info(void *blob, int parent_offset,
708 			   struct mtd_device *dev)
709 {
710 	struct list_head *pentry;
711 	struct part_info *part;
712 	struct reg_cell cell;
713 	int off, ndepth = 0;
714 	int part_num, ret;
715 	char buf[64];
716 
717 	ret = fdt_del_partitions(blob, parent_offset);
718 	if (ret < 0)
719 		return ret;
720 
721 	/*
722 	 * Check if it is nand {}; subnode, adjust
723 	 * the offset in this case
724 	 */
725 	off = fdt_next_node(blob, parent_offset, &ndepth);
726 	if (off > 0 && ndepth == 1)
727 		parent_offset = off;
728 
729 	part_num = 0;
730 	list_for_each_prev(pentry, &dev->parts) {
731 		int newoff;
732 
733 		part = list_entry(pentry, struct part_info, link);
734 
735 		debug("%2d: %-20s0x%08x\t0x%08x\t%d\n",
736 			part_num, part->name, part->size,
737 			part->offset, part->mask_flags);
738 
739 		sprintf(buf, "partition@%x", part->offset);
740 add_sub:
741 		ret = fdt_add_subnode(blob, parent_offset, buf);
742 		if (ret == -FDT_ERR_NOSPACE) {
743 			ret = fdt_increase_size(blob, 512);
744 			if (!ret)
745 				goto add_sub;
746 			else
747 				goto err_size;
748 		} else if (ret < 0) {
749 			printf("Can't add partition node: %s\n",
750 				fdt_strerror(ret));
751 			return ret;
752 		}
753 		newoff = ret;
754 
755 		/* Check MTD_WRITEABLE_CMD flag */
756 		if (part->mask_flags & 1) {
757 add_ro:
758 			ret = fdt_setprop(blob, newoff, "read_only", NULL, 0);
759 			if (ret == -FDT_ERR_NOSPACE) {
760 				ret = fdt_increase_size(blob, 512);
761 				if (!ret)
762 					goto add_ro;
763 				else
764 					goto err_size;
765 			} else if (ret < 0)
766 				goto err_prop;
767 		}
768 
769 		cell.r0 = cpu_to_fdt32(part->offset);
770 		cell.r1 = cpu_to_fdt32(part->size);
771 add_reg:
772 		ret = fdt_setprop(blob, newoff, "reg", &cell, sizeof(cell));
773 		if (ret == -FDT_ERR_NOSPACE) {
774 			ret = fdt_increase_size(blob, 512);
775 			if (!ret)
776 				goto add_reg;
777 			else
778 				goto err_size;
779 		} else if (ret < 0)
780 			goto err_prop;
781 
782 add_label:
783 		ret = fdt_setprop_string(blob, newoff, "label", part->name);
784 		if (ret == -FDT_ERR_NOSPACE) {
785 			ret = fdt_increase_size(blob, 512);
786 			if (!ret)
787 				goto add_label;
788 			else
789 				goto err_size;
790 		} else if (ret < 0)
791 			goto err_prop;
792 
793 		part_num++;
794 	}
795 	return 0;
796 err_size:
797 	printf("Can't increase blob size: %s\n", fdt_strerror(ret));
798 	return ret;
799 err_prop:
800 	printf("Can't add property: %s\n", fdt_strerror(ret));
801 	return ret;
802 }
803 
804 /*
805  * Update partitions in nor/nand nodes using info from
806  * mtdparts environment variable. The nodes to update are
807  * specified by node_info structure which contains mtd device
808  * type and compatible string: E. g. the board code in
809  * ft_board_setup() could use:
810  *
811  *	struct node_info nodes[] = {
812  *		{ "fsl,mpc5121-nfc",    MTD_DEV_TYPE_NAND, },
813  *		{ "cfi-flash",          MTD_DEV_TYPE_NOR,  },
814  *	};
815  *
816  *	fdt_fixup_mtdparts(blob, nodes, ARRAY_SIZE(nodes));
817  */
818 void fdt_fixup_mtdparts(void *blob, void *node_info, int node_info_size)
819 {
820 	struct node_info *ni = node_info;
821 	struct mtd_device *dev;
822 	char *parts;
823 	int i, idx;
824 	int noff;
825 
826 	parts = getenv("mtdparts");
827 	if (!parts)
828 		return;
829 
830 	if (mtdparts_init() != 0)
831 		return;
832 
833 	for (i = 0; i < node_info_size; i++) {
834 		idx = 0;
835 		noff = fdt_node_offset_by_compatible(blob, -1, ni[i].compat);
836 		while (noff != -FDT_ERR_NOTFOUND) {
837 			debug("%s: %s, mtd dev type %d\n",
838 				fdt_get_name(blob, noff, 0),
839 				ni[i].compat, ni[i].type);
840 			dev = device_find(ni[i].type, idx++);
841 			if (dev) {
842 				if (fdt_node_set_part_info(blob, noff, dev))
843 					return; /* return on error */
844 			}
845 
846 			/* Jump to next flash node */
847 			noff = fdt_node_offset_by_compatible(blob, noff,
848 							     ni[i].compat);
849 		}
850 	}
851 }
852 #endif
853 
854 void fdt_del_node_and_alias(void *blob, const char *alias)
855 {
856 	int off = fdt_path_offset(blob, alias);
857 
858 	if (off < 0)
859 		return;
860 
861 	fdt_del_node(blob, off);
862 
863 	off = fdt_path_offset(blob, "/aliases");
864 	fdt_delprop(blob, off, alias);
865 }
866 
867 /* Helper to read a big number; size is in cells (not bytes) */
868 static inline u64 of_read_number(const __be32 *cell, int size)
869 {
870 	u64 r = 0;
871 	while (size--)
872 		r = (r << 32) | be32_to_cpu(*(cell++));
873 	return r;
874 }
875 
876 static int of_n_cells(const void *blob, int nodeoffset, const char *name)
877 {
878 	int np;
879 	const int *ip;
880 
881 	do {
882 		np = fdt_parent_offset(blob, nodeoffset);
883 
884 		if (np >= 0)
885 			nodeoffset = np;
886 		ip = (int *)fdt_getprop(blob, nodeoffset, name, NULL);
887 		if (ip)
888 			return be32_to_cpup(ip);
889 	} while (np >= 0);
890 
891 	/* No #<NAME>-cells property for the root node */
892 	return 1;
893 }
894 
895 int of_n_addr_cells(const void *blob, int nodeoffset)
896 {
897 	return of_n_cells(blob, nodeoffset, "#address-cells");
898 }
899 
900 int of_n_size_cells(const void *blob, int nodeoffset)
901 {
902 	return of_n_cells(blob, nodeoffset, "#size-cells");
903 }
904 
905 #define PRu64	"%llx"
906 
907 /* Max address size we deal with */
908 #define OF_MAX_ADDR_CELLS	4
909 #define OF_BAD_ADDR	((u64)-1)
910 #define OF_CHECK_COUNTS(na, ns)	((na) > 0 && (na) <= OF_MAX_ADDR_CELLS && \
911 			(ns) > 0)
912 
913 /* Debug utility */
914 #ifdef DEBUG
915 static void of_dump_addr(const char *s, const u32 *addr, int na)
916 {
917 	printf("%s", s);
918 	while(na--)
919 		printf(" %08x", *(addr++));
920 	printf("\n");
921 }
922 #else
923 static void of_dump_addr(const char *s, const u32 *addr, int na) { }
924 #endif
925 
926 /* Callbacks for bus specific translators */
927 struct of_bus {
928 	const char	*name;
929 	const char	*addresses;
930 	void		(*count_cells)(void *blob, int offset,
931 				int *addrc, int *sizec);
932 	u64		(*map)(u32 *addr, const u32 *range,
933 				int na, int ns, int pna);
934 	int		(*translate)(u32 *addr, u64 offset, int na);
935 };
936 
937 /* Default translator (generic bus) */
938 static void of_bus_default_count_cells(void *blob, int offset,
939 					int *addrc, int *sizec)
940 {
941 	if (addrc)
942 		*addrc = of_n_addr_cells(blob, offset);
943 	if (sizec)
944 		*sizec = of_n_size_cells(blob, offset);
945 }
946 
947 static u64 of_bus_default_map(u32 *addr, const u32 *range,
948 		int na, int ns, int pna)
949 {
950 	u64 cp, s, da;
951 
952 	cp = of_read_number(range, na);
953 	s  = of_read_number(range + na + pna, ns);
954 	da = of_read_number(addr, na);
955 
956 	debug("OF: default map, cp="PRu64", s="PRu64", da="PRu64"\n",
957 	    cp, s, da);
958 
959 	if (da < cp || da >= (cp + s))
960 		return OF_BAD_ADDR;
961 	return da - cp;
962 }
963 
964 static int of_bus_default_translate(u32 *addr, u64 offset, int na)
965 {
966 	u64 a = of_read_number(addr, na);
967 	memset(addr, 0, na * 4);
968 	a += offset;
969 	if (na > 1)
970 		addr[na - 2] = a >> 32;
971 	addr[na - 1] = a & 0xffffffffu;
972 
973 	return 0;
974 }
975 
976 /* Array of bus specific translators */
977 static struct of_bus of_busses[] = {
978 	/* Default */
979 	{
980 		.name = "default",
981 		.addresses = "reg",
982 		.count_cells = of_bus_default_count_cells,
983 		.map = of_bus_default_map,
984 		.translate = of_bus_default_translate,
985 	},
986 };
987 
988 static int of_translate_one(void * blob, int parent, struct of_bus *bus,
989 			    struct of_bus *pbus, u32 *addr,
990 			    int na, int ns, int pna, const char *rprop)
991 {
992 	const u32 *ranges;
993 	int rlen;
994 	int rone;
995 	u64 offset = OF_BAD_ADDR;
996 
997 	/* Normally, an absence of a "ranges" property means we are
998 	 * crossing a non-translatable boundary, and thus the addresses
999 	 * below the current not cannot be converted to CPU physical ones.
1000 	 * Unfortunately, while this is very clear in the spec, it's not
1001 	 * what Apple understood, and they do have things like /uni-n or
1002 	 * /ht nodes with no "ranges" property and a lot of perfectly
1003 	 * useable mapped devices below them. Thus we treat the absence of
1004 	 * "ranges" as equivalent to an empty "ranges" property which means
1005 	 * a 1:1 translation at that level. It's up to the caller not to try
1006 	 * to translate addresses that aren't supposed to be translated in
1007 	 * the first place. --BenH.
1008 	 */
1009 	ranges = (u32 *)fdt_getprop(blob, parent, rprop, &rlen);
1010 	if (ranges == NULL || rlen == 0) {
1011 		offset = of_read_number(addr, na);
1012 		memset(addr, 0, pna * 4);
1013 		debug("OF: no ranges, 1:1 translation\n");
1014 		goto finish;
1015 	}
1016 
1017 	debug("OF: walking ranges...\n");
1018 
1019 	/* Now walk through the ranges */
1020 	rlen /= 4;
1021 	rone = na + pna + ns;
1022 	for (; rlen >= rone; rlen -= rone, ranges += rone) {
1023 		offset = bus->map(addr, ranges, na, ns, pna);
1024 		if (offset != OF_BAD_ADDR)
1025 			break;
1026 	}
1027 	if (offset == OF_BAD_ADDR) {
1028 		debug("OF: not found !\n");
1029 		return 1;
1030 	}
1031 	memcpy(addr, ranges + na, 4 * pna);
1032 
1033  finish:
1034 	of_dump_addr("OF: parent translation for:", addr, pna);
1035 	debug("OF: with offset: "PRu64"\n", offset);
1036 
1037 	/* Translate it into parent bus space */
1038 	return pbus->translate(addr, offset, pna);
1039 }
1040 
1041 /*
1042  * Translate an address from the device-tree into a CPU physical address,
1043  * this walks up the tree and applies the various bus mappings on the
1044  * way.
1045  *
1046  * Note: We consider that crossing any level with #size-cells == 0 to mean
1047  * that translation is impossible (that is we are not dealing with a value
1048  * that can be mapped to a cpu physical address). This is not really specified
1049  * that way, but this is traditionally the way IBM at least do things
1050  */
1051 u64 __of_translate_address(void *blob, int node_offset, const u32 *in_addr,
1052 			   const char *rprop)
1053 {
1054 	int parent;
1055 	struct of_bus *bus, *pbus;
1056 	u32 addr[OF_MAX_ADDR_CELLS];
1057 	int na, ns, pna, pns;
1058 	u64 result = OF_BAD_ADDR;
1059 
1060 	debug("OF: ** translation for device %s **\n",
1061 		fdt_get_name(blob, node_offset, NULL));
1062 
1063 	/* Get parent & match bus type */
1064 	parent = fdt_parent_offset(blob, node_offset);
1065 	if (parent < 0)
1066 		goto bail;
1067 	bus = &of_busses[0];
1068 
1069 	/* Cound address cells & copy address locally */
1070 	bus->count_cells(blob, node_offset, &na, &ns);
1071 	if (!OF_CHECK_COUNTS(na, ns)) {
1072 		printf("%s: Bad cell count for %s\n", __FUNCTION__,
1073 		       fdt_get_name(blob, node_offset, NULL));
1074 		goto bail;
1075 	}
1076 	memcpy(addr, in_addr, na * 4);
1077 
1078 	debug("OF: bus is %s (na=%d, ns=%d) on %s\n",
1079 	    bus->name, na, ns, fdt_get_name(blob, parent, NULL));
1080 	of_dump_addr("OF: translating address:", addr, na);
1081 
1082 	/* Translate */
1083 	for (;;) {
1084 		/* Switch to parent bus */
1085 		node_offset = parent;
1086 		parent = fdt_parent_offset(blob, node_offset);
1087 
1088 		/* If root, we have finished */
1089 		if (parent < 0) {
1090 			debug("OF: reached root node\n");
1091 			result = of_read_number(addr, na);
1092 			break;
1093 		}
1094 
1095 		/* Get new parent bus and counts */
1096 		pbus = &of_busses[0];
1097 		pbus->count_cells(blob, node_offset, &pna, &pns);
1098 		if (!OF_CHECK_COUNTS(pna, pns)) {
1099 			printf("%s: Bad cell count for %s\n", __FUNCTION__,
1100 				fdt_get_name(blob, node_offset, NULL));
1101 			break;
1102 		}
1103 
1104 		debug("OF: parent bus is %s (na=%d, ns=%d) on %s\n",
1105 		    pbus->name, pna, pns, fdt_get_name(blob, parent, NULL));
1106 
1107 		/* Apply bus translation */
1108 		if (of_translate_one(blob, node_offset, bus, pbus,
1109 					addr, na, ns, pna, rprop))
1110 			break;
1111 
1112 		/* Complete the move up one level */
1113 		na = pna;
1114 		ns = pns;
1115 		bus = pbus;
1116 
1117 		of_dump_addr("OF: one level translation:", addr, na);
1118 	}
1119  bail:
1120 
1121 	return result;
1122 }
1123 
1124 u64 fdt_translate_address(void *blob, int node_offset, const u32 *in_addr)
1125 {
1126 	return __of_translate_address(blob, node_offset, in_addr, "ranges");
1127 }
1128 
1129 /**
1130  * fdt_node_offset_by_compat_reg: Find a node that matches compatiable and
1131  * who's reg property matches a physical cpu address
1132  *
1133  * @blob: ptr to device tree
1134  * @compat: compatiable string to match
1135  * @compat_off: property name
1136  *
1137  */
1138 int fdt_node_offset_by_compat_reg(void *blob, const char *compat,
1139 					phys_addr_t compat_off)
1140 {
1141 	int len, off = fdt_node_offset_by_compatible(blob, -1, compat);
1142 	while (off != -FDT_ERR_NOTFOUND) {
1143 		u32 *reg = (u32 *)fdt_getprop(blob, off, "reg", &len);
1144 		if (reg) {
1145 			if (compat_off == fdt_translate_address(blob, off, reg))
1146 				return off;
1147 		}
1148 		off = fdt_node_offset_by_compatible(blob, off, compat);
1149 	}
1150 
1151 	return -FDT_ERR_NOTFOUND;
1152 }
1153 
1154 /**
1155  * fdt_alloc_phandle: Return next free phandle value
1156  *
1157  * @blob: ptr to device tree
1158  */
1159 int fdt_alloc_phandle(void *blob)
1160 {
1161 	int offset, len, phandle = 0;
1162 	const u32 *val;
1163 
1164 	for (offset = fdt_next_node(blob, -1, NULL); offset >= 0;
1165 	     offset = fdt_next_node(blob, offset, NULL)) {
1166 		val = fdt_getprop(blob, offset, "linux,phandle", &len);
1167 		if (val)
1168 			phandle = max(*val, phandle);
1169 	}
1170 
1171 	return phandle + 1;
1172 }
1173