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;
515 struct preloaded_file *bfp;
518 debugf("fdt_setup_fdtp()\n");
520 /* If we already loaded a file, use it. */
521 if ((bfp = file_findfile(NULL, "dtb")) != NULL) {
522 if (fdt_load_dtb(bfp->f_addr) == 0) {
523 printf("Using DTB from loaded file '%s'.\n",
525 fdt_platform_load_overlays();
530 /* If we were given the address of a valid blob in memory, use it. */
531 if (fdt_to_load != NULL) {
532 if (fdt_load_dtb_addr(fdt_to_load) == 0) {
533 printf("Using DTB from memory address %p.\n",
535 fdt_platform_load_overlays();
540 if (fdt_platform_load_dtb() == 0) {
541 fdt_platform_load_overlays();
545 /* If there is a dtb compiled into the kernel, use it. */
546 if ((va = fdt_find_static_dtb()) != 0) {
547 if (fdt_load_dtb(va) == 0) {
548 printf("Using DTB compiled into kernel.\n");
553 command_errmsg = "No device tree blob found!\n";
557 #define fdt_strtovect(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
558 (cellbuf), (lim), (cellsize), 0);
560 /* Force using base 16 */
561 #define fdt_strtovectx(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
562 (cellbuf), (lim), (cellsize), 16);
565 _fdt_strtovect(const char *str, void *cellbuf, int lim, unsigned char cellsize,
568 const char *buf = str;
569 const char *end = str + strlen(str) - 2;
570 uint32_t *u32buf = NULL;
571 uint8_t *u8buf = NULL;
574 if (cellsize == sizeof(uint32_t))
575 u32buf = (uint32_t *)cellbuf;
577 u8buf = (uint8_t *)cellbuf;
584 /* Skip white whitespace(s)/separators */
585 while (!isxdigit(*buf) && buf < end)
590 cpu_to_fdt32((uint32_t)strtol(buf, NULL, base));
593 u8buf[cnt] = (uint8_t)strtol(buf, NULL, base);
595 if (cnt + 1 <= lim - 1)
600 /* Find another number */
601 while ((isxdigit(*buf) || *buf == 'x') && buf < end)
608 fdt_fixup_ethernet(const char *str, char *ethstr, int len)
612 /* Convert macaddr string into a vector of uints */
613 fdt_strtovectx(str, &tmp_addr, 6, sizeof(uint8_t));
614 /* Set actual property to a value from vect */
615 fdt_setprop(fdtp, fdt_path_offset(fdtp, ethstr),
616 "local-mac-address", &tmp_addr, 6 * sizeof(uint8_t));
620 fdt_fixup_cpubusfreqs(unsigned long cpufreq, unsigned long busfreq)
622 int lo, o = 0, o2, maxo = 0, depth;
623 const uint32_t zero = 0;
625 /* We want to modify every subnode of /cpus */
626 o = fdt_path_offset(fdtp, "/cpus");
630 /* maxo should contain offset of node next to /cpus */
634 maxo = fdt_next_node(fdtp, maxo, &depth);
636 /* Find CPU frequency properties */
637 o = fdt_node_offset_by_prop_value(fdtp, o, "clock-frequency",
638 &zero, sizeof(uint32_t));
640 o2 = fdt_node_offset_by_prop_value(fdtp, o, "bus-frequency", &zero,
645 while (o != -FDT_ERR_NOTFOUND && o2 != -FDT_ERR_NOTFOUND) {
647 o = fdt_node_offset_by_prop_value(fdtp, lo,
648 "clock-frequency", &zero, sizeof(uint32_t));
650 o2 = fdt_node_offset_by_prop_value(fdtp, lo, "bus-frequency",
651 &zero, sizeof(uint32_t));
653 /* We're only interested in /cpus subnode(s) */
657 fdt_setprop_inplace_cell(fdtp, lo, "clock-frequency",
660 fdt_setprop_inplace_cell(fdtp, lo, "bus-frequency",
669 fdt_reg_valid(uint32_t *reg, int len, int addr_cells, int size_cells)
671 int cells_in_tuple, i, tuples, tuple_size;
672 uint32_t cur_start, cur_size;
674 cells_in_tuple = (addr_cells + size_cells);
675 tuple_size = cells_in_tuple * sizeof(uint32_t);
676 tuples = len / tuple_size;
680 for (i = 0; i < tuples; i++) {
682 cur_start = fdt64_to_cpu(reg[i * cells_in_tuple]);
684 cur_start = fdt32_to_cpu(reg[i * cells_in_tuple]);
687 cur_size = fdt64_to_cpu(reg[i * cells_in_tuple + 2]);
689 cur_size = fdt32_to_cpu(reg[i * cells_in_tuple + 1]);
694 debugf(" reg#%d (start: 0x%0x size: 0x%0x) valid!\n",
695 i, cur_start, cur_size);
702 fdt_fixup_memory(struct fdt_mem_region *region, size_t num)
704 struct fdt_mem_region *curmr;
705 uint32_t addr_cells, size_cells;
706 uint32_t *addr_cellsp, *size_cellsp;
707 int err, i, len, memory, root;
710 uint64_t rstart, rsize;
713 root = fdt_path_offset(fdtp, "/");
715 sprintf(command_errbuf, "Could not find root node !");
719 memory = fdt_path_offset(fdtp, "/memory");
721 /* Create proper '/memory' node. */
722 memory = fdt_add_subnode(fdtp, root, "memory");
724 snprintf(command_errbuf, sizeof(command_errbuf),
725 "Could not fixup '/memory' "
726 "node, error code : %d!\n", memory);
730 err = fdt_setprop(fdtp, memory, "device_type", "memory",
737 addr_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#address-cells",
739 size_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#size-cells", NULL);
741 if (addr_cellsp == NULL || size_cellsp == NULL) {
742 snprintf(command_errbuf, sizeof(command_errbuf),
743 "Could not fixup '/memory' node : "
744 "%s %s property not found in root node!\n",
745 (!addr_cellsp) ? "#address-cells" : "",
746 (!size_cellsp) ? "#size-cells" : "");
750 addr_cells = fdt32_to_cpu(*addr_cellsp);
751 size_cells = fdt32_to_cpu(*size_cellsp);
754 * Convert memreserve data to memreserve property
755 * Check if property already exists
757 reserved = fdt_num_mem_rsv(fdtp);
759 (fdt_getprop(fdtp, root, "memreserve", NULL) == NULL)) {
760 len = (addr_cells + size_cells) * reserved * sizeof(uint32_t);
761 sb = buf = (uint8_t *)malloc(len);
767 for (i = 0; i < reserved; i++) {
768 if (fdt_get_mem_rsv(fdtp, i, &rstart, &rsize))
771 /* Ensure endianness, and put cells into a buffer */
774 cpu_to_fdt64(rstart);
777 cpu_to_fdt32(rstart);
779 buf += sizeof(uint32_t) * addr_cells;
787 buf += sizeof(uint32_t) * size_cells;
792 if ((err = fdt_setprop(fdtp, root, "memreserve", sb, len)) < 0)
793 printf("Could not fixup 'memreserve' property.\n");
798 /* Count valid memory regions entries in sysinfo. */
800 for (i = 0; i < num; i++)
801 if (region[i].start == 0 && region[i].size == 0)
805 sprintf(command_errbuf, "Could not fixup '/memory' node : "
806 "sysinfo doesn't contain valid memory regions info!\n");
810 len = (addr_cells + size_cells) * realmrno * sizeof(uint32_t);
811 sb = buf = (uint8_t *)malloc(len);
817 for (i = 0; i < num; i++) {
819 if (curmr->size != 0) {
820 /* Ensure endianness, and put cells into a buffer */
823 cpu_to_fdt64(curmr->start);
826 cpu_to_fdt32(curmr->start);
828 buf += sizeof(uint32_t) * addr_cells;
831 cpu_to_fdt64(curmr->size);
834 cpu_to_fdt32(curmr->size);
836 buf += sizeof(uint32_t) * size_cells;
841 if ((err = fdt_setprop(fdtp, memory, "reg", sb, len)) < 0)
842 sprintf(command_errbuf, "Could not fixup '/memory' node.\n");
848 fdt_fixup_stdout(const char *str)
852 const struct fdt_property *prop;
855 ptr = (char *)str + strlen(str) - 1;
856 while (ptr > str && isdigit(*(str - 1)))
862 no = fdt_path_offset(fdtp, "/chosen");
866 prop = fdt_get_property(fdtp, no, "stdout", &len);
868 /* If /chosen/stdout does not extist, create it */
869 if (prop == NULL || (prop != NULL && len == 0)) {
871 bzero(tmp, 10 * sizeof(char));
872 strcpy((char *)&tmp, "serial");
874 /* Serial number too long */
877 strncpy((char *)tmp + 6, ptr, 3);
878 sero = fdt_path_offset(fdtp, (const char *)tmp);
881 * If serial device we're trying to assign
882 * stdout to doesn't exist in DT -- return.
886 fdt_setprop(fdtp, no, "stdout", &tmp,
887 strlen((char *)&tmp) + 1);
888 fdt_setprop(fdtp, no, "stdin", &tmp,
889 strlen((char *)&tmp) + 1);
894 fdt_load_dtb_overlays(const char *extras)
898 /* Any extra overlays supplied by pre-loader environment */
899 if (extras != NULL && *extras != '\0') {
900 printf("Loading DTB overlays: '%s'\n", extras);
901 fdt_load_dtb_overlays_string(extras);
904 /* Any overlays supplied by loader environment */
905 s = getenv("fdt_overlays");
906 if (s != NULL && *s != '\0') {
907 printf("Loading DTB overlays: '%s'\n", s);
908 fdt_load_dtb_overlays_string(s);
913 * Locate the blob, fix it up and return its location.
920 debugf("fdt_fixup()\n");
922 if (fdtp == NULL && fdt_setup_fdtp() != 0)
925 /* Create /chosen node (if not exists) */
926 if ((chosen = fdt_subnode_offset(fdtp, 0, "chosen")) ==
928 chosen = fdt_add_subnode(fdtp, 0, "chosen");
930 /* Value assigned to fixup-applied does not matter. */
931 if (fdt_getprop(fdtp, chosen, "fixup-applied", NULL))
934 fdt_platform_fixups();
937 * Re-fetch the /chosen subnode; our fixups may apply overlays or add
938 * nodes/properties that invalidate the offset we grabbed or created
939 * above, so we can no longer trust it.
941 chosen = fdt_subnode_offset(fdtp, 0, "chosen");
942 fdt_setprop(fdtp, chosen, "fixup-applied", NULL, 0);
947 * Copy DTB blob to specified location and return size
950 fdt_copy(vm_offset_t va)
953 debugf("fdt_copy va 0x%08x\n", va);
955 err = fdt_setup_fdtp();
957 printf("No valid device tree blob found!\n");
962 if (fdt_fixup() == 0)
965 COPYIN(fdtp, va, fdtp_size);
972 command_fdt_internal(int argc, char *argv[])
979 command_errmsg = "usage is 'fdt <command> [<args>]";
984 * Validate fdt <command>.
988 while (!(commands[i].name == NULL)) {
989 if (strcmp(argv[1], commands[i].name) == 0) {
991 cmdh = commands[i].handler;
992 flags = commands[i].flags;
998 command_errmsg = "unknown command";
1002 if (flags & CMD_REQUIRES_BLOB) {
1004 * Check if uboot env vars were parsed already. If not, do it now.
1006 if (fdt_fixup() == 0)
1011 * Call command handler.
1013 err = (*cmdh)(argc, argv);
1019 fdt_cmd_addr(int argc, char *argv[])
1021 struct preloaded_file *fp;
1022 struct fdt_header *hdr;
1031 sprintf(command_errbuf, "no address specified");
1035 hdr = (struct fdt_header *)strtoul(addr, &cp, 16);
1037 snprintf(command_errbuf, sizeof(command_errbuf),
1038 "Invalid address: %s", addr);
1042 while ((fp = file_findfile(NULL, "dtb")) != NULL) {
1051 fdt_cmd_cd(int argc, char *argv[])
1054 char tmp[FDT_CWD_LEN];
1057 path = (argc > 2) ? argv[2] : "/";
1059 if (path[0] == '/') {
1061 if (len >= FDT_CWD_LEN)
1064 /* Handle path specification relative to cwd */
1065 len = strlen(cwd) + strlen(path) + 1;
1066 if (len >= FDT_CWD_LEN)
1075 o = fdt_path_offset(fdtp, path);
1077 snprintf(command_errbuf, sizeof(command_errbuf),
1078 "could not find node: '%s'", path);
1086 snprintf(command_errbuf, sizeof(command_errbuf),
1087 "path too long: %d, max allowed: %d", len, FDT_CWD_LEN - 1);
1092 fdt_cmd_hdr(int argc __unused, char *argv[] __unused)
1098 command_errmsg = "no device tree blob pointer?!";
1102 ver = fdt_version(fdtp);
1104 sprintf(line, "\nFlattened device tree header (%p):\n", fdtp);
1105 if (pager_output(line))
1107 sprintf(line, " magic = 0x%08x\n", fdt_magic(fdtp));
1108 if (pager_output(line))
1110 sprintf(line, " size = %d\n", fdt_totalsize(fdtp));
1111 if (pager_output(line))
1113 sprintf(line, " off_dt_struct = 0x%08x\n",
1114 fdt_off_dt_struct(fdtp));
1115 if (pager_output(line))
1117 sprintf(line, " off_dt_strings = 0x%08x\n",
1118 fdt_off_dt_strings(fdtp));
1119 if (pager_output(line))
1121 sprintf(line, " off_mem_rsvmap = 0x%08x\n",
1122 fdt_off_mem_rsvmap(fdtp));
1123 if (pager_output(line))
1125 sprintf(line, " version = %d\n", ver);
1126 if (pager_output(line))
1128 sprintf(line, " last compatible version = %d\n",
1129 fdt_last_comp_version(fdtp));
1130 if (pager_output(line))
1133 sprintf(line, " boot_cpuid = %d\n",
1134 fdt_boot_cpuid_phys(fdtp));
1135 if (pager_output(line))
1139 sprintf(line, " size_dt_strings = %d\n",
1140 fdt_size_dt_strings(fdtp));
1141 if (pager_output(line))
1145 sprintf(line, " size_dt_struct = %d\n",
1146 fdt_size_dt_struct(fdtp));
1147 if (pager_output(line))
1157 fdt_cmd_ls(int argc, char *argv[])
1159 const char *prevname[FDT_MAX_DEPTH] = { NULL };
1164 path = (argc > 2) ? argv[2] : NULL;
1168 o = fdt_path_offset(fdtp, path);
1170 snprintf(command_errbuf, sizeof(command_errbuf),
1171 "could not find node: '%s'", path);
1176 (o >= 0) && (depth >= 0);
1177 o = fdt_next_node(fdtp, o, &depth)) {
1179 name = fdt_get_name(fdtp, o, NULL);
1181 if (depth > FDT_MAX_DEPTH) {
1182 printf("max depth exceeded: %d\n", depth);
1186 prevname[depth] = name;
1188 /* Skip root (i = 1) when printing devices */
1189 for (i = 1; i <= depth; i++) {
1190 if (prevname[i] == NULL)
1193 if (strcmp(cwd, "/") == 0)
1195 printf("%s", prevname[i]);
1207 return (c >= ' ' && c <= 0x7e);
1211 fdt_isprint(const void *data, int len, int *count)
1220 d = (const char *)data;
1221 if (d[len - 1] != '\0')
1226 for (i = 0; i < len; i++) {
1228 if (isprint(ch) || (ch == '\0' && i > 0)) {
1243 fdt_data_str(const void *data, int len, int count, char **buf)
1250 * Calculate the length for the string and allocate memory.
1252 * Note that 'len' already includes at least one terminator.
1257 * Each token had already a terminator buried in 'len', but we
1258 * only need one eventually, don't count space for these.
1260 buf_len -= count - 1;
1262 /* Each consecutive token requires a ", " separator. */
1263 buf_len += count * 2;
1266 /* Add some space for surrounding double quotes. */
1267 buf_len += count * 2;
1269 /* Note that string being put in 'tmp' may be as big as 'buf_len'. */
1270 b = (char *)malloc(buf_len);
1271 tmp = (char *)malloc(buf_len);
1283 * Now that we have space, format the string.
1287 d = (const char *)data + i;
1290 sprintf(tmp, "\"%s\"%s", d,
1291 (i + l) < len ? ", " : "");
1307 fdt_data_cell(const void *data, int len, char **buf)
1313 /* Number of cells */
1317 * Calculate the length for the string and allocate memory.
1320 /* Each byte translates to 2 output characters */
1323 /* Each consecutive cell requires a " " separator. */
1324 l += (count - 1) * 1;
1326 /* Each cell will have a "0x" prefix */
1328 /* Space for surrounding <> and terminator */
1331 b = (char *)malloc(l);
1332 tmp = (char *)malloc(l);
1344 for (i = 0; i < len; i += 4) {
1345 c = (const uint32_t *)((const uint8_t *)data + i);
1346 sprintf(tmp, "0x%08x%s", fdt32_to_cpu(*c),
1347 i < (len - 4) ? " " : "");
1361 fdt_data_bytes(const void *data, int len, char **buf)
1368 * Calculate the length for the string and allocate memory.
1371 /* Each byte translates to 2 output characters */
1374 /* Each consecutive byte requires a " " separator. */
1376 /* Each byte will have a "0x" prefix */
1378 /* Space for surrounding [] and terminator. */
1381 b = (char *)malloc(l);
1382 tmp = (char *)malloc(l);
1394 for (i = 0, d = data; i < len; i++) {
1395 sprintf(tmp, "0x%02x%s", d[i], i < len - 1 ? " " : "");
1409 fdt_data_fmt(const void *data, int len, char **buf)
1418 if (fdt_isprint(data, len, &count))
1419 return (fdt_data_str(data, len, count, buf));
1421 else if ((len % 4) == 0)
1422 return (fdt_data_cell(data, len, buf));
1425 return (fdt_data_bytes(data, len, buf));
1429 fdt_prop(int offset)
1432 const struct fdt_property *prop;
1438 prop = fdt_offset_ptr(fdtp, offset, sizeof(*prop));
1442 name = fdt_string(fdtp, fdt32_to_cpu(prop->nameoff));
1443 len = fdt32_to_cpu(prop->len);
1448 /* Property without value */
1449 line = (char *)malloc(strlen(name) + 2);
1454 sprintf(line, "%s\n", name);
1459 * Process property with value
1463 if (fdt_data_fmt(data, len, &buf) != 0) {
1468 line = (char *)malloc(strlen(name) + strlen(FDT_PROP_SEP) +
1471 sprintf(command_errbuf, "could not allocate space for string");
1476 sprintf(line, "%s" FDT_PROP_SEP "%s\n", name, buf);
1494 fdt_modprop(int nodeoff, char *propname, void *value, char mode)
1496 uint32_t cells[100];
1499 const struct fdt_property *p;
1501 p = fdt_get_property(fdtp, nodeoff, propname, NULL);
1505 /* Adding inexistant value in mode 1 is forbidden */
1506 sprintf(command_errbuf, "property already exists!");
1509 } else if (mode == 0) {
1510 sprintf(command_errbuf, "property does not exist!");
1522 len = fdt_strtovect(buf, (void *)&cells, 100,
1525 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1526 len * sizeof(uint32_t));
1530 len = fdt_strtovect(buf, (void *)&cells, 100,
1533 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1534 len * sizeof(uint8_t));
1538 /* Default -- string */
1539 rv = fdt_setprop_string(fdtp, nodeoff, propname, value);
1544 if (rv == -FDT_ERR_NOSPACE)
1545 sprintf(command_errbuf,
1546 "Device tree blob is too small!\n");
1548 sprintf(command_errbuf,
1549 "Could not add/modify property!\n");
1554 /* Merge strings from argv into a single string */
1556 fdt_merge_strings(int argc, char *argv[], int start, char **buffer)
1564 for (i = start; i < argc; i++)
1565 sz += strlen(argv[i]);
1567 /* Additional bytes for whitespaces between args */
1570 buf = (char *)malloc(sizeof(char) * sz);
1572 sprintf(command_errbuf, "could not allocate space "
1576 bzero(buf, sizeof(char) * sz);
1579 for (i = start, idx = 0; i < argc; i++) {
1580 strcpy(buf + idx, argv[i]);
1581 idx += strlen(argv[i]);
1590 /* Extract offset and name of node/property from a given path */
1592 fdt_extract_nameloc(char **pathp, char **namep, int *nodeoff)
1595 char *path = *pathp, *name = NULL, *subpath = NULL;
1597 subpath = strrchr(path, '/');
1598 if (subpath == NULL) {
1599 o = fdt_path_offset(fdtp, cwd);
1601 path = (char *)&cwd;
1604 if (strlen(path) == 0)
1608 o = fdt_path_offset(fdtp, path);
1611 if (strlen(name) == 0) {
1612 sprintf(command_errbuf, "name not specified");
1616 snprintf(command_errbuf, sizeof(command_errbuf),
1617 "could not find node: '%s'", path);
1627 fdt_cmd_prop(int argc, char *argv[])
1629 char *path, *propname, *value;
1630 int o, next, depth, rv;
1633 path = (argc > 2) ? argv[2] : NULL;
1638 /* Merge property value strings into one */
1639 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1650 /* If value is specified -- try to modify prop. */
1651 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1654 rv = fdt_modprop(o, propname, value, 0);
1660 /* User wants to display properties */
1661 o = fdt_path_offset(fdtp, path);
1664 snprintf(command_errbuf, sizeof(command_errbuf),
1665 "could not find node: '%s'", path);
1671 while (depth >= 0) {
1672 tag = fdt_next_tag(fdtp, o, &next);
1678 /* Don't process properties of nested nodes */
1681 if (fdt_prop(o) != 0) {
1682 sprintf(command_errbuf, "could not process "
1688 case FDT_BEGIN_NODE:
1690 if (depth > FDT_MAX_DEPTH) {
1691 printf("warning: nesting too deep: %d\n",
1700 * This is the end of our starting node, force
1713 fdt_cmd_mkprop(int argc, char *argv[])
1716 char *path, *propname, *value;
1718 path = (argc > 2) ? argv[2] : NULL;
1723 /* Merge property value strings into one */
1724 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1729 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1732 if (fdt_modprop(o, propname, value, 1))
1739 fdt_cmd_rm(int argc, char *argv[])
1742 char *path = NULL, *propname;
1747 sprintf(command_errbuf, "no node/property name specified");
1751 o = fdt_path_offset(fdtp, path);
1753 /* If node not found -- try to find & delete property */
1754 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1757 if ((rv = fdt_delprop(fdtp, o, propname)) != 0) {
1758 snprintf(command_errbuf, sizeof(command_errbuf),
1759 "could not delete %s\n",
1760 (rv == -FDT_ERR_NOTFOUND) ?
1761 "(property/node does not exist)" : "");
1767 /* If node exists -- remove node */
1768 rv = fdt_del_node(fdtp, o);
1770 sprintf(command_errbuf, "could not delete node");
1777 fdt_cmd_mknode(int argc, char *argv[])
1780 char *path = NULL, *nodename = NULL;
1785 sprintf(command_errbuf, "no node name specified");
1789 if (fdt_extract_nameloc(&path, &nodename, &o) != 0)
1792 rv = fdt_add_subnode(fdtp, o, nodename);
1795 if (rv == -FDT_ERR_NOSPACE)
1796 sprintf(command_errbuf,
1797 "Device tree blob is too small!\n");
1799 sprintf(command_errbuf,
1800 "Could not add node!\n");
1807 fdt_cmd_pwd(int argc, char *argv[])
1809 char line[FDT_CWD_LEN];
1812 sprintf(line, "%s\n", cwd);
1819 fdt_cmd_mres(int argc, char *argv[])
1821 uint64_t start, size;
1826 total = fdt_num_mem_rsv(fdtp);
1828 if (pager_output("Reserved memory regions:\n"))
1830 for (i = 0; i < total; i++) {
1831 fdt_get_mem_rsv(fdtp, i, &start, &size);
1832 sprintf(line, "reg#%d: (start: 0x%jx, size: 0x%jx)\n",
1834 if (pager_output(line))
1838 pager_output("No reserved memory regions\n");
1846 fdt_cmd_nyi(int argc, char *argv[])
1849 printf("command not yet implemented\n");