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;
71 static int fdt_load_dtb(vm_offset_t va);
72 static void fdt_print_overlay_load_error(int err, const char *filename);
73 static int fdt_check_overlay_compatible(void *base_fdt, void *overlay_fdt);
75 static int fdt_cmd_nyi(int argc, char *argv[]);
76 static int fdt_load_dtb_overlays_string(const char * filenames);
78 static int fdt_cmd_addr(int argc, char *argv[]);
79 static int fdt_cmd_mkprop(int argc, char *argv[]);
80 static int fdt_cmd_cd(int argc, char *argv[]);
81 static int fdt_cmd_hdr(int argc, char *argv[]);
82 static int fdt_cmd_ls(int argc, char *argv[]);
83 static int fdt_cmd_prop(int argc, char *argv[]);
84 static int fdt_cmd_pwd(int argc, char *argv[]);
85 static int fdt_cmd_rm(int argc, char *argv[]);
86 static int fdt_cmd_mknode(int argc, char *argv[]);
87 static int fdt_cmd_mres(int argc, char *argv[]);
89 typedef int cmdf_t(int, char *[]);
97 static const struct cmdtab commands[] = {
98 { "addr", &fdt_cmd_addr, 0 },
99 { "alias", &fdt_cmd_nyi, 0 },
100 { "cd", &fdt_cmd_cd, CMD_REQUIRES_BLOB },
101 { "header", &fdt_cmd_hdr, CMD_REQUIRES_BLOB },
102 { "ls", &fdt_cmd_ls, CMD_REQUIRES_BLOB },
103 { "mknode", &fdt_cmd_mknode, CMD_REQUIRES_BLOB },
104 { "mkprop", &fdt_cmd_mkprop, CMD_REQUIRES_BLOB },
105 { "mres", &fdt_cmd_mres, CMD_REQUIRES_BLOB },
106 { "prop", &fdt_cmd_prop, CMD_REQUIRES_BLOB },
107 { "pwd", &fdt_cmd_pwd, CMD_REQUIRES_BLOB },
108 { "rm", &fdt_cmd_rm, CMD_REQUIRES_BLOB },
112 static char cwd[FDT_CWD_LEN] = "/";
115 fdt_find_static_dtb()
120 vm_offset_t strtab, symtab, fdt_start;
122 struct preloaded_file *kfp;
123 struct file_metadata *md;
127 debugf("fdt_find_static_dtb()\n");
129 sym_count = symtab = strtab = 0;
132 offs = __elfN(relocation_offset);
134 kfp = file_findfile(NULL, NULL);
138 /* Locate the dynamic symbols and strtab. */
139 md = file_findmetadata(kfp, MODINFOMD_ELFHDR);
142 ehdr = (Elf_Ehdr *)md->md_data;
144 md = file_findmetadata(kfp, MODINFOMD_SHDR);
147 shdr = (Elf_Shdr *)md->md_data;
149 for (i = 0; i < ehdr->e_shnum; ++i) {
150 if (shdr[i].sh_type == SHT_DYNSYM && symtab == 0) {
151 symtab = shdr[i].sh_addr + offs;
152 sym_count = shdr[i].sh_size / sizeof(Elf_Sym);
153 } else if (shdr[i].sh_type == SHT_STRTAB && strtab == 0) {
154 strtab = shdr[i].sh_addr + offs;
159 * The most efficient way to find a symbol would be to calculate a
160 * hash, find proper bucket and chain, and thus find a symbol.
161 * However, that would involve code duplication (e.g. for hash
162 * function). So we're using simpler and a bit slower way: we're
163 * iterating through symbols, searching for the one which name is
164 * 'equal' to 'fdt_static_dtb'. To speed up the process a little bit,
165 * we are eliminating symbols type of which is not STT_NOTYPE, or(and)
166 * those which binding attribute is not STB_GLOBAL.
169 while (sym_count > 0 && fdt_start == 0) {
170 COPYOUT(symtab, &sym, sizeof(sym));
171 symtab += sizeof(sym);
173 if (ELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
174 ELF_ST_TYPE(sym.st_info) != STT_NOTYPE)
176 strp = strdupout(strtab + sym.st_name);
177 if (strcmp(strp, FDT_STATIC_DTB_SYMBOL) == 0)
178 fdt_start = (vm_offset_t)sym.st_value + offs;
185 fdt_load_dtb(vm_offset_t va)
187 struct fdt_header header;
190 debugf("fdt_load_dtb(0x%08jx)\n", (uintmax_t)va);
192 COPYOUT(va, &header, sizeof(header));
193 err = fdt_check_header(&header);
195 if (err == -FDT_ERR_BADVERSION) {
196 snprintf(command_errbuf, sizeof(command_errbuf),
197 "incompatible blob version: %d, should be: %d",
198 fdt_version(fdtp), FDT_LAST_SUPPORTED_VERSION);
200 snprintf(command_errbuf, sizeof(command_errbuf),
201 "error validating blob: %s", fdt_strerror(err));
207 * Release previous blob
212 fdtp_size = fdt_totalsize(&header);
213 fdtp = malloc(fdtp_size);
216 command_errmsg = "can't allocate memory for device tree copy";
220 COPYOUT(va, fdtp, fdtp_size);
221 debugf("DTB blob found at 0x%jx, size: 0x%jx\n", (uintmax_t)va, (uintmax_t)fdtp_size);
227 fdt_load_dtb_addr(struct fdt_header *header)
231 debugf("fdt_load_dtb_addr(%p)\n", header);
233 fdtp_size = fdt_totalsize(header);
234 err = fdt_check_header(header);
236 snprintf(command_errbuf, sizeof(command_errbuf),
237 "error validating blob: %s", fdt_strerror(err));
241 if ((fdtp = malloc(fdtp_size)) == NULL) {
242 command_errmsg = "can't allocate memory for device tree copy";
246 bcopy(header, fdtp, fdtp_size);
251 fdt_load_dtb_file(const char * filename)
253 struct preloaded_file *bfp, *oldbfp;
256 debugf("fdt_load_dtb_file(%s)\n", filename);
258 oldbfp = file_findfile(NULL, "dtb");
260 /* Attempt to load and validate a new dtb from a file. */
261 if ((bfp = file_loadraw(filename, "dtb", 1)) == NULL) {
262 snprintf(command_errbuf, sizeof(command_errbuf),
263 "failed to load file '%s'", filename);
266 if ((err = fdt_load_dtb(bfp->f_addr)) != 0) {
271 /* A new dtb was validated, discard any previous file. */
273 file_discard(oldbfp);
278 fdt_load_dtb_overlay(const char * filename)
280 struct preloaded_file *bfp;
281 struct fdt_header header;
284 debugf("fdt_load_dtb_overlay(%s)\n", filename);
286 /* Attempt to load and validate a new dtb from a file. FDT_ERR_NOTFOUND
287 * is normally a libfdt error code, but libfdt would actually return
288 * -FDT_ERR_NOTFOUND. We re-purpose the error code here to convey a
289 * similar meaning: the file itself was not found, which can still be
290 * considered an error dealing with FDT pieces.
292 if ((bfp = file_loadraw(filename, "dtbo", 1)) == NULL)
293 return (FDT_ERR_NOTFOUND);
295 COPYOUT(bfp->f_addr, &header, sizeof(header));
296 err = fdt_check_header(&header);
307 fdt_print_overlay_load_error(int err, const char *filename)
311 case FDT_ERR_NOTFOUND:
312 printf("%s: failed to load file\n", filename);
314 case -FDT_ERR_BADVERSION:
315 printf("%s: incompatible blob version: %d, should be: %d\n",
316 filename, fdt_version(fdtp),
317 FDT_LAST_SUPPORTED_VERSION);
320 /* libfdt errs are negative */
322 printf("%s: error validating blob: %s\n",
323 filename, fdt_strerror(err));
325 printf("%s: unknown load error\n", filename);
331 fdt_load_dtb_overlays_string(const char * filenames)
334 char *name, *name_ext;
338 debugf("fdt_load_dtb_overlays_string(%s)\n", filenames);
340 names = strdup(filenames);
345 comaptr = strchr(name, ',');
348 err = fdt_load_dtb_overlay(name);
349 if (err == FDT_ERR_NOTFOUND) {
350 /* Allocate enough to append ".dtbo" */
351 namesz = strlen(name) + 6;
352 name_ext = malloc(namesz);
353 if (name_ext == NULL) {
354 fdt_print_overlay_load_error(err, name);
358 snprintf(name_ext, namesz, "%s.dtbo", name);
359 err = fdt_load_dtb_overlay(name_ext);
362 /* Catch error with either initial load or fallback load */
364 fdt_print_overlay_load_error(err, name);
373 * fdt_check_overlay_compatible - check that the overlay_fdt is compatible with
374 * base_fdt before we attempt to apply it. It will need to re-calculate offsets
375 * in the base every time, rather than trying to cache them earlier in the
376 * process, because the overlay application process can/will invalidate a lot of
380 fdt_check_overlay_compatible(void *base_fdt, void *overlay_fdt)
383 int compat_len, ocompat_len;
384 int oroot_offset, root_offset;
387 oroot_offset = fdt_path_offset(overlay_fdt, "/");
388 if (oroot_offset < 0)
389 return (oroot_offset);
391 * If /compatible in the overlay does not exist or if it is empty, then
392 * we're automatically compatible. We do this for the sake of rapid
393 * overlay development for overlays that aren't intended to be deployed.
394 * The user assumes the risk of using an overlay without /compatible.
396 if (fdt_get_property(overlay_fdt, oroot_offset, "compatible",
397 &ocompat_len) == NULL || ocompat_len == 0)
399 root_offset = fdt_path_offset(base_fdt, "/");
401 return (root_offset);
403 * However, an empty or missing /compatible on the base is an error,
404 * because allowing this offers no advantages.
406 if (fdt_get_property(base_fdt, root_offset, "compatible",
407 &compat_len) == NULL)
409 else if(compat_len == 0)
413 compat = fdt_stringlist_get(overlay_fdt, oroot_offset, "compatible",
415 while (compat != NULL) {
416 if (fdt_stringlist_search(base_fdt, root_offset, "compatible",
420 compat = fdt_stringlist_get(overlay_fdt, oroot_offset,
421 "compatible", slidx, &sllen);
424 /* We've exhausted the overlay's /compatible property... no match */
431 struct preloaded_file *fp;
432 size_t max_overlay_size, next_fdtp_size;
433 size_t current_fdtp_size;
439 if ((fdtp == NULL) || (fdtp_size == 0))
442 max_overlay_size = 0;
443 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
444 if (max_overlay_size < fp->f_size)
445 max_overlay_size = fp->f_size;
448 /* Nothing to apply */
449 if (max_overlay_size == 0)
452 overlay = malloc(max_overlay_size);
453 if (overlay == NULL) {
454 printf("failed to allocate memory for DTB blob with overlays\n");
458 current_fdtp_size = fdtp_size;
459 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
460 COPYOUT(fp->f_addr, overlay, fp->f_size);
461 /* Check compatible first to avoid unnecessary allocation */
462 rv = fdt_check_overlay_compatible(current_fdtp, overlay);
464 printf("DTB overlay '%s' not compatible\n", fp->f_name);
467 printf("applying DTB overlay '%s'\n", fp->f_name);
468 next_fdtp_size = current_fdtp_size + fp->f_size;
469 next_fdtp = malloc(next_fdtp_size);
470 if (next_fdtp == NULL) {
472 * Output warning, then move on to applying other
473 * overlays in case this one is simply too large.
475 printf("failed to allocate memory for overlay base\n");
478 rv = fdt_open_into(current_fdtp, next_fdtp, next_fdtp_size);
481 printf("failed to open base dtb into overlay base\n");
484 /* Both overlay and next_fdtp may be modified in place */
485 rv = fdt_overlay_apply(next_fdtp, overlay);
487 /* Rotate next -> current */
488 if (current_fdtp != fdtp)
490 current_fdtp = next_fdtp;
491 current_fdtp_size = next_fdtp_size;
494 * Assume here that the base we tried to apply on is
495 * either trashed or in an inconsistent state. Trying to
496 * load it might work, but it's better to discard it and
499 printf("failed to apply overlay: %s\n",
503 /* We could have failed to apply all overlays; then we do nothing */
504 if (current_fdtp != fdtp) {
507 fdtp_size = current_fdtp_size;
525 struct preloaded_file *bfp;
528 debugf("fdt_setup_fdtp()\n");
530 /* If we already loaded a file, use it. */
531 if ((bfp = file_findfile(NULL, "dtb")) != NULL) {
532 if (fdt_load_dtb(bfp->f_addr) == 0) {
533 printf("Using DTB from loaded file '%s'.\n",
535 fdt_platform_load_overlays();
540 /* If we were given the address of a valid blob in memory, use it. */
541 if (fdt_to_load != NULL) {
542 if (fdt_load_dtb_addr(fdt_to_load) == 0) {
543 printf("Using DTB from memory address %p.\n",
545 fdt_platform_load_overlays();
550 if (fdt_platform_load_dtb() == 0) {
551 fdt_platform_load_overlays();
555 /* If there is a dtb compiled into the kernel, use it. */
556 if ((va = fdt_find_static_dtb()) != 0) {
557 if (fdt_load_dtb(va) == 0) {
558 printf("Using DTB compiled into kernel.\n");
563 command_errmsg = "No device tree blob found!\n";
567 #define fdt_strtovect(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
568 (cellbuf), (lim), (cellsize), 0);
570 /* Force using base 16 */
571 #define fdt_strtovectx(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
572 (cellbuf), (lim), (cellsize), 16);
575 _fdt_strtovect(const char *str, void *cellbuf, int lim, unsigned char cellsize,
578 const char *buf = str;
579 const char *end = str + strlen(str) - 2;
580 uint32_t *u32buf = NULL;
581 uint8_t *u8buf = NULL;
584 if (cellsize == sizeof(uint32_t))
585 u32buf = (uint32_t *)cellbuf;
587 u8buf = (uint8_t *)cellbuf;
594 /* Skip white whitespace(s)/separators */
595 while (!isxdigit(*buf) && buf < end)
600 cpu_to_fdt32((uint32_t)strtol(buf, NULL, base));
603 u8buf[cnt] = (uint8_t)strtol(buf, NULL, base);
605 if (cnt + 1 <= lim - 1)
610 /* Find another number */
611 while ((isxdigit(*buf) || *buf == 'x') && buf < end)
618 fdt_fixup_ethernet(const char *str, char *ethstr, int len)
622 /* Convert macaddr string into a vector of uints */
623 fdt_strtovectx(str, &tmp_addr, 6, sizeof(uint8_t));
624 /* Set actual property to a value from vect */
625 fdt_setprop(fdtp, fdt_path_offset(fdtp, ethstr),
626 "local-mac-address", &tmp_addr, 6 * sizeof(uint8_t));
630 fdt_fixup_cpubusfreqs(unsigned long cpufreq, unsigned long busfreq)
632 int lo, o = 0, o2, maxo = 0, depth;
633 const uint32_t zero = 0;
635 /* We want to modify every subnode of /cpus */
636 o = fdt_path_offset(fdtp, "/cpus");
640 /* maxo should contain offset of node next to /cpus */
644 maxo = fdt_next_node(fdtp, maxo, &depth);
646 /* Find CPU frequency properties */
647 o = fdt_node_offset_by_prop_value(fdtp, o, "clock-frequency",
648 &zero, sizeof(uint32_t));
650 o2 = fdt_node_offset_by_prop_value(fdtp, o, "bus-frequency", &zero,
655 while (o != -FDT_ERR_NOTFOUND && o2 != -FDT_ERR_NOTFOUND) {
657 o = fdt_node_offset_by_prop_value(fdtp, lo,
658 "clock-frequency", &zero, sizeof(uint32_t));
660 o2 = fdt_node_offset_by_prop_value(fdtp, lo, "bus-frequency",
661 &zero, sizeof(uint32_t));
663 /* We're only interested in /cpus subnode(s) */
667 fdt_setprop_inplace_cell(fdtp, lo, "clock-frequency",
670 fdt_setprop_inplace_cell(fdtp, lo, "bus-frequency",
679 fdt_reg_valid(uint32_t *reg, int len, int addr_cells, int size_cells)
681 int cells_in_tuple, i, tuples, tuple_size;
682 uint32_t cur_start, cur_size;
684 cells_in_tuple = (addr_cells + size_cells);
685 tuple_size = cells_in_tuple * sizeof(uint32_t);
686 tuples = len / tuple_size;
690 for (i = 0; i < tuples; i++) {
692 cur_start = fdt64_to_cpu(reg[i * cells_in_tuple]);
694 cur_start = fdt32_to_cpu(reg[i * cells_in_tuple]);
697 cur_size = fdt64_to_cpu(reg[i * cells_in_tuple + 2]);
699 cur_size = fdt32_to_cpu(reg[i * cells_in_tuple + 1]);
704 debugf(" reg#%d (start: 0x%0x size: 0x%0x) valid!\n",
705 i, cur_start, cur_size);
712 fdt_fixup_memory(struct fdt_mem_region *region, size_t num)
714 struct fdt_mem_region *curmr;
715 uint32_t addr_cells, size_cells;
716 uint32_t *addr_cellsp, *size_cellsp;
717 int err, i, len, memory, root;
720 uint64_t rstart, rsize;
723 root = fdt_path_offset(fdtp, "/");
725 sprintf(command_errbuf, "Could not find root node !");
729 memory = fdt_path_offset(fdtp, "/memory");
731 /* Create proper '/memory' node. */
732 memory = fdt_add_subnode(fdtp, root, "memory");
734 snprintf(command_errbuf, sizeof(command_errbuf),
735 "Could not fixup '/memory' "
736 "node, error code : %d!\n", memory);
740 err = fdt_setprop(fdtp, memory, "device_type", "memory",
747 addr_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#address-cells",
749 size_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#size-cells", NULL);
751 if (addr_cellsp == NULL || size_cellsp == NULL) {
752 snprintf(command_errbuf, sizeof(command_errbuf),
753 "Could not fixup '/memory' node : "
754 "%s %s property not found in root node!\n",
755 (!addr_cellsp) ? "#address-cells" : "",
756 (!size_cellsp) ? "#size-cells" : "");
760 addr_cells = fdt32_to_cpu(*addr_cellsp);
761 size_cells = fdt32_to_cpu(*size_cellsp);
764 * Convert memreserve data to memreserve property
765 * Check if property already exists
767 reserved = fdt_num_mem_rsv(fdtp);
769 (fdt_getprop(fdtp, root, "memreserve", NULL) == NULL)) {
770 len = (addr_cells + size_cells) * reserved * sizeof(uint32_t);
771 sb = buf = (uint8_t *)malloc(len);
777 for (i = 0; i < reserved; i++) {
778 if (fdt_get_mem_rsv(fdtp, i, &rstart, &rsize))
781 /* Ensure endianness, and put cells into a buffer */
784 cpu_to_fdt64(rstart);
787 cpu_to_fdt32(rstart);
789 buf += sizeof(uint32_t) * addr_cells;
797 buf += sizeof(uint32_t) * size_cells;
802 if ((err = fdt_setprop(fdtp, root, "memreserve", sb, len)) < 0)
803 printf("Could not fixup 'memreserve' property.\n");
808 /* Count valid memory regions entries in sysinfo. */
810 for (i = 0; i < num; i++)
811 if (region[i].start == 0 && region[i].size == 0)
815 sprintf(command_errbuf, "Could not fixup '/memory' node : "
816 "sysinfo doesn't contain valid memory regions info!\n");
820 len = (addr_cells + size_cells) * realmrno * sizeof(uint32_t);
821 sb = buf = (uint8_t *)malloc(len);
827 for (i = 0; i < num; i++) {
829 if (curmr->size != 0) {
830 /* Ensure endianness, and put cells into a buffer */
833 cpu_to_fdt64(curmr->start);
836 cpu_to_fdt32(curmr->start);
838 buf += sizeof(uint32_t) * addr_cells;
841 cpu_to_fdt64(curmr->size);
844 cpu_to_fdt32(curmr->size);
846 buf += sizeof(uint32_t) * size_cells;
851 if ((err = fdt_setprop(fdtp, memory, "reg", sb, len)) < 0)
852 sprintf(command_errbuf, "Could not fixup '/memory' node.\n");
858 fdt_fixup_stdout(const char *str)
862 const struct fdt_property *prop;
865 ptr = (char *)str + strlen(str) - 1;
866 while (ptr > str && isdigit(*(str - 1)))
872 no = fdt_path_offset(fdtp, "/chosen");
876 prop = fdt_get_property(fdtp, no, "stdout", &len);
878 /* If /chosen/stdout does not extist, create it */
879 if (prop == NULL || (prop != NULL && len == 0)) {
881 bzero(tmp, 10 * sizeof(char));
882 strcpy((char *)&tmp, "serial");
884 /* Serial number too long */
887 strncpy((char *)tmp + 6, ptr, 3);
888 sero = fdt_path_offset(fdtp, (const char *)tmp);
891 * If serial device we're trying to assign
892 * stdout to doesn't exist in DT -- return.
896 fdt_setprop(fdtp, no, "stdout", &tmp,
897 strlen((char *)&tmp) + 1);
898 fdt_setprop(fdtp, no, "stdin", &tmp,
899 strlen((char *)&tmp) + 1);
904 fdt_load_dtb_overlays(const char *extras)
908 /* Any extra overlays supplied by pre-loader environment */
909 if (extras != NULL && *extras != '\0') {
910 printf("Loading DTB overlays: '%s'\n", extras);
911 fdt_load_dtb_overlays_string(extras);
914 /* Any overlays supplied by loader environment */
915 s = getenv("fdt_overlays");
916 if (s != NULL && *s != '\0') {
917 printf("Loading DTB overlays: '%s'\n", s);
918 fdt_load_dtb_overlays_string(s);
923 * Locate the blob, fix it up and return its location.
930 debugf("fdt_fixup()\n");
932 if (fdtp == NULL && fdt_setup_fdtp() != 0)
935 /* Create /chosen node (if not exists) */
936 if ((chosen = fdt_subnode_offset(fdtp, 0, "chosen")) ==
938 chosen = fdt_add_subnode(fdtp, 0, "chosen");
940 /* Value assigned to fixup-applied does not matter. */
941 if (fdt_getprop(fdtp, chosen, "fixup-applied", NULL))
944 fdt_platform_fixups();
947 * Re-fetch the /chosen subnode; our fixups may apply overlays or add
948 * nodes/properties that invalidate the offset we grabbed or created
949 * above, so we can no longer trust it.
951 chosen = fdt_subnode_offset(fdtp, 0, "chosen");
952 fdt_setprop(fdtp, chosen, "fixup-applied", NULL, 0);
957 * Copy DTB blob to specified location and return size
960 fdt_copy(vm_offset_t va)
963 debugf("fdt_copy va 0x%08x\n", va);
965 err = fdt_setup_fdtp();
967 printf("No valid device tree blob found!\n");
972 if (fdt_fixup() == 0)
975 COPYIN(fdtp, va, fdtp_size);
982 command_fdt_internal(int argc, char *argv[])
989 command_errmsg = "usage is 'fdt <command> [<args>]";
994 * Validate fdt <command>.
998 while (!(commands[i].name == NULL)) {
999 if (strcmp(argv[1], commands[i].name) == 0) {
1001 cmdh = commands[i].handler;
1002 flags = commands[i].flags;
1008 command_errmsg = "unknown command";
1012 if (flags & CMD_REQUIRES_BLOB) {
1014 * Check if uboot env vars were parsed already. If not, do it now.
1016 if (fdt_fixup() == 0)
1021 * Call command handler.
1023 err = (*cmdh)(argc, argv);
1029 fdt_cmd_addr(int argc, char *argv[])
1031 struct preloaded_file *fp;
1032 struct fdt_header *hdr;
1041 sprintf(command_errbuf, "no address specified");
1045 hdr = (struct fdt_header *)strtoul(addr, &cp, 16);
1047 snprintf(command_errbuf, sizeof(command_errbuf),
1048 "Invalid address: %s", addr);
1052 while ((fp = file_findfile(NULL, "dtb")) != NULL) {
1061 fdt_cmd_cd(int argc, char *argv[])
1064 char tmp[FDT_CWD_LEN];
1067 path = (argc > 2) ? argv[2] : "/";
1069 if (path[0] == '/') {
1071 if (len >= FDT_CWD_LEN)
1074 /* Handle path specification relative to cwd */
1075 len = strlen(cwd) + strlen(path) + 1;
1076 if (len >= FDT_CWD_LEN)
1085 o = fdt_path_offset(fdtp, path);
1087 snprintf(command_errbuf, sizeof(command_errbuf),
1088 "could not find node: '%s'", path);
1096 snprintf(command_errbuf, sizeof(command_errbuf),
1097 "path too long: %d, max allowed: %d", len, FDT_CWD_LEN - 1);
1102 fdt_cmd_hdr(int argc __unused, char *argv[] __unused)
1108 command_errmsg = "no device tree blob pointer?!";
1112 ver = fdt_version(fdtp);
1114 sprintf(line, "\nFlattened device tree header (%p):\n", fdtp);
1115 if (pager_output(line))
1117 sprintf(line, " magic = 0x%08x\n", fdt_magic(fdtp));
1118 if (pager_output(line))
1120 sprintf(line, " size = %d\n", fdt_totalsize(fdtp));
1121 if (pager_output(line))
1123 sprintf(line, " off_dt_struct = 0x%08x\n",
1124 fdt_off_dt_struct(fdtp));
1125 if (pager_output(line))
1127 sprintf(line, " off_dt_strings = 0x%08x\n",
1128 fdt_off_dt_strings(fdtp));
1129 if (pager_output(line))
1131 sprintf(line, " off_mem_rsvmap = 0x%08x\n",
1132 fdt_off_mem_rsvmap(fdtp));
1133 if (pager_output(line))
1135 sprintf(line, " version = %d\n", ver);
1136 if (pager_output(line))
1138 sprintf(line, " last compatible version = %d\n",
1139 fdt_last_comp_version(fdtp));
1140 if (pager_output(line))
1143 sprintf(line, " boot_cpuid = %d\n",
1144 fdt_boot_cpuid_phys(fdtp));
1145 if (pager_output(line))
1149 sprintf(line, " size_dt_strings = %d\n",
1150 fdt_size_dt_strings(fdtp));
1151 if (pager_output(line))
1155 sprintf(line, " size_dt_struct = %d\n",
1156 fdt_size_dt_struct(fdtp));
1157 if (pager_output(line))
1167 fdt_cmd_ls(int argc, char *argv[])
1169 const char *prevname[FDT_MAX_DEPTH] = { NULL };
1174 path = (argc > 2) ? argv[2] : NULL;
1178 o = fdt_path_offset(fdtp, path);
1180 snprintf(command_errbuf, sizeof(command_errbuf),
1181 "could not find node: '%s'", path);
1186 (o >= 0) && (depth >= 0);
1187 o = fdt_next_node(fdtp, o, &depth)) {
1189 name = fdt_get_name(fdtp, o, NULL);
1191 if (depth > FDT_MAX_DEPTH) {
1192 printf("max depth exceeded: %d\n", depth);
1196 prevname[depth] = name;
1198 /* Skip root (i = 1) when printing devices */
1199 for (i = 1; i <= depth; i++) {
1200 if (prevname[i] == NULL)
1203 if (strcmp(cwd, "/") == 0)
1205 printf("%s", prevname[i]);
1217 return (c >= ' ' && c <= 0x7e);
1221 fdt_isprint(const void *data, int len, int *count)
1230 d = (const char *)data;
1231 if (d[len - 1] != '\0')
1236 for (i = 0; i < len; i++) {
1238 if (isprint(ch) || (ch == '\0' && i > 0)) {
1253 fdt_data_str(const void *data, int len, int count, char **buf)
1260 * Calculate the length for the string and allocate memory.
1262 * Note that 'len' already includes at least one terminator.
1267 * Each token had already a terminator buried in 'len', but we
1268 * only need one eventually, don't count space for these.
1270 buf_len -= count - 1;
1272 /* Each consecutive token requires a ", " separator. */
1273 buf_len += count * 2;
1276 /* Add some space for surrounding double quotes. */
1277 buf_len += count * 2;
1279 /* Note that string being put in 'tmp' may be as big as 'buf_len'. */
1280 b = (char *)malloc(buf_len);
1281 tmp = (char *)malloc(buf_len);
1293 * Now that we have space, format the string.
1297 d = (const char *)data + i;
1300 sprintf(tmp, "\"%s\"%s", d,
1301 (i + l) < len ? ", " : "");
1317 fdt_data_cell(const void *data, int len, char **buf)
1323 /* Number of cells */
1327 * Calculate the length for the string and allocate memory.
1330 /* Each byte translates to 2 output characters */
1333 /* Each consecutive cell requires a " " separator. */
1334 l += (count - 1) * 1;
1336 /* Each cell will have a "0x" prefix */
1338 /* Space for surrounding <> and terminator */
1341 b = (char *)malloc(l);
1342 tmp = (char *)malloc(l);
1354 for (i = 0; i < len; i += 4) {
1355 c = (const uint32_t *)((const uint8_t *)data + i);
1356 sprintf(tmp, "0x%08x%s", fdt32_to_cpu(*c),
1357 i < (len - 4) ? " " : "");
1371 fdt_data_bytes(const void *data, int len, char **buf)
1378 * Calculate the length for the string and allocate memory.
1381 /* Each byte translates to 2 output characters */
1384 /* Each consecutive byte requires a " " separator. */
1386 /* Each byte will have a "0x" prefix */
1388 /* Space for surrounding [] and terminator. */
1391 b = (char *)malloc(l);
1392 tmp = (char *)malloc(l);
1404 for (i = 0, d = data; i < len; i++) {
1405 sprintf(tmp, "0x%02x%s", d[i], i < len - 1 ? " " : "");
1419 fdt_data_fmt(const void *data, int len, char **buf)
1428 if (fdt_isprint(data, len, &count))
1429 return (fdt_data_str(data, len, count, buf));
1431 else if ((len % 4) == 0)
1432 return (fdt_data_cell(data, len, buf));
1435 return (fdt_data_bytes(data, len, buf));
1439 fdt_prop(int offset)
1442 const struct fdt_property *prop;
1448 prop = fdt_offset_ptr(fdtp, offset, sizeof(*prop));
1452 name = fdt_string(fdtp, fdt32_to_cpu(prop->nameoff));
1453 len = fdt32_to_cpu(prop->len);
1458 /* Property without value */
1459 line = (char *)malloc(strlen(name) + 2);
1464 sprintf(line, "%s\n", name);
1469 * Process property with value
1473 if (fdt_data_fmt(data, len, &buf) != 0) {
1478 line = (char *)malloc(strlen(name) + strlen(FDT_PROP_SEP) +
1481 sprintf(command_errbuf, "could not allocate space for string");
1486 sprintf(line, "%s" FDT_PROP_SEP "%s\n", name, buf);
1504 fdt_modprop(int nodeoff, char *propname, void *value, char mode)
1506 uint32_t cells[100];
1509 const struct fdt_property *p;
1511 p = fdt_get_property(fdtp, nodeoff, propname, NULL);
1515 /* Adding inexistant value in mode 1 is forbidden */
1516 sprintf(command_errbuf, "property already exists!");
1519 } else if (mode == 0) {
1520 sprintf(command_errbuf, "property does not exist!");
1532 len = fdt_strtovect(buf, (void *)&cells, 100,
1535 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1536 len * sizeof(uint32_t));
1540 len = fdt_strtovect(buf, (void *)&cells, 100,
1543 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1544 len * sizeof(uint8_t));
1548 /* Default -- string */
1549 rv = fdt_setprop_string(fdtp, nodeoff, propname, value);
1554 if (rv == -FDT_ERR_NOSPACE)
1555 sprintf(command_errbuf,
1556 "Device tree blob is too small!\n");
1558 sprintf(command_errbuf,
1559 "Could not add/modify property!\n");
1564 /* Merge strings from argv into a single string */
1566 fdt_merge_strings(int argc, char *argv[], int start, char **buffer)
1574 for (i = start; i < argc; i++)
1575 sz += strlen(argv[i]);
1577 /* Additional bytes for whitespaces between args */
1580 buf = (char *)malloc(sizeof(char) * sz);
1582 sprintf(command_errbuf, "could not allocate space "
1586 bzero(buf, sizeof(char) * sz);
1589 for (i = start, idx = 0; i < argc; i++) {
1590 strcpy(buf + idx, argv[i]);
1591 idx += strlen(argv[i]);
1600 /* Extract offset and name of node/property from a given path */
1602 fdt_extract_nameloc(char **pathp, char **namep, int *nodeoff)
1605 char *path = *pathp, *name = NULL, *subpath = NULL;
1607 subpath = strrchr(path, '/');
1608 if (subpath == NULL) {
1609 o = fdt_path_offset(fdtp, cwd);
1611 path = (char *)&cwd;
1614 if (strlen(path) == 0)
1618 o = fdt_path_offset(fdtp, path);
1621 if (strlen(name) == 0) {
1622 sprintf(command_errbuf, "name not specified");
1626 snprintf(command_errbuf, sizeof(command_errbuf),
1627 "could not find node: '%s'", path);
1637 fdt_cmd_prop(int argc, char *argv[])
1639 char *path, *propname, *value;
1640 int o, next, depth, rv;
1643 path = (argc > 2) ? argv[2] : NULL;
1648 /* Merge property value strings into one */
1649 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1660 /* If value is specified -- try to modify prop. */
1661 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1664 rv = fdt_modprop(o, propname, value, 0);
1670 /* User wants to display properties */
1671 o = fdt_path_offset(fdtp, path);
1674 snprintf(command_errbuf, sizeof(command_errbuf),
1675 "could not find node: '%s'", path);
1681 while (depth >= 0) {
1682 tag = fdt_next_tag(fdtp, o, &next);
1688 /* Don't process properties of nested nodes */
1691 if (fdt_prop(o) != 0) {
1692 sprintf(command_errbuf, "could not process "
1698 case FDT_BEGIN_NODE:
1700 if (depth > FDT_MAX_DEPTH) {
1701 printf("warning: nesting too deep: %d\n",
1710 * This is the end of our starting node, force
1723 fdt_cmd_mkprop(int argc, char *argv[])
1726 char *path, *propname, *value;
1728 path = (argc > 2) ? argv[2] : NULL;
1733 /* Merge property value strings into one */
1734 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1739 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1742 if (fdt_modprop(o, propname, value, 1))
1749 fdt_cmd_rm(int argc, char *argv[])
1752 char *path = NULL, *propname;
1757 sprintf(command_errbuf, "no node/property name specified");
1761 o = fdt_path_offset(fdtp, path);
1763 /* If node not found -- try to find & delete property */
1764 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1767 if ((rv = fdt_delprop(fdtp, o, propname)) != 0) {
1768 snprintf(command_errbuf, sizeof(command_errbuf),
1769 "could not delete %s\n",
1770 (rv == -FDT_ERR_NOTFOUND) ?
1771 "(property/node does not exist)" : "");
1777 /* If node exists -- remove node */
1778 rv = fdt_del_node(fdtp, o);
1780 sprintf(command_errbuf, "could not delete node");
1787 fdt_cmd_mknode(int argc, char *argv[])
1790 char *path = NULL, *nodename = NULL;
1795 sprintf(command_errbuf, "no node name specified");
1799 if (fdt_extract_nameloc(&path, &nodename, &o) != 0)
1802 rv = fdt_add_subnode(fdtp, o, nodename);
1805 if (rv == -FDT_ERR_NOSPACE)
1806 sprintf(command_errbuf,
1807 "Device tree blob is too small!\n");
1809 sprintf(command_errbuf,
1810 "Could not add node!\n");
1817 fdt_cmd_pwd(int argc, char *argv[])
1819 char line[FDT_CWD_LEN];
1822 sprintf(line, "%s\n", cwd);
1829 fdt_cmd_mres(int argc, char *argv[])
1831 uint64_t start, size;
1836 total = fdt_num_mem_rsv(fdtp);
1838 if (pager_output("Reserved memory regions:\n"))
1840 for (i = 0; i < total; i++) {
1841 fdt_get_mem_rsv(fdtp, i, &start, &size);
1842 sprintf(line, "reg#%d: (start: 0x%jx, size: 0x%jx)\n",
1844 if (pager_output(line))
1848 pager_output("No reserved memory regions\n");
1856 fdt_cmd_nyi(int argc, char *argv[])
1859 printf("command not yet implemented\n");