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>
30 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #include <sys/linker.h>
37 #include <machine/elf.h>
39 #include "bootstrap.h"
40 #include "fdt_platform.h"
43 #define debugf(fmt, args...) do { printf("%s(): ", __func__); \
44 printf(fmt,##args); } while (0)
46 #define debugf(fmt, args...)
49 #define FDT_CWD_LEN 256
50 #define FDT_MAX_DEPTH 12
52 #define FDT_PROP_SEP " = "
54 #define COPYOUT(s,d,l) archsw.arch_copyout(s, d, l)
55 #define COPYIN(s,d,l) archsw.arch_copyin(s, d, l)
57 #define FDT_STATIC_DTB_SYMBOL "fdt_static_dtb"
59 #define CMD_REQUIRES_BLOB 0x01
61 /* Location of FDT yet to be loaded. */
62 /* This may be in read-only memory, so can't be manipulated directly. */
63 static struct fdt_header *fdt_to_load = NULL;
64 /* Location of FDT on heap. */
65 /* This is the copy we actually manipulate. */
66 static struct fdt_header *fdtp = NULL;
67 /* Size of FDT blob */
68 static size_t fdtp_size = 0;
69 /* Have we loaded all the needed overlays */
70 static int fdt_overlays_applied = 0;
72 static int fdt_load_dtb(vm_offset_t va);
73 static void fdt_print_overlay_load_error(int err, const char *filename);
74 static int fdt_check_overlay_compatible(void *base_fdt, void *overlay_fdt);
76 static int fdt_cmd_nyi(int argc, char *argv[]);
77 static int fdt_load_dtb_overlays_string(const char * filenames);
79 static int fdt_cmd_addr(int argc, char *argv[]);
80 static int fdt_cmd_mkprop(int argc, char *argv[]);
81 static int fdt_cmd_cd(int argc, char *argv[]);
82 static int fdt_cmd_hdr(int argc, char *argv[]);
83 static int fdt_cmd_ls(int argc, char *argv[]);
84 static int fdt_cmd_prop(int argc, char *argv[]);
85 static int fdt_cmd_pwd(int argc, char *argv[]);
86 static int fdt_cmd_rm(int argc, char *argv[]);
87 static int fdt_cmd_mknode(int argc, char *argv[]);
88 static int fdt_cmd_mres(int argc, char *argv[]);
90 typedef int cmdf_t(int, char *[]);
98 static const struct cmdtab commands[] = {
99 { "addr", &fdt_cmd_addr, 0 },
100 { "alias", &fdt_cmd_nyi, 0 },
101 { "cd", &fdt_cmd_cd, CMD_REQUIRES_BLOB },
102 { "header", &fdt_cmd_hdr, CMD_REQUIRES_BLOB },
103 { "ls", &fdt_cmd_ls, CMD_REQUIRES_BLOB },
104 { "mknode", &fdt_cmd_mknode, CMD_REQUIRES_BLOB },
105 { "mkprop", &fdt_cmd_mkprop, CMD_REQUIRES_BLOB },
106 { "mres", &fdt_cmd_mres, CMD_REQUIRES_BLOB },
107 { "prop", &fdt_cmd_prop, CMD_REQUIRES_BLOB },
108 { "pwd", &fdt_cmd_pwd, CMD_REQUIRES_BLOB },
109 { "rm", &fdt_cmd_rm, CMD_REQUIRES_BLOB },
113 static char cwd[FDT_CWD_LEN] = "/";
116 fdt_find_static_dtb()
121 vm_offset_t strtab, symtab, fdt_start;
123 struct preloaded_file *kfp;
124 struct file_metadata *md;
128 debugf("fdt_find_static_dtb()\n");
130 sym_count = symtab = strtab = 0;
133 offs = __elfN(relocation_offset);
135 kfp = file_findfile(NULL, NULL);
139 /* Locate the dynamic symbols and strtab. */
140 md = file_findmetadata(kfp, MODINFOMD_ELFHDR);
143 ehdr = (Elf_Ehdr *)md->md_data;
145 md = file_findmetadata(kfp, MODINFOMD_SHDR);
148 shdr = (Elf_Shdr *)md->md_data;
150 for (i = 0; i < ehdr->e_shnum; ++i) {
151 if (shdr[i].sh_type == SHT_DYNSYM && symtab == 0) {
152 symtab = shdr[i].sh_addr + offs;
153 sym_count = shdr[i].sh_size / sizeof(Elf_Sym);
154 } else if (shdr[i].sh_type == SHT_STRTAB && strtab == 0) {
155 strtab = shdr[i].sh_addr + offs;
160 * The most efficient way to find a symbol would be to calculate a
161 * hash, find proper bucket and chain, and thus find a symbol.
162 * However, that would involve code duplication (e.g. for hash
163 * function). So we're using simpler and a bit slower way: we're
164 * iterating through symbols, searching for the one which name is
165 * 'equal' to 'fdt_static_dtb'. To speed up the process a little bit,
166 * we are eliminating symbols type of which is not STT_NOTYPE, or(and)
167 * those which binding attribute is not STB_GLOBAL.
170 while (sym_count > 0 && fdt_start == 0) {
171 COPYOUT(symtab, &sym, sizeof(sym));
172 symtab += sizeof(sym);
174 if (ELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
175 ELF_ST_TYPE(sym.st_info) != STT_NOTYPE)
177 strp = strdupout(strtab + sym.st_name);
178 if (strcmp(strp, FDT_STATIC_DTB_SYMBOL) == 0)
179 fdt_start = (vm_offset_t)sym.st_value + offs;
186 fdt_load_dtb(vm_offset_t va)
188 struct fdt_header header;
191 debugf("fdt_load_dtb(0x%08jx)\n", (uintmax_t)va);
193 COPYOUT(va, &header, sizeof(header));
194 err = fdt_check_header(&header);
196 if (err == -FDT_ERR_BADVERSION) {
197 snprintf(command_errbuf, sizeof(command_errbuf),
198 "incompatible blob version: %d, should be: %d",
199 fdt_version(fdtp), FDT_LAST_SUPPORTED_VERSION);
201 snprintf(command_errbuf, sizeof(command_errbuf),
202 "error validating blob: %s", fdt_strerror(err));
208 * Release previous blob
213 fdtp_size = fdt_totalsize(&header);
214 fdtp = malloc(fdtp_size);
217 command_errmsg = "can't allocate memory for device tree copy";
221 COPYOUT(va, fdtp, fdtp_size);
222 debugf("DTB blob found at 0x%jx, size: 0x%jx\n", (uintmax_t)va, (uintmax_t)fdtp_size);
228 fdt_load_dtb_addr(struct fdt_header *header)
232 debugf("fdt_load_dtb_addr(%p)\n", header);
234 fdtp_size = fdt_totalsize(header);
235 err = fdt_check_header(header);
237 snprintf(command_errbuf, sizeof(command_errbuf),
238 "error validating blob: %s", fdt_strerror(err));
242 if ((fdtp = malloc(fdtp_size)) == NULL) {
243 command_errmsg = "can't allocate memory for device tree copy";
247 bcopy(header, fdtp, fdtp_size);
252 fdt_load_dtb_file(const char * filename)
254 struct preloaded_file *bfp, *oldbfp;
257 debugf("fdt_load_dtb_file(%s)\n", filename);
259 oldbfp = file_findfile(NULL, "dtb");
261 /* Attempt to load and validate a new dtb from a file. */
262 if ((bfp = file_loadraw(filename, "dtb", 1)) == NULL) {
263 snprintf(command_errbuf, sizeof(command_errbuf),
264 "failed to load file '%s'", filename);
267 if ((err = fdt_load_dtb(bfp->f_addr)) != 0) {
272 /* A new dtb was validated, discard any previous file. */
274 file_discard(oldbfp);
279 fdt_load_dtb_overlay(const char * filename)
281 struct preloaded_file *bfp;
282 struct fdt_header header;
285 debugf("fdt_load_dtb_overlay(%s)\n", filename);
287 /* Attempt to load and validate a new dtb from a file. FDT_ERR_NOTFOUND
288 * is normally a libfdt error code, but libfdt would actually return
289 * -FDT_ERR_NOTFOUND. We re-purpose the error code here to convey a
290 * similar meaning: the file itself was not found, which can still be
291 * considered an error dealing with FDT pieces.
293 if ((bfp = file_loadraw(filename, "dtbo", 1)) == NULL)
294 return (FDT_ERR_NOTFOUND);
296 COPYOUT(bfp->f_addr, &header, sizeof(header));
297 err = fdt_check_header(&header);
308 fdt_print_overlay_load_error(int err, const char *filename)
312 case FDT_ERR_NOTFOUND:
313 printf("%s: failed to load file\n", filename);
315 case -FDT_ERR_BADVERSION:
316 printf("%s: incompatible blob version: %d, should be: %d\n",
317 filename, fdt_version(fdtp),
318 FDT_LAST_SUPPORTED_VERSION);
321 /* libfdt errs are negative */
323 printf("%s: error validating blob: %s\n",
324 filename, fdt_strerror(err));
326 printf("%s: unknown load error\n", filename);
332 fdt_load_dtb_overlays_string(const char * filenames)
335 char *name, *name_ext;
339 debugf("fdt_load_dtb_overlays_string(%s)\n", filenames);
341 names = strdup(filenames);
346 comaptr = strchr(name, ',');
349 err = fdt_load_dtb_overlay(name);
350 if (err == FDT_ERR_NOTFOUND) {
351 /* Allocate enough to append ".dtbo" */
352 namesz = strlen(name) + 6;
353 name_ext = malloc(namesz);
354 if (name_ext == NULL) {
355 fdt_print_overlay_load_error(err, name);
359 snprintf(name_ext, namesz, "%s.dtbo", name);
360 err = fdt_load_dtb_overlay(name_ext);
363 /* Catch error with either initial load or fallback load */
365 fdt_print_overlay_load_error(err, name);
374 * fdt_check_overlay_compatible - check that the overlay_fdt is compatible with
375 * base_fdt before we attempt to apply it. It will need to re-calculate offsets
376 * in the base every time, rather than trying to cache them earlier in the
377 * process, because the overlay application process can/will invalidate a lot of
381 fdt_check_overlay_compatible(void *base_fdt, void *overlay_fdt)
384 int compat_len, ocompat_len;
385 int oroot_offset, root_offset;
388 oroot_offset = fdt_path_offset(overlay_fdt, "/");
389 if (oroot_offset < 0)
390 return (oroot_offset);
392 * If /compatible in the overlay does not exist or if it is empty, then
393 * we're automatically compatible. We do this for the sake of rapid
394 * overlay development for overlays that aren't intended to be deployed.
395 * The user assumes the risk of using an overlay without /compatible.
397 if (fdt_get_property(overlay_fdt, oroot_offset, "compatible",
398 &ocompat_len) == NULL || ocompat_len == 0)
400 root_offset = fdt_path_offset(base_fdt, "/");
402 return (root_offset);
404 * However, an empty or missing /compatible on the base is an error,
405 * because allowing this offers no advantages.
407 if (fdt_get_property(base_fdt, root_offset, "compatible",
408 &compat_len) == NULL)
410 else if(compat_len == 0)
414 compat = fdt_stringlist_get(overlay_fdt, oroot_offset, "compatible",
416 while (compat != NULL) {
417 if (fdt_stringlist_search(base_fdt, root_offset, "compatible",
421 compat = fdt_stringlist_get(overlay_fdt, oroot_offset,
422 "compatible", slidx, &sllen);
425 /* We've exhausted the overlay's /compatible property... no match */
430 * Returns the number of overlays successfully applied
435 struct preloaded_file *fp;
436 size_t max_overlay_size, next_fdtp_size;
437 size_t current_fdtp_size;
441 int overlays_applied, rv;
443 if ((fdtp == NULL) || (fdtp_size == 0))
446 if (fdt_overlays_applied)
449 max_overlay_size = 0;
450 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
451 if (max_overlay_size < fp->f_size)
452 max_overlay_size = fp->f_size;
455 /* Nothing to apply */
456 if (max_overlay_size == 0)
459 overlay = malloc(max_overlay_size);
460 if (overlay == NULL) {
461 printf("failed to allocate memory for DTB blob with overlays\n");
465 current_fdtp_size = fdtp_size;
466 overlays_applied = 0;
467 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
468 if (strcmp(fp->f_type, "dtbo") != 0)
470 COPYOUT(fp->f_addr, overlay, fp->f_size);
471 /* Check compatible first to avoid unnecessary allocation */
472 rv = fdt_check_overlay_compatible(current_fdtp, overlay);
474 printf("DTB overlay '%s' not compatible\n", fp->f_name);
477 printf("applying DTB overlay '%s'\n", fp->f_name);
478 next_fdtp_size = current_fdtp_size + fp->f_size;
479 next_fdtp = malloc(next_fdtp_size);
480 if (next_fdtp == NULL) {
482 * Output warning, then move on to applying other
483 * overlays in case this one is simply too large.
485 printf("failed to allocate memory for overlay base\n");
488 rv = fdt_open_into(current_fdtp, next_fdtp, next_fdtp_size);
491 printf("failed to open base dtb into overlay base\n");
494 /* Both overlay and next_fdtp may be modified in place */
495 rv = fdt_overlay_apply(next_fdtp, overlay);
497 /* Rotate next -> current */
498 if (current_fdtp != fdtp)
500 current_fdtp = next_fdtp;
501 fdt_pack(current_fdtp);
502 current_fdtp_size = fdt_totalsize(current_fdtp);
506 * Assume here that the base we tried to apply on is
507 * either trashed or in an inconsistent state. Trying to
508 * load it might work, but it's better to discard it and
511 printf("failed to apply overlay: %s\n",
515 /* We could have failed to apply all overlays; then we do nothing */
516 if (current_fdtp != fdtp) {
519 fdtp_size = current_fdtp_size;
522 fdt_overlays_applied = 1;
523 return (overlays_applied);
527 fdt_pad_dtb(size_t padding)
530 size_t padded_fdtp_size;
532 padded_fdtp_size = fdtp_size + padding;
533 padded_fdtp = malloc(padded_fdtp_size);
534 if (padded_fdtp == NULL)
536 if (fdt_open_into(fdtp, padded_fdtp, padded_fdtp_size) != 0) {
541 fdtp_size = padded_fdtp_size;
558 struct preloaded_file *bfp;
561 debugf("fdt_setup_fdtp()\n");
563 /* If we already loaded a file, use it. */
564 if ((bfp = file_findfile(NULL, "dtb")) != NULL) {
565 if (fdt_load_dtb(bfp->f_addr) == 0) {
566 printf("Using DTB from loaded file '%s'.\n",
568 fdt_platform_load_overlays();
573 /* If we were given the address of a valid blob in memory, use it. */
574 if (fdt_to_load != NULL) {
575 if (fdt_load_dtb_addr(fdt_to_load) == 0) {
576 printf("Using DTB from memory address %p.\n",
578 fdt_platform_load_overlays();
583 if (fdt_platform_load_dtb() == 0) {
584 fdt_platform_load_overlays();
588 /* If there is a dtb compiled into the kernel, use it. */
589 if ((va = fdt_find_static_dtb()) != 0) {
590 if (fdt_load_dtb(va) == 0) {
591 printf("Using DTB compiled into kernel.\n");
596 command_errmsg = "No device tree blob found!\n";
600 #define fdt_strtovect(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
601 (cellbuf), (lim), (cellsize), 0);
603 /* Force using base 16 */
604 #define fdt_strtovectx(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
605 (cellbuf), (lim), (cellsize), 16);
608 _fdt_strtovect(const char *str, void *cellbuf, int lim, unsigned char cellsize,
611 const char *buf = str;
612 const char *end = str + strlen(str) - 2;
613 uint32_t *u32buf = NULL;
614 uint8_t *u8buf = NULL;
617 if (cellsize == sizeof(uint32_t))
618 u32buf = (uint32_t *)cellbuf;
620 u8buf = (uint8_t *)cellbuf;
627 /* Skip white whitespace(s)/separators */
628 while (!isxdigit(*buf) && buf < end)
633 cpu_to_fdt32((uint32_t)strtol(buf, NULL, base));
636 u8buf[cnt] = (uint8_t)strtol(buf, NULL, base);
638 if (cnt + 1 <= lim - 1)
643 /* Find another number */
644 while ((isxdigit(*buf) || *buf == 'x') && buf < end)
651 fdt_fixup_ethernet(const char *str, char *ethstr, int len)
655 /* Convert macaddr string into a vector of uints */
656 fdt_strtovectx(str, &tmp_addr, 6, sizeof(uint8_t));
657 /* Set actual property to a value from vect */
658 fdt_setprop(fdtp, fdt_path_offset(fdtp, ethstr),
659 "local-mac-address", &tmp_addr, 6 * sizeof(uint8_t));
663 fdt_fixup_cpubusfreqs(unsigned long cpufreq, unsigned long busfreq)
665 int lo, o = 0, o2, maxo = 0, depth;
666 const uint32_t zero = 0;
668 /* We want to modify every subnode of /cpus */
669 o = fdt_path_offset(fdtp, "/cpus");
673 /* maxo should contain offset of node next to /cpus */
677 maxo = fdt_next_node(fdtp, maxo, &depth);
679 /* Find CPU frequency properties */
680 o = fdt_node_offset_by_prop_value(fdtp, o, "clock-frequency",
681 &zero, sizeof(uint32_t));
683 o2 = fdt_node_offset_by_prop_value(fdtp, o, "bus-frequency", &zero,
688 while (o != -FDT_ERR_NOTFOUND && o2 != -FDT_ERR_NOTFOUND) {
690 o = fdt_node_offset_by_prop_value(fdtp, lo,
691 "clock-frequency", &zero, sizeof(uint32_t));
693 o2 = fdt_node_offset_by_prop_value(fdtp, lo, "bus-frequency",
694 &zero, sizeof(uint32_t));
696 /* We're only interested in /cpus subnode(s) */
700 fdt_setprop_inplace_cell(fdtp, lo, "clock-frequency",
703 fdt_setprop_inplace_cell(fdtp, lo, "bus-frequency",
712 fdt_reg_valid(uint32_t *reg, int len, int addr_cells, int size_cells)
714 int cells_in_tuple, i, tuples, tuple_size;
715 uint32_t cur_start, cur_size;
717 cells_in_tuple = (addr_cells + size_cells);
718 tuple_size = cells_in_tuple * sizeof(uint32_t);
719 tuples = len / tuple_size;
723 for (i = 0; i < tuples; i++) {
725 cur_start = fdt64_to_cpu(reg[i * cells_in_tuple]);
727 cur_start = fdt32_to_cpu(reg[i * cells_in_tuple]);
730 cur_size = fdt64_to_cpu(reg[i * cells_in_tuple + 2]);
732 cur_size = fdt32_to_cpu(reg[i * cells_in_tuple + 1]);
737 debugf(" reg#%d (start: 0x%0x size: 0x%0x) valid!\n",
738 i, cur_start, cur_size);
745 fdt_fixup_memory(struct fdt_mem_region *region, size_t num)
747 struct fdt_mem_region *curmr;
748 uint32_t addr_cells, size_cells;
749 uint32_t *addr_cellsp, *size_cellsp;
750 int err, i, len, memory, root;
753 uint64_t rstart, rsize;
756 root = fdt_path_offset(fdtp, "/");
758 sprintf(command_errbuf, "Could not find root node !");
762 memory = fdt_path_offset(fdtp, "/memory");
764 /* Create proper '/memory' node. */
765 memory = fdt_add_subnode(fdtp, root, "memory");
767 snprintf(command_errbuf, sizeof(command_errbuf),
768 "Could not fixup '/memory' "
769 "node, error code : %d!\n", memory);
773 err = fdt_setprop(fdtp, memory, "device_type", "memory",
780 addr_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#address-cells",
782 size_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#size-cells", NULL);
784 if (addr_cellsp == NULL || size_cellsp == NULL) {
785 snprintf(command_errbuf, sizeof(command_errbuf),
786 "Could not fixup '/memory' node : "
787 "%s %s property not found in root node!\n",
788 (!addr_cellsp) ? "#address-cells" : "",
789 (!size_cellsp) ? "#size-cells" : "");
793 addr_cells = fdt32_to_cpu(*addr_cellsp);
794 size_cells = fdt32_to_cpu(*size_cellsp);
797 * Convert memreserve data to memreserve property
798 * Check if property already exists
800 reserved = fdt_num_mem_rsv(fdtp);
802 (fdt_getprop(fdtp, root, "memreserve", NULL) == NULL)) {
803 len = (addr_cells + size_cells) * reserved * sizeof(uint32_t);
804 sb = buf = (uint8_t *)malloc(len);
810 for (i = 0; i < reserved; i++) {
811 if (fdt_get_mem_rsv(fdtp, i, &rstart, &rsize))
814 /* Ensure endianness, and put cells into a buffer */
817 cpu_to_fdt64(rstart);
820 cpu_to_fdt32(rstart);
822 buf += sizeof(uint32_t) * addr_cells;
830 buf += sizeof(uint32_t) * size_cells;
835 if ((err = fdt_setprop(fdtp, root, "memreserve", sb, len)) < 0)
836 printf("Could not fixup 'memreserve' property.\n");
841 /* Count valid memory regions entries in sysinfo. */
843 for (i = 0; i < num; i++)
844 if (region[i].start == 0 && region[i].size == 0)
848 sprintf(command_errbuf, "Could not fixup '/memory' node : "
849 "sysinfo doesn't contain valid memory regions info!\n");
853 len = (addr_cells + size_cells) * realmrno * sizeof(uint32_t);
854 sb = buf = (uint8_t *)malloc(len);
860 for (i = 0; i < num; i++) {
862 if (curmr->size != 0) {
863 /* Ensure endianness, and put cells into a buffer */
866 cpu_to_fdt64(curmr->start);
869 cpu_to_fdt32(curmr->start);
871 buf += sizeof(uint32_t) * addr_cells;
874 cpu_to_fdt64(curmr->size);
877 cpu_to_fdt32(curmr->size);
879 buf += sizeof(uint32_t) * size_cells;
884 if ((err = fdt_setprop(fdtp, memory, "reg", sb, len)) < 0)
885 sprintf(command_errbuf, "Could not fixup '/memory' node.\n");
891 fdt_fixup_stdout(const char *str)
895 const struct fdt_property *prop;
898 ptr = (char *)str + strlen(str) - 1;
899 while (ptr > str && isdigit(*(str - 1)))
905 no = fdt_path_offset(fdtp, "/chosen");
909 prop = fdt_get_property(fdtp, no, "stdout", &len);
911 /* If /chosen/stdout does not extist, create it */
912 if (prop == NULL || (prop != NULL && len == 0)) {
914 bzero(tmp, 10 * sizeof(char));
915 strcpy((char *)&tmp, "serial");
917 /* Serial number too long */
920 strncpy((char *)tmp + 6, ptr, 3);
921 sero = fdt_path_offset(fdtp, (const char *)tmp);
924 * If serial device we're trying to assign
925 * stdout to doesn't exist in DT -- return.
929 fdt_setprop(fdtp, no, "stdout", &tmp,
930 strlen((char *)&tmp) + 1);
931 fdt_setprop(fdtp, no, "stdin", &tmp,
932 strlen((char *)&tmp) + 1);
937 fdt_load_dtb_overlays(const char *extras)
941 /* Any extra overlays supplied by pre-loader environment */
942 if (extras != NULL && *extras != '\0') {
943 printf("Loading DTB overlays: '%s'\n", extras);
944 fdt_load_dtb_overlays_string(extras);
947 /* Any overlays supplied by loader environment */
948 s = getenv("fdt_overlays");
949 if (s != NULL && *s != '\0') {
950 printf("Loading DTB overlays: '%s'\n", s);
951 fdt_load_dtb_overlays_string(s);
956 * Locate the blob, fix it up and return its location.
963 debugf("fdt_fixup()\n");
965 if (fdtp == NULL && fdt_setup_fdtp() != 0)
968 /* Create /chosen node (if not exists) */
969 if ((chosen = fdt_subnode_offset(fdtp, 0, "chosen")) ==
971 chosen = fdt_add_subnode(fdtp, 0, "chosen");
973 /* Value assigned to fixup-applied does not matter. */
974 if (fdt_getprop(fdtp, chosen, "fixup-applied", NULL))
977 fdt_platform_fixups();
980 * Re-fetch the /chosen subnode; our fixups may apply overlays or add
981 * nodes/properties that invalidate the offset we grabbed or created
982 * above, so we can no longer trust it.
984 chosen = fdt_subnode_offset(fdtp, 0, "chosen");
985 fdt_setprop(fdtp, chosen, "fixup-applied", NULL, 0);
990 * Copy DTB blob to specified location and return size
993 fdt_copy(vm_offset_t va)
996 debugf("fdt_copy va 0x%08x\n", va);
998 err = fdt_setup_fdtp();
1000 printf("No valid device tree blob found!\n");
1005 if (fdt_fixup() == 0)
1008 COPYIN(fdtp, va, fdtp_size);
1015 command_fdt_internal(int argc, char *argv[])
1022 command_errmsg = "usage is 'fdt <command> [<args>]";
1027 * Validate fdt <command>.
1031 while (!(commands[i].name == NULL)) {
1032 if (strcmp(argv[1], commands[i].name) == 0) {
1034 cmdh = commands[i].handler;
1035 flags = commands[i].flags;
1041 command_errmsg = "unknown command";
1045 if (flags & CMD_REQUIRES_BLOB) {
1047 * Check if uboot env vars were parsed already. If not, do it now.
1049 if (fdt_fixup() == 0)
1054 * Call command handler.
1056 err = (*cmdh)(argc, argv);
1062 fdt_cmd_addr(int argc, char *argv[])
1064 struct preloaded_file *fp;
1065 struct fdt_header *hdr;
1074 sprintf(command_errbuf, "no address specified");
1078 hdr = (struct fdt_header *)strtoul(addr, &cp, 16);
1080 snprintf(command_errbuf, sizeof(command_errbuf),
1081 "Invalid address: %s", addr);
1085 while ((fp = file_findfile(NULL, "dtb")) != NULL) {
1094 fdt_cmd_cd(int argc, char *argv[])
1097 char tmp[FDT_CWD_LEN];
1100 path = (argc > 2) ? argv[2] : "/";
1102 if (path[0] == '/') {
1104 if (len >= FDT_CWD_LEN)
1107 /* Handle path specification relative to cwd */
1108 len = strlen(cwd) + strlen(path) + 1;
1109 if (len >= FDT_CWD_LEN)
1118 o = fdt_path_offset(fdtp, path);
1120 snprintf(command_errbuf, sizeof(command_errbuf),
1121 "could not find node: '%s'", path);
1129 snprintf(command_errbuf, sizeof(command_errbuf),
1130 "path too long: %d, max allowed: %d", len, FDT_CWD_LEN - 1);
1135 fdt_cmd_hdr(int argc __unused, char *argv[] __unused)
1141 command_errmsg = "no device tree blob pointer?!";
1145 ver = fdt_version(fdtp);
1147 sprintf(line, "\nFlattened device tree header (%p):\n", fdtp);
1148 if (pager_output(line))
1150 sprintf(line, " magic = 0x%08x\n", fdt_magic(fdtp));
1151 if (pager_output(line))
1153 sprintf(line, " size = %d\n", fdt_totalsize(fdtp));
1154 if (pager_output(line))
1156 sprintf(line, " off_dt_struct = 0x%08x\n",
1157 fdt_off_dt_struct(fdtp));
1158 if (pager_output(line))
1160 sprintf(line, " off_dt_strings = 0x%08x\n",
1161 fdt_off_dt_strings(fdtp));
1162 if (pager_output(line))
1164 sprintf(line, " off_mem_rsvmap = 0x%08x\n",
1165 fdt_off_mem_rsvmap(fdtp));
1166 if (pager_output(line))
1168 sprintf(line, " version = %d\n", ver);
1169 if (pager_output(line))
1171 sprintf(line, " last compatible version = %d\n",
1172 fdt_last_comp_version(fdtp));
1173 if (pager_output(line))
1176 sprintf(line, " boot_cpuid = %d\n",
1177 fdt_boot_cpuid_phys(fdtp));
1178 if (pager_output(line))
1182 sprintf(line, " size_dt_strings = %d\n",
1183 fdt_size_dt_strings(fdtp));
1184 if (pager_output(line))
1188 sprintf(line, " size_dt_struct = %d\n",
1189 fdt_size_dt_struct(fdtp));
1190 if (pager_output(line))
1200 fdt_cmd_ls(int argc, char *argv[])
1202 const char *prevname[FDT_MAX_DEPTH] = { NULL };
1207 path = (argc > 2) ? argv[2] : NULL;
1211 o = fdt_path_offset(fdtp, path);
1213 snprintf(command_errbuf, sizeof(command_errbuf),
1214 "could not find node: '%s'", path);
1219 (o >= 0) && (depth >= 0);
1220 o = fdt_next_node(fdtp, o, &depth)) {
1222 name = fdt_get_name(fdtp, o, NULL);
1224 if (depth > FDT_MAX_DEPTH) {
1225 printf("max depth exceeded: %d\n", depth);
1229 prevname[depth] = name;
1231 /* Skip root (i = 1) when printing devices */
1232 for (i = 1; i <= depth; i++) {
1233 if (prevname[i] == NULL)
1236 if (strcmp(cwd, "/") == 0)
1238 printf("%s", prevname[i]);
1250 return (c >= ' ' && c <= 0x7e);
1254 fdt_isprint(const void *data, int len, int *count)
1263 d = (const char *)data;
1264 if (d[len - 1] != '\0')
1269 for (i = 0; i < len; i++) {
1271 if (isprint(ch) || (ch == '\0' && i > 0)) {
1286 fdt_data_str(const void *data, int len, int count, char **buf)
1293 * Calculate the length for the string and allocate memory.
1295 * Note that 'len' already includes at least one terminator.
1300 * Each token had already a terminator buried in 'len', but we
1301 * only need one eventually, don't count space for these.
1303 buf_len -= count - 1;
1305 /* Each consecutive token requires a ", " separator. */
1306 buf_len += count * 2;
1309 /* Add some space for surrounding double quotes. */
1310 buf_len += count * 2;
1312 /* Note that string being put in 'tmp' may be as big as 'buf_len'. */
1313 b = (char *)malloc(buf_len);
1314 tmp = (char *)malloc(buf_len);
1326 * Now that we have space, format the string.
1330 d = (const char *)data + i;
1333 sprintf(tmp, "\"%s\"%s", d,
1334 (i + l) < len ? ", " : "");
1350 fdt_data_cell(const void *data, int len, char **buf)
1356 /* Number of cells */
1360 * Calculate the length for the string and allocate memory.
1363 /* Each byte translates to 2 output characters */
1366 /* Each consecutive cell requires a " " separator. */
1367 l += (count - 1) * 1;
1369 /* Each cell will have a "0x" prefix */
1371 /* Space for surrounding <> and terminator */
1374 b = (char *)malloc(l);
1375 tmp = (char *)malloc(l);
1387 for (i = 0; i < len; i += 4) {
1388 c = (const uint32_t *)((const uint8_t *)data + i);
1389 sprintf(tmp, "0x%08x%s", fdt32_to_cpu(*c),
1390 i < (len - 4) ? " " : "");
1404 fdt_data_bytes(const void *data, int len, char **buf)
1411 * Calculate the length for the string and allocate memory.
1414 /* Each byte translates to 2 output characters */
1417 /* Each consecutive byte requires a " " separator. */
1419 /* Each byte will have a "0x" prefix */
1421 /* Space for surrounding [] and terminator. */
1424 b = (char *)malloc(l);
1425 tmp = (char *)malloc(l);
1437 for (i = 0, d = data; i < len; i++) {
1438 sprintf(tmp, "0x%02x%s", d[i], i < len - 1 ? " " : "");
1452 fdt_data_fmt(const void *data, int len, char **buf)
1461 if (fdt_isprint(data, len, &count))
1462 return (fdt_data_str(data, len, count, buf));
1464 else if ((len % 4) == 0)
1465 return (fdt_data_cell(data, len, buf));
1468 return (fdt_data_bytes(data, len, buf));
1472 fdt_prop(int offset)
1475 const struct fdt_property *prop;
1481 prop = fdt_offset_ptr(fdtp, offset, sizeof(*prop));
1485 name = fdt_string(fdtp, fdt32_to_cpu(prop->nameoff));
1486 len = fdt32_to_cpu(prop->len);
1491 /* Property without value */
1492 line = (char *)malloc(strlen(name) + 2);
1497 sprintf(line, "%s\n", name);
1502 * Process property with value
1506 if (fdt_data_fmt(data, len, &buf) != 0) {
1511 line = (char *)malloc(strlen(name) + strlen(FDT_PROP_SEP) +
1514 sprintf(command_errbuf, "could not allocate space for string");
1519 sprintf(line, "%s" FDT_PROP_SEP "%s\n", name, buf);
1537 fdt_modprop(int nodeoff, char *propname, void *value, char mode)
1539 uint32_t cells[100];
1542 const struct fdt_property *p;
1544 p = fdt_get_property(fdtp, nodeoff, propname, NULL);
1548 /* Adding inexistant value in mode 1 is forbidden */
1549 sprintf(command_errbuf, "property already exists!");
1552 } else if (mode == 0) {
1553 sprintf(command_errbuf, "property does not exist!");
1565 len = fdt_strtovect(buf, (void *)&cells, 100,
1568 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1569 len * sizeof(uint32_t));
1573 len = fdt_strtovect(buf, (void *)&cells, 100,
1576 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1577 len * sizeof(uint8_t));
1581 /* Default -- string */
1582 rv = fdt_setprop_string(fdtp, nodeoff, propname, value);
1587 if (rv == -FDT_ERR_NOSPACE)
1588 sprintf(command_errbuf,
1589 "Device tree blob is too small!\n");
1591 sprintf(command_errbuf,
1592 "Could not add/modify property!\n");
1597 /* Merge strings from argv into a single string */
1599 fdt_merge_strings(int argc, char *argv[], int start, char **buffer)
1607 for (i = start; i < argc; i++)
1608 sz += strlen(argv[i]);
1610 /* Additional bytes for whitespaces between args */
1613 buf = (char *)malloc(sizeof(char) * sz);
1615 sprintf(command_errbuf, "could not allocate space "
1619 bzero(buf, sizeof(char) * sz);
1622 for (i = start, idx = 0; i < argc; i++) {
1623 strcpy(buf + idx, argv[i]);
1624 idx += strlen(argv[i]);
1633 /* Extract offset and name of node/property from a given path */
1635 fdt_extract_nameloc(char **pathp, char **namep, int *nodeoff)
1638 char *path = *pathp, *name = NULL, *subpath = NULL;
1640 subpath = strrchr(path, '/');
1641 if (subpath == NULL) {
1642 o = fdt_path_offset(fdtp, cwd);
1644 path = (char *)&cwd;
1647 if (strlen(path) == 0)
1651 o = fdt_path_offset(fdtp, path);
1654 if (strlen(name) == 0) {
1655 sprintf(command_errbuf, "name not specified");
1659 snprintf(command_errbuf, sizeof(command_errbuf),
1660 "could not find node: '%s'", path);
1670 fdt_cmd_prop(int argc, char *argv[])
1672 char *path, *propname, *value;
1673 int o, next, depth, rv;
1676 path = (argc > 2) ? argv[2] : NULL;
1681 /* Merge property value strings into one */
1682 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1693 /* If value is specified -- try to modify prop. */
1694 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1697 rv = fdt_modprop(o, propname, value, 0);
1703 /* User wants to display properties */
1704 o = fdt_path_offset(fdtp, path);
1707 snprintf(command_errbuf, sizeof(command_errbuf),
1708 "could not find node: '%s'", path);
1714 while (depth >= 0) {
1715 tag = fdt_next_tag(fdtp, o, &next);
1721 /* Don't process properties of nested nodes */
1724 if (fdt_prop(o) != 0) {
1725 sprintf(command_errbuf, "could not process "
1731 case FDT_BEGIN_NODE:
1733 if (depth > FDT_MAX_DEPTH) {
1734 printf("warning: nesting too deep: %d\n",
1743 * This is the end of our starting node, force
1756 fdt_cmd_mkprop(int argc, char *argv[])
1759 char *path, *propname, *value;
1761 path = (argc > 2) ? argv[2] : NULL;
1766 /* Merge property value strings into one */
1767 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1772 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1775 if (fdt_modprop(o, propname, value, 1))
1782 fdt_cmd_rm(int argc, char *argv[])
1785 char *path = NULL, *propname;
1790 sprintf(command_errbuf, "no node/property name specified");
1794 o = fdt_path_offset(fdtp, path);
1796 /* If node not found -- try to find & delete property */
1797 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1800 if ((rv = fdt_delprop(fdtp, o, propname)) != 0) {
1801 snprintf(command_errbuf, sizeof(command_errbuf),
1802 "could not delete %s\n",
1803 (rv == -FDT_ERR_NOTFOUND) ?
1804 "(property/node does not exist)" : "");
1810 /* If node exists -- remove node */
1811 rv = fdt_del_node(fdtp, o);
1813 sprintf(command_errbuf, "could not delete node");
1820 fdt_cmd_mknode(int argc, char *argv[])
1823 char *path = NULL, *nodename = NULL;
1828 sprintf(command_errbuf, "no node name specified");
1832 if (fdt_extract_nameloc(&path, &nodename, &o) != 0)
1835 rv = fdt_add_subnode(fdtp, o, nodename);
1838 if (rv == -FDT_ERR_NOSPACE)
1839 sprintf(command_errbuf,
1840 "Device tree blob is too small!\n");
1842 sprintf(command_errbuf,
1843 "Could not add node!\n");
1850 fdt_cmd_pwd(int argc, char *argv[])
1852 char line[FDT_CWD_LEN];
1855 sprintf(line, "%s\n", cwd);
1862 fdt_cmd_mres(int argc, char *argv[])
1864 uint64_t start, size;
1869 total = fdt_num_mem_rsv(fdtp);
1871 if (pager_output("Reserved memory regions:\n"))
1873 for (i = 0; i < total; i++) {
1874 fdt_get_mem_rsv(fdtp, i, &start, &size);
1875 sprintf(line, "reg#%d: (start: 0x%jx, size: 0x%jx)\n",
1877 if (pager_output(line))
1881 pager_output("No reserved memory regions\n");
1889 fdt_cmd_nyi(int argc, char *argv[])
1892 printf("command not yet implemented\n");
1897 fdt_devmatch_next(int *tag, int *compatlen)
1899 const struct fdt_property *p;
1900 const struct fdt_property *status;
1902 static int depth = 0;
1906 fdt_apply_overlays();
1911 /* We are at the end of the DTB */
1915 o = fdt_path_offset(fdtp, "/");
1917 printf("Can't find dtb\n");
1923 /* Find the next node with a compatible property */
1926 if (o >= 0 && depth >= 0) {
1927 /* skip disabled nodes */
1928 status = fdt_get_property(fdtp, o, "status", &len);
1930 if (strcmp(status->data, "disabled") == 0) {
1931 o = fdt_next_node(fdtp, o, &depth);
1932 if (o < 0) /* End of tree */
1938 p = fdt_get_property(fdtp, o, "compatible", &len);
1942 o = fdt_next_node(fdtp, o, &depth);
1943 if (o < 0) /* End of tree */
1947 /* Prepare next node for next call */
1948 o = fdt_next_node(fdtp, o, &depth);