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)
853 const struct fdt_property *prop;
856 ptr = (char *)str + strlen(str) - 1;
857 while (ptr > str && isdigit(*(str - 1)))
863 serialno = (int)strtol(ptr, NULL, 0);
864 no = fdt_path_offset(fdtp, "/chosen");
868 prop = fdt_get_property(fdtp, no, "stdout", &len);
870 /* If /chosen/stdout does not extist, create it */
871 if (prop == NULL || (prop != NULL && len == 0)) {
873 bzero(tmp, 10 * sizeof(char));
874 strcpy((char *)&tmp, "serial");
876 /* Serial number too long */
879 strncpy((char *)tmp + 6, ptr, 3);
880 sero = fdt_path_offset(fdtp, (const char *)tmp);
883 * If serial device we're trying to assign
884 * stdout to doesn't exist in DT -- return.
888 fdt_setprop(fdtp, no, "stdout", &tmp,
889 strlen((char *)&tmp) + 1);
890 fdt_setprop(fdtp, no, "stdin", &tmp,
891 strlen((char *)&tmp) + 1);
896 fdt_load_dtb_overlays(const char *extras)
900 /* Any extra overlays supplied by pre-loader environment */
901 if (extras != NULL && *extras != '\0') {
902 printf("Loading DTB overlays: '%s'\n", extras);
903 fdt_load_dtb_overlays_string(extras);
906 /* Any overlays supplied by loader environment */
907 s = getenv("fdt_overlays");
908 if (s != NULL && *s != '\0') {
909 printf("Loading DTB overlays: '%s'\n", s);
910 fdt_load_dtb_overlays_string(s);
915 * Locate the blob, fix it up and return its location.
924 debugf("fdt_fixup()\n");
926 if (fdtp == NULL && fdt_setup_fdtp() != 0)
929 /* Create /chosen node (if not exists) */
930 if ((chosen = fdt_subnode_offset(fdtp, 0, "chosen")) ==
932 chosen = fdt_add_subnode(fdtp, 0, "chosen");
934 /* Value assigned to fixup-applied does not matter. */
935 if (fdt_getprop(fdtp, chosen, "fixup-applied", NULL))
938 fdt_platform_fixups();
941 * Re-fetch the /chosen subnode; our fixups may apply overlays or add
942 * nodes/properties that invalidate the offset we grabbed or created
943 * above, so we can no longer trust it.
945 chosen = fdt_subnode_offset(fdtp, 0, "chosen");
946 fdt_setprop(fdtp, chosen, "fixup-applied", NULL, 0);
951 * Copy DTB blob to specified location and return size
954 fdt_copy(vm_offset_t va)
957 debugf("fdt_copy va 0x%08x\n", va);
959 err = fdt_setup_fdtp();
961 printf("No valid device tree blob found!\n");
966 if (fdt_fixup() == 0)
969 COPYIN(fdtp, va, fdtp_size);
976 command_fdt_internal(int argc, char *argv[])
984 command_errmsg = "usage is 'fdt <command> [<args>]";
989 * Validate fdt <command>.
991 cmd = strdup(argv[1]);
994 while (!(commands[i].name == NULL)) {
995 if (strcmp(cmd, commands[i].name) == 0) {
997 cmdh = commands[i].handler;
998 flags = commands[i].flags;
1004 command_errmsg = "unknown command";
1008 if (flags & CMD_REQUIRES_BLOB) {
1010 * Check if uboot env vars were parsed already. If not, do it now.
1012 if (fdt_fixup() == 0)
1017 * Call command handler.
1019 err = (*cmdh)(argc, argv);
1025 fdt_cmd_addr(int argc, char *argv[])
1027 struct preloaded_file *fp;
1028 struct fdt_header *hdr;
1037 sprintf(command_errbuf, "no address specified");
1041 hdr = (struct fdt_header *)strtoul(addr, &cp, 16);
1043 snprintf(command_errbuf, sizeof(command_errbuf),
1044 "Invalid address: %s", addr);
1048 while ((fp = file_findfile(NULL, "dtb")) != NULL) {
1057 fdt_cmd_cd(int argc, char *argv[])
1060 char tmp[FDT_CWD_LEN];
1063 path = (argc > 2) ? argv[2] : "/";
1065 if (path[0] == '/') {
1067 if (len >= FDT_CWD_LEN)
1070 /* Handle path specification relative to cwd */
1071 len = strlen(cwd) + strlen(path) + 1;
1072 if (len >= FDT_CWD_LEN)
1081 o = fdt_path_offset(fdtp, path);
1083 snprintf(command_errbuf, sizeof(command_errbuf),
1084 "could not find node: '%s'", path);
1092 snprintf(command_errbuf, sizeof(command_errbuf),
1093 "path too long: %d, max allowed: %d", len, FDT_CWD_LEN - 1);
1098 fdt_cmd_hdr(int argc __unused, char *argv[] __unused)
1104 command_errmsg = "no device tree blob pointer?!";
1108 ver = fdt_version(fdtp);
1110 sprintf(line, "\nFlattened device tree header (%p):\n", fdtp);
1111 if (pager_output(line))
1113 sprintf(line, " magic = 0x%08x\n", fdt_magic(fdtp));
1114 if (pager_output(line))
1116 sprintf(line, " size = %d\n", fdt_totalsize(fdtp));
1117 if (pager_output(line))
1119 sprintf(line, " off_dt_struct = 0x%08x\n",
1120 fdt_off_dt_struct(fdtp));
1121 if (pager_output(line))
1123 sprintf(line, " off_dt_strings = 0x%08x\n",
1124 fdt_off_dt_strings(fdtp));
1125 if (pager_output(line))
1127 sprintf(line, " off_mem_rsvmap = 0x%08x\n",
1128 fdt_off_mem_rsvmap(fdtp));
1129 if (pager_output(line))
1131 sprintf(line, " version = %d\n", ver);
1132 if (pager_output(line))
1134 sprintf(line, " last compatible version = %d\n",
1135 fdt_last_comp_version(fdtp));
1136 if (pager_output(line))
1139 sprintf(line, " boot_cpuid = %d\n",
1140 fdt_boot_cpuid_phys(fdtp));
1141 if (pager_output(line))
1145 sprintf(line, " size_dt_strings = %d\n",
1146 fdt_size_dt_strings(fdtp));
1147 if (pager_output(line))
1151 sprintf(line, " size_dt_struct = %d\n",
1152 fdt_size_dt_struct(fdtp));
1153 if (pager_output(line))
1163 fdt_cmd_ls(int argc, char *argv[])
1165 const char *prevname[FDT_MAX_DEPTH] = { NULL };
1170 path = (argc > 2) ? argv[2] : NULL;
1174 o = fdt_path_offset(fdtp, path);
1176 snprintf(command_errbuf, sizeof(command_errbuf),
1177 "could not find node: '%s'", path);
1182 (o >= 0) && (depth >= 0);
1183 o = fdt_next_node(fdtp, o, &depth)) {
1185 name = fdt_get_name(fdtp, o, NULL);
1187 if (depth > FDT_MAX_DEPTH) {
1188 printf("max depth exceeded: %d\n", depth);
1192 prevname[depth] = name;
1194 /* Skip root (i = 1) when printing devices */
1195 for (i = 1; i <= depth; i++) {
1196 if (prevname[i] == NULL)
1199 if (strcmp(cwd, "/") == 0)
1201 printf("%s", prevname[i]);
1213 return (c >= ' ' && c <= 0x7e);
1217 fdt_isprint(const void *data, int len, int *count)
1226 d = (const char *)data;
1227 if (d[len - 1] != '\0')
1232 for (i = 0; i < len; i++) {
1234 if (isprint(ch) || (ch == '\0' && i > 0)) {
1249 fdt_data_str(const void *data, int len, int count, char **buf)
1256 * Calculate the length for the string and allocate memory.
1258 * Note that 'len' already includes at least one terminator.
1263 * Each token had already a terminator buried in 'len', but we
1264 * only need one eventually, don't count space for these.
1266 buf_len -= count - 1;
1268 /* Each consecutive token requires a ", " separator. */
1269 buf_len += count * 2;
1272 /* Add some space for surrounding double quotes. */
1273 buf_len += count * 2;
1275 /* Note that string being put in 'tmp' may be as big as 'buf_len'. */
1276 b = (char *)malloc(buf_len);
1277 tmp = (char *)malloc(buf_len);
1289 * Now that we have space, format the string.
1293 d = (const char *)data + i;
1296 sprintf(tmp, "\"%s\"%s", d,
1297 (i + l) < len ? ", " : "");
1313 fdt_data_cell(const void *data, int len, char **buf)
1319 /* Number of cells */
1323 * Calculate the length for the string and allocate memory.
1326 /* Each byte translates to 2 output characters */
1329 /* Each consecutive cell requires a " " separator. */
1330 l += (count - 1) * 1;
1332 /* Each cell will have a "0x" prefix */
1334 /* Space for surrounding <> and terminator */
1337 b = (char *)malloc(l);
1338 tmp = (char *)malloc(l);
1350 for (i = 0; i < len; i += 4) {
1351 c = (const uint32_t *)((const uint8_t *)data + i);
1352 sprintf(tmp, "0x%08x%s", fdt32_to_cpu(*c),
1353 i < (len - 4) ? " " : "");
1367 fdt_data_bytes(const void *data, int len, char **buf)
1374 * Calculate the length for the string and allocate memory.
1377 /* Each byte translates to 2 output characters */
1380 /* Each consecutive byte requires a " " separator. */
1382 /* Each byte will have a "0x" prefix */
1384 /* Space for surrounding [] and terminator. */
1387 b = (char *)malloc(l);
1388 tmp = (char *)malloc(l);
1400 for (i = 0, d = data; i < len; i++) {
1401 sprintf(tmp, "0x%02x%s", d[i], i < len - 1 ? " " : "");
1415 fdt_data_fmt(const void *data, int len, char **buf)
1424 if (fdt_isprint(data, len, &count))
1425 return (fdt_data_str(data, len, count, buf));
1427 else if ((len % 4) == 0)
1428 return (fdt_data_cell(data, len, buf));
1431 return (fdt_data_bytes(data, len, buf));
1435 fdt_prop(int offset)
1438 const struct fdt_property *prop;
1444 prop = fdt_offset_ptr(fdtp, offset, sizeof(*prop));
1448 name = fdt_string(fdtp, fdt32_to_cpu(prop->nameoff));
1449 len = fdt32_to_cpu(prop->len);
1454 /* Property without value */
1455 line = (char *)malloc(strlen(name) + 2);
1460 sprintf(line, "%s\n", name);
1465 * Process property with value
1469 if (fdt_data_fmt(data, len, &buf) != 0) {
1474 line = (char *)malloc(strlen(name) + strlen(FDT_PROP_SEP) +
1477 sprintf(command_errbuf, "could not allocate space for string");
1482 sprintf(line, "%s" FDT_PROP_SEP "%s\n", name, buf);
1500 fdt_modprop(int nodeoff, char *propname, void *value, char mode)
1502 uint32_t cells[100];
1505 const struct fdt_property *p;
1507 p = fdt_get_property(fdtp, nodeoff, propname, NULL);
1511 /* Adding inexistant value in mode 1 is forbidden */
1512 sprintf(command_errbuf, "property already exists!");
1515 } else if (mode == 0) {
1516 sprintf(command_errbuf, "property does not exist!");
1519 len = strlen(value);
1529 len = fdt_strtovect(buf, (void *)&cells, 100,
1532 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1533 len * sizeof(uint32_t));
1537 len = fdt_strtovect(buf, (void *)&cells, 100,
1540 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1541 len * sizeof(uint8_t));
1545 /* Default -- string */
1546 rv = fdt_setprop_string(fdtp, nodeoff, propname, value);
1551 if (rv == -FDT_ERR_NOSPACE)
1552 sprintf(command_errbuf,
1553 "Device tree blob is too small!\n");
1555 sprintf(command_errbuf,
1556 "Could not add/modify property!\n");
1561 /* Merge strings from argv into a single string */
1563 fdt_merge_strings(int argc, char *argv[], int start, char **buffer)
1571 for (i = start; i < argc; i++)
1572 sz += strlen(argv[i]);
1574 /* Additional bytes for whitespaces between args */
1577 buf = (char *)malloc(sizeof(char) * sz);
1579 sprintf(command_errbuf, "could not allocate space "
1583 bzero(buf, sizeof(char) * sz);
1586 for (i = start, idx = 0; i < argc; i++) {
1587 strcpy(buf + idx, argv[i]);
1588 idx += strlen(argv[i]);
1597 /* Extract offset and name of node/property from a given path */
1599 fdt_extract_nameloc(char **pathp, char **namep, int *nodeoff)
1602 char *path = *pathp, *name = NULL, *subpath = NULL;
1604 subpath = strrchr(path, '/');
1605 if (subpath == NULL) {
1606 o = fdt_path_offset(fdtp, cwd);
1608 path = (char *)&cwd;
1611 if (strlen(path) == 0)
1615 o = fdt_path_offset(fdtp, path);
1618 if (strlen(name) == 0) {
1619 sprintf(command_errbuf, "name not specified");
1623 snprintf(command_errbuf, sizeof(command_errbuf),
1624 "could not find node: '%s'", path);
1634 fdt_cmd_prop(int argc, char *argv[])
1636 char *path, *propname, *value;
1637 int o, next, depth, rv;
1640 path = (argc > 2) ? argv[2] : NULL;
1645 /* Merge property value strings into one */
1646 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1657 /* If value is specified -- try to modify prop. */
1658 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1661 rv = fdt_modprop(o, propname, value, 0);
1667 /* User wants to display properties */
1668 o = fdt_path_offset(fdtp, path);
1671 snprintf(command_errbuf, sizeof(command_errbuf),
1672 "could not find node: '%s'", path);
1678 while (depth >= 0) {
1679 tag = fdt_next_tag(fdtp, o, &next);
1685 /* Don't process properties of nested nodes */
1688 if (fdt_prop(o) != 0) {
1689 sprintf(command_errbuf, "could not process "
1695 case FDT_BEGIN_NODE:
1697 if (depth > FDT_MAX_DEPTH) {
1698 printf("warning: nesting too deep: %d\n",
1707 * This is the end of our starting node, force
1720 fdt_cmd_mkprop(int argc, char *argv[])
1723 char *path, *propname, *value;
1725 path = (argc > 2) ? argv[2] : NULL;
1730 /* Merge property value strings into one */
1731 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1736 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1739 if (fdt_modprop(o, propname, value, 1))
1746 fdt_cmd_rm(int argc, char *argv[])
1749 char *path = NULL, *propname;
1754 sprintf(command_errbuf, "no node/property name specified");
1758 o = fdt_path_offset(fdtp, path);
1760 /* If node not found -- try to find & delete property */
1761 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1764 if ((rv = fdt_delprop(fdtp, o, propname)) != 0) {
1765 snprintf(command_errbuf, sizeof(command_errbuf),
1766 "could not delete %s\n",
1767 (rv == -FDT_ERR_NOTFOUND) ?
1768 "(property/node does not exist)" : "");
1774 /* If node exists -- remove node */
1775 rv = fdt_del_node(fdtp, o);
1777 sprintf(command_errbuf, "could not delete node");
1784 fdt_cmd_mknode(int argc, char *argv[])
1787 char *path = NULL, *nodename = NULL;
1792 sprintf(command_errbuf, "no node name specified");
1796 if (fdt_extract_nameloc(&path, &nodename, &o) != 0)
1799 rv = fdt_add_subnode(fdtp, o, nodename);
1802 if (rv == -FDT_ERR_NOSPACE)
1803 sprintf(command_errbuf,
1804 "Device tree blob is too small!\n");
1806 sprintf(command_errbuf,
1807 "Could not add node!\n");
1814 fdt_cmd_pwd(int argc, char *argv[])
1816 char line[FDT_CWD_LEN];
1819 sprintf(line, "%s\n", cwd);
1826 fdt_cmd_mres(int argc, char *argv[])
1828 uint64_t start, size;
1833 total = fdt_num_mem_rsv(fdtp);
1835 if (pager_output("Reserved memory regions:\n"))
1837 for (i = 0; i < total; i++) {
1838 fdt_get_mem_rsv(fdtp, i, &start, &size);
1839 sprintf(line, "reg#%d: (start: 0x%jx, size: 0x%jx)\n",
1841 if (pager_output(line))
1845 pager_output("No reserved memory regions\n");
1853 fdt_cmd_nyi(int argc, char *argv[])
1856 printf("command not yet implemented\n");