2 * Copyright (c) 2009-2010 The FreeBSD Foundation
5 * This software was developed by Semihalf under sponsorship from
6 * the FreeBSD Foundation.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
36 #include <sys/param.h>
37 #include <sys/linker.h>
38 #include <machine/elf.h>
40 #include "bootstrap.h"
41 #include "fdt_platform.h"
44 #define debugf(fmt, args...) do { printf("%s(): ", __func__); \
45 printf(fmt,##args); } while (0)
47 #define debugf(fmt, args...)
50 #define FDT_CWD_LEN 256
51 #define FDT_MAX_DEPTH 12
53 #define FDT_PROP_SEP " = "
55 #define COPYOUT(s,d,l) archsw.arch_copyout(s, d, l)
56 #define COPYIN(s,d,l) archsw.arch_copyin(s, d, l)
58 #define FDT_STATIC_DTB_SYMBOL "fdt_static_dtb"
60 #define CMD_REQUIRES_BLOB 0x01
62 /* Location of FDT yet to be loaded. */
63 /* This may be in read-only memory, so can't be manipulated directly. */
64 static struct fdt_header *fdt_to_load = NULL;
65 /* Location of FDT on heap. */
66 /* This is the copy we actually manipulate. */
67 static struct fdt_header *fdtp = NULL;
68 /* Size of FDT blob */
69 static size_t fdtp_size = 0;
70 /* Location of FDT in kernel or module. */
71 /* This won't be set if FDT is loaded from disk or memory. */
72 /* If it is set, we'll update it when fdt_copy() gets called. */
73 static vm_offset_t fdtp_va = 0;
75 static int fdt_load_dtb(vm_offset_t va);
76 static void fdt_print_overlay_load_error(int err, const char *filename);
78 static int fdt_cmd_nyi(int argc, char *argv[]);
80 static int fdt_cmd_addr(int argc, char *argv[]);
81 static int fdt_cmd_mkprop(int argc, char *argv[]);
82 static int fdt_cmd_cd(int argc, char *argv[]);
83 static int fdt_cmd_hdr(int argc, char *argv[]);
84 static int fdt_cmd_ls(int argc, char *argv[]);
85 static int fdt_cmd_prop(int argc, char *argv[]);
86 static int fdt_cmd_pwd(int argc, char *argv[]);
87 static int fdt_cmd_rm(int argc, char *argv[]);
88 static int fdt_cmd_mknode(int argc, char *argv[]);
89 static int fdt_cmd_mres(int argc, char *argv[]);
91 typedef int cmdf_t(int, char *[]);
99 static const struct cmdtab commands[] = {
100 { "addr", &fdt_cmd_addr, 0 },
101 { "alias", &fdt_cmd_nyi, 0 },
102 { "cd", &fdt_cmd_cd, CMD_REQUIRES_BLOB },
103 { "header", &fdt_cmd_hdr, CMD_REQUIRES_BLOB },
104 { "ls", &fdt_cmd_ls, CMD_REQUIRES_BLOB },
105 { "mknode", &fdt_cmd_mknode, CMD_REQUIRES_BLOB },
106 { "mkprop", &fdt_cmd_mkprop, CMD_REQUIRES_BLOB },
107 { "mres", &fdt_cmd_mres, CMD_REQUIRES_BLOB },
108 { "prop", &fdt_cmd_prop, CMD_REQUIRES_BLOB },
109 { "pwd", &fdt_cmd_pwd, CMD_REQUIRES_BLOB },
110 { "rm", &fdt_cmd_rm, CMD_REQUIRES_BLOB },
114 static char cwd[FDT_CWD_LEN] = "/";
117 fdt_find_static_dtb()
122 vm_offset_t strtab, symtab, fdt_start;
124 struct preloaded_file *kfp;
125 struct file_metadata *md;
129 debugf("fdt_find_static_dtb()\n");
131 sym_count = symtab = strtab = 0;
134 offs = __elfN(relocation_offset);
136 kfp = file_findfile(NULL, NULL);
140 /* Locate the dynamic symbols and strtab. */
141 md = file_findmetadata(kfp, MODINFOMD_ELFHDR);
144 ehdr = (Elf_Ehdr *)md->md_data;
146 md = file_findmetadata(kfp, MODINFOMD_SHDR);
149 shdr = (Elf_Shdr *)md->md_data;
151 for (i = 0; i < ehdr->e_shnum; ++i) {
152 if (shdr[i].sh_type == SHT_DYNSYM && symtab == 0) {
153 symtab = shdr[i].sh_addr + offs;
154 sym_count = shdr[i].sh_size / sizeof(Elf_Sym);
155 } else if (shdr[i].sh_type == SHT_STRTAB && strtab == 0) {
156 strtab = shdr[i].sh_addr + offs;
161 * The most efficient way to find a symbol would be to calculate a
162 * hash, find proper bucket and chain, and thus find a symbol.
163 * However, that would involve code duplication (e.g. for hash
164 * function). So we're using simpler and a bit slower way: we're
165 * iterating through symbols, searching for the one which name is
166 * 'equal' to 'fdt_static_dtb'. To speed up the process a little bit,
167 * we are eliminating symbols type of which is not STT_NOTYPE, or(and)
168 * those which binding attribute is not STB_GLOBAL.
171 while (sym_count > 0 && fdt_start == 0) {
172 COPYOUT(symtab, &sym, sizeof(sym));
173 symtab += sizeof(sym);
175 if (ELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
176 ELF_ST_TYPE(sym.st_info) != STT_NOTYPE)
178 strp = strdupout(strtab + sym.st_name);
179 if (strcmp(strp, FDT_STATIC_DTB_SYMBOL) == 0)
180 fdt_start = (vm_offset_t)sym.st_value + offs;
187 fdt_load_dtb(vm_offset_t va)
189 struct fdt_header header;
192 debugf("fdt_load_dtb(0x%08jx)\n", (uintmax_t)va);
194 COPYOUT(va, &header, sizeof(header));
195 err = fdt_check_header(&header);
197 if (err == -FDT_ERR_BADVERSION) {
198 snprintf(command_errbuf, sizeof(command_errbuf),
199 "incompatible blob version: %d, should be: %d",
200 fdt_version(fdtp), FDT_LAST_SUPPORTED_VERSION);
202 snprintf(command_errbuf, sizeof(command_errbuf),
203 "error validating blob: %s", fdt_strerror(err));
209 * Release previous blob
214 fdtp_size = fdt_totalsize(&header);
215 fdtp = malloc(fdtp_size);
218 command_errmsg = "can't allocate memory for device tree copy";
223 COPYOUT(va, fdtp, fdtp_size);
224 debugf("DTB blob found at 0x%jx, size: 0x%jx\n", (uintmax_t)va, (uintmax_t)fdtp_size);
230 fdt_load_dtb_addr(struct fdt_header *header)
234 debugf("fdt_load_dtb_addr(%p)\n", header);
236 fdtp_size = fdt_totalsize(header);
237 err = fdt_check_header(header);
239 snprintf(command_errbuf, sizeof(command_errbuf),
240 "error validating blob: %s", fdt_strerror(err));
244 if ((fdtp = malloc(fdtp_size)) == NULL) {
245 command_errmsg = "can't allocate memory for device tree copy";
249 fdtp_va = 0; // Don't write this back into module or kernel.
250 bcopy(header, fdtp, fdtp_size);
255 fdt_load_dtb_file(const char * filename)
257 struct preloaded_file *bfp, *oldbfp;
260 debugf("fdt_load_dtb_file(%s)\n", filename);
262 oldbfp = file_findfile(NULL, "dtb");
264 /* Attempt to load and validate a new dtb from a file. */
265 if ((bfp = file_loadraw(filename, "dtb", 1)) == NULL) {
266 snprintf(command_errbuf, sizeof(command_errbuf),
267 "failed to load file '%s'", filename);
270 if ((err = fdt_load_dtb(bfp->f_addr)) != 0) {
275 /* A new dtb was validated, discard any previous file. */
277 file_discard(oldbfp);
282 fdt_load_dtb_overlay(const char * filename)
284 struct preloaded_file *bfp;
285 struct fdt_header header;
288 debugf("fdt_load_dtb_overlay(%s)\n", filename);
290 /* Attempt to load and validate a new dtb from a file. FDT_ERR_NOTFOUND
291 * is normally a libfdt error code, but libfdt would actually return
292 * -FDT_ERR_NOTFOUND. We re-purpose the error code here to convey a
293 * similar meaning: the file itself was not found, which can still be
294 * considered an error dealing with FDT pieces.
296 if ((bfp = file_loadraw(filename, "dtbo", 1)) == NULL)
297 return (FDT_ERR_NOTFOUND);
299 COPYOUT(bfp->f_addr, &header, sizeof(header));
300 err = fdt_check_header(&header);
311 fdt_print_overlay_load_error(int err, const char *filename)
315 case FDT_ERR_NOTFOUND:
316 printf("%s: failed to load file\n", filename);
318 case -FDT_ERR_BADVERSION:
319 printf("%s: incompatible blob version: %d, should be: %d\n",
320 filename, fdt_version(fdtp),
321 FDT_LAST_SUPPORTED_VERSION);
324 /* libfdt errs are negative */
326 printf("%s: error validating blob: %s\n",
327 filename, fdt_strerror(err));
329 printf("%s: unknown load error\n", filename);
335 fdt_load_dtb_overlays(const char * filenames)
338 char *name, *name_ext;
342 debugf("fdt_load_dtb_overlay(%s)\n", filenames);
344 names = strdup(filenames);
349 comaptr = strchr(name, ',');
352 err = fdt_load_dtb_overlay(name);
353 if (err == FDT_ERR_NOTFOUND) {
354 /* Allocate enough to append ".dtbo" */
355 namesz = strlen(name) + 6;
356 name_ext = malloc(namesz);
357 if (name_ext == NULL) {
358 fdt_print_overlay_load_error(err, name);
362 snprintf(name_ext, namesz, "%s.dtbo", name);
363 err = fdt_load_dtb_overlay(name_ext);
366 /* Catch error with either initial load or fallback load */
368 fdt_print_overlay_load_error(err, name);
379 struct preloaded_file *fp;
380 size_t max_overlay_size, next_fdtp_size;
381 size_t current_fdtp_size;
388 if ((fdtp == NULL) || (fdtp_size == 0))
392 max_overlay_size = 0;
393 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
394 if (max_overlay_size < fp->f_size)
395 max_overlay_size = fp->f_size;
398 /* Nothing to apply */
399 if (max_overlay_size == 0)
402 overlay = malloc(max_overlay_size);
403 if (overlay == NULL) {
404 printf("failed to allocate memory for DTB blob with overlays\n");
408 current_fdtp_size = fdtp_size;
409 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
410 printf("applying DTB overlay '%s'\n", fp->f_name);
411 next_fdtp_size = current_fdtp_size + fp->f_size;
412 next_fdtp = malloc(next_fdtp_size);
413 if (next_fdtp == NULL) {
415 * Output warning, then move on to applying other
416 * overlays in case this one is simply too large.
418 printf("failed to allocate memory for overlay base\n");
421 rv = fdt_open_into(current_fdtp, next_fdtp, next_fdtp_size);
424 printf("failed to open base dtb into overlay base\n");
427 COPYOUT(fp->f_addr, overlay, fp->f_size);
428 /* Both overlay and new_fdtp may be modified in place */
429 rv = fdt_overlay_apply(next_fdtp, overlay);
431 /* Rotate next -> current */
432 if (current_fdtp != fdtp)
434 current_fdtp = next_fdtp;
435 current_fdtp_size = next_fdtp_size;
438 * Assume here that the base we tried to apply on is
439 * either trashed or in an inconsistent state. Trying to
440 * load it might work, but it's better to discard it and
443 printf("failed to apply overlay: %s\n",
447 /* We could have failed to apply all overlays; then we do nothing */
448 if (current_fdtp != fdtp) {
451 fdtp_size = current_fdtp_size;
459 struct preloaded_file *bfp;
462 debugf("fdt_setup_fdtp()\n");
464 /* If we already loaded a file, use it. */
465 if ((bfp = file_findfile(NULL, "dtb")) != NULL) {
466 if (fdt_load_dtb(bfp->f_addr) == 0) {
467 printf("Using DTB from loaded file '%s'.\n",
473 /* If we were given the address of a valid blob in memory, use it. */
474 if (fdt_to_load != NULL) {
475 if (fdt_load_dtb_addr(fdt_to_load) == 0) {
476 printf("Using DTB from memory address %p.\n",
482 if (fdt_platform_load_dtb() == 0)
485 /* If there is a dtb compiled into the kernel, use it. */
486 if ((va = fdt_find_static_dtb()) != 0) {
487 if (fdt_load_dtb(va) == 0) {
488 printf("Using DTB compiled into kernel.\n");
493 command_errmsg = "No device tree blob found!\n";
497 #define fdt_strtovect(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
498 (cellbuf), (lim), (cellsize), 0);
500 /* Force using base 16 */
501 #define fdt_strtovectx(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
502 (cellbuf), (lim), (cellsize), 16);
505 _fdt_strtovect(const char *str, void *cellbuf, int lim, unsigned char cellsize,
508 const char *buf = str;
509 const char *end = str + strlen(str) - 2;
510 uint32_t *u32buf = NULL;
511 uint8_t *u8buf = NULL;
514 if (cellsize == sizeof(uint32_t))
515 u32buf = (uint32_t *)cellbuf;
517 u8buf = (uint8_t *)cellbuf;
524 /* Skip white whitespace(s)/separators */
525 while (!isxdigit(*buf) && buf < end)
530 cpu_to_fdt32((uint32_t)strtol(buf, NULL, base));
533 u8buf[cnt] = (uint8_t)strtol(buf, NULL, base);
535 if (cnt + 1 <= lim - 1)
540 /* Find another number */
541 while ((isxdigit(*buf) || *buf == 'x') && buf < end)
548 fdt_fixup_ethernet(const char *str, char *ethstr, int len)
552 /* Convert macaddr string into a vector of uints */
553 fdt_strtovectx(str, &tmp_addr, 6, sizeof(uint8_t));
554 /* Set actual property to a value from vect */
555 fdt_setprop(fdtp, fdt_path_offset(fdtp, ethstr),
556 "local-mac-address", &tmp_addr, 6 * sizeof(uint8_t));
560 fdt_fixup_cpubusfreqs(unsigned long cpufreq, unsigned long busfreq)
562 int lo, o = 0, o2, maxo = 0, depth;
563 const uint32_t zero = 0;
565 /* We want to modify every subnode of /cpus */
566 o = fdt_path_offset(fdtp, "/cpus");
570 /* maxo should contain offset of node next to /cpus */
574 maxo = fdt_next_node(fdtp, maxo, &depth);
576 /* Find CPU frequency properties */
577 o = fdt_node_offset_by_prop_value(fdtp, o, "clock-frequency",
578 &zero, sizeof(uint32_t));
580 o2 = fdt_node_offset_by_prop_value(fdtp, o, "bus-frequency", &zero,
585 while (o != -FDT_ERR_NOTFOUND && o2 != -FDT_ERR_NOTFOUND) {
587 o = fdt_node_offset_by_prop_value(fdtp, lo,
588 "clock-frequency", &zero, sizeof(uint32_t));
590 o2 = fdt_node_offset_by_prop_value(fdtp, lo, "bus-frequency",
591 &zero, sizeof(uint32_t));
593 /* We're only interested in /cpus subnode(s) */
597 fdt_setprop_inplace_cell(fdtp, lo, "clock-frequency",
600 fdt_setprop_inplace_cell(fdtp, lo, "bus-frequency",
609 fdt_reg_valid(uint32_t *reg, int len, int addr_cells, int size_cells)
611 int cells_in_tuple, i, tuples, tuple_size;
612 uint32_t cur_start, cur_size;
614 cells_in_tuple = (addr_cells + size_cells);
615 tuple_size = cells_in_tuple * sizeof(uint32_t);
616 tuples = len / tuple_size;
620 for (i = 0; i < tuples; i++) {
622 cur_start = fdt64_to_cpu(reg[i * cells_in_tuple]);
624 cur_start = fdt32_to_cpu(reg[i * cells_in_tuple]);
627 cur_size = fdt64_to_cpu(reg[i * cells_in_tuple + 2]);
629 cur_size = fdt32_to_cpu(reg[i * cells_in_tuple + 1]);
634 debugf(" reg#%d (start: 0x%0x size: 0x%0x) valid!\n",
635 i, cur_start, cur_size);
642 fdt_fixup_memory(struct fdt_mem_region *region, size_t num)
644 struct fdt_mem_region *curmr;
645 uint32_t addr_cells, size_cells;
646 uint32_t *addr_cellsp, *size_cellsp;
647 int err, i, len, memory, root;
650 uint64_t rstart, rsize;
653 root = fdt_path_offset(fdtp, "/");
655 sprintf(command_errbuf, "Could not find root node !");
659 memory = fdt_path_offset(fdtp, "/memory");
661 /* Create proper '/memory' node. */
662 memory = fdt_add_subnode(fdtp, root, "memory");
664 snprintf(command_errbuf, sizeof(command_errbuf),
665 "Could not fixup '/memory' "
666 "node, error code : %d!\n", memory);
670 err = fdt_setprop(fdtp, memory, "device_type", "memory",
677 addr_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#address-cells",
679 size_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#size-cells", NULL);
681 if (addr_cellsp == NULL || size_cellsp == NULL) {
682 snprintf(command_errbuf, sizeof(command_errbuf),
683 "Could not fixup '/memory' node : "
684 "%s %s property not found in root node!\n",
685 (!addr_cellsp) ? "#address-cells" : "",
686 (!size_cellsp) ? "#size-cells" : "");
690 addr_cells = fdt32_to_cpu(*addr_cellsp);
691 size_cells = fdt32_to_cpu(*size_cellsp);
694 * Convert memreserve data to memreserve property
695 * Check if property already exists
697 reserved = fdt_num_mem_rsv(fdtp);
699 (fdt_getprop(fdtp, root, "memreserve", NULL) == NULL)) {
700 len = (addr_cells + size_cells) * reserved * sizeof(uint32_t);
701 sb = buf = (uint8_t *)malloc(len);
707 for (i = 0; i < reserved; i++) {
708 if (fdt_get_mem_rsv(fdtp, i, &rstart, &rsize))
711 /* Ensure endianness, and put cells into a buffer */
714 cpu_to_fdt64(rstart);
717 cpu_to_fdt32(rstart);
719 buf += sizeof(uint32_t) * addr_cells;
727 buf += sizeof(uint32_t) * size_cells;
732 if ((err = fdt_setprop(fdtp, root, "memreserve", sb, len)) < 0)
733 printf("Could not fixup 'memreserve' property.\n");
738 /* Count valid memory regions entries in sysinfo. */
740 for (i = 0; i < num; i++)
741 if (region[i].start == 0 && region[i].size == 0)
745 sprintf(command_errbuf, "Could not fixup '/memory' node : "
746 "sysinfo doesn't contain valid memory regions info!\n");
750 len = (addr_cells + size_cells) * realmrno * sizeof(uint32_t);
751 sb = buf = (uint8_t *)malloc(len);
757 for (i = 0; i < num; i++) {
759 if (curmr->size != 0) {
760 /* Ensure endianness, and put cells into a buffer */
763 cpu_to_fdt64(curmr->start);
766 cpu_to_fdt32(curmr->start);
768 buf += sizeof(uint32_t) * addr_cells;
771 cpu_to_fdt64(curmr->size);
774 cpu_to_fdt32(curmr->size);
776 buf += sizeof(uint32_t) * size_cells;
781 if ((err = fdt_setprop(fdtp, memory, "reg", sb, len)) < 0)
782 sprintf(command_errbuf, "Could not fixup '/memory' node.\n");
788 fdt_fixup_stdout(const char *str)
793 const struct fdt_property *prop;
796 ptr = (char *)str + strlen(str) - 1;
797 while (ptr > str && isdigit(*(str - 1)))
803 serialno = (int)strtol(ptr, NULL, 0);
804 no = fdt_path_offset(fdtp, "/chosen");
808 prop = fdt_get_property(fdtp, no, "stdout", &len);
810 /* If /chosen/stdout does not extist, create it */
811 if (prop == NULL || (prop != NULL && len == 0)) {
813 bzero(tmp, 10 * sizeof(char));
814 strcpy((char *)&tmp, "serial");
816 /* Serial number too long */
819 strncpy((char *)tmp + 6, ptr, 3);
820 sero = fdt_path_offset(fdtp, (const char *)tmp);
823 * If serial device we're trying to assign
824 * stdout to doesn't exist in DT -- return.
828 fdt_setprop(fdtp, no, "stdout", &tmp,
829 strlen((char *)&tmp) + 1);
830 fdt_setprop(fdtp, no, "stdin", &tmp,
831 strlen((char *)&tmp) + 1);
836 * Locate the blob, fix it up and return its location.
845 debugf("fdt_fixup()\n");
847 if (fdtp == NULL && fdt_setup_fdtp() != 0)
850 /* Create /chosen node (if not exists) */
851 if ((chosen = fdt_subnode_offset(fdtp, 0, "chosen")) ==
853 chosen = fdt_add_subnode(fdtp, 0, "chosen");
855 /* Value assigned to fixup-applied does not matter. */
856 if (fdt_getprop(fdtp, chosen, "fixup-applied", NULL))
859 fdt_platform_fixups();
861 fdt_setprop(fdtp, chosen, "fixup-applied", NULL, 0);
866 * Copy DTB blob to specified location and return size
869 fdt_copy(vm_offset_t va)
872 debugf("fdt_copy va 0x%08x\n", va);
874 err = fdt_setup_fdtp();
876 printf("No valid device tree blob found!\n");
881 if (fdt_fixup() == 0)
885 /* Overwrite the FDT with the fixed version. */
886 /* XXX Is this really appropriate? */
887 COPYIN(fdtp, fdtp_va, fdtp_size);
889 COPYIN(fdtp, va, fdtp_size);
896 command_fdt_internal(int argc, char *argv[])
904 command_errmsg = "usage is 'fdt <command> [<args>]";
909 * Validate fdt <command>.
911 cmd = strdup(argv[1]);
914 while (!(commands[i].name == NULL)) {
915 if (strcmp(cmd, commands[i].name) == 0) {
917 cmdh = commands[i].handler;
918 flags = commands[i].flags;
924 command_errmsg = "unknown command";
928 if (flags & CMD_REQUIRES_BLOB) {
930 * Check if uboot env vars were parsed already. If not, do it now.
932 if (fdt_fixup() == 0)
937 * Call command handler.
939 err = (*cmdh)(argc, argv);
945 fdt_cmd_addr(int argc, char *argv[])
947 struct preloaded_file *fp;
948 struct fdt_header *hdr;
957 sprintf(command_errbuf, "no address specified");
961 hdr = (struct fdt_header *)strtoul(addr, &cp, 16);
963 snprintf(command_errbuf, sizeof(command_errbuf),
964 "Invalid address: %s", addr);
968 while ((fp = file_findfile(NULL, "dtb")) != NULL) {
977 fdt_cmd_cd(int argc, char *argv[])
980 char tmp[FDT_CWD_LEN];
983 path = (argc > 2) ? argv[2] : "/";
985 if (path[0] == '/') {
987 if (len >= FDT_CWD_LEN)
990 /* Handle path specification relative to cwd */
991 len = strlen(cwd) + strlen(path) + 1;
992 if (len >= FDT_CWD_LEN)
1001 o = fdt_path_offset(fdtp, path);
1003 snprintf(command_errbuf, sizeof(command_errbuf),
1004 "could not find node: '%s'", path);
1012 snprintf(command_errbuf, sizeof(command_errbuf),
1013 "path too long: %d, max allowed: %d", len, FDT_CWD_LEN - 1);
1018 fdt_cmd_hdr(int argc __unused, char *argv[] __unused)
1024 command_errmsg = "no device tree blob pointer?!";
1028 ver = fdt_version(fdtp);
1030 sprintf(line, "\nFlattened device tree header (%p):\n", fdtp);
1031 if (pager_output(line))
1033 sprintf(line, " magic = 0x%08x\n", fdt_magic(fdtp));
1034 if (pager_output(line))
1036 sprintf(line, " size = %d\n", fdt_totalsize(fdtp));
1037 if (pager_output(line))
1039 sprintf(line, " off_dt_struct = 0x%08x\n",
1040 fdt_off_dt_struct(fdtp));
1041 if (pager_output(line))
1043 sprintf(line, " off_dt_strings = 0x%08x\n",
1044 fdt_off_dt_strings(fdtp));
1045 if (pager_output(line))
1047 sprintf(line, " off_mem_rsvmap = 0x%08x\n",
1048 fdt_off_mem_rsvmap(fdtp));
1049 if (pager_output(line))
1051 sprintf(line, " version = %d\n", ver);
1052 if (pager_output(line))
1054 sprintf(line, " last compatible version = %d\n",
1055 fdt_last_comp_version(fdtp));
1056 if (pager_output(line))
1059 sprintf(line, " boot_cpuid = %d\n",
1060 fdt_boot_cpuid_phys(fdtp));
1061 if (pager_output(line))
1065 sprintf(line, " size_dt_strings = %d\n",
1066 fdt_size_dt_strings(fdtp));
1067 if (pager_output(line))
1071 sprintf(line, " size_dt_struct = %d\n",
1072 fdt_size_dt_struct(fdtp));
1073 if (pager_output(line))
1083 fdt_cmd_ls(int argc, char *argv[])
1085 const char *prevname[FDT_MAX_DEPTH] = { NULL };
1090 path = (argc > 2) ? argv[2] : NULL;
1094 o = fdt_path_offset(fdtp, path);
1096 snprintf(command_errbuf, sizeof(command_errbuf),
1097 "could not find node: '%s'", path);
1102 (o >= 0) && (depth >= 0);
1103 o = fdt_next_node(fdtp, o, &depth)) {
1105 name = fdt_get_name(fdtp, o, NULL);
1107 if (depth > FDT_MAX_DEPTH) {
1108 printf("max depth exceeded: %d\n", depth);
1112 prevname[depth] = name;
1114 /* Skip root (i = 1) when printing devices */
1115 for (i = 1; i <= depth; i++) {
1116 if (prevname[i] == NULL)
1119 if (strcmp(cwd, "/") == 0)
1121 printf("%s", prevname[i]);
1133 return (c >= ' ' && c <= 0x7e);
1137 fdt_isprint(const void *data, int len, int *count)
1146 d = (const char *)data;
1147 if (d[len - 1] != '\0')
1152 for (i = 0; i < len; i++) {
1154 if (isprint(ch) || (ch == '\0' && i > 0)) {
1169 fdt_data_str(const void *data, int len, int count, char **buf)
1176 * Calculate the length for the string and allocate memory.
1178 * Note that 'len' already includes at least one terminator.
1183 * Each token had already a terminator buried in 'len', but we
1184 * only need one eventually, don't count space for these.
1186 buf_len -= count - 1;
1188 /* Each consecutive token requires a ", " separator. */
1189 buf_len += count * 2;
1192 /* Add some space for surrounding double quotes. */
1193 buf_len += count * 2;
1195 /* Note that string being put in 'tmp' may be as big as 'buf_len'. */
1196 b = (char *)malloc(buf_len);
1197 tmp = (char *)malloc(buf_len);
1209 * Now that we have space, format the string.
1213 d = (const char *)data + i;
1216 sprintf(tmp, "\"%s\"%s", d,
1217 (i + l) < len ? ", " : "");
1233 fdt_data_cell(const void *data, int len, char **buf)
1239 /* Number of cells */
1243 * Calculate the length for the string and allocate memory.
1246 /* Each byte translates to 2 output characters */
1249 /* Each consecutive cell requires a " " separator. */
1250 l += (count - 1) * 1;
1252 /* Each cell will have a "0x" prefix */
1254 /* Space for surrounding <> and terminator */
1257 b = (char *)malloc(l);
1258 tmp = (char *)malloc(l);
1270 for (i = 0; i < len; i += 4) {
1271 c = (const uint32_t *)((const uint8_t *)data + i);
1272 sprintf(tmp, "0x%08x%s", fdt32_to_cpu(*c),
1273 i < (len - 4) ? " " : "");
1287 fdt_data_bytes(const void *data, int len, char **buf)
1294 * Calculate the length for the string and allocate memory.
1297 /* Each byte translates to 2 output characters */
1300 /* Each consecutive byte requires a " " separator. */
1302 /* Each byte will have a "0x" prefix */
1304 /* Space for surrounding [] and terminator. */
1307 b = (char *)malloc(l);
1308 tmp = (char *)malloc(l);
1320 for (i = 0, d = data; i < len; i++) {
1321 sprintf(tmp, "0x%02x%s", d[i], i < len - 1 ? " " : "");
1335 fdt_data_fmt(const void *data, int len, char **buf)
1344 if (fdt_isprint(data, len, &count))
1345 return (fdt_data_str(data, len, count, buf));
1347 else if ((len % 4) == 0)
1348 return (fdt_data_cell(data, len, buf));
1351 return (fdt_data_bytes(data, len, buf));
1355 fdt_prop(int offset)
1358 const struct fdt_property *prop;
1364 prop = fdt_offset_ptr(fdtp, offset, sizeof(*prop));
1368 name = fdt_string(fdtp, fdt32_to_cpu(prop->nameoff));
1369 len = fdt32_to_cpu(prop->len);
1374 /* Property without value */
1375 line = (char *)malloc(strlen(name) + 2);
1380 sprintf(line, "%s\n", name);
1385 * Process property with value
1389 if (fdt_data_fmt(data, len, &buf) != 0) {
1394 line = (char *)malloc(strlen(name) + strlen(FDT_PROP_SEP) +
1397 sprintf(command_errbuf, "could not allocate space for string");
1402 sprintf(line, "%s" FDT_PROP_SEP "%s\n", name, buf);
1420 fdt_modprop(int nodeoff, char *propname, void *value, char mode)
1422 uint32_t cells[100];
1425 const struct fdt_property *p;
1427 p = fdt_get_property(fdtp, nodeoff, propname, NULL);
1431 /* Adding inexistant value in mode 1 is forbidden */
1432 sprintf(command_errbuf, "property already exists!");
1435 } else if (mode == 0) {
1436 sprintf(command_errbuf, "property does not exist!");
1439 len = strlen(value);
1449 len = fdt_strtovect(buf, (void *)&cells, 100,
1452 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1453 len * sizeof(uint32_t));
1457 len = fdt_strtovect(buf, (void *)&cells, 100,
1460 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1461 len * sizeof(uint8_t));
1465 /* Default -- string */
1466 rv = fdt_setprop_string(fdtp, nodeoff, propname, value);
1471 if (rv == -FDT_ERR_NOSPACE)
1472 sprintf(command_errbuf,
1473 "Device tree blob is too small!\n");
1475 sprintf(command_errbuf,
1476 "Could not add/modify property!\n");
1481 /* Merge strings from argv into a single string */
1483 fdt_merge_strings(int argc, char *argv[], int start, char **buffer)
1491 for (i = start; i < argc; i++)
1492 sz += strlen(argv[i]);
1494 /* Additional bytes for whitespaces between args */
1497 buf = (char *)malloc(sizeof(char) * sz);
1499 sprintf(command_errbuf, "could not allocate space "
1503 bzero(buf, sizeof(char) * sz);
1506 for (i = start, idx = 0; i < argc; i++) {
1507 strcpy(buf + idx, argv[i]);
1508 idx += strlen(argv[i]);
1517 /* Extract offset and name of node/property from a given path */
1519 fdt_extract_nameloc(char **pathp, char **namep, int *nodeoff)
1522 char *path = *pathp, *name = NULL, *subpath = NULL;
1524 subpath = strrchr(path, '/');
1525 if (subpath == NULL) {
1526 o = fdt_path_offset(fdtp, cwd);
1528 path = (char *)&cwd;
1531 if (strlen(path) == 0)
1535 o = fdt_path_offset(fdtp, path);
1538 if (strlen(name) == 0) {
1539 sprintf(command_errbuf, "name not specified");
1543 snprintf(command_errbuf, sizeof(command_errbuf),
1544 "could not find node: '%s'", path);
1554 fdt_cmd_prop(int argc, char *argv[])
1556 char *path, *propname, *value;
1557 int o, next, depth, rv;
1560 path = (argc > 2) ? argv[2] : NULL;
1565 /* Merge property value strings into one */
1566 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1577 /* If value is specified -- try to modify prop. */
1578 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1581 rv = fdt_modprop(o, propname, value, 0);
1587 /* User wants to display properties */
1588 o = fdt_path_offset(fdtp, path);
1591 snprintf(command_errbuf, sizeof(command_errbuf),
1592 "could not find node: '%s'", path);
1598 while (depth >= 0) {
1599 tag = fdt_next_tag(fdtp, o, &next);
1605 /* Don't process properties of nested nodes */
1608 if (fdt_prop(o) != 0) {
1609 sprintf(command_errbuf, "could not process "
1615 case FDT_BEGIN_NODE:
1617 if (depth > FDT_MAX_DEPTH) {
1618 printf("warning: nesting too deep: %d\n",
1627 * This is the end of our starting node, force
1640 fdt_cmd_mkprop(int argc, char *argv[])
1643 char *path, *propname, *value;
1645 path = (argc > 2) ? argv[2] : NULL;
1650 /* Merge property value strings into one */
1651 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1656 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1659 if (fdt_modprop(o, propname, value, 1))
1666 fdt_cmd_rm(int argc, char *argv[])
1669 char *path = NULL, *propname;
1674 sprintf(command_errbuf, "no node/property name specified");
1678 o = fdt_path_offset(fdtp, path);
1680 /* If node not found -- try to find & delete property */
1681 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1684 if ((rv = fdt_delprop(fdtp, o, propname)) != 0) {
1685 snprintf(command_errbuf, sizeof(command_errbuf),
1686 "could not delete %s\n",
1687 (rv == -FDT_ERR_NOTFOUND) ?
1688 "(property/node does not exist)" : "");
1694 /* If node exists -- remove node */
1695 rv = fdt_del_node(fdtp, o);
1697 sprintf(command_errbuf, "could not delete node");
1704 fdt_cmd_mknode(int argc, char *argv[])
1707 char *path = NULL, *nodename = NULL;
1712 sprintf(command_errbuf, "no node name specified");
1716 if (fdt_extract_nameloc(&path, &nodename, &o) != 0)
1719 rv = fdt_add_subnode(fdtp, o, nodename);
1722 if (rv == -FDT_ERR_NOSPACE)
1723 sprintf(command_errbuf,
1724 "Device tree blob is too small!\n");
1726 sprintf(command_errbuf,
1727 "Could not add node!\n");
1734 fdt_cmd_pwd(int argc, char *argv[])
1736 char line[FDT_CWD_LEN];
1739 sprintf(line, "%s\n", cwd);
1746 fdt_cmd_mres(int argc, char *argv[])
1748 uint64_t start, size;
1753 total = fdt_num_mem_rsv(fdtp);
1755 if (pager_output("Reserved memory regions:\n"))
1757 for (i = 0; i < total; i++) {
1758 fdt_get_mem_rsv(fdtp, i, &start, &size);
1759 sprintf(line, "reg#%d: (start: 0x%jx, size: 0x%jx)\n",
1761 if (pager_output(line))
1765 pager_output("No reserved memory regions\n");
1773 fdt_cmd_nyi(int argc, char *argv[])
1776 printf("command not yet implemented\n");