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 /* Have we loaded all the needed overlays */
71 static int fdt_overlays_applied = 0;
73 static int fdt_load_dtb(vm_offset_t va);
74 static void fdt_print_overlay_load_error(int err, const char *filename);
75 static int fdt_check_overlay_compatible(void *base_fdt, void *overlay_fdt);
77 static int fdt_cmd_nyi(int argc, char *argv[]);
78 static int fdt_load_dtb_overlays_string(const char * filenames);
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";
222 COPYOUT(va, fdtp, fdtp_size);
223 debugf("DTB blob found at 0x%jx, size: 0x%jx\n", (uintmax_t)va, (uintmax_t)fdtp_size);
229 fdt_load_dtb_addr(struct fdt_header *header)
233 debugf("fdt_load_dtb_addr(%p)\n", header);
235 fdtp_size = fdt_totalsize(header);
236 err = fdt_check_header(header);
238 snprintf(command_errbuf, sizeof(command_errbuf),
239 "error validating blob: %s", fdt_strerror(err));
243 if ((fdtp = malloc(fdtp_size)) == NULL) {
244 command_errmsg = "can't allocate memory for device tree copy";
248 bcopy(header, fdtp, fdtp_size);
253 fdt_load_dtb_file(const char * filename)
255 struct preloaded_file *bfp, *oldbfp;
258 debugf("fdt_load_dtb_file(%s)\n", filename);
260 oldbfp = file_findfile(NULL, "dtb");
262 /* Attempt to load and validate a new dtb from a file. */
263 if ((bfp = file_loadraw(filename, "dtb", 1)) == NULL) {
264 snprintf(command_errbuf, sizeof(command_errbuf),
265 "failed to load file '%s'", filename);
268 if ((err = fdt_load_dtb(bfp->f_addr)) != 0) {
273 /* A new dtb was validated, discard any previous file. */
275 file_discard(oldbfp);
280 fdt_load_dtb_overlay(const char * filename)
282 struct preloaded_file *bfp;
283 struct fdt_header header;
286 debugf("fdt_load_dtb_overlay(%s)\n", filename);
288 /* Attempt to load and validate a new dtb from a file. FDT_ERR_NOTFOUND
289 * is normally a libfdt error code, but libfdt would actually return
290 * -FDT_ERR_NOTFOUND. We re-purpose the error code here to convey a
291 * similar meaning: the file itself was not found, which can still be
292 * considered an error dealing with FDT pieces.
294 if ((bfp = file_loadraw(filename, "dtbo", 1)) == NULL)
295 return (FDT_ERR_NOTFOUND);
297 COPYOUT(bfp->f_addr, &header, sizeof(header));
298 err = fdt_check_header(&header);
309 fdt_print_overlay_load_error(int err, const char *filename)
313 case FDT_ERR_NOTFOUND:
314 printf("%s: failed to load file\n", filename);
316 case -FDT_ERR_BADVERSION:
317 printf("%s: incompatible blob version: %d, should be: %d\n",
318 filename, fdt_version(fdtp),
319 FDT_LAST_SUPPORTED_VERSION);
322 /* libfdt errs are negative */
324 printf("%s: error validating blob: %s\n",
325 filename, fdt_strerror(err));
327 printf("%s: unknown load error\n", filename);
333 fdt_load_dtb_overlays_string(const char * filenames)
336 char *name, *name_ext;
340 debugf("fdt_load_dtb_overlays_string(%s)\n", filenames);
342 names = strdup(filenames);
347 comaptr = strchr(name, ',');
350 err = fdt_load_dtb_overlay(name);
351 if (err == FDT_ERR_NOTFOUND) {
352 /* Allocate enough to append ".dtbo" */
353 namesz = strlen(name) + 6;
354 name_ext = malloc(namesz);
355 if (name_ext == NULL) {
356 fdt_print_overlay_load_error(err, name);
360 snprintf(name_ext, namesz, "%s.dtbo", name);
361 err = fdt_load_dtb_overlay(name_ext);
364 /* Catch error with either initial load or fallback load */
366 fdt_print_overlay_load_error(err, name);
375 * fdt_check_overlay_compatible - check that the overlay_fdt is compatible with
376 * base_fdt before we attempt to apply it. It will need to re-calculate offsets
377 * in the base every time, rather than trying to cache them earlier in the
378 * process, because the overlay application process can/will invalidate a lot of
382 fdt_check_overlay_compatible(void *base_fdt, void *overlay_fdt)
385 int compat_len, ocompat_len;
386 int oroot_offset, root_offset;
389 oroot_offset = fdt_path_offset(overlay_fdt, "/");
390 if (oroot_offset < 0)
391 return (oroot_offset);
393 * If /compatible in the overlay does not exist or if it is empty, then
394 * we're automatically compatible. We do this for the sake of rapid
395 * overlay development for overlays that aren't intended to be deployed.
396 * The user assumes the risk of using an overlay without /compatible.
398 if (fdt_get_property(overlay_fdt, oroot_offset, "compatible",
399 &ocompat_len) == NULL || ocompat_len == 0)
401 root_offset = fdt_path_offset(base_fdt, "/");
403 return (root_offset);
405 * However, an empty or missing /compatible on the base is an error,
406 * because allowing this offers no advantages.
408 if (fdt_get_property(base_fdt, root_offset, "compatible",
409 &compat_len) == NULL)
411 else if(compat_len == 0)
415 compat = fdt_stringlist_get(overlay_fdt, oroot_offset, "compatible",
417 while (compat != NULL) {
418 if (fdt_stringlist_search(base_fdt, root_offset, "compatible",
422 compat = fdt_stringlist_get(overlay_fdt, oroot_offset,
423 "compatible", slidx, &sllen);
426 /* We've exhausted the overlay's /compatible property... no match */
431 * Returns the number of overlays successfully applied
436 struct preloaded_file *fp;
437 size_t max_overlay_size, next_fdtp_size;
438 size_t current_fdtp_size;
442 int overlays_applied, rv;
444 if ((fdtp == NULL) || (fdtp_size == 0))
447 if (fdt_overlays_applied)
450 max_overlay_size = 0;
451 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
452 if (max_overlay_size < fp->f_size)
453 max_overlay_size = fp->f_size;
456 /* Nothing to apply */
457 if (max_overlay_size == 0)
460 overlay = malloc(max_overlay_size);
461 if (overlay == NULL) {
462 printf("failed to allocate memory for DTB blob with overlays\n");
466 current_fdtp_size = fdtp_size;
467 overlays_applied = 0;
468 for (fp = file_findfile(NULL, "dtbo"); fp != NULL; fp = fp->f_next) {
469 if (strcmp(fp->f_type, "dtbo") != 0)
471 COPYOUT(fp->f_addr, overlay, fp->f_size);
472 /* Check compatible first to avoid unnecessary allocation */
473 rv = fdt_check_overlay_compatible(current_fdtp, overlay);
475 printf("DTB overlay '%s' not compatible\n", fp->f_name);
478 printf("applying DTB overlay '%s'\n", fp->f_name);
479 next_fdtp_size = current_fdtp_size + fp->f_size;
480 next_fdtp = malloc(next_fdtp_size);
481 if (next_fdtp == NULL) {
483 * Output warning, then move on to applying other
484 * overlays in case this one is simply too large.
486 printf("failed to allocate memory for overlay base\n");
489 rv = fdt_open_into(current_fdtp, next_fdtp, next_fdtp_size);
492 printf("failed to open base dtb into overlay base\n");
495 /* Both overlay and next_fdtp may be modified in place */
496 rv = fdt_overlay_apply(next_fdtp, overlay);
498 /* Rotate next -> current */
499 if (current_fdtp != fdtp)
501 current_fdtp = next_fdtp;
502 fdt_pack(current_fdtp);
503 current_fdtp_size = fdt_totalsize(current_fdtp);
507 * Assume here that the base we tried to apply on is
508 * either trashed or in an inconsistent state. Trying to
509 * load it might work, but it's better to discard it and
512 printf("failed to apply overlay: %s\n",
516 /* We could have failed to apply all overlays; then we do nothing */
517 if (current_fdtp != fdtp) {
520 fdtp_size = current_fdtp_size;
523 fdt_overlays_applied = 1;
524 return (overlays_applied);
528 fdt_pad_dtb(size_t padding)
531 size_t padded_fdtp_size;
533 padded_fdtp_size = fdtp_size + padding;
534 padded_fdtp = malloc(padded_fdtp_size);
535 if (padded_fdtp == NULL)
537 if (fdt_open_into(fdtp, padded_fdtp, padded_fdtp_size) != 0) {
542 fdtp_size = padded_fdtp_size;
559 struct preloaded_file *bfp;
562 debugf("fdt_setup_fdtp()\n");
564 /* If we already loaded a file, use it. */
565 if ((bfp = file_findfile(NULL, "dtb")) != NULL) {
566 if (fdt_load_dtb(bfp->f_addr) == 0) {
567 printf("Using DTB from loaded file '%s'.\n",
569 fdt_platform_load_overlays();
574 /* If we were given the address of a valid blob in memory, use it. */
575 if (fdt_to_load != NULL) {
576 if (fdt_load_dtb_addr(fdt_to_load) == 0) {
577 printf("Using DTB from memory address %p.\n",
579 fdt_platform_load_overlays();
584 if (fdt_platform_load_dtb() == 0) {
585 fdt_platform_load_overlays();
589 /* If there is a dtb compiled into the kernel, use it. */
590 if ((va = fdt_find_static_dtb()) != 0) {
591 if (fdt_load_dtb(va) == 0) {
592 printf("Using DTB compiled into kernel.\n");
597 command_errmsg = "No device tree blob found!\n";
601 #define fdt_strtovect(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
602 (cellbuf), (lim), (cellsize), 0);
604 /* Force using base 16 */
605 #define fdt_strtovectx(str, cellbuf, lim, cellsize) _fdt_strtovect((str), \
606 (cellbuf), (lim), (cellsize), 16);
609 _fdt_strtovect(const char *str, void *cellbuf, int lim, unsigned char cellsize,
612 const char *buf = str;
613 const char *end = str + strlen(str) - 2;
614 uint32_t *u32buf = NULL;
615 uint8_t *u8buf = NULL;
618 if (cellsize == sizeof(uint32_t))
619 u32buf = (uint32_t *)cellbuf;
621 u8buf = (uint8_t *)cellbuf;
628 /* Skip white whitespace(s)/separators */
629 while (!isxdigit(*buf) && buf < end)
634 cpu_to_fdt32((uint32_t)strtol(buf, NULL, base));
637 u8buf[cnt] = (uint8_t)strtol(buf, NULL, base);
639 if (cnt + 1 <= lim - 1)
644 /* Find another number */
645 while ((isxdigit(*buf) || *buf == 'x') && buf < end)
652 fdt_fixup_ethernet(const char *str, char *ethstr, int len)
656 /* Convert macaddr string into a vector of uints */
657 fdt_strtovectx(str, &tmp_addr, 6, sizeof(uint8_t));
658 /* Set actual property to a value from vect */
659 fdt_setprop(fdtp, fdt_path_offset(fdtp, ethstr),
660 "local-mac-address", &tmp_addr, 6 * sizeof(uint8_t));
664 fdt_fixup_cpubusfreqs(unsigned long cpufreq, unsigned long busfreq)
666 int lo, o = 0, o2, maxo = 0, depth;
667 const uint32_t zero = 0;
669 /* We want to modify every subnode of /cpus */
670 o = fdt_path_offset(fdtp, "/cpus");
674 /* maxo should contain offset of node next to /cpus */
678 maxo = fdt_next_node(fdtp, maxo, &depth);
680 /* Find CPU frequency properties */
681 o = fdt_node_offset_by_prop_value(fdtp, o, "clock-frequency",
682 &zero, sizeof(uint32_t));
684 o2 = fdt_node_offset_by_prop_value(fdtp, o, "bus-frequency", &zero,
689 while (o != -FDT_ERR_NOTFOUND && o2 != -FDT_ERR_NOTFOUND) {
691 o = fdt_node_offset_by_prop_value(fdtp, lo,
692 "clock-frequency", &zero, sizeof(uint32_t));
694 o2 = fdt_node_offset_by_prop_value(fdtp, lo, "bus-frequency",
695 &zero, sizeof(uint32_t));
697 /* We're only interested in /cpus subnode(s) */
701 fdt_setprop_inplace_cell(fdtp, lo, "clock-frequency",
704 fdt_setprop_inplace_cell(fdtp, lo, "bus-frequency",
713 fdt_reg_valid(uint32_t *reg, int len, int addr_cells, int size_cells)
715 int cells_in_tuple, i, tuples, tuple_size;
716 uint32_t cur_start, cur_size;
718 cells_in_tuple = (addr_cells + size_cells);
719 tuple_size = cells_in_tuple * sizeof(uint32_t);
720 tuples = len / tuple_size;
724 for (i = 0; i < tuples; i++) {
726 cur_start = fdt64_to_cpu(reg[i * cells_in_tuple]);
728 cur_start = fdt32_to_cpu(reg[i * cells_in_tuple]);
731 cur_size = fdt64_to_cpu(reg[i * cells_in_tuple + 2]);
733 cur_size = fdt32_to_cpu(reg[i * cells_in_tuple + 1]);
738 debugf(" reg#%d (start: 0x%0x size: 0x%0x) valid!\n",
739 i, cur_start, cur_size);
746 fdt_fixup_memory(struct fdt_mem_region *region, size_t num)
748 struct fdt_mem_region *curmr;
749 uint32_t addr_cells, size_cells;
750 uint32_t *addr_cellsp, *size_cellsp;
751 int err, i, len, memory, root;
754 uint64_t rstart, rsize;
757 root = fdt_path_offset(fdtp, "/");
759 sprintf(command_errbuf, "Could not find root node !");
763 memory = fdt_path_offset(fdtp, "/memory");
765 /* Create proper '/memory' node. */
766 memory = fdt_add_subnode(fdtp, root, "memory");
768 snprintf(command_errbuf, sizeof(command_errbuf),
769 "Could not fixup '/memory' "
770 "node, error code : %d!\n", memory);
774 err = fdt_setprop(fdtp, memory, "device_type", "memory",
781 addr_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#address-cells",
783 size_cellsp = (uint32_t *)fdt_getprop(fdtp, root, "#size-cells", NULL);
785 if (addr_cellsp == NULL || size_cellsp == NULL) {
786 snprintf(command_errbuf, sizeof(command_errbuf),
787 "Could not fixup '/memory' node : "
788 "%s %s property not found in root node!\n",
789 (!addr_cellsp) ? "#address-cells" : "",
790 (!size_cellsp) ? "#size-cells" : "");
794 addr_cells = fdt32_to_cpu(*addr_cellsp);
795 size_cells = fdt32_to_cpu(*size_cellsp);
798 * Convert memreserve data to memreserve property
799 * Check if property already exists
801 reserved = fdt_num_mem_rsv(fdtp);
803 (fdt_getprop(fdtp, root, "memreserve", NULL) == NULL)) {
804 len = (addr_cells + size_cells) * reserved * sizeof(uint32_t);
805 sb = buf = (uint8_t *)malloc(len);
811 for (i = 0; i < reserved; i++) {
812 if (fdt_get_mem_rsv(fdtp, i, &rstart, &rsize))
815 /* Ensure endianness, and put cells into a buffer */
818 cpu_to_fdt64(rstart);
821 cpu_to_fdt32(rstart);
823 buf += sizeof(uint32_t) * addr_cells;
831 buf += sizeof(uint32_t) * size_cells;
836 if ((err = fdt_setprop(fdtp, root, "memreserve", sb, len)) < 0)
837 printf("Could not fixup 'memreserve' property.\n");
842 /* Count valid memory regions entries in sysinfo. */
844 for (i = 0; i < num; i++)
845 if (region[i].start == 0 && region[i].size == 0)
849 sprintf(command_errbuf, "Could not fixup '/memory' node : "
850 "sysinfo doesn't contain valid memory regions info!\n");
854 len = (addr_cells + size_cells) * realmrno * sizeof(uint32_t);
855 sb = buf = (uint8_t *)malloc(len);
861 for (i = 0; i < num; i++) {
863 if (curmr->size != 0) {
864 /* Ensure endianness, and put cells into a buffer */
867 cpu_to_fdt64(curmr->start);
870 cpu_to_fdt32(curmr->start);
872 buf += sizeof(uint32_t) * addr_cells;
875 cpu_to_fdt64(curmr->size);
878 cpu_to_fdt32(curmr->size);
880 buf += sizeof(uint32_t) * size_cells;
885 if ((err = fdt_setprop(fdtp, memory, "reg", sb, len)) < 0)
886 sprintf(command_errbuf, "Could not fixup '/memory' node.\n");
892 fdt_fixup_stdout(const char *str)
896 const struct fdt_property *prop;
899 ptr = (char *)str + strlen(str) - 1;
900 while (ptr > str && isdigit(*(str - 1)))
906 no = fdt_path_offset(fdtp, "/chosen");
910 prop = fdt_get_property(fdtp, no, "stdout", &len);
912 /* If /chosen/stdout does not extist, create it */
913 if (prop == NULL || (prop != NULL && len == 0)) {
915 bzero(tmp, 10 * sizeof(char));
916 strcpy((char *)&tmp, "serial");
918 /* Serial number too long */
921 strncpy((char *)tmp + 6, ptr, 3);
922 sero = fdt_path_offset(fdtp, (const char *)tmp);
925 * If serial device we're trying to assign
926 * stdout to doesn't exist in DT -- return.
930 fdt_setprop(fdtp, no, "stdout", &tmp,
931 strlen((char *)&tmp) + 1);
932 fdt_setprop(fdtp, no, "stdin", &tmp,
933 strlen((char *)&tmp) + 1);
938 fdt_load_dtb_overlays(const char *extras)
942 /* Any extra overlays supplied by pre-loader environment */
943 if (extras != NULL && *extras != '\0') {
944 printf("Loading DTB overlays: '%s'\n", extras);
945 fdt_load_dtb_overlays_string(extras);
948 /* Any overlays supplied by loader environment */
949 s = getenv("fdt_overlays");
950 if (s != NULL && *s != '\0') {
951 printf("Loading DTB overlays: '%s'\n", s);
952 fdt_load_dtb_overlays_string(s);
957 * Locate the blob, fix it up and return its location.
964 debugf("fdt_fixup()\n");
966 if (fdtp == NULL && fdt_setup_fdtp() != 0)
969 /* Create /chosen node (if not exists) */
970 if ((chosen = fdt_subnode_offset(fdtp, 0, "chosen")) ==
972 chosen = fdt_add_subnode(fdtp, 0, "chosen");
974 /* Value assigned to fixup-applied does not matter. */
975 if (fdt_getprop(fdtp, chosen, "fixup-applied", NULL))
978 fdt_platform_fixups();
981 * Re-fetch the /chosen subnode; our fixups may apply overlays or add
982 * nodes/properties that invalidate the offset we grabbed or created
983 * above, so we can no longer trust it.
985 chosen = fdt_subnode_offset(fdtp, 0, "chosen");
986 fdt_setprop(fdtp, chosen, "fixup-applied", NULL, 0);
991 * Copy DTB blob to specified location and return size
994 fdt_copy(vm_offset_t va)
997 debugf("fdt_copy va 0x%08x\n", va);
999 err = fdt_setup_fdtp();
1001 printf("No valid device tree blob found!\n");
1006 if (fdt_fixup() == 0)
1009 COPYIN(fdtp, va, fdtp_size);
1016 command_fdt_internal(int argc, char *argv[])
1023 command_errmsg = "usage is 'fdt <command> [<args>]";
1028 * Validate fdt <command>.
1032 while (!(commands[i].name == NULL)) {
1033 if (strcmp(argv[1], commands[i].name) == 0) {
1035 cmdh = commands[i].handler;
1036 flags = commands[i].flags;
1042 command_errmsg = "unknown command";
1046 if (flags & CMD_REQUIRES_BLOB) {
1048 * Check if uboot env vars were parsed already. If not, do it now.
1050 if (fdt_fixup() == 0)
1055 * Call command handler.
1057 err = (*cmdh)(argc, argv);
1063 fdt_cmd_addr(int argc, char *argv[])
1065 struct preloaded_file *fp;
1066 struct fdt_header *hdr;
1075 sprintf(command_errbuf, "no address specified");
1079 hdr = (struct fdt_header *)strtoul(addr, &cp, 16);
1081 snprintf(command_errbuf, sizeof(command_errbuf),
1082 "Invalid address: %s", addr);
1086 while ((fp = file_findfile(NULL, "dtb")) != NULL) {
1095 fdt_cmd_cd(int argc, char *argv[])
1098 char tmp[FDT_CWD_LEN];
1101 path = (argc > 2) ? argv[2] : "/";
1103 if (path[0] == '/') {
1105 if (len >= FDT_CWD_LEN)
1108 /* Handle path specification relative to cwd */
1109 len = strlen(cwd) + strlen(path) + 1;
1110 if (len >= FDT_CWD_LEN)
1119 o = fdt_path_offset(fdtp, path);
1121 snprintf(command_errbuf, sizeof(command_errbuf),
1122 "could not find node: '%s'", path);
1130 snprintf(command_errbuf, sizeof(command_errbuf),
1131 "path too long: %d, max allowed: %d", len, FDT_CWD_LEN - 1);
1136 fdt_cmd_hdr(int argc __unused, char *argv[] __unused)
1142 command_errmsg = "no device tree blob pointer?!";
1146 ver = fdt_version(fdtp);
1148 sprintf(line, "\nFlattened device tree header (%p):\n", fdtp);
1149 if (pager_output(line))
1151 sprintf(line, " magic = 0x%08x\n", fdt_magic(fdtp));
1152 if (pager_output(line))
1154 sprintf(line, " size = %d\n", fdt_totalsize(fdtp));
1155 if (pager_output(line))
1157 sprintf(line, " off_dt_struct = 0x%08x\n",
1158 fdt_off_dt_struct(fdtp));
1159 if (pager_output(line))
1161 sprintf(line, " off_dt_strings = 0x%08x\n",
1162 fdt_off_dt_strings(fdtp));
1163 if (pager_output(line))
1165 sprintf(line, " off_mem_rsvmap = 0x%08x\n",
1166 fdt_off_mem_rsvmap(fdtp));
1167 if (pager_output(line))
1169 sprintf(line, " version = %d\n", ver);
1170 if (pager_output(line))
1172 sprintf(line, " last compatible version = %d\n",
1173 fdt_last_comp_version(fdtp));
1174 if (pager_output(line))
1177 sprintf(line, " boot_cpuid = %d\n",
1178 fdt_boot_cpuid_phys(fdtp));
1179 if (pager_output(line))
1183 sprintf(line, " size_dt_strings = %d\n",
1184 fdt_size_dt_strings(fdtp));
1185 if (pager_output(line))
1189 sprintf(line, " size_dt_struct = %d\n",
1190 fdt_size_dt_struct(fdtp));
1191 if (pager_output(line))
1201 fdt_cmd_ls(int argc, char *argv[])
1203 const char *prevname[FDT_MAX_DEPTH] = { NULL };
1208 path = (argc > 2) ? argv[2] : NULL;
1212 o = fdt_path_offset(fdtp, path);
1214 snprintf(command_errbuf, sizeof(command_errbuf),
1215 "could not find node: '%s'", path);
1220 (o >= 0) && (depth >= 0);
1221 o = fdt_next_node(fdtp, o, &depth)) {
1223 name = fdt_get_name(fdtp, o, NULL);
1225 if (depth > FDT_MAX_DEPTH) {
1226 printf("max depth exceeded: %d\n", depth);
1230 prevname[depth] = name;
1232 /* Skip root (i = 1) when printing devices */
1233 for (i = 1; i <= depth; i++) {
1234 if (prevname[i] == NULL)
1237 if (strcmp(cwd, "/") == 0)
1239 printf("%s", prevname[i]);
1251 return (c >= ' ' && c <= 0x7e);
1255 fdt_isprint(const void *data, int len, int *count)
1264 d = (const char *)data;
1265 if (d[len - 1] != '\0')
1270 for (i = 0; i < len; i++) {
1272 if (isprint(ch) || (ch == '\0' && i > 0)) {
1287 fdt_data_str(const void *data, int len, int count, char **buf)
1294 * Calculate the length for the string and allocate memory.
1296 * Note that 'len' already includes at least one terminator.
1301 * Each token had already a terminator buried in 'len', but we
1302 * only need one eventually, don't count space for these.
1304 buf_len -= count - 1;
1306 /* Each consecutive token requires a ", " separator. */
1307 buf_len += count * 2;
1310 /* Add some space for surrounding double quotes. */
1311 buf_len += count * 2;
1313 /* Note that string being put in 'tmp' may be as big as 'buf_len'. */
1314 b = (char *)malloc(buf_len);
1315 tmp = (char *)malloc(buf_len);
1327 * Now that we have space, format the string.
1331 d = (const char *)data + i;
1334 sprintf(tmp, "\"%s\"%s", d,
1335 (i + l) < len ? ", " : "");
1351 fdt_data_cell(const void *data, int len, char **buf)
1357 /* Number of cells */
1361 * Calculate the length for the string and allocate memory.
1364 /* Each byte translates to 2 output characters */
1367 /* Each consecutive cell requires a " " separator. */
1368 l += (count - 1) * 1;
1370 /* Each cell will have a "0x" prefix */
1372 /* Space for surrounding <> and terminator */
1375 b = (char *)malloc(l);
1376 tmp = (char *)malloc(l);
1388 for (i = 0; i < len; i += 4) {
1389 c = (const uint32_t *)((const uint8_t *)data + i);
1390 sprintf(tmp, "0x%08x%s", fdt32_to_cpu(*c),
1391 i < (len - 4) ? " " : "");
1405 fdt_data_bytes(const void *data, int len, char **buf)
1412 * Calculate the length for the string and allocate memory.
1415 /* Each byte translates to 2 output characters */
1418 /* Each consecutive byte requires a " " separator. */
1420 /* Each byte will have a "0x" prefix */
1422 /* Space for surrounding [] and terminator. */
1425 b = (char *)malloc(l);
1426 tmp = (char *)malloc(l);
1438 for (i = 0, d = data; i < len; i++) {
1439 sprintf(tmp, "0x%02x%s", d[i], i < len - 1 ? " " : "");
1453 fdt_data_fmt(const void *data, int len, char **buf)
1462 if (fdt_isprint(data, len, &count))
1463 return (fdt_data_str(data, len, count, buf));
1465 else if ((len % 4) == 0)
1466 return (fdt_data_cell(data, len, buf));
1469 return (fdt_data_bytes(data, len, buf));
1473 fdt_prop(int offset)
1476 const struct fdt_property *prop;
1482 prop = fdt_offset_ptr(fdtp, offset, sizeof(*prop));
1486 name = fdt_string(fdtp, fdt32_to_cpu(prop->nameoff));
1487 len = fdt32_to_cpu(prop->len);
1492 /* Property without value */
1493 line = (char *)malloc(strlen(name) + 2);
1498 sprintf(line, "%s\n", name);
1503 * Process property with value
1507 if (fdt_data_fmt(data, len, &buf) != 0) {
1512 line = (char *)malloc(strlen(name) + strlen(FDT_PROP_SEP) +
1515 sprintf(command_errbuf, "could not allocate space for string");
1520 sprintf(line, "%s" FDT_PROP_SEP "%s\n", name, buf);
1538 fdt_modprop(int nodeoff, char *propname, void *value, char mode)
1540 uint32_t cells[100];
1543 const struct fdt_property *p;
1545 p = fdt_get_property(fdtp, nodeoff, propname, NULL);
1549 /* Adding inexistant value in mode 1 is forbidden */
1550 sprintf(command_errbuf, "property already exists!");
1553 } else if (mode == 0) {
1554 sprintf(command_errbuf, "property does not exist!");
1566 len = fdt_strtovect(buf, (void *)&cells, 100,
1569 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1570 len * sizeof(uint32_t));
1574 len = fdt_strtovect(buf, (void *)&cells, 100,
1577 rv = fdt_setprop(fdtp, nodeoff, propname, &cells,
1578 len * sizeof(uint8_t));
1582 /* Default -- string */
1583 rv = fdt_setprop_string(fdtp, nodeoff, propname, value);
1588 if (rv == -FDT_ERR_NOSPACE)
1589 sprintf(command_errbuf,
1590 "Device tree blob is too small!\n");
1592 sprintf(command_errbuf,
1593 "Could not add/modify property!\n");
1598 /* Merge strings from argv into a single string */
1600 fdt_merge_strings(int argc, char *argv[], int start, char **buffer)
1608 for (i = start; i < argc; i++)
1609 sz += strlen(argv[i]);
1611 /* Additional bytes for whitespaces between args */
1614 buf = (char *)malloc(sizeof(char) * sz);
1616 sprintf(command_errbuf, "could not allocate space "
1620 bzero(buf, sizeof(char) * sz);
1623 for (i = start, idx = 0; i < argc; i++) {
1624 strcpy(buf + idx, argv[i]);
1625 idx += strlen(argv[i]);
1634 /* Extract offset and name of node/property from a given path */
1636 fdt_extract_nameloc(char **pathp, char **namep, int *nodeoff)
1639 char *path = *pathp, *name = NULL, *subpath = NULL;
1641 subpath = strrchr(path, '/');
1642 if (subpath == NULL) {
1643 o = fdt_path_offset(fdtp, cwd);
1645 path = (char *)&cwd;
1648 if (strlen(path) == 0)
1652 o = fdt_path_offset(fdtp, path);
1655 if (strlen(name) == 0) {
1656 sprintf(command_errbuf, "name not specified");
1660 snprintf(command_errbuf, sizeof(command_errbuf),
1661 "could not find node: '%s'", path);
1671 fdt_cmd_prop(int argc, char *argv[])
1673 char *path, *propname, *value;
1674 int o, next, depth, rv;
1677 path = (argc > 2) ? argv[2] : NULL;
1682 /* Merge property value strings into one */
1683 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1694 /* If value is specified -- try to modify prop. */
1695 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1698 rv = fdt_modprop(o, propname, value, 0);
1704 /* User wants to display properties */
1705 o = fdt_path_offset(fdtp, path);
1708 snprintf(command_errbuf, sizeof(command_errbuf),
1709 "could not find node: '%s'", path);
1715 while (depth >= 0) {
1716 tag = fdt_next_tag(fdtp, o, &next);
1722 /* Don't process properties of nested nodes */
1725 if (fdt_prop(o) != 0) {
1726 sprintf(command_errbuf, "could not process "
1732 case FDT_BEGIN_NODE:
1734 if (depth > FDT_MAX_DEPTH) {
1735 printf("warning: nesting too deep: %d\n",
1744 * This is the end of our starting node, force
1757 fdt_cmd_mkprop(int argc, char *argv[])
1760 char *path, *propname, *value;
1762 path = (argc > 2) ? argv[2] : NULL;
1767 /* Merge property value strings into one */
1768 if (fdt_merge_strings(argc, argv, 3, &value) != 0)
1773 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1776 if (fdt_modprop(o, propname, value, 1))
1783 fdt_cmd_rm(int argc, char *argv[])
1786 char *path = NULL, *propname;
1791 sprintf(command_errbuf, "no node/property name specified");
1795 o = fdt_path_offset(fdtp, path);
1797 /* If node not found -- try to find & delete property */
1798 if (fdt_extract_nameloc(&path, &propname, &o) != 0)
1801 if ((rv = fdt_delprop(fdtp, o, propname)) != 0) {
1802 snprintf(command_errbuf, sizeof(command_errbuf),
1803 "could not delete %s\n",
1804 (rv == -FDT_ERR_NOTFOUND) ?
1805 "(property/node does not exist)" : "");
1811 /* If node exists -- remove node */
1812 rv = fdt_del_node(fdtp, o);
1814 sprintf(command_errbuf, "could not delete node");
1821 fdt_cmd_mknode(int argc, char *argv[])
1824 char *path = NULL, *nodename = NULL;
1829 sprintf(command_errbuf, "no node name specified");
1833 if (fdt_extract_nameloc(&path, &nodename, &o) != 0)
1836 rv = fdt_add_subnode(fdtp, o, nodename);
1839 if (rv == -FDT_ERR_NOSPACE)
1840 sprintf(command_errbuf,
1841 "Device tree blob is too small!\n");
1843 sprintf(command_errbuf,
1844 "Could not add node!\n");
1851 fdt_cmd_pwd(int argc, char *argv[])
1853 char line[FDT_CWD_LEN];
1856 sprintf(line, "%s\n", cwd);
1863 fdt_cmd_mres(int argc, char *argv[])
1865 uint64_t start, size;
1870 total = fdt_num_mem_rsv(fdtp);
1872 if (pager_output("Reserved memory regions:\n"))
1874 for (i = 0; i < total; i++) {
1875 fdt_get_mem_rsv(fdtp, i, &start, &size);
1876 sprintf(line, "reg#%d: (start: 0x%jx, size: 0x%jx)\n",
1878 if (pager_output(line))
1882 pager_output("No reserved memory regions\n");
1890 fdt_cmd_nyi(int argc, char *argv[])
1893 printf("command not yet implemented\n");
1898 fdt_devmatch_next(int *tag, int *compatlen)
1900 const struct fdt_property *p;
1901 const struct fdt_property *status;
1903 static int depth = 0;
1907 fdt_apply_overlays();
1912 /* We are at the end of the DTB */
1916 o = fdt_path_offset(fdtp, "/");
1918 printf("Can't find dtb\n");
1924 /* Find the next node with a compatible property */
1927 if (o >= 0 && depth >= 0) {
1928 /* skip disabled nodes */
1929 status = fdt_get_property(fdtp, o, "status", &len);
1931 if (strcmp(status->data, "disabled") == 0) {
1932 o = fdt_next_node(fdtp, o, &depth);
1933 if (o < 0) /* End of tree */
1939 p = fdt_get_property(fdtp, o, "compatible", &len);
1943 o = fdt_next_node(fdtp, o, &depth);
1944 if (o < 0) /* End of tree */
1948 /* Prepare next node for next call */
1949 o = fdt_next_node(fdtp, o, &depth);