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