2 * Copyright (c) 2009-2010 The FreeBSD Foundation
5 * This software was developed by Semihalf under sponsorship from
6 * the FreeBSD Foundation.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
36 #include <sys/param.h>
37 #include <sys/linker.h>
38 #include <machine/elf.h>
40 #include "bootstrap.h"
41 #include "fdt_platform.h"
44 #define debugf(fmt, args...) do { printf("%s(): ", __func__); \
45 printf(fmt,##args); } while (0)
47 #define debugf(fmt, args...)
50 #define FDT_CWD_LEN 256
51 #define FDT_MAX_DEPTH 12
53 #define FDT_PROP_SEP " = "
55 #define COPYOUT(s,d,l) archsw.arch_copyout(s, d, l)
56 #define COPYIN(s,d,l) archsw.arch_copyin(s, d, l)
58 #define FDT_STATIC_DTB_SYMBOL "fdt_static_dtb"
60 #define CMD_REQUIRES_BLOB 0x01
62 /* Location of FDT yet to be loaded. */
63 /* This may be in read-only memory, so can't be manipulated directly. */
64 static struct fdt_header *fdt_to_load = NULL;
65 /* Location of FDT on heap. */
66 /* This is the copy we actually manipulate. */
67 static struct fdt_header *fdtp = NULL;
68 /* Size of FDT blob */
69 static size_t fdtp_size = 0;
70 /* Have we loaded all the needed overlays */
71 static int fdt_overlays_applied = 0;
73 static int fdt_load_dtb(vm_offset_t va);
74 static void fdt_print_overlay_load_error(int err, const char *filename);
75 static int fdt_check_overlay_compatible(void *base_fdt, void *overlay_fdt);
77 static int fdt_cmd_nyi(int argc, char *argv[]);
78 static int fdt_load_dtb_overlays_string(const char * filenames);
80 static int fdt_cmd_addr(int argc, char *argv[]);
81 static int fdt_cmd_mkprop(int argc, char *argv[]);
82 static int fdt_cmd_cd(int argc, char *argv[]);
83 static int fdt_cmd_hdr(int argc, char *argv[]);
84 static int fdt_cmd_ls(int argc, char *argv[]);
85 static int fdt_cmd_prop(int argc, char *argv[]);
86 static int fdt_cmd_pwd(int argc, char *argv[]);
87 static int fdt_cmd_rm(int argc, char *argv[]);
88 static int fdt_cmd_mknode(int argc, char *argv[]);
89 static int fdt_cmd_mres(int argc, char *argv[]);
91 typedef int cmdf_t(int, char *[]);
99 static const struct cmdtab commands[] = {
100 { "addr", &fdt_cmd_addr, 0 },
101 { "alias", &fdt_cmd_nyi, 0 },
102 { "cd", &fdt_cmd_cd, CMD_REQUIRES_BLOB },
103 { "header", &fdt_cmd_hdr, CMD_REQUIRES_BLOB },
104 { "ls", &fdt_cmd_ls, CMD_REQUIRES_BLOB },
105 { "mknode", &fdt_cmd_mknode, CMD_REQUIRES_BLOB },
106 { "mkprop", &fdt_cmd_mkprop, CMD_REQUIRES_BLOB },
107 { "mres", &fdt_cmd_mres, CMD_REQUIRES_BLOB },
108 { "prop", &fdt_cmd_prop, CMD_REQUIRES_BLOB },
109 { "pwd", &fdt_cmd_pwd, CMD_REQUIRES_BLOB },
110 { "rm", &fdt_cmd_rm, CMD_REQUIRES_BLOB },
114 static char cwd[FDT_CWD_LEN] = "/";
117 fdt_find_static_dtb()
122 vm_offset_t strtab, symtab, fdt_start;
124 struct preloaded_file *kfp;
125 struct file_metadata *md;
129 debugf("fdt_find_static_dtb()\n");
131 sym_count = symtab = strtab = 0;
134 offs = __elfN(relocation_offset);
136 kfp = file_findfile(NULL, NULL);
140 /* Locate the dynamic symbols and strtab. */
141 md = file_findmetadata(kfp, MODINFOMD_ELFHDR);
144 ehdr = (Elf_Ehdr *)md->md_data;
146 md = file_findmetadata(kfp, MODINFOMD_SHDR);
149 shdr = (Elf_Shdr *)md->md_data;
151 for (i = 0; i < ehdr->e_shnum; ++i) {
152 if (shdr[i].sh_type == SHT_DYNSYM && symtab == 0) {
153 symtab = shdr[i].sh_addr + offs;
154 sym_count = shdr[i].sh_size / sizeof(Elf_Sym);
155 } else if (shdr[i].sh_type == SHT_STRTAB && strtab == 0) {
156 strtab = shdr[i].sh_addr + offs;
161 * The most efficient way to find a symbol would be to calculate a
162 * hash, find proper bucket and chain, and thus find a symbol.
163 * However, that would involve code duplication (e.g. for hash
164 * function). So we're using simpler and a bit slower way: we're
165 * iterating through symbols, searching for the one which name is
166 * 'equal' to 'fdt_static_dtb'. To speed up the process a little bit,
167 * we are eliminating symbols type of which is not STT_NOTYPE, or(and)
168 * those which binding attribute is not STB_GLOBAL.
171 while (sym_count > 0 && fdt_start == 0) {
172 COPYOUT(symtab, &sym, sizeof(sym));
173 symtab += sizeof(sym);
175 if (ELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
176 ELF_ST_TYPE(sym.st_info) != STT_NOTYPE)
178 strp = strdupout(strtab + sym.st_name);
179 if (strcmp(strp, FDT_STATIC_DTB_SYMBOL) == 0)
180 fdt_start = (vm_offset_t)sym.st_value + offs;
187 fdt_load_dtb(vm_offset_t va)
189 struct fdt_header header;
192 debugf("fdt_load_dtb(0x%08jx)\n", (uintmax_t)va);
194 COPYOUT(va, &header, sizeof(header));
195 err = fdt_check_header(&header);
197 if (err == -FDT_ERR_BADVERSION) {
198 snprintf(command_errbuf, sizeof(command_errbuf),
199 "incompatible blob version: %d, should be: %d",
200 fdt_version(fdtp), FDT_LAST_SUPPORTED_VERSION);
202 snprintf(command_errbuf, sizeof(command_errbuf),
203 "error validating blob: %s", fdt_strerror(err));
209 * Release previous blob
214 fdtp_size = fdt_totalsize(&header);
215 fdtp = malloc(fdtp_size);
218 command_errmsg = "can't allocate memory for device tree copy";
222 COPYOUT(va, fdtp, fdtp_size);
223 debugf("DTB blob found at 0x%jx, size: 0x%jx\n", (uintmax_t)va, (uintmax_t)fdtp_size);
229 fdt_load_dtb_addr(struct fdt_header *header)
233 debugf("fdt_load_dtb_addr(%p)\n", header);
235 fdtp_size = fdt_totalsize(header);
236 err = fdt_check_header(header);
238 snprintf(command_errbuf, sizeof(command_errbuf),
239 "error validating blob: %s", fdt_strerror(err));
243 if ((fdtp = malloc(fdtp_size)) == NULL) {
244 command_errmsg = "can't allocate memory for device tree copy";
248 bcopy(header, fdtp, fdtp_size);
253 fdt_load_dtb_file(const char * filename)
255 struct preloaded_file *bfp, *oldbfp;
258 debugf("fdt_load_dtb_file(%s)\n", filename);
260 oldbfp = file_findfile(NULL, "dtb");
262 /* Attempt to load and validate a new dtb from a file. */
263 if ((bfp = file_loadraw(filename, "dtb", 1)) == NULL) {
264 snprintf(command_errbuf, sizeof(command_errbuf),
265 "failed to load file '%s'", filename);
268 if ((err = fdt_load_dtb(bfp->f_addr)) != 0) {
273 /* A new dtb was validated, discard any previous file. */
275 file_discard(oldbfp);
280 fdt_load_dtb_overlay(const char * filename)
282 struct preloaded_file *bfp;
283 struct fdt_header header;
286 debugf("fdt_load_dtb_overlay(%s)\n", filename);
288 /* Attempt to load and validate a new dtb from a file. FDT_ERR_NOTFOUND
289 * is normally a libfdt error code, but libfdt would actually return
290 * -FDT_ERR_NOTFOUND. We re-purpose the error code here to convey a
291 * similar meaning: the file itself was not found, which can still be
292 * considered an error dealing with FDT pieces.
294 if ((bfp = file_loadraw(filename, "dtbo", 1)) == NULL)
295 return (FDT_ERR_NOTFOUND);
297 COPYOUT(bfp->f_addr, &header, sizeof(header));
298 err = fdt_check_header(&header);
309 fdt_print_overlay_load_error(int err, const char *filename)
313 case FDT_ERR_NOTFOUND:
314 printf("%s: failed to load file\n", filename);
316 case -FDT_ERR_BADVERSION:
317 printf("%s: incompatible blob version: %d, should be: %d\n",
318 filename, fdt_version(fdtp),
319 FDT_LAST_SUPPORTED_VERSION);
322 /* libfdt errs are negative */
324 printf("%s: error validating blob: %s\n",
325 filename, fdt_strerror(err));
327 printf("%s: unknown load error\n", filename);
333 fdt_load_dtb_overlays_string(const char * filenames)
336 char *name, *name_ext;
340 debugf("fdt_load_dtb_overlays_string(%s)\n", filenames);
342 names = strdup(filenames);
347 comaptr = strchr(name, ',');
350 err = fdt_load_dtb_overlay(name);
351 if (err == FDT_ERR_NOTFOUND) {
352 /* Allocate enough to append ".dtbo" */
353 namesz = strlen(name) + 6;
354 name_ext = malloc(namesz);
355 if (name_ext == NULL) {
356 fdt_print_overlay_load_error(err, name);
360 snprintf(name_ext, namesz, "%s.dtbo", name);
361 err = fdt_load_dtb_overlay(name_ext);
364 /* Catch error with either initial load or fallback load */
366 fdt_print_overlay_load_error(err, name);
375 * fdt_check_overlay_compatible - check that the overlay_fdt is compatible with
376 * base_fdt before we attempt to apply it. It will need to re-calculate offsets
377 * in the base every time, rather than trying to cache them earlier in the
378 * process, because the overlay application process can/will invalidate a lot of
382 fdt_check_overlay_compatible(void *base_fdt, void *overlay_fdt)
385 int compat_len, ocompat_len;
386 int oroot_offset, root_offset;
389 oroot_offset = fdt_path_offset(overlay_fdt, "/");
390 if (oroot_offset < 0)
391 return (oroot_offset);
393 * If /compatible in the overlay does not exist or if it is empty, then
394 * we're automatically compatible. We do this for the sake of rapid
395 * overlay development for overlays that aren't intended to be deployed.
396 * The user assumes the risk of using an overlay without /compatible.
398 if (fdt_get_property(overlay_fdt, oroot_offset, "compatible",
399 &ocompat_len) == NULL || ocompat_len == 0)
401 root_offset = fdt_path_offset(base_fdt, "/");
403 return (root_offset);
405 * However, an empty or missing /compatible on the base is an error,
406 * because allowing this offers no advantages.
408 if (fdt_get_property(base_fdt, root_offset, "compatible",
409 &compat_len) == NULL)
411 else if(compat_len == 0)
415 compat = fdt_stringlist_get(overlay_fdt, oroot_offset, "compatible",
417 while (compat != NULL) {
418 if (fdt_stringlist_search(base_fdt, root_offset, "compatible",
422 compat = fdt_stringlist_get(overlay_fdt, oroot_offset,
423 "compatible", slidx, &sllen);
426 /* We've exhausted the overlay's /compatible property... no match */
431 * Returns the number of overlays successfully applied
436 struct preloaded_file *fp;
437 size_t max_overlay_size, next_fdtp_size;
438 size_t current_fdtp_size;
442 int overlays_applied, rv;
444 if ((fdtp == NULL) || (fdtp_size == 0))
447 if (fdt_overlays_applied)
450 max_overlay_size = 0;
451 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
452 if (max_overlay_size < fp->f_size)
453 max_overlay_size = fp->f_size;
456 /* Nothing to apply */
457 if (max_overlay_size == 0)
460 overlay = malloc(max_overlay_size);
461 if (overlay == NULL) {
462 printf("failed to allocate memory for DTB blob with overlays\n");
466 current_fdtp_size = fdtp_size;
467 overlays_applied = 0;
468 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
469 COPYOUT(fp->f_addr, overlay, fp->f_size);
470 /* Check compatible first to avoid unnecessary allocation */
471 rv = fdt_check_overlay_compatible(current_fdtp, overlay);
473 printf("DTB overlay '%s' not compatible\n", fp->f_name);
476 printf("applying DTB overlay '%s'\n", fp->f_name);
477 next_fdtp_size = current_fdtp_size + fp->f_size;
478 next_fdtp = malloc(next_fdtp_size);
479 if (next_fdtp == NULL) {
481 * Output warning, then move on to applying other
482 * overlays in case this one is simply too large.
484 printf("failed to allocate memory for overlay base\n");
487 rv = fdt_open_into(current_fdtp, next_fdtp, next_fdtp_size);
490 printf("failed to open base dtb into overlay base\n");
493 /* Both overlay and next_fdtp may be modified in place */
494 rv = fdt_overlay_apply(next_fdtp, overlay);
496 /* Rotate next -> current */
497 if (current_fdtp != fdtp)
499 current_fdtp = next_fdtp;
500 fdt_pack(current_fdtp);
501 current_fdtp_size = fdt_totalsize(current_fdtp);
505 * Assume here that the base we tried to apply on is
506 * either trashed or in an inconsistent state. Trying to
507 * load it might work, but it's better to discard it and
510 printf("failed to apply overlay: %s\n",
514 /* We could have failed to apply all overlays; then we do nothing */
515 if (current_fdtp != fdtp) {
518 fdtp_size = current_fdtp_size;
521 fdt_overlays_applied = 1;
522 return (overlays_applied);
526 fdt_pad_dtb(size_t padding)
529 size_t padded_fdtp_size;
531 padded_fdtp_size = fdtp_size + padding;
532 padded_fdtp = malloc(padded_fdtp_size);
533 if (padded_fdtp == NULL)
535 if (fdt_open_into(fdtp, padded_fdtp, padded_fdtp_size) != 0) {
540 fdtp_size = padded_fdtp_size;
557 struct preloaded_file *bfp;
560 debugf("fdt_setup_fdtp()\n");
562 /* If we already loaded a file, use it. */
563 if ((bfp = file_findfile(NULL, "dtb")) != NULL) {
564 if (fdt_load_dtb(bfp->f_addr) == 0) {
565 printf("Using DTB from loaded file '%s'.\n",
567 fdt_platform_load_overlays();
572 /* If we were given the address of a valid blob in memory, use it. */
573 if (fdt_to_load != NULL) {
574 if (fdt_load_dtb_addr(fdt_to_load) == 0) {
575 printf("Using DTB from memory address %p.\n",
577 fdt_platform_load_overlays();
582 if (fdt_platform_load_dtb() == 0) {
583 fdt_platform_load_overlays();
587 /* If there is a dtb compiled into the kernel, use it. */
588 if ((va = fdt_find_static_dtb()) != 0) {
589 if (fdt_load_dtb(va) == 0) {
590 printf("Using DTB compiled into kernel.\n");
595 command_errmsg = "No device tree blob found!\n";
599 #define fdt_strtovect(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
600 (cellbuf), (lim), (cellsize), 0);
602 /* Force using base 16 */
603 #define fdt_strtovectx(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
604 (cellbuf), (lim), (cellsize), 16);
607 _fdt_strtovect(const char *str, void *cellbuf, int lim, unsigned char cellsize,
610 const char *buf = str;
611 const char *end = str + strlen(str) - 2;
612 uint32_t *u32buf = NULL;
613 uint8_t *u8buf = NULL;
616 if (cellsize == sizeof(uint32_t))
617 u32buf = (uint32_t *)cellbuf;
619 u8buf = (uint8_t *)cellbuf;
626 /* Skip white whitespace(s)/separators */
627 while (!isxdigit(*buf) && buf < end)
632 cpu_to_fdt32((uint32_t)strtol(buf, NULL, base));
635 u8buf[cnt] = (uint8_t)strtol(buf, NULL, base);
637 if (cnt + 1 <= lim - 1)
642 /* Find another number */
643 while ((isxdigit(*buf) || *buf == 'x') && buf < end)
650 fdt_fixup_ethernet(const char *str, char *ethstr, int len)
654 /* Convert macaddr string into a vector of uints */
655 fdt_strtovectx(str, &tmp_addr, 6, sizeof(uint8_t));
656 /* Set actual property to a value from vect */
657 fdt_setprop(fdtp, fdt_path_offset(fdtp, ethstr),
658 "local-mac-address", &tmp_addr, 6 * sizeof(uint8_t));
662 fdt_fixup_cpubusfreqs(unsigned long cpufreq, unsigned long busfreq)
664 int lo, o = 0, o2, maxo = 0, depth;
665 const uint32_t zero = 0;
667 /* We want to modify every subnode of /cpus */
668 o = fdt_path_offset(fdtp, "/cpus");
672 /* maxo should contain offset of node next to /cpus */
676 maxo = fdt_next_node(fdtp, maxo, &depth);
678 /* Find CPU frequency properties */
679 o = fdt_node_offset_by_prop_value(fdtp, o, "clock-frequency",
680 &zero, sizeof(uint32_t));
682 o2 = fdt_node_offset_by_prop_value(fdtp, o, "bus-frequency", &zero,
687 while (o != -FDT_ERR_NOTFOUND && o2 != -FDT_ERR_NOTFOUND) {
689 o = fdt_node_offset_by_prop_value(fdtp, lo,
690 "clock-frequency", &zero, sizeof(uint32_t));
692 o2 = fdt_node_offset_by_prop_value(fdtp, lo, "bus-frequency",
693 &zero, sizeof(uint32_t));
695 /* We're only interested in /cpus subnode(s) */
699 fdt_setprop_inplace_cell(fdtp, lo, "clock-frequency",
702 fdt_setprop_inplace_cell(fdtp, lo, "bus-frequency",
711 fdt_reg_valid(uint32_t *reg, int len, int addr_cells, int size_cells)
713 int cells_in_tuple, i, tuples, tuple_size;
714 uint32_t cur_start, cur_size;
716 cells_in_tuple = (addr_cells + size_cells);
717 tuple_size = cells_in_tuple * sizeof(uint32_t);
718 tuples = len / tuple_size;
722 for (i = 0; i < tuples; i++) {
724 cur_start = fdt64_to_cpu(reg[i * cells_in_tuple]);
726 cur_start = fdt32_to_cpu(reg[i * cells_in_tuple]);
729 cur_size = fdt64_to_cpu(reg[i * cells_in_tuple + 2]);
731 cur_size = fdt32_to_cpu(reg[i * cells_in_tuple + 1]);
736 debugf(" reg#%d (start: 0x%0x size: 0x%0x) valid!\n",
737 i, cur_start, cur_size);
744 fdt_fixup_memory(struct fdt_mem_region *region, size_t num)
746 struct fdt_mem_region *curmr;
747 uint32_t addr_cells, size_cells;
748 uint32_t *addr_cellsp, *size_cellsp;
749 int err, i, len, memory, root;
752 uint64_t rstart, rsize;
755 root = fdt_path_offset(fdtp, "/");
757 sprintf(command_errbuf, "Could not find root node !");
761 memory = fdt_path_offset(fdtp, "/memory");
763 /* Create proper '/memory' node. */
764 memory = fdt_add_subnode(fdtp, root, "memory");
766 snprintf(command_errbuf, sizeof(command_errbuf),
767 "Could not fixup '/memory' "
768 "node, error code : %d!\n", memory);
772 err = fdt_setprop(fdtp, memory, "device_type", "memory",
779 addr_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#address-cells",
781 size_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#size-cells", NULL);
783 if (addr_cellsp == NULL || size_cellsp == NULL) {
784 snprintf(command_errbuf, sizeof(command_errbuf),
785 "Could not fixup '/memory' node : "
786 "%s %s property not found in root node!\n",
787 (!addr_cellsp) ? "#address-cells" : "",
788 (!size_cellsp) ? "#size-cells" : "");
792 addr_cells = fdt32_to_cpu(*addr_cellsp);
793 size_cells = fdt32_to_cpu(*size_cellsp);
796 * Convert memreserve data to memreserve property
797 * Check if property already exists
799 reserved = fdt_num_mem_rsv(fdtp);
801 (fdt_getprop(fdtp, root, "memreserve", NULL) == NULL)) {
802 len = (addr_cells + size_cells) * reserved * sizeof(uint32_t);
803 sb = buf = (uint8_t *)malloc(len);
809 for (i = 0; i < reserved; i++) {
810 if (fdt_get_mem_rsv(fdtp, i, &rstart, &rsize))
813 /* Ensure endianness, and put cells into a buffer */
816 cpu_to_fdt64(rstart);
819 cpu_to_fdt32(rstart);
821 buf += sizeof(uint32_t) * addr_cells;
829 buf += sizeof(uint32_t) * size_cells;
834 if ((err = fdt_setprop(fdtp, root, "memreserve", sb, len)) < 0)
835 printf("Could not fixup 'memreserve' property.\n");
840 /* Count valid memory regions entries in sysinfo. */
842 for (i = 0; i < num; i++)
843 if (region[i].start == 0 && region[i].size == 0)
847 sprintf(command_errbuf, "Could not fixup '/memory' node : "
848 "sysinfo doesn't contain valid memory regions info!\n");
852 len = (addr_cells + size_cells) * realmrno * sizeof(uint32_t);
853 sb = buf = (uint8_t *)malloc(len);
859 for (i = 0; i < num; i++) {
861 if (curmr->size != 0) {
862 /* Ensure endianness, and put cells into a buffer */
865 cpu_to_fdt64(curmr->start);
868 cpu_to_fdt32(curmr->start);
870 buf += sizeof(uint32_t) * addr_cells;
873 cpu_to_fdt64(curmr->size);
876 cpu_to_fdt32(curmr->size);
878 buf += sizeof(uint32_t) * size_cells;
883 if ((err = fdt_setprop(fdtp, memory, "reg", sb, len)) < 0)
884 sprintf(command_errbuf, "Could not fixup '/memory' node.\n");
890 fdt_fixup_stdout(const char *str)
894 const struct fdt_property *prop;
897 ptr = (char *)str + strlen(str) - 1;
898 while (ptr > str && isdigit(*(str - 1)))
904 no = fdt_path_offset(fdtp, "/chosen");
908 prop = fdt_get_property(fdtp, no, "stdout", &len);
910 /* If /chosen/stdout does not extist, create it */
911 if (prop == NULL || (prop != NULL && len == 0)) {
913 bzero(tmp, 10 * sizeof(char));
914 strcpy((char *)&tmp, "serial");
916 /* Serial number too long */
919 strncpy((char *)tmp + 6, ptr, 3);
920 sero = fdt_path_offset(fdtp, (const char *)tmp);
923 * If serial device we're trying to assign
924 * stdout to doesn't exist in DT -- return.
928 fdt_setprop(fdtp, no, "stdout", &tmp,
929 strlen((char *)&tmp) + 1);
930 fdt_setprop(fdtp, no, "stdin", &tmp,
931 strlen((char *)&tmp) + 1);
936 fdt_load_dtb_overlays(const char *extras)
940 /* Any extra overlays supplied by pre-loader environment */
941 if (extras != NULL && *extras != '\0') {
942 printf("Loading DTB overlays: '%s'\n", extras);
943 fdt_load_dtb_overlays_string(extras);
946 /* Any overlays supplied by loader environment */
947 s = getenv("fdt_overlays");
948 if (s != NULL && *s != '\0') {
949 printf("Loading DTB overlays: '%s'\n", s);
950 fdt_load_dtb_overlays_string(s);
955 * Locate the blob, fix it up and return its location.
962 debugf("fdt_fixup()\n");
964 if (fdtp == NULL && fdt_setup_fdtp() != 0)
967 /* Create /chosen node (if not exists) */
968 if ((chosen = fdt_subnode_offset(fdtp, 0, "chosen")) ==
970 chosen = fdt_add_subnode(fdtp, 0, "chosen");
972 /* Value assigned to fixup-applied does not matter. */
973 if (fdt_getprop(fdtp, chosen, "fixup-applied", NULL))
976 fdt_platform_fixups();
979 * Re-fetch the /chosen subnode; our fixups may apply overlays or add
980 * nodes/properties that invalidate the offset we grabbed or created
981 * above, so we can no longer trust it.
983 chosen = fdt_subnode_offset(fdtp, 0, "chosen");
984 fdt_setprop(fdtp, chosen, "fixup-applied", NULL, 0);
989 * Copy DTB blob to specified location and return size
992 fdt_copy(vm_offset_t va)
995 debugf("fdt_copy va 0x%08x\n", va);
997 err = fdt_setup_fdtp();
999 printf("No valid device tree blob found!\n");
1004 if (fdt_fixup() == 0)
1007 COPYIN(fdtp, va, fdtp_size);
1014 command_fdt_internal(int argc, char *argv[])
1021 command_errmsg = "usage is 'fdt <command> [<args>]";
1026 * Validate fdt <command>.
1030 while (!(commands[i].name == NULL)) {
1031 if (strcmp(argv[1], commands[i].name) == 0) {
1033 cmdh = commands[i].handler;
1034 flags = commands[i].flags;
1040 command_errmsg = "unknown command";
1044 if (flags & CMD_REQUIRES_BLOB) {
1046 * Check if uboot env vars were parsed already. If not, do it now.
1048 if (fdt_fixup() == 0)
1053 * Call command handler.
1055 err = (*cmdh)(argc, argv);
1061 fdt_cmd_addr(int argc, char *argv[])
1063 struct preloaded_file *fp;
1064 struct fdt_header *hdr;
1073 sprintf(command_errbuf, "no address specified");
1077 hdr = (struct fdt_header *)strtoul(addr, &cp, 16);
1079 snprintf(command_errbuf, sizeof(command_errbuf),
1080 "Invalid address: %s", addr);
1084 while ((fp = file_findfile(NULL, "dtb")) != NULL) {
1093 fdt_cmd_cd(int argc, char *argv[])
1096 char tmp[FDT_CWD_LEN];
1099 path = (argc > 2) ? argv[2] : "/";
1101 if (path[0] == '/') {
1103 if (len >= FDT_CWD_LEN)
1106 /* Handle path specification relative to cwd */
1107 len = strlen(cwd) + strlen(path) + 1;
1108 if (len >= FDT_CWD_LEN)
1117 o = fdt_path_offset(fdtp, path);
1119 snprintf(command_errbuf, sizeof(command_errbuf),
1120 "could not find node: '%s'", path);
1128 snprintf(command_errbuf, sizeof(command_errbuf),
1129 "path too long: %d, max allowed: %d", len, FDT_CWD_LEN - 1);
1134 fdt_cmd_hdr(int argc __unused, char *argv[] __unused)
1140 command_errmsg = "no device tree blob pointer?!";
1144 ver = fdt_version(fdtp);
1146 sprintf(line, "\nFlattened device tree header (%p):\n", fdtp);
1147 if (pager_output(line))
1149 sprintf(line, " magic = 0x%08x\n", fdt_magic(fdtp));
1150 if (pager_output(line))
1152 sprintf(line, " size = %d\n", fdt_totalsize(fdtp));
1153 if (pager_output(line))
1155 sprintf(line, " off_dt_struct = 0x%08x\n",
1156 fdt_off_dt_struct(fdtp));
1157 if (pager_output(line))
1159 sprintf(line, " off_dt_strings = 0x%08x\n",
1160 fdt_off_dt_strings(fdtp));
1161 if (pager_output(line))
1163 sprintf(line, " off_mem_rsvmap = 0x%08x\n",
1164 fdt_off_mem_rsvmap(fdtp));
1165 if (pager_output(line))
1167 sprintf(line, " version = %d\n", ver);
1168 if (pager_output(line))
1170 sprintf(line, " last compatible version = %d\n",
1171 fdt_last_comp_version(fdtp));
1172 if (pager_output(line))
1175 sprintf(line, " boot_cpuid = %d\n",
1176 fdt_boot_cpuid_phys(fdtp));
1177 if (pager_output(line))
1181 sprintf(line, " size_dt_strings = %d\n",
1182 fdt_size_dt_strings(fdtp));
1183 if (pager_output(line))
1187 sprintf(line, " size_dt_struct = %d\n",
1188 fdt_size_dt_struct(fdtp));
1189 if (pager_output(line))
1199 fdt_cmd_ls(int argc, char *argv[])
1201 const char *prevname[FDT_MAX_DEPTH] = { NULL };
1206 path = (argc > 2) ? argv[2] : NULL;
1210 o = fdt_path_offset(fdtp, path);
1212 snprintf(command_errbuf, sizeof(command_errbuf),
1213 "could not find node: '%s'", path);
1218 (o >= 0) && (depth >= 0);
1219 o = fdt_next_node(fdtp, o, &depth)) {
1221 name = fdt_get_name(fdtp, o, NULL);
1223 if (depth > FDT_MAX_DEPTH) {
1224 printf("max depth exceeded: %d\n", depth);
1228 prevname[depth] = name;
1230 /* Skip root (i = 1) when printing devices */
1231 for (i = 1; i <= depth; i++) {
1232 if (prevname[i] == NULL)
1235 if (strcmp(cwd, "/") == 0)
1237 printf("%s", prevname[i]);
1249 return (c >= ' ' && c <= 0x7e);
1253 fdt_isprint(const void *data, int len, int *count)
1262 d = (const char *)data;
1263 if (d[len - 1] != '\0')
1268 for (i = 0; i < len; i++) {
1270 if (isprint(ch) || (ch == '\0' && i > 0)) {
1285 fdt_data_str(const void *data, int len, int count, char **buf)
1292 * Calculate the length for the string and allocate memory.
1294 * Note that 'len' already includes at least one terminator.
1299 * Each token had already a terminator buried in 'len', but we
1300 * only need one eventually, don't count space for these.
1302 buf_len -= count - 1;
1304 /* Each consecutive token requires a ", " separator. */
1305 buf_len += count * 2;
1308 /* Add some space for surrounding double quotes. */
1309 buf_len += count * 2;
1311 /* Note that string being put in 'tmp' may be as big as 'buf_len'. */
1312 b = (char *)malloc(buf_len);
1313 tmp = (char *)malloc(buf_len);
1325 * Now that we have space, format the string.
1329 d = (const char *)data + i;
1332 sprintf(tmp, "\"%s\"%s", d,
1333 (i + l) < len ? ", " : "");
1349 fdt_data_cell(const void *data, int len, char **buf)
1355 /* Number of cells */
1359 * Calculate the length for the string and allocate memory.
1362 /* Each byte translates to 2 output characters */
1365 /* Each consecutive cell requires a " " separator. */
1366 l += (count - 1) * 1;
1368 /* Each cell will have a "0x" prefix */
1370 /* Space for surrounding <> and terminator */
1373 b = (char *)malloc(l);
1374 tmp = (char *)malloc(l);
1386 for (i = 0; i < len; i += 4) {
1387 c = (const uint32_t *)((const uint8_t *)data + i);
1388 sprintf(tmp, "0x%08x%s", fdt32_to_cpu(*c),
1389 i < (len - 4) ? " " : "");
1403 fdt_data_bytes(const void *data, int len, char **buf)
1410 * Calculate the length for the string and allocate memory.
1413 /* Each byte translates to 2 output characters */
1416 /* Each consecutive byte requires a " " separator. */
1418 /* Each byte will have a "0x" prefix */
1420 /* Space for surrounding [] and terminator. */
1423 b = (char *)malloc(l);
1424 tmp = (char *)malloc(l);
1436 for (i = 0, d = data; i < len; i++) {
1437 sprintf(tmp, "0x%02x%s", d[i], i < len - 1 ? " " : "");
1451 fdt_data_fmt(const void *data, int len, char **buf)
1460 if (fdt_isprint(data, len, &count))
1461 return (fdt_data_str(data, len, count, buf));
1463 else if ((len % 4) == 0)
1464 return (fdt_data_cell(data, len, buf));
1467 return (fdt_data_bytes(data, len, buf));
1471 fdt_prop(int offset)
1474 const struct fdt_property *prop;
1480 prop = fdt_offset_ptr(fdtp, offset, sizeof(*prop));
1484 name = fdt_string(fdtp, fdt32_to_cpu(prop->nameoff));
1485 len = fdt32_to_cpu(prop->len);
1490 /* Property without value */
1491 line = (char *)malloc(strlen(name) + 2);
1496 sprintf(line, "%s\n", name);
1501 * Process property with value
1505 if (fdt_data_fmt(data, len, &buf) != 0) {
1510 line = (char *)malloc(strlen(name) + strlen(FDT_PROP_SEP) +
1513 sprintf(command_errbuf, "could not allocate space for string");
1518 sprintf(line, "%s" FDT_PROP_SEP "%s\n", name, buf);
1536 fdt_modprop(int nodeoff, char *propname, void *value, char mode)
1538 uint32_t cells[100];
1541 const struct fdt_property *p;
1543 p = fdt_get_property(fdtp, nodeoff, propname, NULL);
1547 /* Adding inexistant value in mode 1 is forbidden */
1548 sprintf(command_errbuf, "property already exists!");
1551 } else if (mode == 0) {
1552 sprintf(command_errbuf, "property does not exist!");
1564 len = fdt_strtovect(buf, (void *)&cells, 100,
1567 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1568 len * sizeof(uint32_t));
1572 len = fdt_strtovect(buf, (void *)&cells, 100,
1575 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1576 len * sizeof(uint8_t));
1580 /* Default -- string */
1581 rv = fdt_setprop_string(fdtp, nodeoff, propname, value);
1586 if (rv == -FDT_ERR_NOSPACE)
1587 sprintf(command_errbuf,
1588 "Device tree blob is too small!\n");
1590 sprintf(command_errbuf,
1591 "Could not add/modify property!\n");
1596 /* Merge strings from argv into a single string */
1598 fdt_merge_strings(int argc, char *argv[], int start, char **buffer)
1606 for (i = start; i < argc; i++)
1607 sz += strlen(argv[i]);
1609 /* Additional bytes for whitespaces between args */
1612 buf = (char *)malloc(sizeof(char) * sz);
1614 sprintf(command_errbuf, "could not allocate space "
1618 bzero(buf, sizeof(char) * sz);
1621 for (i = start, idx = 0; i < argc; i++) {
1622 strcpy(buf + idx, argv[i]);
1623 idx += strlen(argv[i]);
1632 /* Extract offset and name of node/property from a given path */
1634 fdt_extract_nameloc(char **pathp, char **namep, int *nodeoff)
1637 char *path = *pathp, *name = NULL, *subpath = NULL;
1639 subpath = strrchr(path, '/');
1640 if (subpath == NULL) {
1641 o = fdt_path_offset(fdtp, cwd);
1643 path = (char *)&cwd;
1646 if (strlen(path) == 0)
1650 o = fdt_path_offset(fdtp, path);
1653 if (strlen(name) == 0) {
1654 sprintf(command_errbuf, "name not specified");
1658 snprintf(command_errbuf, sizeof(command_errbuf),
1659 "could not find node: '%s'", path);
1669 fdt_cmd_prop(int argc, char *argv[])
1671 char *path, *propname, *value;
1672 int o, next, depth, rv;
1675 path = (argc > 2) ? argv[2] : NULL;
1680 /* Merge property value strings into one */
1681 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1692 /* If value is specified -- try to modify prop. */
1693 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1696 rv = fdt_modprop(o, propname, value, 0);
1702 /* User wants to display properties */
1703 o = fdt_path_offset(fdtp, path);
1706 snprintf(command_errbuf, sizeof(command_errbuf),
1707 "could not find node: '%s'", path);
1713 while (depth >= 0) {
1714 tag = fdt_next_tag(fdtp, o, &next);
1720 /* Don't process properties of nested nodes */
1723 if (fdt_prop(o) != 0) {
1724 sprintf(command_errbuf, "could not process "
1730 case FDT_BEGIN_NODE:
1732 if (depth > FDT_MAX_DEPTH) {
1733 printf("warning: nesting too deep: %d\n",
1742 * This is the end of our starting node, force
1755 fdt_cmd_mkprop(int argc, char *argv[])
1758 char *path, *propname, *value;
1760 path = (argc > 2) ? argv[2] : NULL;
1765 /* Merge property value strings into one */
1766 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1771 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1774 if (fdt_modprop(o, propname, value, 1))
1781 fdt_cmd_rm(int argc, char *argv[])
1784 char *path = NULL, *propname;
1789 sprintf(command_errbuf, "no node/property name specified");
1793 o = fdt_path_offset(fdtp, path);
1795 /* If node not found -- try to find & delete property */
1796 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1799 if ((rv = fdt_delprop(fdtp, o, propname)) != 0) {
1800 snprintf(command_errbuf, sizeof(command_errbuf),
1801 "could not delete %s\n",
1802 (rv == -FDT_ERR_NOTFOUND) ?
1803 "(property/node does not exist)" : "");
1809 /* If node exists -- remove node */
1810 rv = fdt_del_node(fdtp, o);
1812 sprintf(command_errbuf, "could not delete node");
1819 fdt_cmd_mknode(int argc, char *argv[])
1822 char *path = NULL, *nodename = NULL;
1827 sprintf(command_errbuf, "no node name specified");
1831 if (fdt_extract_nameloc(&path, &nodename, &o) != 0)
1834 rv = fdt_add_subnode(fdtp, o, nodename);
1837 if (rv == -FDT_ERR_NOSPACE)
1838 sprintf(command_errbuf,
1839 "Device tree blob is too small!\n");
1841 sprintf(command_errbuf,
1842 "Could not add node!\n");
1849 fdt_cmd_pwd(int argc, char *argv[])
1851 char line[FDT_CWD_LEN];
1854 sprintf(line, "%s\n", cwd);
1861 fdt_cmd_mres(int argc, char *argv[])
1863 uint64_t start, size;
1868 total = fdt_num_mem_rsv(fdtp);
1870 if (pager_output("Reserved memory regions:\n"))
1872 for (i = 0; i < total; i++) {
1873 fdt_get_mem_rsv(fdtp, i, &start, &size);
1874 sprintf(line, "reg#%d: (start: 0x%jx, size: 0x%jx)\n",
1876 if (pager_output(line))
1880 pager_output("No reserved memory regions\n");
1888 fdt_cmd_nyi(int argc, char *argv[])
1891 printf("command not yet implemented\n");
1896 fdt_devmatch_next(int *tag, int *compatlen)
1898 const struct fdt_property *p;
1899 const struct fdt_property *status;
1901 static int depth = 0;
1905 fdt_apply_overlays();
1910 /* We are at the end of the DTB */
1914 o = fdt_path_offset(fdtp, "/");
1916 printf("Can't find dtb\n");
1922 /* Find the next node with a compatible property */
1925 if (o >= 0 && depth >= 0) {
1926 /* skip disabled nodes */
1927 status = fdt_get_property(fdtp, o, "status", &len);
1929 if (strcmp(status->data, "disabled") == 0) {
1930 o = fdt_next_node(fdtp, o, &depth);
1931 if (o < 0) /* End of tree */
1937 p = fdt_get_property(fdtp, o, "compatible", &len);
1941 o = fdt_next_node(fdtp, o, &depth);
1942 if (o < 0) /* End of tree */
1946 /* Prepare next node for next call */
1947 o = fdt_next_node(fdtp, o, &depth);