2 * Copyright (c) 2009-2010 The FreeBSD Foundation
4 * This software was developed by Semihalf under sponsorship from
5 * the FreeBSD Foundation.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
33 #include <sys/param.h>
34 #include <sys/linker.h>
35 #include <machine/elf.h>
37 #include "bootstrap.h"
38 #include "fdt_platform.h"
41 #define debugf(fmt, args...) do { printf("%s(): ", __func__); \
42 printf(fmt,##args); } while (0)
44 #define debugf(fmt, args...)
47 #define FDT_CWD_LEN 256
48 #define FDT_MAX_DEPTH 12
50 #define FDT_PROP_SEP " = "
52 #define COPYOUT(s,d,l) archsw.arch_copyout(s, d, l)
53 #define COPYIN(s,d,l) archsw.arch_copyin(s, d, l)
55 #define FDT_STATIC_DTB_SYMBOL "fdt_static_dtb"
57 #define CMD_REQUIRES_BLOB 0x01
59 /* Location of FDT yet to be loaded. */
60 /* This may be in read-only memory, so can't be manipulated directly. */
61 static struct fdt_header *fdt_to_load = NULL;
62 /* Location of FDT on heap. */
63 /* This is the copy we actually manipulate. */
64 static struct fdt_header *fdtp = NULL;
65 /* Size of FDT blob */
66 static size_t fdtp_size = 0;
67 /* Have we loaded all the needed overlays */
68 static int fdt_overlays_applied = 0;
70 static int fdt_load_dtb(vm_offset_t va);
71 static void fdt_print_overlay_load_error(int err, const char *filename);
72 static int fdt_check_overlay_compatible(void *base_fdt, void *overlay_fdt);
74 static int fdt_cmd_nyi(int argc, char *argv[]);
75 static int fdt_load_dtb_overlays_string(const char * filenames);
77 static int fdt_cmd_addr(int argc, char *argv[]);
78 static int fdt_cmd_mkprop(int argc, char *argv[]);
79 static int fdt_cmd_cd(int argc, char *argv[]);
80 static int fdt_cmd_hdr(int argc, char *argv[]);
81 static int fdt_cmd_ls(int argc, char *argv[]);
82 static int fdt_cmd_prop(int argc, char *argv[]);
83 static int fdt_cmd_pwd(int argc, char *argv[]);
84 static int fdt_cmd_rm(int argc, char *argv[]);
85 static int fdt_cmd_mknode(int argc, char *argv[]);
86 static int fdt_cmd_mres(int argc, char *argv[]);
88 typedef int cmdf_t(int, char *[]);
96 static const struct cmdtab commands[] = {
97 { "addr", &fdt_cmd_addr, 0 },
98 { "alias", &fdt_cmd_nyi, 0 },
99 { "cd", &fdt_cmd_cd, CMD_REQUIRES_BLOB },
100 { "header", &fdt_cmd_hdr, CMD_REQUIRES_BLOB },
101 { "ls", &fdt_cmd_ls, CMD_REQUIRES_BLOB },
102 { "mknode", &fdt_cmd_mknode, CMD_REQUIRES_BLOB },
103 { "mkprop", &fdt_cmd_mkprop, CMD_REQUIRES_BLOB },
104 { "mres", &fdt_cmd_mres, CMD_REQUIRES_BLOB },
105 { "prop", &fdt_cmd_prop, CMD_REQUIRES_BLOB },
106 { "pwd", &fdt_cmd_pwd, CMD_REQUIRES_BLOB },
107 { "rm", &fdt_cmd_rm, CMD_REQUIRES_BLOB },
111 static char cwd[FDT_CWD_LEN] = "/";
114 fdt_find_static_dtb(void)
119 vm_offset_t strtab, symtab, fdt_start;
121 struct preloaded_file *kfp;
122 struct file_metadata *md;
126 debugf("fdt_find_static_dtb()\n");
128 sym_count = symtab = strtab = 0;
131 offs = __elfN(relocation_offset);
133 kfp = file_findfile(NULL, NULL);
137 /* Locate the dynamic symbols and strtab. */
138 md = file_findmetadata(kfp, MODINFOMD_ELFHDR);
141 ehdr = (Elf_Ehdr *)md->md_data;
143 md = file_findmetadata(kfp, MODINFOMD_SHDR);
146 shdr = (Elf_Shdr *)md->md_data;
148 for (i = 0; i < ehdr->e_shnum; ++i) {
149 if (shdr[i].sh_type == SHT_DYNSYM && symtab == 0) {
150 symtab = shdr[i].sh_addr + offs;
151 sym_count = shdr[i].sh_size / sizeof(Elf_Sym);
152 } else if (shdr[i].sh_type == SHT_STRTAB && strtab == 0) {
153 strtab = shdr[i].sh_addr + offs;
158 * The most efficient way to find a symbol would be to calculate a
159 * hash, find proper bucket and chain, and thus find a symbol.
160 * However, that would involve code duplication (e.g. for hash
161 * function). So we're using simpler and a bit slower way: we're
162 * iterating through symbols, searching for the one which name is
163 * 'equal' to 'fdt_static_dtb'. To speed up the process a little bit,
164 * we are eliminating symbols type of which is not STT_NOTYPE, or(and)
165 * those which binding attribute is not STB_GLOBAL.
168 while (sym_count > 0 && fdt_start == 0) {
169 COPYOUT(symtab, &sym, sizeof(sym));
170 symtab += sizeof(sym);
172 if (ELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
173 ELF_ST_TYPE(sym.st_info) != STT_NOTYPE)
175 strp = strdupout(strtab + sym.st_name);
176 if (strcmp(strp, FDT_STATIC_DTB_SYMBOL) == 0)
177 fdt_start = (vm_offset_t)sym.st_value + offs;
184 fdt_load_dtb(vm_offset_t va)
186 struct fdt_header header;
189 debugf("fdt_load_dtb(0x%08jx)\n", (uintmax_t)va);
191 COPYOUT(va, &header, sizeof(header));
192 err = fdt_check_header(&header);
194 if (err == -FDT_ERR_BADVERSION) {
195 snprintf(command_errbuf, sizeof(command_errbuf),
196 "incompatible blob version: %d, should be: %d",
197 fdt_version(fdtp), FDT_LAST_SUPPORTED_VERSION);
199 snprintf(command_errbuf, sizeof(command_errbuf),
200 "error validating blob: %s", fdt_strerror(err));
206 * Release previous blob
211 fdtp_size = fdt_totalsize(&header);
212 fdtp = malloc(fdtp_size);
215 command_errmsg = "can't allocate memory for device tree copy";
219 COPYOUT(va, fdtp, fdtp_size);
220 debugf("DTB blob found at 0x%jx, size: 0x%jx\n", (uintmax_t)va, (uintmax_t)fdtp_size);
226 fdt_load_dtb_addr(struct fdt_header *header)
230 debugf("fdt_load_dtb_addr(%p)\n", header);
232 fdtp_size = fdt_totalsize(header);
233 err = fdt_check_header(header);
235 snprintf(command_errbuf, sizeof(command_errbuf),
236 "error validating blob: %s", fdt_strerror(err));
240 if ((fdtp = malloc(fdtp_size)) == NULL) {
241 command_errmsg = "can't allocate memory for device tree copy";
245 bcopy(header, fdtp, fdtp_size);
250 fdt_load_dtb_file(const char * filename)
252 struct preloaded_file *bfp, *oldbfp;
255 debugf("fdt_load_dtb_file(%s)\n", filename);
257 oldbfp = file_findfile(NULL, "dtb");
259 /* Attempt to load and validate a new dtb from a file. */
260 if ((bfp = file_loadraw(filename, "dtb", 1)) == NULL) {
261 snprintf(command_errbuf, sizeof(command_errbuf),
262 "failed to load file '%s'", filename);
265 if ((err = fdt_load_dtb(bfp->f_addr)) != 0) {
270 /* A new dtb was validated, discard any previous file. */
272 file_discard(oldbfp);
277 fdt_load_dtb_overlay(const char * filename)
279 struct preloaded_file *bfp;
280 struct fdt_header header;
283 debugf("fdt_load_dtb_overlay(%s)\n", filename);
285 /* Attempt to load and validate a new dtb from a file. FDT_ERR_NOTFOUND
286 * is normally a libfdt error code, but libfdt would actually return
287 * -FDT_ERR_NOTFOUND. We re-purpose the error code here to convey a
288 * similar meaning: the file itself was not found, which can still be
289 * considered an error dealing with FDT pieces.
291 if ((bfp = file_loadraw(filename, "dtbo", 1)) == NULL)
292 return (FDT_ERR_NOTFOUND);
294 COPYOUT(bfp->f_addr, &header, sizeof(header));
295 err = fdt_check_header(&header);
306 fdt_print_overlay_load_error(int err, const char *filename)
310 case FDT_ERR_NOTFOUND:
311 printf("%s: failed to load file\n", filename);
313 case -FDT_ERR_BADVERSION:
314 printf("%s: incompatible blob version: %d, should be: %d\n",
315 filename, fdt_version(fdtp),
316 FDT_LAST_SUPPORTED_VERSION);
319 /* libfdt errs are negative */
321 printf("%s: error validating blob: %s\n",
322 filename, fdt_strerror(err));
324 printf("%s: unknown load error\n", filename);
330 fdt_load_dtb_overlays_string(const char * filenames)
333 char *name, *name_ext;
337 debugf("fdt_load_dtb_overlays_string(%s)\n", filenames);
339 names = strdup(filenames);
344 comaptr = strchr(name, ',');
347 err = fdt_load_dtb_overlay(name);
348 if (err == FDT_ERR_NOTFOUND) {
349 /* Allocate enough to append ".dtbo" */
350 namesz = strlen(name) + 6;
351 name_ext = malloc(namesz);
352 if (name_ext == NULL) {
353 fdt_print_overlay_load_error(err, name);
357 snprintf(name_ext, namesz, "%s.dtbo", name);
358 err = fdt_load_dtb_overlay(name_ext);
361 /* Catch error with either initial load or fallback load */
363 fdt_print_overlay_load_error(err, name);
372 * fdt_check_overlay_compatible - check that the overlay_fdt is compatible with
373 * base_fdt before we attempt to apply it. It will need to re-calculate offsets
374 * in the base every time, rather than trying to cache them earlier in the
375 * process, because the overlay application process can/will invalidate a lot of
379 fdt_check_overlay_compatible(void *base_fdt, void *overlay_fdt)
382 int compat_len, ocompat_len;
383 int oroot_offset, root_offset;
386 oroot_offset = fdt_path_offset(overlay_fdt, "/");
387 if (oroot_offset < 0)
388 return (oroot_offset);
390 * If /compatible in the overlay does not exist or if it is empty, then
391 * we're automatically compatible. We do this for the sake of rapid
392 * overlay development for overlays that aren't intended to be deployed.
393 * The user assumes the risk of using an overlay without /compatible.
395 if (fdt_get_property(overlay_fdt, oroot_offset, "compatible",
396 &ocompat_len) == NULL || ocompat_len == 0)
398 root_offset = fdt_path_offset(base_fdt, "/");
400 return (root_offset);
402 * However, an empty or missing /compatible on the base is an error,
403 * because allowing this offers no advantages.
405 if (fdt_get_property(base_fdt, root_offset, "compatible",
406 &compat_len) == NULL)
408 else if(compat_len == 0)
412 compat = fdt_stringlist_get(overlay_fdt, oroot_offset, "compatible",
414 while (compat != NULL) {
415 if (fdt_stringlist_search(base_fdt, root_offset, "compatible",
419 compat = fdt_stringlist_get(overlay_fdt, oroot_offset,
420 "compatible", slidx, &sllen);
423 /* We've exhausted the overlay's /compatible property... no match */
428 * Returns the number of overlays successfully applied
431 fdt_apply_overlays(void)
433 struct preloaded_file *fp;
434 size_t max_overlay_size, next_fdtp_size;
435 size_t current_fdtp_size;
439 int overlays_applied, rv;
441 if ((fdtp == NULL) || (fdtp_size == 0))
444 if (fdt_overlays_applied)
447 max_overlay_size = 0;
448 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
449 if (max_overlay_size < fp->f_size)
450 max_overlay_size = fp->f_size;
453 /* Nothing to apply */
454 if (max_overlay_size == 0)
457 overlay = malloc(max_overlay_size);
458 if (overlay == NULL) {
459 printf("failed to allocate memory for DTB blob with overlays\n");
463 current_fdtp_size = fdtp_size;
464 overlays_applied = 0;
465 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
466 if (strcmp(fp->f_type, "dtbo") != 0)
468 COPYOUT(fp->f_addr, overlay, fp->f_size);
469 /* Check compatible first to avoid unnecessary allocation */
470 rv = fdt_check_overlay_compatible(current_fdtp, overlay);
472 printf("DTB overlay '%s' not compatible\n", fp->f_name);
475 printf("applying DTB overlay '%s'\n", fp->f_name);
476 next_fdtp_size = current_fdtp_size + fp->f_size;
477 next_fdtp = malloc(next_fdtp_size);
478 if (next_fdtp == NULL) {
480 * Output warning, then move on to applying other
481 * overlays in case this one is simply too large.
483 printf("failed to allocate memory for overlay base\n");
486 rv = fdt_open_into(current_fdtp, next_fdtp, next_fdtp_size);
489 printf("failed to open base dtb into overlay base\n");
492 /* Both overlay and next_fdtp may be modified in place */
493 rv = fdt_overlay_apply(next_fdtp, overlay);
495 /* Rotate next -> current */
496 if (current_fdtp != fdtp)
498 current_fdtp = next_fdtp;
499 fdt_pack(current_fdtp);
500 current_fdtp_size = fdt_totalsize(current_fdtp);
504 * Assume here that the base we tried to apply on is
505 * either trashed or in an inconsistent state. Trying to
506 * load it might work, but it's better to discard it and
509 printf("failed to apply overlay: %s\n",
513 /* We could have failed to apply all overlays; then we do nothing */
514 if (current_fdtp != fdtp) {
517 fdtp_size = current_fdtp_size;
520 fdt_overlays_applied = 1;
521 return (overlays_applied);
525 fdt_pad_dtb(size_t padding)
528 size_t padded_fdtp_size;
530 padded_fdtp_size = fdtp_size + padding;
531 padded_fdtp = malloc(padded_fdtp_size);
532 if (padded_fdtp == NULL)
534 if (fdt_open_into(fdtp, padded_fdtp, padded_fdtp_size) != 0) {
539 fdtp_size = padded_fdtp_size;
556 struct preloaded_file *bfp;
559 debugf("fdt_setup_fdtp()\n");
561 /* If we already loaded a file, use it. */
562 if ((bfp = file_findfile(NULL, "dtb")) != NULL) {
563 if (fdt_load_dtb(bfp->f_addr) == 0) {
564 printf("Using DTB from loaded file '%s'.\n",
566 fdt_platform_load_overlays();
571 /* If we were given the address of a valid blob in memory, use it. */
572 if (fdt_to_load != NULL) {
573 if (fdt_load_dtb_addr(fdt_to_load) == 0) {
574 printf("Using DTB from memory address %p.\n",
576 fdt_platform_load_overlays();
581 if (fdt_platform_load_dtb() == 0) {
582 fdt_platform_load_overlays();
586 /* If there is a dtb compiled into the kernel, use it. */
587 if ((va = fdt_find_static_dtb()) != 0) {
588 if (fdt_load_dtb(va) == 0) {
589 printf("Using DTB compiled into kernel.\n");
594 command_errmsg = "No device tree blob found!\n";
598 #define fdt_strtovect(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
599 (cellbuf), (lim), (cellsize), 0);
601 /* Force using base 16 */
602 #define fdt_strtovectx(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
603 (cellbuf), (lim), (cellsize), 16);
606 _fdt_strtovect(const char *str, void *cellbuf, int lim, unsigned char cellsize,
609 const char *buf = str;
610 const char *end = str + strlen(str) - 2;
611 uint32_t *u32buf = NULL;
612 uint8_t *u8buf = NULL;
615 if (cellsize == sizeof(uint32_t))
616 u32buf = (uint32_t *)cellbuf;
618 u8buf = (uint8_t *)cellbuf;
625 /* Skip white whitespace(s)/separators */
626 while (!isxdigit(*buf) && buf < end)
631 cpu_to_fdt32((uint32_t)strtol(buf, NULL, base));
634 u8buf[cnt] = (uint8_t)strtol(buf, NULL, base);
636 if (cnt + 1 <= lim - 1)
641 /* Find another number */
642 while ((isxdigit(*buf) || *buf == 'x') && buf < end)
649 fdt_fixup_ethernet(const char *str, char *ethstr, int len)
653 /* Convert macaddr string into a vector of uints */
654 fdt_strtovectx(str, &tmp_addr, 6, sizeof(uint8_t));
655 /* Set actual property to a value from vect */
656 fdt_setprop(fdtp, fdt_path_offset(fdtp, ethstr),
657 "local-mac-address", &tmp_addr, 6 * sizeof(uint8_t));
661 fdt_fixup_cpubusfreqs(unsigned long cpufreq, unsigned long busfreq)
663 int lo, o = 0, o2, maxo = 0, depth;
664 const uint32_t zero = 0;
666 /* We want to modify every subnode of /cpus */
667 o = fdt_path_offset(fdtp, "/cpus");
671 /* maxo should contain offset of node next to /cpus */
675 maxo = fdt_next_node(fdtp, maxo, &depth);
677 /* Find CPU frequency properties */
678 o = fdt_node_offset_by_prop_value(fdtp, o, "clock-frequency",
679 &zero, sizeof(uint32_t));
681 o2 = fdt_node_offset_by_prop_value(fdtp, o, "bus-frequency", &zero,
686 while (o != -FDT_ERR_NOTFOUND && o2 != -FDT_ERR_NOTFOUND) {
688 o = fdt_node_offset_by_prop_value(fdtp, lo,
689 "clock-frequency", &zero, sizeof(uint32_t));
691 o2 = fdt_node_offset_by_prop_value(fdtp, lo, "bus-frequency",
692 &zero, sizeof(uint32_t));
694 /* We're only interested in /cpus subnode(s) */
698 fdt_setprop_inplace_cell(fdtp, lo, "clock-frequency",
701 fdt_setprop_inplace_cell(fdtp, lo, "bus-frequency",
710 fdt_reg_valid(uint32_t *reg, int len, int addr_cells, int size_cells)
712 int cells_in_tuple, i, tuples, tuple_size;
713 uint32_t cur_start, cur_size;
715 cells_in_tuple = (addr_cells + size_cells);
716 tuple_size = cells_in_tuple * sizeof(uint32_t);
717 tuples = len / tuple_size;
721 for (i = 0; i < tuples; i++) {
723 cur_start = fdt64_to_cpu(reg[i * cells_in_tuple]);
725 cur_start = fdt32_to_cpu(reg[i * cells_in_tuple]);
728 cur_size = fdt64_to_cpu(reg[i * cells_in_tuple + 2]);
730 cur_size = fdt32_to_cpu(reg[i * cells_in_tuple + 1]);
735 debugf(" reg#%d (start: 0x%0x size: 0x%0x) valid!\n",
736 i, cur_start, cur_size);
743 fdt_fixup_memory(struct fdt_mem_region *region, size_t num)
745 struct fdt_mem_region *curmr;
746 uint32_t addr_cells, size_cells;
747 uint32_t *addr_cellsp, *size_cellsp;
748 int err, i, len, memory, root;
751 uint64_t rstart, rsize;
754 root = fdt_path_offset(fdtp, "/");
756 sprintf(command_errbuf, "Could not find root node !");
760 memory = fdt_path_offset(fdtp, "/memory");
762 /* Create proper '/memory' node. */
763 memory = fdt_add_subnode(fdtp, root, "memory");
765 snprintf(command_errbuf, sizeof(command_errbuf),
766 "Could not fixup '/memory' "
767 "node, error code : %d!\n", memory);
771 err = fdt_setprop(fdtp, memory, "device_type", "memory",
778 addr_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#address-cells",
780 size_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#size-cells", NULL);
782 if (addr_cellsp == NULL || size_cellsp == NULL) {
783 snprintf(command_errbuf, sizeof(command_errbuf),
784 "Could not fixup '/memory' node : "
785 "%s %s property not found in root node!\n",
786 (!addr_cellsp) ? "#address-cells" : "",
787 (!size_cellsp) ? "#size-cells" : "");
791 addr_cells = fdt32_to_cpu(*addr_cellsp);
792 size_cells = fdt32_to_cpu(*size_cellsp);
795 * Convert memreserve data to memreserve property
796 * Check if property already exists
798 reserved = fdt_num_mem_rsv(fdtp);
800 (fdt_getprop(fdtp, root, "memreserve", NULL) == NULL)) {
801 len = (addr_cells + size_cells) * reserved * sizeof(uint32_t);
802 sb = buf = (uint8_t *)malloc(len);
808 for (i = 0; i < reserved; i++) {
809 if (fdt_get_mem_rsv(fdtp, i, &rstart, &rsize))
812 /* Ensure endianness, and put cells into a buffer */
815 cpu_to_fdt64(rstart);
818 cpu_to_fdt32(rstart);
820 buf += sizeof(uint32_t) * addr_cells;
828 buf += sizeof(uint32_t) * size_cells;
833 if ((err = fdt_setprop(fdtp, root, "memreserve", sb, len)) < 0)
834 printf("Could not fixup 'memreserve' property.\n");
839 /* Count valid memory regions entries in sysinfo. */
841 for (i = 0; i < num; i++)
842 if (region[i].start == 0 && region[i].size == 0)
846 sprintf(command_errbuf, "Could not fixup '/memory' node : "
847 "sysinfo doesn't contain valid memory regions info!\n");
851 len = (addr_cells + size_cells) * realmrno * sizeof(uint32_t);
852 sb = buf = (uint8_t *)malloc(len);
858 for (i = 0; i < num; i++) {
860 if (curmr->size != 0) {
861 /* Ensure endianness, and put cells into a buffer */
864 cpu_to_fdt64(curmr->start);
867 cpu_to_fdt32(curmr->start);
869 buf += sizeof(uint32_t) * addr_cells;
872 cpu_to_fdt64(curmr->size);
875 cpu_to_fdt32(curmr->size);
877 buf += sizeof(uint32_t) * size_cells;
882 if ((err = fdt_setprop(fdtp, memory, "reg", sb, len)) < 0)
883 sprintf(command_errbuf, "Could not fixup '/memory' node.\n");
889 fdt_fixup_stdout(const char *str)
893 const struct fdt_property *prop;
896 ptr = (char *)str + strlen(str) - 1;
897 while (ptr > str && isdigit(*(str - 1)))
903 no = fdt_path_offset(fdtp, "/chosen");
907 prop = fdt_get_property(fdtp, no, "stdout", &len);
909 /* If /chosen/stdout does not extist, create it */
910 if (prop == NULL || (prop != NULL && len == 0)) {
912 bzero(tmp, 10 * sizeof(char));
913 strcpy((char *)&tmp, "serial");
915 /* Serial number too long */
918 strncpy((char *)tmp + 6, ptr, 3);
919 sero = fdt_path_offset(fdtp, (const char *)tmp);
922 * If serial device we're trying to assign
923 * stdout to doesn't exist in DT -- return.
927 fdt_setprop(fdtp, no, "stdout", &tmp,
928 strlen((char *)&tmp) + 1);
929 fdt_setprop(fdtp, no, "stdin", &tmp,
930 strlen((char *)&tmp) + 1);
935 fdt_load_dtb_overlays(const char *extras)
939 /* Any extra overlays supplied by pre-loader environment */
940 if (extras != NULL && *extras != '\0') {
941 printf("Loading DTB overlays: '%s'\n", extras);
942 fdt_load_dtb_overlays_string(extras);
945 /* Any overlays supplied by loader environment */
946 s = getenv("fdt_overlays");
947 if (s != NULL && *s != '\0') {
948 printf("Loading DTB overlays: '%s'\n", s);
949 fdt_load_dtb_overlays_string(s);
954 * Locate the blob, fix it up and return its location.
961 debugf("fdt_fixup()\n");
963 if (fdtp == NULL && fdt_setup_fdtp() != 0)
966 /* Create /chosen node (if not exists) */
967 if ((chosen = fdt_subnode_offset(fdtp, 0, "chosen")) ==
969 chosen = fdt_add_subnode(fdtp, 0, "chosen");
971 /* Value assigned to fixup-applied does not matter. */
972 if (fdt_getprop(fdtp, chosen, "fixup-applied", NULL))
975 fdt_platform_fixups();
978 * Re-fetch the /chosen subnode; our fixups may apply overlays or add
979 * nodes/properties that invalidate the offset we grabbed or created
980 * above, so we can no longer trust it.
982 chosen = fdt_subnode_offset(fdtp, 0, "chosen");
983 fdt_setprop(fdtp, chosen, "fixup-applied", NULL, 0);
988 * Copy DTB blob to specified location and return size
991 fdt_copy(vm_offset_t va)
994 debugf("fdt_copy va 0x%08x\n", va);
996 err = fdt_setup_fdtp();
998 printf("No valid device tree blob found!\n");
1003 if (fdt_fixup() == 0)
1006 COPYIN(fdtp, va, fdtp_size);
1013 command_fdt_internal(int argc, char *argv[])
1020 command_errmsg = "usage is 'fdt <command> [<args>]";
1025 * Validate fdt <command>.
1029 while (!(commands[i].name == NULL)) {
1030 if (strcmp(argv[1], commands[i].name) == 0) {
1032 cmdh = commands[i].handler;
1033 flags = commands[i].flags;
1039 command_errmsg = "unknown command";
1043 if (flags & CMD_REQUIRES_BLOB) {
1045 * Check if uboot env vars were parsed already. If not, do it now.
1047 if (fdt_fixup() == 0)
1052 * Call command handler.
1054 err = (*cmdh)(argc, argv);
1060 fdt_cmd_addr(int argc, char *argv[])
1062 struct preloaded_file *fp;
1063 struct fdt_header *hdr;
1072 sprintf(command_errbuf, "no address specified");
1076 hdr = (struct fdt_header *)strtoul(addr, &cp, 16);
1078 snprintf(command_errbuf, sizeof(command_errbuf),
1079 "Invalid address: %s", addr);
1083 while ((fp = file_findfile(NULL, "dtb")) != NULL) {
1092 fdt_cmd_cd(int argc, char *argv[])
1095 char tmp[FDT_CWD_LEN];
1098 path = (argc > 2) ? argv[2] : "/";
1100 if (path[0] == '/') {
1102 if (len >= FDT_CWD_LEN)
1105 /* Handle path specification relative to cwd */
1106 len = strlen(cwd) + strlen(path) + 1;
1107 if (len >= FDT_CWD_LEN)
1116 o = fdt_path_offset(fdtp, path);
1118 snprintf(command_errbuf, sizeof(command_errbuf),
1119 "could not find node: '%s'", path);
1127 snprintf(command_errbuf, sizeof(command_errbuf),
1128 "path too long: %d, max allowed: %d", len, FDT_CWD_LEN - 1);
1133 fdt_cmd_hdr(int argc __unused, char *argv[] __unused)
1139 command_errmsg = "no device tree blob pointer?!";
1143 ver = fdt_version(fdtp);
1145 sprintf(line, "\nFlattened device tree header (%p):\n", fdtp);
1146 if (pager_output(line))
1148 sprintf(line, " magic = 0x%08x\n", fdt_magic(fdtp));
1149 if (pager_output(line))
1151 sprintf(line, " size = %d\n", fdt_totalsize(fdtp));
1152 if (pager_output(line))
1154 sprintf(line, " off_dt_struct = 0x%08x\n",
1155 fdt_off_dt_struct(fdtp));
1156 if (pager_output(line))
1158 sprintf(line, " off_dt_strings = 0x%08x\n",
1159 fdt_off_dt_strings(fdtp));
1160 if (pager_output(line))
1162 sprintf(line, " off_mem_rsvmap = 0x%08x\n",
1163 fdt_off_mem_rsvmap(fdtp));
1164 if (pager_output(line))
1166 sprintf(line, " version = %d\n", ver);
1167 if (pager_output(line))
1169 sprintf(line, " last compatible version = %d\n",
1170 fdt_last_comp_version(fdtp));
1171 if (pager_output(line))
1174 sprintf(line, " boot_cpuid = %d\n",
1175 fdt_boot_cpuid_phys(fdtp));
1176 if (pager_output(line))
1180 sprintf(line, " size_dt_strings = %d\n",
1181 fdt_size_dt_strings(fdtp));
1182 if (pager_output(line))
1186 sprintf(line, " size_dt_struct = %d\n",
1187 fdt_size_dt_struct(fdtp));
1188 if (pager_output(line))
1198 fdt_cmd_ls(int argc, char *argv[])
1200 const char *prevname[FDT_MAX_DEPTH] = { NULL };
1205 path = (argc > 2) ? argv[2] : NULL;
1209 o = fdt_path_offset(fdtp, path);
1211 snprintf(command_errbuf, sizeof(command_errbuf),
1212 "could not find node: '%s'", path);
1217 (o >= 0) && (depth >= 0);
1218 o = fdt_next_node(fdtp, o, &depth)) {
1220 name = fdt_get_name(fdtp, o, NULL);
1222 if (depth > FDT_MAX_DEPTH) {
1223 printf("max depth exceeded: %d\n", depth);
1227 prevname[depth] = name;
1229 /* Skip root (i = 1) when printing devices */
1230 for (i = 1; i <= depth; i++) {
1231 if (prevname[i] == NULL)
1234 if (strcmp(cwd, "/") == 0)
1236 printf("%s", prevname[i]);
1248 return (c >= ' ' && c <= 0x7e);
1252 fdt_isprint(const void *data, int len, int *count)
1261 d = (const char *)data;
1262 if (d[len - 1] != '\0')
1267 for (i = 0; i < len; i++) {
1269 if (isprint(ch) || (ch == '\0' && i > 0)) {
1284 fdt_data_str(const void *data, int len, int count, char **buf)
1291 * Calculate the length for the string and allocate memory.
1293 * Note that 'len' already includes at least one terminator.
1298 * Each token had already a terminator buried in 'len', but we
1299 * only need one eventually, don't count space for these.
1301 buf_len -= count - 1;
1303 /* Each consecutive token requires a ", " separator. */
1304 buf_len += count * 2;
1307 /* Add some space for surrounding double quotes. */
1308 buf_len += count * 2;
1310 /* Note that string being put in 'tmp' may be as big as 'buf_len'. */
1311 b = (char *)malloc(buf_len);
1312 tmp = (char *)malloc(buf_len);
1324 * Now that we have space, format the string.
1328 d = (const char *)data + i;
1331 sprintf(tmp, "\"%s\"%s", d,
1332 (i + l) < len ? ", " : "");
1348 fdt_data_cell(const void *data, int len, char **buf)
1354 /* Number of cells */
1358 * Calculate the length for the string and allocate memory.
1361 /* Each byte translates to 2 output characters */
1364 /* Each consecutive cell requires a " " separator. */
1365 l += (count - 1) * 1;
1367 /* Each cell will have a "0x" prefix */
1369 /* Space for surrounding <> and terminator */
1372 b = (char *)malloc(l);
1373 tmp = (char *)malloc(l);
1385 for (i = 0; i < len; i += 4) {
1386 c = (const uint32_t *)((const uint8_t *)data + i);
1387 sprintf(tmp, "0x%08x%s", fdt32_to_cpu(*c),
1388 i < (len - 4) ? " " : "");
1402 fdt_data_bytes(const void *data, int len, char **buf)
1409 * Calculate the length for the string and allocate memory.
1412 /* Each byte translates to 2 output characters */
1415 /* Each consecutive byte requires a " " separator. */
1417 /* Each byte will have a "0x" prefix */
1419 /* Space for surrounding [] and terminator. */
1422 b = (char *)malloc(l);
1423 tmp = (char *)malloc(l);
1435 for (i = 0, d = data; i < len; i++) {
1436 sprintf(tmp, "0x%02x%s", d[i], i < len - 1 ? " " : "");
1450 fdt_data_fmt(const void *data, int len, char **buf)
1459 if (fdt_isprint(data, len, &count))
1460 return (fdt_data_str(data, len, count, buf));
1462 else if ((len % 4) == 0)
1463 return (fdt_data_cell(data, len, buf));
1466 return (fdt_data_bytes(data, len, buf));
1470 fdt_prop(int offset)
1473 const struct fdt_property *prop;
1479 prop = fdt_offset_ptr(fdtp, offset, sizeof(*prop));
1483 name = fdt_string(fdtp, fdt32_to_cpu(prop->nameoff));
1484 len = fdt32_to_cpu(prop->len);
1489 /* Property without value */
1490 line = (char *)malloc(strlen(name) + 2);
1495 sprintf(line, "%s\n", name);
1500 * Process property with value
1504 if (fdt_data_fmt(data, len, &buf) != 0) {
1509 line = (char *)malloc(strlen(name) + strlen(FDT_PROP_SEP) +
1512 sprintf(command_errbuf, "could not allocate space for string");
1517 sprintf(line, "%s" FDT_PROP_SEP "%s\n", name, buf);
1535 fdt_modprop(int nodeoff, char *propname, void *value, char mode)
1537 uint32_t cells[100];
1540 const struct fdt_property *p;
1542 p = fdt_get_property(fdtp, nodeoff, propname, NULL);
1546 /* Adding inexistant value in mode 1 is forbidden */
1547 sprintf(command_errbuf, "property already exists!");
1550 } else if (mode == 0) {
1551 sprintf(command_errbuf, "property does not exist!");
1563 len = fdt_strtovect(buf, (void *)&cells, 100,
1566 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1567 len * sizeof(uint32_t));
1571 len = fdt_strtovect(buf, (void *)&cells, 100,
1574 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1575 len * sizeof(uint8_t));
1579 /* Default -- string */
1580 rv = fdt_setprop_string(fdtp, nodeoff, propname, value);
1585 if (rv == -FDT_ERR_NOSPACE)
1586 sprintf(command_errbuf,
1587 "Device tree blob is too small!\n");
1589 sprintf(command_errbuf,
1590 "Could not add/modify property!\n");
1595 /* Merge strings from argv into a single string */
1597 fdt_merge_strings(int argc, char *argv[], int start, char **buffer)
1605 for (i = start; i < argc; i++)
1606 sz += strlen(argv[i]);
1608 /* Additional bytes for whitespaces between args */
1611 buf = (char *)malloc(sizeof(char) * sz);
1613 sprintf(command_errbuf, "could not allocate space "
1617 bzero(buf, sizeof(char) * sz);
1620 for (i = start, idx = 0; i < argc; i++) {
1621 strcpy(buf + idx, argv[i]);
1622 idx += strlen(argv[i]);
1631 /* Extract offset and name of node/property from a given path */
1633 fdt_extract_nameloc(char **pathp, char **namep, int *nodeoff)
1636 char *path = *pathp, *name = NULL, *subpath = NULL;
1638 subpath = strrchr(path, '/');
1639 if (subpath == NULL) {
1640 o = fdt_path_offset(fdtp, cwd);
1642 path = (char *)&cwd;
1645 if (strlen(path) == 0)
1649 o = fdt_path_offset(fdtp, path);
1652 if (strlen(name) == 0) {
1653 sprintf(command_errbuf, "name not specified");
1657 snprintf(command_errbuf, sizeof(command_errbuf),
1658 "could not find node: '%s'", path);
1668 fdt_cmd_prop(int argc, char *argv[])
1670 char *path, *propname, *value;
1671 int o, next, depth, rv;
1674 path = (argc > 2) ? argv[2] : NULL;
1679 /* Merge property value strings into one */
1680 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1691 /* If value is specified -- try to modify prop. */
1692 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1695 rv = fdt_modprop(o, propname, value, 0);
1701 /* User wants to display properties */
1702 o = fdt_path_offset(fdtp, path);
1705 snprintf(command_errbuf, sizeof(command_errbuf),
1706 "could not find node: '%s'", path);
1712 while (depth >= 0) {
1713 tag = fdt_next_tag(fdtp, o, &next);
1719 /* Don't process properties of nested nodes */
1722 if (fdt_prop(o) != 0) {
1723 sprintf(command_errbuf, "could not process "
1729 case FDT_BEGIN_NODE:
1731 if (depth > FDT_MAX_DEPTH) {
1732 printf("warning: nesting too deep: %d\n",
1741 * This is the end of our starting node, force
1754 fdt_cmd_mkprop(int argc, char *argv[])
1757 char *path, *propname, *value;
1759 path = (argc > 2) ? argv[2] : NULL;
1764 /* Merge property value strings into one */
1765 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1770 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1773 if (fdt_modprop(o, propname, value, 1))
1780 fdt_cmd_rm(int argc, char *argv[])
1783 char *path = NULL, *propname;
1788 sprintf(command_errbuf, "no node/property name specified");
1792 o = fdt_path_offset(fdtp, path);
1794 /* If node not found -- try to find & delete property */
1795 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1798 if ((rv = fdt_delprop(fdtp, o, propname)) != 0) {
1799 snprintf(command_errbuf, sizeof(command_errbuf),
1800 "could not delete %s\n",
1801 (rv == -FDT_ERR_NOTFOUND) ?
1802 "(property/node does not exist)" : "");
1808 /* If node exists -- remove node */
1809 rv = fdt_del_node(fdtp, o);
1811 sprintf(command_errbuf, "could not delete node");
1818 fdt_cmd_mknode(int argc, char *argv[])
1821 char *path = NULL, *nodename = NULL;
1826 sprintf(command_errbuf, "no node name specified");
1830 if (fdt_extract_nameloc(&path, &nodename, &o) != 0)
1833 rv = fdt_add_subnode(fdtp, o, nodename);
1836 if (rv == -FDT_ERR_NOSPACE)
1837 sprintf(command_errbuf,
1838 "Device tree blob is too small!\n");
1840 sprintf(command_errbuf,
1841 "Could not add node!\n");
1848 fdt_cmd_pwd(int argc, char *argv[])
1850 char line[FDT_CWD_LEN];
1853 sprintf(line, "%s\n", cwd);
1860 fdt_cmd_mres(int argc, char *argv[])
1862 uint64_t start, size;
1867 total = fdt_num_mem_rsv(fdtp);
1869 if (pager_output("Reserved memory regions:\n"))
1871 for (i = 0; i < total; i++) {
1872 fdt_get_mem_rsv(fdtp, i, &start, &size);
1873 sprintf(line, "reg#%d: (start: 0x%jx, size: 0x%jx)\n",
1875 if (pager_output(line))
1879 pager_output("No reserved memory regions\n");
1887 fdt_cmd_nyi(int argc, char *argv[])
1890 printf("command not yet implemented\n");
1895 fdt_devmatch_next(int *tag, int *compatlen)
1897 const struct fdt_property *p;
1898 const struct fdt_property *status;
1900 static int depth = 0;
1904 fdt_apply_overlays();
1909 /* We are at the end of the DTB */
1913 o = fdt_path_offset(fdtp, "/");
1915 printf("Can't find dtb\n");
1921 /* Find the next node with a compatible property */
1924 if (o >= 0 && depth >= 0) {
1925 /* skip disabled nodes */
1926 status = fdt_get_property(fdtp, o, "status", &len);
1928 if (strcmp(status->data, "disabled") == 0) {
1929 o = fdt_next_node(fdtp, o, &depth);
1930 if (o < 0) /* End of tree */
1936 p = fdt_get_property(fdtp, o, "compatible", &len);
1940 o = fdt_next_node(fdtp, o, &depth);
1941 if (o < 0) /* End of tree */
1945 /* Prepare next node for next call */
1946 o = fdt_next_node(fdtp, o, &depth);