]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - ti-u-boot/ti-u-boot.git/blob - common/fdt_support.c
Prepare v2024.04
[ti-u-boot/ti-u-boot.git] / common / fdt_support.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2007
4  * Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com
5  *
6  * Copyright 2010-2011 Freescale Semiconductor, Inc.
7  */
9 #include <common.h>
10 #include <env.h>
11 #include <log.h>
12 #include <mapmem.h>
13 #include <net.h>
14 #include <stdio_dev.h>
15 #include <linux/ctype.h>
16 #include <linux/types.h>
17 #include <asm/global_data.h>
18 #include <linux/libfdt.h>
19 #include <fdt_support.h>
20 #include <exports.h>
21 #include <fdtdec.h>
23 DECLARE_GLOBAL_DATA_PTR;
25 /**
26  * fdt_getprop_u32_default_node - Return a node's property or a default
27  *
28  * @fdt: ptr to device tree
29  * @off: offset of node
30  * @cell: cell offset in property
31  * @prop: property name
32  * @dflt: default value if the property isn't found
33  *
34  * Convenience function to return a node's property or a default value if
35  * the property doesn't exist.
36  */
37 u32 fdt_getprop_u32_default_node(const void *fdt, int off, int cell,
38                                 const char *prop, const u32 dflt)
39 {
40         const fdt32_t *val;
41         int len;
43         val = fdt_getprop(fdt, off, prop, &len);
45         /* Check if property exists */
46         if (!val)
47                 return dflt;
49         /* Check if property is long enough */
50         if (len < ((cell + 1) * sizeof(uint32_t)))
51                 return dflt;
53         return fdt32_to_cpu(*val);
54 }
56 /**
57  * fdt_getprop_u32_default - Find a node and return it's property or a default
58  *
59  * @fdt: ptr to device tree
60  * @path: path of node
61  * @prop: property name
62  * @dflt: default value if the property isn't found
63  *
64  * Convenience function to find a node and return it's property or a
65  * default value if it doesn't exist.
66  */
67 u32 fdt_getprop_u32_default(const void *fdt, const char *path,
68                                 const char *prop, const u32 dflt)
69 {
70         int off;
72         off = fdt_path_offset(fdt, path);
73         if (off < 0)
74                 return dflt;
76         return fdt_getprop_u32_default_node(fdt, off, 0, prop, dflt);
77 }
79 /**
80  * fdt_find_and_setprop: Find a node and set it's property
81  *
82  * @fdt: ptr to device tree
83  * @node: path of node
84  * @prop: property name
85  * @val: ptr to new value
86  * @len: length of new property value
87  * @create: flag to create the property if it doesn't exist
88  *
89  * Convenience function to directly set a property given the path to the node.
90  */
91 int fdt_find_and_setprop(void *fdt, const char *node, const char *prop,
92                          const void *val, int len, int create)
93 {
94         int nodeoff = fdt_path_offset(fdt, node);
96         if (nodeoff < 0)
97                 return nodeoff;
99         if ((!create) && (fdt_get_property(fdt, nodeoff, prop, NULL) == NULL))
100                 return 0; /* create flag not set; so exit quietly */
102         return fdt_setprop(fdt, nodeoff, prop, val, len);
105 /**
106  * fdt_find_or_add_subnode() - find or possibly add a subnode of a given node
107  *
108  * @fdt: pointer to the device tree blob
109  * @parentoffset: structure block offset of a node
110  * @name: name of the subnode to locate
111  *
112  * fdt_subnode_offset() finds a subnode of the node with a given name.
113  * If the subnode does not exist, it will be created.
114  */
115 int fdt_find_or_add_subnode(void *fdt, int parentoffset, const char *name)
117         int offset;
119         offset = fdt_subnode_offset(fdt, parentoffset, name);
121         if (offset == -FDT_ERR_NOTFOUND)
122                 offset = fdt_add_subnode(fdt, parentoffset, name);
124         if (offset < 0)
125                 printf("%s: %s: %s\n", __func__, name, fdt_strerror(offset));
127         return offset;
130 #if defined(CONFIG_OF_STDOUT_VIA_ALIAS) && defined(CONFIG_CONS_INDEX)
131 static int fdt_fixup_stdout(void *fdt, int chosenoff)
133         int err;
134         int aliasoff;
135         char sername[9] = { 0 };
136         const void *path;
137         int len;
138         char tmp[256]; /* long enough */
140         sprintf(sername, "serial%d", CONFIG_CONS_INDEX - 1);
142         aliasoff = fdt_path_offset(fdt, "/aliases");
143         if (aliasoff < 0) {
144                 err = aliasoff;
145                 goto noalias;
146         }
148         path = fdt_getprop(fdt, aliasoff, sername, &len);
149         if (!path) {
150                 err = len;
151                 goto noalias;
152         }
154         /* fdt_setprop may break "path" so we copy it to tmp buffer */
155         memcpy(tmp, path, len);
157         err = fdt_setprop(fdt, chosenoff, "linux,stdout-path", tmp, len);
158         if (err < 0)
159                 printf("WARNING: could not set linux,stdout-path %s.\n",
160                        fdt_strerror(err));
162         return err;
164 noalias:
165         printf("WARNING: %s: could not read %s alias: %s\n",
166                __func__, sername, fdt_strerror(err));
168         return 0;
170 #else
171 static int fdt_fixup_stdout(void *fdt, int chosenoff)
173         return 0;
175 #endif
177 static inline int fdt_setprop_uxx(void *fdt, int nodeoffset, const char *name,
178                                   uint64_t val, int is_u64)
180         if (is_u64)
181                 return fdt_setprop_u64(fdt, nodeoffset, name, val);
182         else
183                 return fdt_setprop_u32(fdt, nodeoffset, name, (uint32_t)val);
186 int fdt_root(void *fdt)
188         char *serial;
189         int err;
191         err = fdt_check_header(fdt);
192         if (err < 0) {
193                 printf("fdt_root: %s\n", fdt_strerror(err));
194                 return err;
195         }
197         serial = env_get("serial#");
198         if (serial) {
199                 err = fdt_setprop(fdt, 0, "serial-number", serial,
200                                   strlen(serial) + 1);
202                 if (err < 0) {
203                         printf("WARNING: could not set serial-number %s.\n",
204                                fdt_strerror(err));
205                         return err;
206                 }
207         }
209         return 0;
212 int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end)
214         int   nodeoffset;
215         int   err, j, total;
216         int is_u64;
217         uint64_t addr, size;
219         /* just return if the size of initrd is zero */
220         if (initrd_start == initrd_end)
221                 return 0;
223         /* find or create "/chosen" node. */
224         nodeoffset = fdt_find_or_add_subnode(fdt, 0, "chosen");
225         if (nodeoffset < 0)
226                 return nodeoffset;
228         total = fdt_num_mem_rsv(fdt);
230         /*
231          * Look for an existing entry and update it.  If we don't find
232          * the entry, we will j be the next available slot.
233          */
234         for (j = 0; j < total; j++) {
235                 err = fdt_get_mem_rsv(fdt, j, &addr, &size);
236                 if (addr == initrd_start) {
237                         fdt_del_mem_rsv(fdt, j);
238                         break;
239                 }
240         }
242         err = fdt_add_mem_rsv(fdt, initrd_start, initrd_end - initrd_start);
243         if (err < 0) {
244                 printf("fdt_initrd: %s\n", fdt_strerror(err));
245                 return err;
246         }
248         is_u64 = (fdt_address_cells(fdt, 0) == 2);
250         err = fdt_setprop_uxx(fdt, nodeoffset, "linux,initrd-start",
251                               (uint64_t)initrd_start, is_u64);
253         if (err < 0) {
254                 printf("WARNING: could not set linux,initrd-start %s.\n",
255                        fdt_strerror(err));
256                 return err;
257         }
259         err = fdt_setprop_uxx(fdt, nodeoffset, "linux,initrd-end",
260                               (uint64_t)initrd_end, is_u64);
262         if (err < 0) {
263                 printf("WARNING: could not set linux,initrd-end %s.\n",
264                        fdt_strerror(err));
266                 return err;
267         }
269         return 0;
272 int fdt_chosen(void *fdt)
274         int   nodeoffset;
275         int   err;
276         char  *str;             /* used to set string properties */
278         err = fdt_check_header(fdt);
279         if (err < 0) {
280                 printf("fdt_chosen: %s\n", fdt_strerror(err));
281                 return err;
282         }
284         /* find or create "/chosen" node. */
285         nodeoffset = fdt_find_or_add_subnode(fdt, 0, "chosen");
286         if (nodeoffset < 0)
287                 return nodeoffset;
289         str = env_get("bootargs");
290         if (str) {
291                 err = fdt_setprop(fdt, nodeoffset, "bootargs", str,
292                                   strlen(str) + 1);
293                 if (err < 0) {
294                         printf("WARNING: could not set bootargs %s.\n",
295                                fdt_strerror(err));
296                         return err;
297                 }
298         }
300         return fdt_fixup_stdout(fdt, nodeoffset);
303 void do_fixup_by_path(void *fdt, const char *path, const char *prop,
304                       const void *val, int len, int create)
306 #if defined(DEBUG)
307         int i;
308         debug("Updating property '%s/%s' = ", path, prop);
309         for (i = 0; i < len; i++)
310                 debug(" %.2x", *(u8*)(val+i));
311         debug("\n");
312 #endif
313         int rc = fdt_find_and_setprop(fdt, path, prop, val, len, create);
314         if (rc)
315                 printf("Unable to update property %s:%s, err=%s\n",
316                         path, prop, fdt_strerror(rc));
319 void do_fixup_by_path_u32(void *fdt, const char *path, const char *prop,
320                           u32 val, int create)
322         fdt32_t tmp = cpu_to_fdt32(val);
323         do_fixup_by_path(fdt, path, prop, &tmp, sizeof(tmp), create);
326 void do_fixup_by_prop(void *fdt,
327                       const char *pname, const void *pval, int plen,
328                       const char *prop, const void *val, int len,
329                       int create)
331         int off;
332 #if defined(DEBUG)
333         int i;
334         debug("Updating property '%s' = ", prop);
335         for (i = 0; i < len; i++)
336                 debug(" %.2x", *(u8*)(val+i));
337         debug("\n");
338 #endif
339         off = fdt_node_offset_by_prop_value(fdt, -1, pname, pval, plen);
340         while (off != -FDT_ERR_NOTFOUND) {
341                 if (create || (fdt_get_property(fdt, off, prop, NULL) != NULL))
342                         fdt_setprop(fdt, off, prop, val, len);
343                 off = fdt_node_offset_by_prop_value(fdt, off, pname, pval, plen);
344         }
347 void do_fixup_by_prop_u32(void *fdt,
348                           const char *pname, const void *pval, int plen,
349                           const char *prop, u32 val, int create)
351         fdt32_t tmp = cpu_to_fdt32(val);
352         do_fixup_by_prop(fdt, pname, pval, plen, prop, &tmp, 4, create);
355 void do_fixup_by_compat(void *fdt, const char *compat,
356                         const char *prop, const void *val, int len, int create)
358         int off = -1;
359 #if defined(DEBUG)
360         int i;
361         debug("Updating property '%s' = ", prop);
362         for (i = 0; i < len; i++)
363                 debug(" %.2x", *(u8*)(val+i));
364         debug("\n");
365 #endif
366         off = fdt_node_offset_by_compatible(fdt, -1, compat);
367         while (off != -FDT_ERR_NOTFOUND) {
368                 if (create || (fdt_get_property(fdt, off, prop, NULL) != NULL))
369                         fdt_setprop(fdt, off, prop, val, len);
370                 off = fdt_node_offset_by_compatible(fdt, off, compat);
371         }
374 void do_fixup_by_compat_u32(void *fdt, const char *compat,
375                             const char *prop, u32 val, int create)
377         fdt32_t tmp = cpu_to_fdt32(val);
378         do_fixup_by_compat(fdt, compat, prop, &tmp, 4, create);
381 #ifdef CONFIG_ARCH_FIXUP_FDT_MEMORY
382 /*
383  * fdt_pack_reg - pack address and size array into the "reg"-suitable stream
384  */
385 static int fdt_pack_reg(const void *fdt, void *buf, u64 *address, u64 *size,
386                         int n)
388         int i;
389         int address_cells = fdt_address_cells(fdt, 0);
390         int size_cells = fdt_size_cells(fdt, 0);
391         char *p = buf;
393         for (i = 0; i < n; i++) {
394                 if (address_cells == 2)
395                         *(fdt64_t *)p = cpu_to_fdt64(address[i]);
396                 else
397                         *(fdt32_t *)p = cpu_to_fdt32(address[i]);
398                 p += 4 * address_cells;
400                 if (size_cells == 2)
401                         *(fdt64_t *)p = cpu_to_fdt64(size[i]);
402                 else
403                         *(fdt32_t *)p = cpu_to_fdt32(size[i]);
404                 p += 4 * size_cells;
405         }
407         return p - (char *)buf;
410 #if CONFIG_NR_DRAM_BANKS > 4
411 #define MEMORY_BANKS_MAX CONFIG_NR_DRAM_BANKS
412 #else
413 #define MEMORY_BANKS_MAX 4
414 #endif
415 int fdt_fixup_memory_banks(void *blob, u64 start[], u64 size[], int banks)
417         int err, nodeoffset;
418         int len, i;
419         u8 tmp[MEMORY_BANKS_MAX * 16]; /* Up to 64-bit address + 64-bit size */
421         if (banks > MEMORY_BANKS_MAX) {
422                 printf("%s: num banks %d exceeds hardcoded limit %d."
423                        " Recompile with higher MEMORY_BANKS_MAX?\n",
424                        __FUNCTION__, banks, MEMORY_BANKS_MAX);
425                 return -1;
426         }
428         err = fdt_check_header(blob);
429         if (err < 0) {
430                 printf("%s: %s\n", __FUNCTION__, fdt_strerror(err));
431                 return err;
432         }
434         /* find or create "/memory" node. */
435         nodeoffset = fdt_find_or_add_subnode(blob, 0, "memory");
436         if (nodeoffset < 0)
437                         return nodeoffset;
439         err = fdt_setprop(blob, nodeoffset, "device_type", "memory",
440                         sizeof("memory"));
441         if (err < 0) {
442                 printf("WARNING: could not set %s %s.\n", "device_type",
443                                 fdt_strerror(err));
444                 return err;
445         }
447         for (i = 0; i < banks; i++) {
448                 if (start[i] == 0 && size[i] == 0)
449                         break;
450         }
452         banks = i;
454         if (!banks)
455                 return 0;
457         len = fdt_pack_reg(blob, tmp, start, size, banks);
459         err = fdt_setprop(blob, nodeoffset, "reg", tmp, len);
460         if (err < 0) {
461                 printf("WARNING: could not set %s %s.\n",
462                                 "reg", fdt_strerror(err));
463                 return err;
464         }
465         return 0;
468 int fdt_set_usable_memory(void *blob, u64 start[], u64 size[], int areas)
470         int err, nodeoffset;
471         int len;
472         u8 tmp[8 * 16]; /* Up to 64-bit address + 64-bit size */
474         if (areas > 8) {
475                 printf("%s: num areas %d exceeds hardcoded limit %d\n",
476                        __func__, areas, 8);
477                 return -1;
478         }
480         err = fdt_check_header(blob);
481         if (err < 0) {
482                 printf("%s: %s\n", __func__, fdt_strerror(err));
483                 return err;
484         }
486         /* find or create "/memory" node. */
487         nodeoffset = fdt_find_or_add_subnode(blob, 0, "memory");
488         if (nodeoffset < 0)
489                 return nodeoffset;
491         len = fdt_pack_reg(blob, tmp, start, size, areas);
493         err = fdt_setprop(blob, nodeoffset, "linux,usable-memory", tmp, len);
494         if (err < 0) {
495                 printf("WARNING: could not set %s %s.\n",
496                        "reg", fdt_strerror(err));
497                 return err;
498         }
500         return 0;
502 #endif
504 int fdt_fixup_memory(void *blob, u64 start, u64 size)
506         return fdt_fixup_memory_banks(blob, &start, &size, 1);
509 void fdt_fixup_ethernet(void *fdt)
511         int i = 0, j, prop;
512         char *tmp, *end;
513         char mac[16];
514         const char *path;
515         unsigned char mac_addr[ARP_HLEN];
516         int offset;
517 #ifdef FDT_SEQ_MACADDR_FROM_ENV
518         int nodeoff;
519         const struct fdt_property *fdt_prop;
520 #endif
522         if (fdt_path_offset(fdt, "/aliases") < 0)
523                 return;
525         /* Cycle through all aliases */
526         for (prop = 0; ; prop++) {
527                 const char *name;
529                 /* FDT might have been edited, recompute the offset */
530                 offset = fdt_first_property_offset(fdt,
531                         fdt_path_offset(fdt, "/aliases"));
532                 /* Select property number 'prop' */
533                 for (j = 0; j < prop; j++)
534                         offset = fdt_next_property_offset(fdt, offset);
536                 if (offset < 0)
537                         break;
539                 path = fdt_getprop_by_offset(fdt, offset, &name, NULL);
540                 if (!strncmp(name, "ethernet", 8)) {
541                         /* Treat plain "ethernet" same as "ethernet0". */
542                         if (!strcmp(name, "ethernet")
543 #ifdef FDT_SEQ_MACADDR_FROM_ENV
544                          || !strcmp(name, "ethernet0")
545 #endif
546                         )
547                                 i = 0;
548 #ifndef FDT_SEQ_MACADDR_FROM_ENV
549                         else
550                                 i = trailing_strtol(name);
551 #endif
552                         if (i != -1) {
553                                 if (i == 0)
554                                         strcpy(mac, "ethaddr");
555                                 else
556                                         sprintf(mac, "eth%daddr", i);
557                         } else {
558                                 continue;
559                         }
560 #ifdef FDT_SEQ_MACADDR_FROM_ENV
561                         nodeoff = fdt_path_offset(fdt, path);
562                         fdt_prop = fdt_get_property(fdt, nodeoff, "status",
563                                                     NULL);
564                         if (fdt_prop && !strcmp(fdt_prop->data, "disabled"))
565                                 continue;
566                         i++;
567 #endif
568                         tmp = env_get(mac);
569                         if (!tmp)
570                                 continue;
572                         for (j = 0; j < 6; j++) {
573                                 mac_addr[j] = tmp ?
574                                               simple_strtoul(tmp, &end, 16) : 0;
575                                 if (tmp)
576                                         tmp = (*end) ? end + 1 : end;
577                         }
579                         do_fixup_by_path(fdt, path, "mac-address",
580                                          &mac_addr, 6, 0);
581                         do_fixup_by_path(fdt, path, "local-mac-address",
582                                          &mac_addr, 6, 1);
583                 }
584         }
587 int fdt_record_loadable(void *blob, u32 index, const char *name,
588                         uintptr_t load_addr, u32 size, uintptr_t entry_point,
589                         const char *type, const char *os)
591         int err, node;
593         err = fdt_check_header(blob);
594         if (err < 0) {
595                 printf("%s: %s\n", __func__, fdt_strerror(err));
596                 return err;
597         }
599         /* find or create "/fit-images" node */
600         node = fdt_find_or_add_subnode(blob, 0, "fit-images");
601         if (node < 0)
602                 return node;
604         /* find or create "/fit-images/<name>" node */
605         node = fdt_find_or_add_subnode(blob, node, name);
606         if (node < 0)
607                 return node;
609         fdt_setprop_u64(blob, node, "load", load_addr);
610         if (entry_point != -1)
611                 fdt_setprop_u64(blob, node, "entry", entry_point);
612         fdt_setprop_u32(blob, node, "size", size);
613         if (type)
614                 fdt_setprop_string(blob, node, "type", type);
615         if (os)
616                 fdt_setprop_string(blob, node, "os", os);
618         return node;
621 /* Resize the fdt to its actual size + a bit of padding */
622 int fdt_shrink_to_minimum(void *blob, uint extrasize)
624         int i;
625         uint64_t addr, size;
626         int total, ret;
627         uint actualsize;
628         int fdt_memrsv = 0;
630         if (!blob)
631                 return 0;
633         total = fdt_num_mem_rsv(blob);
634         for (i = 0; i < total; i++) {
635                 fdt_get_mem_rsv(blob, i, &addr, &size);
636                 if (addr == (uintptr_t)blob) {
637                         fdt_del_mem_rsv(blob, i);
638                         fdt_memrsv = 1;
639                         break;
640                 }
641         }
643         /*
644          * Calculate the actual size of the fdt
645          * plus the size needed for 5 fdt_add_mem_rsv, one
646          * for the fdt itself and 4 for a possible initrd
647          * ((initrd-start + initrd-end) * 2 (name & value))
648          */
649         actualsize = fdt_off_dt_strings(blob) +
650                 fdt_size_dt_strings(blob) + 5 * sizeof(struct fdt_reserve_entry);
652         actualsize += extrasize;
653         /* Make it so the fdt ends on a page boundary */
654         actualsize = ALIGN(actualsize + ((uintptr_t)blob & 0xfff), 0x1000);
655         actualsize = actualsize - ((uintptr_t)blob & 0xfff);
657         /* Change the fdt header to reflect the correct size */
658         fdt_set_totalsize(blob, actualsize);
660         if (fdt_memrsv) {
661                 /* Add the new reservation */
662                 ret = fdt_add_mem_rsv(blob, map_to_sysmem(blob), actualsize);
663                 if (ret < 0)
664                         return ret;
665         }
667         return actualsize;
670 #ifdef CONFIG_PCI
671 #define CONFIG_SYS_PCI_NR_INBOUND_WIN 4
673 #define FDT_PCI_PREFETCH        (0x40000000)
674 #define FDT_PCI_MEM32           (0x02000000)
675 #define FDT_PCI_IO              (0x01000000)
676 #define FDT_PCI_MEM64           (0x03000000)
678 int fdt_pci_dma_ranges(void *blob, int phb_off, struct pci_controller *hose) {
680         int addrcell, sizecell, len, r;
681         u32 *dma_range;
682         /* sized based on pci addr cells, size-cells, & address-cells */
683         u32 dma_ranges[(3 + 2 + 2) * CONFIG_SYS_PCI_NR_INBOUND_WIN];
685         addrcell = fdt_getprop_u32_default(blob, "/", "#address-cells", 1);
686         sizecell = fdt_getprop_u32_default(blob, "/", "#size-cells", 1);
688         dma_range = &dma_ranges[0];
689         for (r = 0; r < hose->region_count; r++) {
690                 u64 bus_start, phys_start, size;
692                 /* skip if !PCI_REGION_SYS_MEMORY */
693                 if (!(hose->regions[r].flags & PCI_REGION_SYS_MEMORY))
694                         continue;
696                 bus_start = (u64)hose->regions[r].bus_start;
697                 phys_start = (u64)hose->regions[r].phys_start;
698                 size = (u64)hose->regions[r].size;
700                 dma_range[0] = 0;
701                 if (size >= 0x100000000ull)
702                         dma_range[0] |= cpu_to_fdt32(FDT_PCI_MEM64);
703                 else
704                         dma_range[0] |= cpu_to_fdt32(FDT_PCI_MEM32);
705                 if (hose->regions[r].flags & PCI_REGION_PREFETCH)
706                         dma_range[0] |= cpu_to_fdt32(FDT_PCI_PREFETCH);
707 #ifdef CONFIG_SYS_PCI_64BIT
708                 dma_range[1] = cpu_to_fdt32(bus_start >> 32);
709 #else
710                 dma_range[1] = 0;
711 #endif
712                 dma_range[2] = cpu_to_fdt32(bus_start & 0xffffffff);
714                 if (addrcell == 2) {
715                         dma_range[3] = cpu_to_fdt32(phys_start >> 32);
716                         dma_range[4] = cpu_to_fdt32(phys_start & 0xffffffff);
717                 } else {
718                         dma_range[3] = cpu_to_fdt32(phys_start & 0xffffffff);
719                 }
721                 if (sizecell == 2) {
722                         dma_range[3 + addrcell + 0] =
723                                 cpu_to_fdt32(size >> 32);
724                         dma_range[3 + addrcell + 1] =
725                                 cpu_to_fdt32(size & 0xffffffff);
726                 } else {
727                         dma_range[3 + addrcell + 0] =
728                                 cpu_to_fdt32(size & 0xffffffff);
729                 }
731                 dma_range += (3 + addrcell + sizecell);
732         }
734         len = dma_range - &dma_ranges[0];
735         if (len)
736                 fdt_setprop(blob, phb_off, "dma-ranges", &dma_ranges[0], len*4);
738         return 0;
740 #endif
742 int fdt_increase_size(void *fdt, int add_len)
744         int newlen;
746         newlen = fdt_totalsize(fdt) + add_len;
748         /* Open in place with a new len */
749         return fdt_open_into(fdt, fdt, newlen);
752 #ifdef CONFIG_FDT_FIXUP_PARTITIONS
753 #include <jffs2/load_kernel.h>
754 #include <mtd_node.h>
756 static int fdt_del_subnodes(const void *blob, int parent_offset)
758         int off, ndepth;
759         int ret;
761         for (ndepth = 0, off = fdt_next_node(blob, parent_offset, &ndepth);
762              (off >= 0) && (ndepth > 0);
763              off = fdt_next_node(blob, off, &ndepth)) {
764                 if (ndepth == 1) {
765                         debug("delete %s: offset: %x\n",
766                                 fdt_get_name(blob, off, 0), off);
767                         ret = fdt_del_node((void *)blob, off);
768                         if (ret < 0) {
769                                 printf("Can't delete node: %s\n",
770                                         fdt_strerror(ret));
771                                 return ret;
772                         } else {
773                                 ndepth = 0;
774                                 off = parent_offset;
775                         }
776                 }
777         }
778         return 0;
781 static int fdt_del_partitions(void *blob, int parent_offset)
783         const void *prop;
784         int ndepth = 0;
785         int off;
786         int ret;
788         off = fdt_next_node(blob, parent_offset, &ndepth);
789         if (off > 0 && ndepth == 1) {
790                 prop = fdt_getprop(blob, off, "label", NULL);
791                 if (prop == NULL) {
792                         /*
793                          * Could not find label property, nand {}; node?
794                          * Check subnode, delete partitions there if any.
795                          */
796                         return fdt_del_partitions(blob, off);
797                 } else {
798                         ret = fdt_del_subnodes(blob, parent_offset);
799                         if (ret < 0) {
800                                 printf("Can't remove subnodes: %s\n",
801                                         fdt_strerror(ret));
802                                 return ret;
803                         }
804                 }
805         }
806         return 0;
809 static int fdt_node_set_part_info(void *blob, int parent_offset,
810                                   struct mtd_device *dev)
812         struct list_head *pentry;
813         struct part_info *part;
814         int off, ndepth = 0;
815         int part_num, ret;
816         int sizecell;
817         char buf[64];
819         ret = fdt_del_partitions(blob, parent_offset);
820         if (ret < 0)
821                 return ret;
823         /*
824          * Check if size/address is 1 or 2 cells.
825          * We assume #address-cells and #size-cells have same value.
826          */
827         sizecell = fdt_getprop_u32_default_node(blob, parent_offset,
828                                                 0, "#size-cells", 1);
830         /*
831          * Check if it is nand {}; subnode, adjust
832          * the offset in this case
833          */
834         off = fdt_next_node(blob, parent_offset, &ndepth);
835         if (off > 0 && ndepth == 1)
836                 parent_offset = off;
838         part_num = 0;
839         list_for_each_prev(pentry, &dev->parts) {
840                 int newoff;
842                 part = list_entry(pentry, struct part_info, link);
844                 debug("%2d: %-20s0x%08llx\t0x%08llx\t%d\n",
845                         part_num, part->name, part->size,
846                         part->offset, part->mask_flags);
848                 sprintf(buf, "partition@%llx", part->offset);
849 add_sub:
850                 ret = fdt_add_subnode(blob, parent_offset, buf);
851                 if (ret == -FDT_ERR_NOSPACE) {
852                         ret = fdt_increase_size(blob, 512);
853                         if (!ret)
854                                 goto add_sub;
855                         else
856                                 goto err_size;
857                 } else if (ret < 0) {
858                         printf("Can't add partition node: %s\n",
859                                 fdt_strerror(ret));
860                         return ret;
861                 }
862                 newoff = ret;
864                 /* Check MTD_WRITEABLE_CMD flag */
865                 if (part->mask_flags & 1) {
866 add_ro:
867                         ret = fdt_setprop(blob, newoff, "read_only", NULL, 0);
868                         if (ret == -FDT_ERR_NOSPACE) {
869                                 ret = fdt_increase_size(blob, 512);
870                                 if (!ret)
871                                         goto add_ro;
872                                 else
873                                         goto err_size;
874                         } else if (ret < 0)
875                                 goto err_prop;
876                 }
878 add_reg:
879                 if (sizecell == 2) {
880                         ret = fdt_setprop_u64(blob, newoff,
881                                               "reg", part->offset);
882                         if (!ret)
883                                 ret = fdt_appendprop_u64(blob, newoff,
884                                                          "reg", part->size);
885                 } else {
886                         ret = fdt_setprop_u32(blob, newoff,
887                                               "reg", part->offset);
888                         if (!ret)
889                                 ret = fdt_appendprop_u32(blob, newoff,
890                                                          "reg", part->size);
891                 }
893                 if (ret == -FDT_ERR_NOSPACE) {
894                         ret = fdt_increase_size(blob, 512);
895                         if (!ret)
896                                 goto add_reg;
897                         else
898                                 goto err_size;
899                 } else if (ret < 0)
900                         goto err_prop;
902 add_label:
903                 ret = fdt_setprop_string(blob, newoff, "label", part->name);
904                 if (ret == -FDT_ERR_NOSPACE) {
905                         ret = fdt_increase_size(blob, 512);
906                         if (!ret)
907                                 goto add_label;
908                         else
909                                 goto err_size;
910                 } else if (ret < 0)
911                         goto err_prop;
913                 part_num++;
914         }
915         return 0;
916 err_size:
917         printf("Can't increase blob size: %s\n", fdt_strerror(ret));
918         return ret;
919 err_prop:
920         printf("Can't add property: %s\n", fdt_strerror(ret));
921         return ret;
924 /*
925  * Update partitions in nor/nand nodes using info from
926  * mtdparts environment variable. The nodes to update are
927  * specified by node_info structure which contains mtd device
928  * type and compatible string: E. g. the board code in
929  * ft_board_setup() could use:
930  *
931  *      struct node_info nodes[] = {
932  *              { "fsl,mpc5121-nfc",    MTD_DEV_TYPE_NAND, },
933  *              { "cfi-flash",          MTD_DEV_TYPE_NOR,  },
934  *      };
935  *
936  *      fdt_fixup_mtdparts(blob, nodes, ARRAY_SIZE(nodes));
937  */
938 void fdt_fixup_mtdparts(void *blob, const struct node_info *node_info,
939                         int node_info_size)
941         struct mtd_device *dev;
942         int i, idx;
943         int noff;
944         bool inited = false;
946         for (i = 0; i < node_info_size; i++) {
947                 idx = 0;
948                 noff = -1;
950                 while ((noff = fdt_node_offset_by_compatible(blob, noff,
951                                                 node_info[i].compat)) >= 0) {
952                         const char *prop;
954                         prop = fdt_getprop(blob, noff, "status", NULL);
955                         if (prop && !strcmp(prop, "disabled"))
956                                 continue;
958                         debug("%s: %s, mtd dev type %d\n",
959                                 fdt_get_name(blob, noff, 0),
960                                 node_info[i].compat, node_info[i].type);
962                         if (!inited) {
963                                 if (mtdparts_init() != 0)
964                                         return;
965                                 inited = true;
966                         }
968                         dev = device_find(node_info[i].type, idx++);
969                         if (dev) {
970                                 if (fdt_node_set_part_info(blob, noff, dev))
971                                         return; /* return on error */
972                         }
973                 }
974         }
976 #endif
978 void fdt_del_node_and_alias(void *blob, const char *alias)
980         int off = fdt_path_offset(blob, alias);
982         if (off < 0)
983                 return;
985         fdt_del_node(blob, off);
987         off = fdt_path_offset(blob, "/aliases");
988         fdt_delprop(blob, off, alias);
991 /* Max address size we deal with */
992 #define OF_MAX_ADDR_CELLS       4
993 #define OF_BAD_ADDR     FDT_ADDR_T_NONE
994 #define OF_CHECK_COUNTS(na, ns) (((na) > 0 && (na) <= OF_MAX_ADDR_CELLS) && \
995                          ((ns) > 0 || gd_size_cells_0()))
997 /* Debug utility */
998 #ifdef DEBUG
999 static void of_dump_addr(const char *s, const fdt32_t *addr, int na)
1001         printf("%s", s);
1002         while(na--)
1003                 printf(" %08x", *(addr++));
1004         printf("\n");
1006 #else
1007 static void of_dump_addr(const char *s, const fdt32_t *addr, int na) { }
1008 #endif
1010 /**
1011  * struct of_bus - Callbacks for bus specific translators
1012  * @name:       A string used to identify this bus in debug output.
1013  * @addresses:  The name of the DT property from which addresses are
1014  *              to be read, typically "reg".
1015  * @match:      Return non-zero if the node whose parent is at
1016  *              parentoffset in the FDT blob corresponds to a bus
1017  *              of this type, otherwise return zero. If NULL a match
1018  *              is assumed.
1019  * @count_cells:Count how many cells (be32 values) a node whose parent
1020  *              is at parentoffset in the FDT blob will require to
1021  *              represent its address (written to *addrc) & size
1022  *              (written to *sizec).
1023  * @map:        Map the address addr from the address space of this
1024  *              bus to that of its parent, making use of the ranges
1025  *              read from DT to an array at range. na and ns are the
1026  *              number of cells (be32 values) used to hold and address
1027  *              or size, respectively, for this bus. pna is the number
1028  *              of cells used to hold an address for the parent bus.
1029  *              Returns the address in the address space of the parent
1030  *              bus.
1031  * @translate:  Update the value of the address cells at addr within an
1032  *              FDT by adding offset to it. na specifies the number of
1033  *              cells used to hold the address being translated. Returns
1034  *              zero on success, non-zero on error.
1035  *
1036  * Each bus type will include a struct of_bus in the of_busses array,
1037  * providing implementations of some or all of the functions used to
1038  * match the bus & handle address translation for its children.
1039  */
1040 struct of_bus {
1041         const char      *name;
1042         const char      *addresses;
1043         int             (*match)(const void *blob, int parentoffset);
1044         void            (*count_cells)(const void *blob, int parentoffset,
1045                                 int *addrc, int *sizec);
1046         u64             (*map)(fdt32_t *addr, const fdt32_t *range,
1047                                 int na, int ns, int pna);
1048         int             (*translate)(fdt32_t *addr, u64 offset, int na);
1049 };
1051 /* Default translator (generic bus) */
1052 void fdt_support_default_count_cells(const void *blob, int parentoffset,
1053                                         int *addrc, int *sizec)
1055         const fdt32_t *prop;
1057         if (addrc)
1058                 *addrc = fdt_address_cells(blob, parentoffset);
1060         if (sizec) {
1061                 prop = fdt_getprop(blob, parentoffset, "#size-cells", NULL);
1062                 if (prop)
1063                         *sizec = be32_to_cpup(prop);
1064                 else
1065                         *sizec = 1;
1066         }
1069 static u64 of_bus_default_map(fdt32_t *addr, const fdt32_t *range,
1070                 int na, int ns, int pna)
1072         u64 cp, s, da;
1074         cp = fdt_read_number(range, na);
1075         s  = fdt_read_number(range + na + pna, ns);
1076         da = fdt_read_number(addr, na);
1078         debug("OF: default map, cp=%llx, s=%llx, da=%llx\n", cp, s, da);
1080         if (da < cp || da >= (cp + s))
1081                 return OF_BAD_ADDR;
1082         return da - cp;
1085 static int of_bus_default_translate(fdt32_t *addr, u64 offset, int na)
1087         u64 a = fdt_read_number(addr, na);
1088         memset(addr, 0, na * 4);
1089         a += offset;
1090         if (na > 1)
1091                 addr[na - 2] = cpu_to_fdt32(a >> 32);
1092         addr[na - 1] = cpu_to_fdt32(a & 0xffffffffu);
1094         return 0;
1097 #ifdef CONFIG_OF_ISA_BUS
1099 /* ISA bus translator */
1100 static int of_bus_isa_match(const void *blob, int parentoffset)
1102         const char *name;
1104         name = fdt_get_name(blob, parentoffset, NULL);
1105         if (!name)
1106                 return 0;
1108         return !strcmp(name, "isa");
1111 static void of_bus_isa_count_cells(const void *blob, int parentoffset,
1112                                    int *addrc, int *sizec)
1114         if (addrc)
1115                 *addrc = 2;
1116         if (sizec)
1117                 *sizec = 1;
1120 static u64 of_bus_isa_map(fdt32_t *addr, const fdt32_t *range,
1121                           int na, int ns, int pna)
1123         u64 cp, s, da;
1125         /* Check address type match */
1126         if ((addr[0] ^ range[0]) & cpu_to_be32(1))
1127                 return OF_BAD_ADDR;
1129         cp = fdt_read_number(range + 1, na - 1);
1130         s  = fdt_read_number(range + na + pna, ns);
1131         da = fdt_read_number(addr + 1, na - 1);
1133         debug("OF: ISA map, cp=%llx, s=%llx, da=%llx\n", cp, s, da);
1135         if (da < cp || da >= (cp + s))
1136                 return OF_BAD_ADDR;
1137         return da - cp;
1140 static int of_bus_isa_translate(fdt32_t *addr, u64 offset, int na)
1142         return of_bus_default_translate(addr + 1, offset, na - 1);
1145 #endif /* CONFIG_OF_ISA_BUS */
1147 /* Array of bus specific translators */
1148 static struct of_bus of_busses[] = {
1149 #ifdef CONFIG_OF_ISA_BUS
1150         /* ISA */
1151         {
1152                 .name = "isa",
1153                 .addresses = "reg",
1154                 .match = of_bus_isa_match,
1155                 .count_cells = of_bus_isa_count_cells,
1156                 .map = of_bus_isa_map,
1157                 .translate = of_bus_isa_translate,
1158         },
1159 #endif /* CONFIG_OF_ISA_BUS */
1160         /* Default */
1161         {
1162                 .name = "default",
1163                 .addresses = "reg",
1164                 .count_cells = fdt_support_default_count_cells,
1165                 .map = of_bus_default_map,
1166                 .translate = of_bus_default_translate,
1167         },
1168 };
1170 static struct of_bus *of_match_bus(const void *blob, int parentoffset)
1172         struct of_bus *bus;
1174         if (ARRAY_SIZE(of_busses) == 1)
1175                 return of_busses;
1177         for (bus = of_busses; bus; bus++) {
1178                 if (!bus->match || bus->match(blob, parentoffset))
1179                         return bus;
1180         }
1182         /*
1183          * We should always have matched the default bus at least, since
1184          * it has a NULL match field. If we didn't then it somehow isn't
1185          * in the of_busses array or something equally catastrophic has
1186          * gone wrong.
1187          */
1188         assert(0);
1189         return NULL;
1192 static int of_translate_one(const void *blob, int parent, struct of_bus *bus,
1193                             struct of_bus *pbus, fdt32_t *addr,
1194                             int na, int ns, int pna, const char *rprop)
1196         const fdt32_t *ranges;
1197         int rlen;
1198         int rone;
1199         u64 offset = OF_BAD_ADDR;
1201         /* Normally, an absence of a "ranges" property means we are
1202          * crossing a non-translatable boundary, and thus the addresses
1203          * below the current not cannot be converted to CPU physical ones.
1204          * Unfortunately, while this is very clear in the spec, it's not
1205          * what Apple understood, and they do have things like /uni-n or
1206          * /ht nodes with no "ranges" property and a lot of perfectly
1207          * useable mapped devices below them. Thus we treat the absence of
1208          * "ranges" as equivalent to an empty "ranges" property which means
1209          * a 1:1 translation at that level. It's up to the caller not to try
1210          * to translate addresses that aren't supposed to be translated in
1211          * the first place. --BenH.
1212          */
1213         ranges = fdt_getprop(blob, parent, rprop, &rlen);
1214         if (ranges == NULL || rlen == 0) {
1215                 offset = fdt_read_number(addr, na);
1216                 memset(addr, 0, pna * 4);
1217                 debug("OF: no ranges, 1:1 translation\n");
1218                 goto finish;
1219         }
1221         debug("OF: walking ranges...\n");
1223         /* Now walk through the ranges */
1224         rlen /= 4;
1225         rone = na + pna + ns;
1226         for (; rlen >= rone; rlen -= rone, ranges += rone) {
1227                 offset = bus->map(addr, ranges, na, ns, pna);
1228                 if (offset != OF_BAD_ADDR)
1229                         break;
1230         }
1231         if (offset == OF_BAD_ADDR) {
1232                 debug("OF: not found !\n");
1233                 return 1;
1234         }
1235         memcpy(addr, ranges + na, 4 * pna);
1237  finish:
1238         of_dump_addr("OF: parent translation for:", addr, pna);
1239         debug("OF: with offset: %llu\n", offset);
1241         /* Translate it into parent bus space */
1242         return pbus->translate(addr, offset, pna);
1245 /*
1246  * Translate an address from the device-tree into a CPU physical address,
1247  * this walks up the tree and applies the various bus mappings on the
1248  * way.
1249  *
1250  * Note: We consider that crossing any level with #size-cells == 0 to mean
1251  * that translation is impossible (that is we are not dealing with a value
1252  * that can be mapped to a cpu physical address). This is not really specified
1253  * that way, but this is traditionally the way IBM at least do things
1254  */
1255 static u64 __of_translate_address(const void *blob, int node_offset,
1256                                   const fdt32_t *in_addr, const char *rprop)
1258         int parent;
1259         struct of_bus *bus, *pbus;
1260         fdt32_t addr[OF_MAX_ADDR_CELLS];
1261         int na, ns, pna, pns;
1262         u64 result = OF_BAD_ADDR;
1264         debug("OF: ** translation for device %s **\n",
1265                 fdt_get_name(blob, node_offset, NULL));
1267         /* Get parent & match bus type */
1268         parent = fdt_parent_offset(blob, node_offset);
1269         if (parent < 0)
1270                 goto bail;
1271         bus = of_match_bus(blob, parent);
1273         /* Cound address cells & copy address locally */
1274         bus->count_cells(blob, parent, &na, &ns);
1275         if (!OF_CHECK_COUNTS(na, ns)) {
1276                 printf("%s: Bad cell count for %s\n", __FUNCTION__,
1277                        fdt_get_name(blob, node_offset, NULL));
1278                 goto bail;
1279         }
1280         memcpy(addr, in_addr, na * 4);
1282         debug("OF: bus is %s (na=%d, ns=%d) on %s\n",
1283             bus->name, na, ns, fdt_get_name(blob, parent, NULL));
1284         of_dump_addr("OF: translating address:", addr, na);
1286         /* Translate */
1287         for (;;) {
1288                 /* Switch to parent bus */
1289                 node_offset = parent;
1290                 parent = fdt_parent_offset(blob, node_offset);
1292                 /* If root, we have finished */
1293                 if (parent < 0) {
1294                         debug("OF: reached root node\n");
1295                         result = fdt_read_number(addr, na);
1296                         break;
1297                 }
1299                 /* Get new parent bus and counts */
1300                 pbus = of_match_bus(blob, parent);
1301                 pbus->count_cells(blob, parent, &pna, &pns);
1302                 if (!OF_CHECK_COUNTS(pna, pns)) {
1303                         printf("%s: Bad cell count for %s\n", __FUNCTION__,
1304                                 fdt_get_name(blob, node_offset, NULL));
1305                         break;
1306                 }
1308                 debug("OF: parent bus is %s (na=%d, ns=%d) on %s\n",
1309                     pbus->name, pna, pns, fdt_get_name(blob, parent, NULL));
1311                 /* Apply bus translation */
1312                 if (of_translate_one(blob, node_offset, bus, pbus,
1313                                         addr, na, ns, pna, rprop))
1314                         break;
1316                 /* Complete the move up one level */
1317                 na = pna;
1318                 ns = pns;
1319                 bus = pbus;
1321                 of_dump_addr("OF: one level translation:", addr, na);
1322         }
1323  bail:
1325         return result;
1328 u64 fdt_translate_address(const void *blob, int node_offset,
1329                           const fdt32_t *in_addr)
1331         return __of_translate_address(blob, node_offset, in_addr, "ranges");
1334 u64 fdt_translate_dma_address(const void *blob, int node_offset,
1335                               const fdt32_t *in_addr)
1337         return __of_translate_address(blob, node_offset, in_addr, "dma-ranges");
1340 int fdt_get_dma_range(const void *blob, int node, phys_addr_t *cpu,
1341                       dma_addr_t *bus, u64 *size)
1343         bool found_dma_ranges = false;
1344         struct of_bus *bus_node;
1345         const fdt32_t *ranges;
1346         int na, ns, pna, pns;
1347         int parent = node;
1348         int ret = 0;
1349         int len;
1351         /* Find the closest dma-ranges property */
1352         while (parent >= 0) {
1353                 ranges = fdt_getprop(blob, parent, "dma-ranges", &len);
1355                 /* Ignore empty ranges, they imply no translation required */
1356                 if (ranges && len > 0)
1357                         break;
1359                 /* Once we find 'dma-ranges', then a missing one is an error */
1360                 if (found_dma_ranges && !ranges) {
1361                         ret = -EINVAL;
1362                         goto out;
1363                 }
1365                 if (ranges)
1366                         found_dma_ranges = true;
1368                 parent = fdt_parent_offset(blob, parent);
1369         }
1371         if (!ranges || parent < 0) {
1372                 debug("no dma-ranges found for node %s\n",
1373                       fdt_get_name(blob, node, NULL));
1374                 ret = -ENOENT;
1375                 goto out;
1376         }
1378         /* switch to that node */
1379         node = parent;
1380         parent = fdt_parent_offset(blob, node);
1381         if (parent < 0) {
1382                 printf("Found dma-ranges in root node, shoudln't happen\n");
1383                 ret = -EINVAL;
1384                 goto out;
1385         }
1387         /* Get the address sizes both for the bus and its parent */
1388         bus_node = of_match_bus(blob, node);
1389         bus_node->count_cells(blob, node, &na, &ns);
1390         if (!OF_CHECK_COUNTS(na, ns)) {
1391                 printf("%s: Bad cell count for %s\n", __FUNCTION__,
1392                        fdt_get_name(blob, node, NULL));
1393                 return -EINVAL;
1394                 goto out;
1395         }
1397         bus_node = of_match_bus(blob, parent);
1398         bus_node->count_cells(blob, parent, &pna, &pns);
1399         if (!OF_CHECK_COUNTS(pna, pns)) {
1400                 printf("%s: Bad cell count for %s\n", __FUNCTION__,
1401                        fdt_get_name(blob, parent, NULL));
1402                 return -EINVAL;
1403                 goto out;
1404         }
1406         *bus = fdt_read_number(ranges, na);
1407         *cpu = fdt_translate_dma_address(blob, node, ranges + na);
1408         *size = fdt_read_number(ranges + na + pna, ns);
1409 out:
1410         return ret;
1413 /**
1414  * fdt_node_offset_by_compat_reg: Find a node that matches compatiable and
1415  * who's reg property matches a physical cpu address
1416  *
1417  * @blob: ptr to device tree
1418  * @compat: compatiable string to match
1419  * @compat_off: property name
1420  *
1421  */
1422 int fdt_node_offset_by_compat_reg(void *blob, const char *compat,
1423                                         phys_addr_t compat_off)
1425         int len, off = fdt_node_offset_by_compatible(blob, -1, compat);
1426         while (off != -FDT_ERR_NOTFOUND) {
1427                 const fdt32_t *reg = fdt_getprop(blob, off, "reg", &len);
1428                 if (reg) {
1429                         if (compat_off == fdt_translate_address(blob, off, reg))
1430                                 return off;
1431                 }
1432                 off = fdt_node_offset_by_compatible(blob, off, compat);
1433         }
1435         return -FDT_ERR_NOTFOUND;
1438 /**
1439  * fdt_alloc_phandle: Return next free phandle value
1440  *
1441  * @blob: ptr to device tree
1442  */
1443 int fdt_alloc_phandle(void *blob)
1445         int offset;
1446         uint32_t phandle = 0;
1448         for (offset = fdt_next_node(blob, -1, NULL); offset >= 0;
1449              offset = fdt_next_node(blob, offset, NULL)) {
1450                 phandle = max(phandle, fdt_get_phandle(blob, offset));
1451         }
1453         return phandle + 1;
1456 /*
1457  * fdt_set_phandle: Create a phandle property for the given node
1458  *
1459  * @fdt: ptr to device tree
1460  * @nodeoffset: node to update
1461  * @phandle: phandle value to set (must be unique)
1462  */
1463 int fdt_set_phandle(void *fdt, int nodeoffset, uint32_t phandle)
1465         int ret;
1467 #ifdef DEBUG
1468         int off = fdt_node_offset_by_phandle(fdt, phandle);
1470         if ((off >= 0) && (off != nodeoffset)) {
1471                 char buf[64];
1473                 fdt_get_path(fdt, nodeoffset, buf, sizeof(buf));
1474                 printf("Trying to update node %s with phandle %u ",
1475                        buf, phandle);
1477                 fdt_get_path(fdt, off, buf, sizeof(buf));
1478                 printf("that already exists in node %s.\n", buf);
1479                 return -FDT_ERR_BADPHANDLE;
1480         }
1481 #endif
1483         ret = fdt_setprop_cell(fdt, nodeoffset, "phandle", phandle);
1484         if (ret < 0)
1485                 return ret;
1487         /*
1488          * For now, also set the deprecated "linux,phandle" property, so that we
1489          * don't break older kernels.
1490          */
1491         ret = fdt_setprop_cell(fdt, nodeoffset, "linux,phandle", phandle);
1493         return ret;
1496 /*
1497  * fdt_create_phandle: Create a phandle property for the given node
1498  *
1499  * @fdt: ptr to device tree
1500  * @nodeoffset: node to update
1501  */
1502 unsigned int fdt_create_phandle(void *fdt, int nodeoffset)
1504         /* see if there is a phandle already */
1505         int phandle = fdt_get_phandle(fdt, nodeoffset);
1507         /* if we got 0, means no phandle so create one */
1508         if (phandle == 0) {
1509                 int ret;
1511                 phandle = fdt_alloc_phandle(fdt);
1512                 ret = fdt_set_phandle(fdt, nodeoffset, phandle);
1513                 if (ret < 0) {
1514                         printf("Can't set phandle %u: %s\n", phandle,
1515                                fdt_strerror(ret));
1516                         return 0;
1517                 }
1518         }
1520         return phandle;
1523 /*
1524  * fdt_set_node_status: Set status for the given node
1525  *
1526  * @fdt: ptr to device tree
1527  * @nodeoffset: node to update
1528  * @status: FDT_STATUS_OKAY, FDT_STATUS_DISABLED,
1529  *          FDT_STATUS_FAIL, FDT_STATUS_FAIL_ERROR_CODE
1530  * @error_code: optional, only used if status is FDT_STATUS_FAIL_ERROR_CODE
1531  */
1532 int fdt_set_node_status(void *fdt, int nodeoffset,
1533                         enum fdt_status status, unsigned int error_code)
1535         char buf[16];
1536         int ret = 0;
1538         if (nodeoffset < 0)
1539                 return nodeoffset;
1541         switch (status) {
1542         case FDT_STATUS_OKAY:
1543                 ret = fdt_setprop_string(fdt, nodeoffset, "status", "okay");
1544                 break;
1545         case FDT_STATUS_DISABLED:
1546                 ret = fdt_setprop_string(fdt, nodeoffset, "status", "disabled");
1547                 break;
1548         case FDT_STATUS_FAIL:
1549                 ret = fdt_setprop_string(fdt, nodeoffset, "status", "fail");
1550                 break;
1551         case FDT_STATUS_FAIL_ERROR_CODE:
1552                 sprintf(buf, "fail-%d", error_code);
1553                 ret = fdt_setprop_string(fdt, nodeoffset, "status", buf);
1554                 break;
1555         default:
1556                 printf("Invalid fdt status: %x\n", status);
1557                 ret = -1;
1558                 break;
1559         }
1561         return ret;
1564 /*
1565  * fdt_set_status_by_alias: Set status for the given node given an alias
1566  *
1567  * @fdt: ptr to device tree
1568  * @alias: alias of node to update
1569  * @status: FDT_STATUS_OKAY, FDT_STATUS_DISABLED,
1570  *          FDT_STATUS_FAIL, FDT_STATUS_FAIL_ERROR_CODE
1571  * @error_code: optional, only used if status is FDT_STATUS_FAIL_ERROR_CODE
1572  */
1573 int fdt_set_status_by_alias(void *fdt, const char* alias,
1574                             enum fdt_status status, unsigned int error_code)
1576         int offset = fdt_path_offset(fdt, alias);
1578         return fdt_set_node_status(fdt, offset, status, error_code);
1581 #if defined(CONFIG_VIDEO) || defined(CONFIG_LCD)
1582 int fdt_add_edid(void *blob, const char *compat, unsigned char *edid_buf)
1584         int noff;
1585         int ret;
1587         noff = fdt_node_offset_by_compatible(blob, -1, compat);
1588         if (noff != -FDT_ERR_NOTFOUND) {
1589                 debug("%s: %s\n", fdt_get_name(blob, noff, 0), compat);
1590 add_edid:
1591                 ret = fdt_setprop(blob, noff, "edid", edid_buf, 128);
1592                 if (ret == -FDT_ERR_NOSPACE) {
1593                         ret = fdt_increase_size(blob, 512);
1594                         if (!ret)
1595                                 goto add_edid;
1596                         else
1597                                 goto err_size;
1598                 } else if (ret < 0) {
1599                         printf("Can't add property: %s\n", fdt_strerror(ret));
1600                         return ret;
1601                 }
1602         }
1603         return 0;
1604 err_size:
1605         printf("Can't increase blob size: %s\n", fdt_strerror(ret));
1606         return ret;
1608 #endif
1610 /*
1611  * Verify the physical address of device tree node for a given alias
1612  *
1613  * This function locates the device tree node of a given alias, and then
1614  * verifies that the physical address of that device matches the given
1615  * parameter.  It displays a message if there is a mismatch.
1616  *
1617  * Returns 1 on success, 0 on failure
1618  */
1619 int fdt_verify_alias_address(void *fdt, int anode, const char *alias, u64 addr)
1621         const char *path;
1622         const fdt32_t *reg;
1623         int node, len;
1624         u64 dt_addr;
1626         path = fdt_getprop(fdt, anode, alias, NULL);
1627         if (!path) {
1628                 /* If there's no such alias, then it's not a failure */
1629                 return 1;
1630         }
1632         node = fdt_path_offset(fdt, path);
1633         if (node < 0) {
1634                 printf("Warning: device tree alias '%s' points to invalid "
1635                        "node %s.\n", alias, path);
1636                 return 0;
1637         }
1639         reg = fdt_getprop(fdt, node, "reg", &len);
1640         if (!reg) {
1641                 printf("Warning: device tree node '%s' has no address.\n",
1642                        path);
1643                 return 0;
1644         }
1646         dt_addr = fdt_translate_address(fdt, node, reg);
1647         if (addr != dt_addr) {
1648                 printf("Warning: U-Boot configured device %s at address %llu,\n"
1649                        "but the device tree has it address %llx.\n",
1650                        alias, addr, dt_addr);
1651                 return 0;
1652         }
1654         return 1;
1657 /*
1658  * Returns the base address of an SOC or PCI node
1659  */
1660 u64 fdt_get_base_address(const void *fdt, int node)
1662         int size;
1663         const fdt32_t *prop;
1665         prop = fdt_getprop(fdt, node, "reg", &size);
1667         return prop ? fdt_translate_address(fdt, node, prop) : OF_BAD_ADDR;
1670 /*
1671  * Read a property of size <prop_len>. Currently only supports 1 or 2 cells,
1672  * or 3 cells specially for a PCI address.
1673  */
1674 static int fdt_read_prop(const fdt32_t *prop, int prop_len, int cell_off,
1675                          uint64_t *val, int cells)
1677         const fdt32_t *prop32;
1678         const unaligned_fdt64_t *prop64;
1680         if ((cell_off + cells) > prop_len)
1681                 return -FDT_ERR_NOSPACE;
1683         prop32 = &prop[cell_off];
1685         /*
1686          * Special handling for PCI address in PCI bus <ranges>
1687          *
1688          * PCI child address is made up of 3 cells. Advance the cell offset
1689          * by 1 so that the PCI child address can be correctly read.
1690          */
1691         if (cells == 3)
1692                 cell_off += 1;
1693         prop64 = (const fdt64_t *)&prop[cell_off];
1695         switch (cells) {
1696         case 1:
1697                 *val = fdt32_to_cpu(*prop32);
1698                 break;
1699         case 2:
1700         case 3:
1701                 *val = fdt64_to_cpu(*prop64);
1702                 break;
1703         default:
1704                 return -FDT_ERR_NOSPACE;
1705         }
1707         return 0;
1710 /**
1711  * fdt_read_range - Read a node's n'th range property
1712  *
1713  * @fdt: ptr to device tree
1714  * @node: offset of node
1715  * @n: range index
1716  * @child_addr: pointer to storage for the "child address" field
1717  * @addr: pointer to storage for the CPU view translated physical start
1718  * @len: pointer to storage for the range length
1719  *
1720  * Convenience function that reads and interprets a specific range out of
1721  * a number of the "ranges" property array.
1722  */
1723 int fdt_read_range(void *fdt, int node, int n, uint64_t *child_addr,
1724                    uint64_t *addr, uint64_t *len)
1726         int pnode = fdt_parent_offset(fdt, node);
1727         const fdt32_t *ranges;
1728         int pacells;
1729         int acells;
1730         int scells;
1731         int ranges_len;
1732         int cell = 0;
1733         int r = 0;
1735         /*
1736          * The "ranges" property is an array of
1737          * { <child address> <parent address> <size in child address space> }
1738          *
1739          * All 3 elements can span a diffent number of cells. Fetch their size.
1740          */
1741         pacells = fdt_getprop_u32_default_node(fdt, pnode, 0, "#address-cells", 1);
1742         acells = fdt_getprop_u32_default_node(fdt, node, 0, "#address-cells", 1);
1743         scells = fdt_getprop_u32_default_node(fdt, node, 0, "#size-cells", 1);
1745         /* Now try to get the ranges property */
1746         ranges = fdt_getprop(fdt, node, "ranges", &ranges_len);
1747         if (!ranges)
1748                 return -FDT_ERR_NOTFOUND;
1749         ranges_len /= sizeof(uint32_t);
1751         /* Jump to the n'th entry */
1752         cell = n * (pacells + acells + scells);
1754         /* Read <child address> */
1755         if (child_addr) {
1756                 r = fdt_read_prop(ranges, ranges_len, cell, child_addr,
1757                                   acells);
1758                 if (r)
1759                         return r;
1760         }
1761         cell += acells;
1763         /* Read <parent address> */
1764         if (addr)
1765                 *addr = fdt_translate_address(fdt, node, ranges + cell);
1766         cell += pacells;
1768         /* Read <size in child address space> */
1769         if (len) {
1770                 r = fdt_read_prop(ranges, ranges_len, cell, len, scells);
1771                 if (r)
1772                         return r;
1773         }
1775         return 0;
1778 /**
1779  * fdt_setup_simplefb_node - Fill and enable a simplefb node
1780  *
1781  * @fdt: ptr to device tree
1782  * @node: offset of the simplefb node
1783  * @base_address: framebuffer base address
1784  * @width: width in pixels
1785  * @height: height in pixels
1786  * @stride: bytes per line
1787  * @format: pixel format string
1788  *
1789  * Convenience function to fill and enable a simplefb node.
1790  */
1791 int fdt_setup_simplefb_node(void *fdt, int node, u64 base_address, u32 width,
1792                             u32 height, u32 stride, const char *format)
1794         char name[32];
1795         fdt32_t cells[4];
1796         int i, addrc, sizec, ret;
1798         fdt_support_default_count_cells(fdt, fdt_parent_offset(fdt, node),
1799                                         &addrc, &sizec);
1800         i = 0;
1801         if (addrc == 2)
1802                 cells[i++] = cpu_to_fdt32(base_address >> 32);
1803         cells[i++] = cpu_to_fdt32(base_address);
1804         if (sizec == 2)
1805                 cells[i++] = 0;
1806         cells[i++] = cpu_to_fdt32(height * stride);
1808         ret = fdt_setprop(fdt, node, "reg", cells, sizeof(cells[0]) * i);
1809         if (ret < 0)
1810                 return ret;
1812         snprintf(name, sizeof(name), "framebuffer@%llx", base_address);
1813         ret = fdt_set_name(fdt, node, name);
1814         if (ret < 0)
1815                 return ret;
1817         ret = fdt_setprop_u32(fdt, node, "width", width);
1818         if (ret < 0)
1819                 return ret;
1821         ret = fdt_setprop_u32(fdt, node, "height", height);
1822         if (ret < 0)
1823                 return ret;
1825         ret = fdt_setprop_u32(fdt, node, "stride", stride);
1826         if (ret < 0)
1827                 return ret;
1829         ret = fdt_setprop_string(fdt, node, "format", format);
1830         if (ret < 0)
1831                 return ret;
1833         ret = fdt_setprop_string(fdt, node, "status", "okay");
1834         if (ret < 0)
1835                 return ret;
1837         return 0;
1840 /*
1841  * Update native-mode in display-timings from display environment variable.
1842  * The node to update are specified by path.
1843  */
1844 int fdt_fixup_display(void *blob, const char *path, const char *display)
1846         int off, toff;
1848         if (!display || !path)
1849                 return -FDT_ERR_NOTFOUND;
1851         toff = fdt_path_offset(blob, path);
1852         if (toff >= 0)
1853                 toff = fdt_subnode_offset(blob, toff, "display-timings");
1854         if (toff < 0)
1855                 return toff;
1857         for (off = fdt_first_subnode(blob, toff);
1858              off >= 0;
1859              off = fdt_next_subnode(blob, off)) {
1860                 uint32_t h = fdt_get_phandle(blob, off);
1861                 debug("%s:0x%x\n", fdt_get_name(blob, off, NULL),
1862                       fdt32_to_cpu(h));
1863                 if (strcasecmp(fdt_get_name(blob, off, NULL), display) == 0)
1864                         return fdt_setprop_u32(blob, toff, "native-mode", h);
1865         }
1866         return toff;
1869 #ifdef CONFIG_OF_LIBFDT_OVERLAY
1870 /**
1871  * fdt_overlay_apply_verbose - Apply an overlay with verbose error reporting
1872  *
1873  * @fdt: ptr to device tree
1874  * @fdto: ptr to device tree overlay
1875  *
1876  * Convenience function to apply an overlay and display helpful messages
1877  * in the case of an error
1878  */
1879 int fdt_overlay_apply_verbose(void *fdt, void *fdto)
1881         int err;
1882         bool has_symbols;
1884         err = fdt_path_offset(fdt, "/__symbols__");
1885         has_symbols = err >= 0;
1887         err = fdt_overlay_apply(fdt, fdto);
1888         if (err < 0) {
1889                 printf("failed on fdt_overlay_apply(): %s\n",
1890                                 fdt_strerror(err));
1891                 if (!has_symbols) {
1892                         printf("base fdt does did not have a /__symbols__ node\n");
1893                         printf("make sure you've compiled with -@\n");
1894                 }
1895         }
1896         return err;
1898 #endif