Merge tag 'clk-2023.01' of https://source.denx.de/u-boot/custodians/u-boot-clk
[platform/kernel/u-boot.git] / cmd / fdt.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2007
4  * Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com
5  * Based on code written by:
6  *   Pantelis Antoniou <pantelis.antoniou@gmail.com> and
7  *   Matthew McClintock <msm@freescale.com>
8  */
9
10 #include <common.h>
11 #include <command.h>
12 #include <env.h>
13 #include <image.h>
14 #include <linux/ctype.h>
15 #include <linux/types.h>
16 #include <asm/global_data.h>
17 #include <linux/libfdt.h>
18 #include <fdt_support.h>
19 #include <mapmem.h>
20 #include <asm/io.h>
21
22 #define MAX_LEVEL       32              /* how deeply nested we will go */
23 #define SCRATCHPAD      1024            /* bytes of scratchpad memory */
24
25 /*
26  * Global data (for the gd->bd)
27  */
28 DECLARE_GLOBAL_DATA_PTR;
29
30 static int fdt_parse_prop(char *const*newval, int count, char *data, int *len);
31 static int fdt_print(const char *pathp, char *prop, int depth);
32 static int is_printable_string(const void *data, int len);
33
34 /*
35  * The working_fdt points to our working flattened device tree.
36  */
37 struct fdt_header *working_fdt;
38
39 void set_working_fdt_addr(ulong addr)
40 {
41         void *buf;
42
43         printf("Working FDT set to %lx\n", addr);
44         buf = map_sysmem(addr, 0);
45         working_fdt = buf;
46         env_set_hex("fdtaddr", addr);
47 }
48
49 /*
50  * Get a value from the fdt and format it to be set in the environment
51  */
52 static int fdt_value_env_set(const void *nodep, int len,
53                              const char *var, int index)
54 {
55         if (is_printable_string(nodep, len)) {
56                 const char *nodec = (const char *)nodep;
57                 int i;
58
59                 /*
60                  * Iterate over all members in stringlist and find the one at
61                  * offset $index. If no such index exists, indicate failure.
62                  */
63                 for (i = 0; i < len; i += strlen(nodec) + 1) {
64                         if (index-- > 0)
65                                 continue;
66
67                         env_set(var, nodec + i);
68                         return 0;
69                 }
70
71                 return 1;
72         } else if (len == 4) {
73                 char buf[11];
74
75                 sprintf(buf, "0x%08X", fdt32_to_cpu(*(fdt32_t *)nodep));
76                 env_set(var, buf);
77         } else if (len%4 == 0 && len <= 20) {
78                 /* Needed to print things like sha1 hashes. */
79                 char buf[41];
80                 int i;
81
82                 for (i = 0; i < len; i += sizeof(unsigned int))
83                         sprintf(buf + (i * 2), "%08x",
84                                 *(unsigned int *)(nodep + i));
85                 env_set(var, buf);
86         } else {
87                 printf("error: unprintable value\n");
88                 return 1;
89         }
90         return 0;
91 }
92
93 static const char * const fdt_member_table[] = {
94         "magic",
95         "totalsize",
96         "off_dt_struct",
97         "off_dt_strings",
98         "off_mem_rsvmap",
99         "version",
100         "last_comp_version",
101         "boot_cpuid_phys",
102         "size_dt_strings",
103         "size_dt_struct",
104 };
105
106 static int fdt_get_header_value(int argc, char *const argv[])
107 {
108         fdt32_t *fdtp = (fdt32_t *)working_fdt;
109         ulong val;
110         int i;
111
112         if (argv[2][0] != 'g')
113                 return CMD_RET_FAILURE;
114
115         for (i = 0; i < ARRAY_SIZE(fdt_member_table); i++) {
116                 if (strcmp(fdt_member_table[i], argv[4]))
117                         continue;
118
119                 val = fdt32_to_cpu(fdtp[i]);
120                 env_set_hex(argv[3], val);
121                 return CMD_RET_SUCCESS;
122         }
123
124         return CMD_RET_FAILURE;
125 }
126
127 /*
128  * Flattened Device Tree command, see the help for parameter definitions.
129  */
130 static int do_fdt(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
131 {
132         if (argc < 2)
133                 return CMD_RET_USAGE;
134
135         /* fdt addr: Set the address of the fdt */
136         if (strncmp(argv[1], "ad", 2) == 0) {
137                 unsigned long addr;
138                 int control = 0;
139                 int quiet = 0;
140                 struct fdt_header *blob;
141
142                 /* Set the address [and length] of the fdt */
143                 argc -= 2;
144                 argv += 2;
145                 while (argc > 0 && **argv == '-') {
146                         char *arg = *argv;
147
148                         while (*++arg) {
149                                 switch (*arg) {
150                                 case 'c':
151                                         control = 1;
152                                         break;
153                                 case 'q':
154                                         quiet = 1;
155                                         break;
156                                 default:
157                                         return CMD_RET_USAGE;
158                                 }
159                         }
160                         argc--;
161                         argv++;
162                 }
163                 if (argc == 0) {
164                         if (control)
165                                 blob = (struct fdt_header *)gd->fdt_blob;
166                         else
167                                 blob = working_fdt;
168                         if (!blob || !fdt_valid(&blob))
169                                 return 1;
170                         printf("%s fdt: %08lx\n",
171                                control ? "Control" : "Working",
172                                control ? (ulong)map_to_sysmem(blob) :
173                                env_get_hex("fdtaddr", 0));
174                         return 0;
175                 }
176
177                 addr = hextoul(argv[0], NULL);
178                 blob = map_sysmem(addr, 0);
179                 if ((quiet && fdt_check_header(blob)) ||
180                     (!quiet && !fdt_valid(&blob)))
181                         return 1;
182                 if (control)
183                         gd->fdt_blob = blob;
184                 else
185                         set_working_fdt_addr(addr);
186
187                 if (argc >= 2) {
188                         int  len;
189                         int  err;
190
191                         /* Optional new length */
192                         len = hextoul(argv[1], NULL);
193                         if (len < fdt_totalsize(blob)) {
194                                 if (!quiet)
195                                         printf("New length %d < existing length %d, ignoring\n",
196                                                len, fdt_totalsize(blob));
197                         } else {
198                                 /* Open in place with a new length */
199                                 err = fdt_open_into(blob, blob, len);
200                                 if (!quiet && err != 0) {
201                                         printf("libfdt fdt_open_into(): %s\n",
202                                                fdt_strerror(err));
203                                 }
204                         }
205                 }
206
207                 return CMD_RET_SUCCESS;
208         }
209
210         if (!working_fdt) {
211                 puts("No FDT memory address configured. Please configure\n"
212                      "the FDT address via \"fdt addr <address>\" command.\n"
213                      "Aborting!\n");
214                 return CMD_RET_FAILURE;
215         }
216
217         /*
218          * Move the working_fdt
219          */
220         if (strncmp(argv[1], "mo", 2) == 0) {
221                 struct fdt_header *newaddr;
222                 int  len;
223                 int  err;
224
225                 if (argc < 4)
226                         return CMD_RET_USAGE;
227
228                 /*
229                  * Set the address and length of the fdt.
230                  */
231                 working_fdt = (struct fdt_header *)hextoul(argv[2], NULL);
232                 if (!fdt_valid(&working_fdt))
233                         return 1;
234
235                 newaddr = (struct fdt_header *)hextoul(argv[3], NULL);
236
237                 /*
238                  * If the user specifies a length, use that.  Otherwise use the
239                  * current length.
240                  */
241                 if (argc <= 4) {
242                         len = fdt_totalsize(working_fdt);
243                 } else {
244                         len = hextoul(argv[4], NULL);
245                         if (len < fdt_totalsize(working_fdt)) {
246                                 printf ("New length 0x%X < existing length "
247                                         "0x%X, aborting.\n",
248                                         len, fdt_totalsize(working_fdt));
249                                 return 1;
250                         }
251                 }
252
253                 /*
254                  * Copy to the new location.
255                  */
256                 err = fdt_open_into(working_fdt, newaddr, len);
257                 if (err != 0) {
258                         printf ("libfdt fdt_open_into(): %s\n",
259                                 fdt_strerror(err));
260                         return 1;
261                 }
262                 set_working_fdt_addr((ulong)newaddr);
263 #ifdef CONFIG_OF_SYSTEM_SETUP
264         /* Call the board-specific fixup routine */
265         } else if (strncmp(argv[1], "sys", 3) == 0) {
266                 int err = ft_system_setup(working_fdt, gd->bd);
267
268                 if (err) {
269                         printf("Failed to add system information to FDT: %s\n",
270                                fdt_strerror(err));
271                         return CMD_RET_FAILURE;
272                 }
273 #endif
274         /*
275          * Make a new node
276          */
277         } else if (strncmp(argv[1], "mk", 2) == 0) {
278                 char *pathp;            /* path */
279                 char *nodep;            /* new node to add */
280                 int  nodeoffset;        /* node offset from libfdt */
281                 int  err;
282
283                 /*
284                  * Parameters: Node path, new node to be appended to the path.
285                  */
286                 if (argc < 4)
287                         return CMD_RET_USAGE;
288
289                 pathp = argv[2];
290                 nodep = argv[3];
291
292                 nodeoffset = fdt_path_offset (working_fdt, pathp);
293                 if (nodeoffset < 0) {
294                         /*
295                          * Not found or something else bad happened.
296                          */
297                         printf ("libfdt fdt_path_offset() returned %s\n",
298                                 fdt_strerror(nodeoffset));
299                         return 1;
300                 }
301                 err = fdt_add_subnode(working_fdt, nodeoffset, nodep);
302                 if (err < 0) {
303                         printf ("libfdt fdt_add_subnode(): %s\n",
304                                 fdt_strerror(err));
305                         return 1;
306                 }
307
308         /*
309          * Set the value of a property in the working_fdt.
310          */
311         } else if (strncmp(argv[1], "se", 2) == 0) {
312                 char *pathp;            /* path */
313                 char *prop;             /* property */
314                 int  nodeoffset;        /* node offset from libfdt */
315                 static char data[SCRATCHPAD] __aligned(4);/* property storage */
316                 const void *ptmp;
317                 int  len;               /* new length of the property */
318                 int  ret;               /* return value */
319
320                 /*
321                  * Parameters: Node path, property, optional value.
322                  */
323                 if (argc < 4)
324                         return CMD_RET_USAGE;
325
326                 pathp  = argv[2];
327                 prop   = argv[3];
328
329                 nodeoffset = fdt_path_offset (working_fdt, pathp);
330                 if (nodeoffset < 0) {
331                         /*
332                          * Not found or something else bad happened.
333                          */
334                         printf ("libfdt fdt_path_offset() returned %s\n",
335                                 fdt_strerror(nodeoffset));
336                         return 1;
337                 }
338
339                 if (argc == 4) {
340                         len = 0;
341                 } else {
342                         ptmp = fdt_getprop(working_fdt, nodeoffset, prop, &len);
343                         if (len > SCRATCHPAD) {
344                                 printf("prop (%d) doesn't fit in scratchpad!\n",
345                                        len);
346                                 return 1;
347                         }
348                         if (ptmp != NULL)
349                                 memcpy(data, ptmp, len);
350
351                         ret = fdt_parse_prop(&argv[4], argc - 4, data, &len);
352                         if (ret != 0)
353                                 return ret;
354                 }
355
356                 ret = fdt_setprop(working_fdt, nodeoffset, prop, data, len);
357                 if (ret < 0) {
358                         printf ("libfdt fdt_setprop(): %s\n", fdt_strerror(ret));
359                         return 1;
360                 }
361
362         /********************************************************************
363          * Get the value of a property in the working_fdt.
364          ********************************************************************/
365         } else if (argv[1][0] == 'g') {
366                 char *subcmd;           /* sub-command */
367                 char *pathp;            /* path */
368                 char *prop;             /* property */
369                 char *var;              /* variable to store result */
370                 int  nodeoffset;        /* node offset from libfdt */
371                 const void *nodep;      /* property node pointer */
372                 int  len = 0;           /* new length of the property */
373
374                 /*
375                  * Parameters: Node path, property, optional value.
376                  */
377                 if (argc < 5)
378                         return CMD_RET_USAGE;
379
380                 subcmd = argv[2];
381
382                 if (argc < 6 && subcmd[0] != 's')
383                         return CMD_RET_USAGE;
384
385                 var    = argv[3];
386                 pathp  = argv[4];
387                 prop   = argv[5];
388
389                 nodeoffset = fdt_path_offset(working_fdt, pathp);
390                 if (nodeoffset < 0) {
391                         /*
392                          * Not found or something else bad happened.
393                          */
394                         printf("libfdt fdt_path_offset() returned %s\n",
395                                 fdt_strerror(nodeoffset));
396                         return 1;
397                 }
398
399                 if (subcmd[0] == 'n' || (subcmd[0] == 's' && argc == 5)) {
400                         int req_index = -1;
401                         int startDepth = fdt_node_depth(
402                                 working_fdt, nodeoffset);
403                         int curDepth = startDepth;
404                         int cur_index = -1;
405                         int nextNodeOffset = fdt_next_node(
406                                 working_fdt, nodeoffset, &curDepth);
407
408                         if (subcmd[0] == 'n')
409                                 req_index = hextoul(argv[5], NULL);
410
411                         while (curDepth > startDepth) {
412                                 if (curDepth == startDepth + 1)
413                                         cur_index++;
414                                 if (subcmd[0] == 'n' &&
415                                     cur_index == req_index) {
416                                         const char *node_name;
417
418                                         node_name = fdt_get_name(working_fdt,
419                                                                  nextNodeOffset,
420                                                                  NULL);
421                                         env_set(var, node_name);
422                                         return 0;
423                                 }
424                                 nextNodeOffset = fdt_next_node(
425                                         working_fdt, nextNodeOffset, &curDepth);
426                                 if (nextNodeOffset < 0)
427                                         break;
428                         }
429                         if (subcmd[0] == 's') {
430                                 /* get the num nodes at this level */
431                                 env_set_ulong(var, cur_index + 1);
432                         } else {
433                                 /* node index not found */
434                                 printf("libfdt node not found\n");
435                                 return 1;
436                         }
437                 } else {
438                         nodep = fdt_getprop(
439                                 working_fdt, nodeoffset, prop, &len);
440                         if (len == 0) {
441                                 /* no property value */
442                                 env_set(var, "");
443                                 return 0;
444                         } else if (nodep && len > 0) {
445                                 if (subcmd[0] == 'v') {
446                                         int index = 0;
447                                         int ret;
448
449                                         if (argc == 7)
450                                                 index = simple_strtoul(argv[6], NULL, 10);
451
452                                         ret = fdt_value_env_set(nodep, len,
453                                                                 var, index);
454                                         if (ret != 0)
455                                                 return ret;
456                                 } else if (subcmd[0] == 'a') {
457                                         /* Get address */
458                                         char buf[11];
459
460                                         sprintf(buf, "0x%p", nodep);
461                                         env_set(var, buf);
462                                 } else if (subcmd[0] == 's') {
463                                         /* Get size */
464                                         char buf[11];
465
466                                         sprintf(buf, "0x%08X", len);
467                                         env_set(var, buf);
468                                 } else
469                                         return CMD_RET_USAGE;
470                                 return 0;
471                         } else {
472                                 printf("libfdt fdt_getprop(): %s\n",
473                                         fdt_strerror(len));
474                                 return 1;
475                         }
476                 }
477
478         /*
479          * Print (recursive) / List (single level)
480          */
481         } else if ((argv[1][0] == 'p') || (argv[1][0] == 'l')) {
482                 int depth = MAX_LEVEL;  /* how deep to print */
483                 char *pathp;            /* path */
484                 char *prop;             /* property */
485                 int  ret;               /* return value */
486                 static char root[2] = "/";
487
488                 /*
489                  * list is an alias for print, but limited to 1 level
490                  */
491                 if (argv[1][0] == 'l') {
492                         depth = 1;
493                 }
494
495                 /*
496                  * Get the starting path.  The root node is an oddball,
497                  * the offset is zero and has no name.
498                  */
499                 if (argc == 2)
500                         pathp = root;
501                 else
502                         pathp = argv[2];
503                 if (argc > 3)
504                         prop = argv[3];
505                 else
506                         prop = NULL;
507
508                 ret = fdt_print(pathp, prop, depth);
509                 if (ret != 0)
510                         return ret;
511
512         /*
513          * Remove a property/node
514          */
515         } else if (strncmp(argv[1], "rm", 2) == 0) {
516                 int  nodeoffset;        /* node offset from libfdt */
517                 int  err;
518
519                 /*
520                  * Get the path.  The root node is an oddball, the offset
521                  * is zero and has no name.
522                  */
523                 nodeoffset = fdt_path_offset (working_fdt, argv[2]);
524                 if (nodeoffset < 0) {
525                         /*
526                          * Not found or something else bad happened.
527                          */
528                         printf ("libfdt fdt_path_offset() returned %s\n",
529                                 fdt_strerror(nodeoffset));
530                         return 1;
531                 }
532                 /*
533                  * Do the delete.  A fourth parameter means delete a property,
534                  * otherwise delete the node.
535                  */
536                 if (argc > 3) {
537                         err = fdt_delprop(working_fdt, nodeoffset, argv[3]);
538                         if (err < 0) {
539                                 printf("libfdt fdt_delprop():  %s\n",
540                                         fdt_strerror(err));
541                                 return err;
542                         }
543                 } else {
544                         err = fdt_del_node(working_fdt, nodeoffset);
545                         if (err < 0) {
546                                 printf("libfdt fdt_del_node():  %s\n",
547                                         fdt_strerror(err));
548                                 return err;
549                         }
550                 }
551
552         /*
553          * Display header info
554          */
555         } else if (argv[1][0] == 'h') {
556                 if (argc == 5)
557                         return fdt_get_header_value(argc, argv);
558
559                 u32 version = fdt_version(working_fdt);
560                 printf("magic:\t\t\t0x%x\n", fdt_magic(working_fdt));
561                 printf("totalsize:\t\t0x%x (%d)\n", fdt_totalsize(working_fdt),
562                        fdt_totalsize(working_fdt));
563                 printf("off_dt_struct:\t\t0x%x\n",
564                        fdt_off_dt_struct(working_fdt));
565                 printf("off_dt_strings:\t\t0x%x\n",
566                        fdt_off_dt_strings(working_fdt));
567                 printf("off_mem_rsvmap:\t\t0x%x\n",
568                        fdt_off_mem_rsvmap(working_fdt));
569                 printf("version:\t\t%d\n", version);
570                 printf("last_comp_version:\t%d\n",
571                        fdt_last_comp_version(working_fdt));
572                 if (version >= 2)
573                         printf("boot_cpuid_phys:\t0x%x\n",
574                                 fdt_boot_cpuid_phys(working_fdt));
575                 if (version >= 3)
576                         printf("size_dt_strings:\t0x%x\n",
577                                 fdt_size_dt_strings(working_fdt));
578                 if (version >= 17)
579                         printf("size_dt_struct:\t\t0x%x\n",
580                                 fdt_size_dt_struct(working_fdt));
581                 printf("number mem_rsv:\t\t0x%x\n",
582                        fdt_num_mem_rsv(working_fdt));
583                 printf("\n");
584
585         /*
586          * Set boot cpu id
587          */
588         } else if (strncmp(argv[1], "boo", 3) == 0) {
589                 unsigned long tmp = hextoul(argv[2], NULL);
590                 fdt_set_boot_cpuid_phys(working_fdt, tmp);
591
592         /*
593          * memory command
594          */
595         } else if (strncmp(argv[1], "me", 2) == 0) {
596                 uint64_t addr, size;
597                 int err;
598                 addr = simple_strtoull(argv[2], NULL, 16);
599                 size = simple_strtoull(argv[3], NULL, 16);
600                 err = fdt_fixup_memory(working_fdt, addr, size);
601                 if (err < 0)
602                         return err;
603
604         /*
605          * mem reserve commands
606          */
607         } else if (strncmp(argv[1], "rs", 2) == 0) {
608                 if (argv[2][0] == 'p') {
609                         uint64_t addr, size;
610                         int total = fdt_num_mem_rsv(working_fdt);
611                         int j, err;
612                         printf("index\t\t   start\t\t    size\n");
613                         printf("-------------------------------"
614                                 "-----------------\n");
615                         for (j = 0; j < total; j++) {
616                                 err = fdt_get_mem_rsv(working_fdt, j, &addr, &size);
617                                 if (err < 0) {
618                                         printf("libfdt fdt_get_mem_rsv():  %s\n",
619                                                         fdt_strerror(err));
620                                         return err;
621                                 }
622                                 printf("    %x\t%08x%08x\t%08x%08x\n", j,
623                                         (u32)(addr >> 32),
624                                         (u32)(addr & 0xffffffff),
625                                         (u32)(size >> 32),
626                                         (u32)(size & 0xffffffff));
627                         }
628                 } else if (argv[2][0] == 'a') {
629                         uint64_t addr, size;
630                         int err;
631                         addr = simple_strtoull(argv[3], NULL, 16);
632                         size = simple_strtoull(argv[4], NULL, 16);
633                         err = fdt_add_mem_rsv(working_fdt, addr, size);
634
635                         if (err < 0) {
636                                 printf("libfdt fdt_add_mem_rsv():  %s\n",
637                                         fdt_strerror(err));
638                                 return err;
639                         }
640                 } else if (argv[2][0] == 'd') {
641                         unsigned long idx = hextoul(argv[3], NULL);
642                         int err = fdt_del_mem_rsv(working_fdt, idx);
643
644                         if (err < 0) {
645                                 printf("libfdt fdt_del_mem_rsv():  %s\n",
646                                         fdt_strerror(err));
647                                 return err;
648                         }
649                 } else {
650                         /* Unrecognized command */
651                         return CMD_RET_USAGE;
652                 }
653         }
654 #ifdef CONFIG_OF_BOARD_SETUP
655         /* Call the board-specific fixup routine */
656         else if (strncmp(argv[1], "boa", 3) == 0) {
657                 int err = ft_board_setup(working_fdt, gd->bd);
658
659                 if (err) {
660                         printf("Failed to update board information in FDT: %s\n",
661                                fdt_strerror(err));
662                         return CMD_RET_FAILURE;
663                 }
664 #ifdef CONFIG_ARCH_KEYSTONE
665                 ft_board_setup_ex(working_fdt, gd->bd);
666 #endif
667         }
668 #endif
669         /* Create a chosen node */
670         else if (strncmp(argv[1], "cho", 3) == 0) {
671                 unsigned long initrd_start = 0, initrd_end = 0;
672
673                 if ((argc != 2) && (argc != 4))
674                         return CMD_RET_USAGE;
675
676                 if (argc == 4) {
677                         initrd_start = hextoul(argv[2], NULL);
678                         initrd_end = initrd_start + hextoul(argv[3], NULL) - 1;
679                 }
680
681                 fdt_chosen(working_fdt);
682                 fdt_initrd(working_fdt, initrd_start, initrd_end);
683
684 #if defined(CONFIG_FIT_SIGNATURE)
685         } else if (strncmp(argv[1], "che", 3) == 0) {
686                 int cfg_noffset;
687                 int ret;
688                 unsigned long addr;
689                 struct fdt_header *blob;
690
691                 if (!working_fdt)
692                         return CMD_RET_FAILURE;
693
694                 if (argc > 2) {
695                         addr = hextoul(argv[2], NULL);
696                         blob = map_sysmem(addr, 0);
697                 } else {
698                         blob = (struct fdt_header *)gd->fdt_blob;
699                 }
700                 if (!fdt_valid(&blob))
701                         return 1;
702
703                 gd->fdt_blob = blob;
704                 cfg_noffset = fit_conf_get_node(working_fdt, NULL);
705                 if (!cfg_noffset) {
706                         printf("Could not find configuration node: %s\n",
707                                fdt_strerror(cfg_noffset));
708                         return CMD_RET_FAILURE;
709                 }
710
711                 ret = fit_config_verify(working_fdt, cfg_noffset);
712                 if (ret == 0)
713                         return CMD_RET_SUCCESS;
714                 else
715                         return CMD_RET_FAILURE;
716 #endif
717
718         }
719 #ifdef CONFIG_OF_LIBFDT_OVERLAY
720         /* apply an overlay */
721         else if (strncmp(argv[1], "ap", 2) == 0) {
722                 unsigned long addr;
723                 struct fdt_header *blob;
724                 int ret;
725
726                 if (argc != 3)
727                         return CMD_RET_USAGE;
728
729                 if (!working_fdt)
730                         return CMD_RET_FAILURE;
731
732                 addr = hextoul(argv[2], NULL);
733                 blob = map_sysmem(addr, 0);
734                 if (!fdt_valid(&blob))
735                         return CMD_RET_FAILURE;
736
737                 /* apply method prints messages on error */
738                 ret = fdt_overlay_apply_verbose(working_fdt, blob);
739                 if (ret)
740                         return CMD_RET_FAILURE;
741         }
742 #endif
743         /* resize the fdt */
744         else if (strncmp(argv[1], "re", 2) == 0) {
745                 uint extrasize;
746                 if (argc > 2)
747                         extrasize = hextoul(argv[2], NULL);
748                 else
749                         extrasize = 0;
750                 fdt_shrink_to_minimum(working_fdt, extrasize);
751         }
752         else {
753                 /* Unrecognized command */
754                 return CMD_RET_USAGE;
755         }
756
757         return 0;
758 }
759
760 /****************************************************************************/
761
762 /*
763  * Parse the user's input, partially heuristic.  Valid formats:
764  * <0x00112233 4 05>    - an array of cells.  Numbers follow standard
765  *                      C conventions.
766  * [00 11 22 .. nn] - byte stream
767  * "string"     - If the the value doesn't start with "<" or "[", it is
768  *                      treated as a string.  Note that the quotes are
769  *                      stripped by the parser before we get the string.
770  * newval: An array of strings containing the new property as specified
771  *      on the command line
772  * count: The number of strings in the array
773  * data: A bytestream to be placed in the property
774  * len: The length of the resulting bytestream
775  */
776 static int fdt_parse_prop(char * const *newval, int count, char *data, int *len)
777 {
778         char *cp;               /* temporary char pointer */
779         char *newp;             /* temporary newval char pointer */
780         unsigned long tmp;      /* holds converted values */
781         int stridx = 0;
782
783         *len = 0;
784         newp = newval[0];
785
786         /* An array of cells */
787         if (*newp == '<') {
788                 newp++;
789                 while ((*newp != '>') && (stridx < count)) {
790                         /*
791                          * Keep searching until we find that last ">"
792                          * That way users don't have to escape the spaces
793                          */
794                         if (*newp == '\0') {
795                                 newp = newval[++stridx];
796                                 continue;
797                         }
798
799                         cp = newp;
800                         tmp = simple_strtoul(cp, &newp, 0);
801                         if (*cp != '?')
802                                 *(fdt32_t *)data = cpu_to_fdt32(tmp);
803                         else
804                                 newp++;
805
806                         data  += 4;
807                         *len += 4;
808
809                         /* If the ptr didn't advance, something went wrong */
810                         if ((newp - cp) <= 0) {
811                                 printf("Sorry, I could not convert \"%s\"\n",
812                                         cp);
813                                 return 1;
814                         }
815
816                         while (*newp == ' ')
817                                 newp++;
818                 }
819
820                 if (*newp != '>') {
821                         printf("Unexpected character '%c'\n", *newp);
822                         return 1;
823                 }
824         } else if (*newp == '[') {
825                 /*
826                  * Byte stream.  Convert the values.
827                  */
828                 newp++;
829                 while ((stridx < count) && (*newp != ']')) {
830                         while (*newp == ' ')
831                                 newp++;
832                         if (*newp == '\0') {
833                                 newp = newval[++stridx];
834                                 continue;
835                         }
836                         if (!isxdigit(*newp))
837                                 break;
838                         tmp = hextoul(newp, &newp);
839                         *data++ = tmp & 0xFF;
840                         *len    = *len + 1;
841                 }
842                 if (*newp != ']') {
843                         printf("Unexpected character '%c'\n", *newp);
844                         return 1;
845                 }
846         } else {
847                 /*
848                  * Assume it is one or more strings.  Copy it into our
849                  * data area for convenience (including the
850                  * terminating '\0's).
851                  */
852                 while (stridx < count) {
853                         size_t length = strlen(newp) + 1;
854                         strcpy(data, newp);
855                         data += length;
856                         *len += length;
857                         newp = newval[++stridx];
858                 }
859         }
860         return 0;
861 }
862
863 /****************************************************************************/
864
865 /*
866  * Heuristic to guess if this is a string or concatenated strings.
867  */
868
869 static int is_printable_string(const void *data, int len)
870 {
871         const char *s = data;
872
873         /* zero length is not */
874         if (len == 0)
875                 return 0;
876
877         /* must terminate with zero or '\n' */
878         if (s[len - 1] != '\0' && s[len - 1] != '\n')
879                 return 0;
880
881         /* printable or a null byte (concatenated strings) */
882         while (((*s == '\0') || isprint(*s) || isspace(*s)) && (len > 0)) {
883                 /*
884                  * If we see a null, there are three possibilities:
885                  * 1) If len == 1, it is the end of the string, printable
886                  * 2) Next character also a null, not printable.
887                  * 3) Next character not a null, continue to check.
888                  */
889                 if (s[0] == '\0') {
890                         if (len == 1)
891                                 return 1;
892                         if (s[1] == '\0')
893                                 return 0;
894                 }
895                 s++;
896                 len--;
897         }
898
899         /* Not the null termination, or not done yet: not printable */
900         if (*s != '\0' || (len != 0))
901                 return 0;
902
903         return 1;
904 }
905
906
907 /*
908  * Print the property in the best format, a heuristic guess.  Print as
909  * a string, concatenated strings, a byte, word, double word, or (if all
910  * else fails) it is printed as a stream of bytes.
911  */
912 static void print_data(const void *data, int len)
913 {
914         int j;
915         const char *env_max_dump;
916         ulong max_dump = ULONG_MAX;
917
918         /* no data, don't print */
919         if (len == 0)
920                 return;
921
922         env_max_dump = env_get("fdt_max_dump");
923         if (env_max_dump)
924                 max_dump = hextoul(env_max_dump, NULL);
925
926         /*
927          * It is a string, but it may have multiple strings (embedded '\0's).
928          */
929         if (is_printable_string(data, len)) {
930                 puts("\"");
931                 j = 0;
932                 while (j < len) {
933                         if (j > 0)
934                                 puts("\", \"");
935                         puts(data);
936                         j    += strlen(data) + 1;
937                         data += strlen(data) + 1;
938                 }
939                 puts("\"");
940                 return;
941         }
942
943         if ((len %4) == 0) {
944                 if (len > max_dump)
945                         printf("* 0x%p [0x%08x]", data, len);
946                 else {
947                         const __be32 *p;
948
949                         printf("<");
950                         for (j = 0, p = data; j < len/4; j++)
951                                 printf("0x%08x%s", fdt32_to_cpu(p[j]),
952                                         j < (len/4 - 1) ? " " : "");
953                         printf(">");
954                 }
955         } else { /* anything else... hexdump */
956                 if (len > max_dump)
957                         printf("* 0x%p [0x%08x]", data, len);
958                 else {
959                         const u8 *s;
960
961                         printf("[");
962                         for (j = 0, s = data; j < len; j++)
963                                 printf("%02x%s", s[j], j < len - 1 ? " " : "");
964                         printf("]");
965                 }
966         }
967 }
968
969 /****************************************************************************/
970
971 /*
972  * Recursively print (a portion of) the working_fdt.  The depth parameter
973  * determines how deeply nested the fdt is printed.
974  */
975 static int fdt_print(const char *pathp, char *prop, int depth)
976 {
977         static char tabs[MAX_LEVEL+1] =
978                 "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
979                 "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
980         const void *nodep;      /* property node pointer */
981         int  nodeoffset;        /* node offset from libfdt */
982         int  nextoffset;        /* next node offset from libfdt */
983         uint32_t tag;           /* tag */
984         int  len;               /* length of the property */
985         int  level = 0;         /* keep track of nesting level */
986         const struct fdt_property *fdt_prop;
987
988         nodeoffset = fdt_path_offset (working_fdt, pathp);
989         if (nodeoffset < 0) {
990                 /*
991                  * Not found or something else bad happened.
992                  */
993                 printf ("libfdt fdt_path_offset() returned %s\n",
994                         fdt_strerror(nodeoffset));
995                 return 1;
996         }
997         /*
998          * The user passed in a property as well as node path.
999          * Print only the given property and then return.
1000          */
1001         if (prop) {
1002                 nodep = fdt_getprop (working_fdt, nodeoffset, prop, &len);
1003                 if (len == 0) {
1004                         /* no property value */
1005                         printf("%s %s\n", pathp, prop);
1006                         return 0;
1007                 } else if (nodep && len > 0) {
1008                         printf("%s = ", prop);
1009                         print_data (nodep, len);
1010                         printf("\n");
1011                         return 0;
1012                 } else {
1013                         printf ("libfdt fdt_getprop(): %s\n",
1014                                 fdt_strerror(len));
1015                         return 1;
1016                 }
1017         }
1018
1019         /*
1020          * The user passed in a node path and no property,
1021          * print the node and all subnodes.
1022          */
1023         while(level >= 0) {
1024                 tag = fdt_next_tag(working_fdt, nodeoffset, &nextoffset);
1025                 switch(tag) {
1026                 case FDT_BEGIN_NODE:
1027                         pathp = fdt_get_name(working_fdt, nodeoffset, NULL);
1028                         if (level <= depth) {
1029                                 if (pathp == NULL)
1030                                         pathp = "/* NULL pointer error */";
1031                                 if (*pathp == '\0')
1032                                         pathp = "/";    /* root is nameless */
1033                                 printf("%s%s {\n",
1034                                         &tabs[MAX_LEVEL - level], pathp);
1035                         }
1036                         level++;
1037                         if (level >= MAX_LEVEL) {
1038                                 printf("Nested too deep, aborting.\n");
1039                                 return 1;
1040                         }
1041                         break;
1042                 case FDT_END_NODE:
1043                         level--;
1044                         if (level <= depth)
1045                                 printf("%s};\n", &tabs[MAX_LEVEL - level]);
1046                         if (level == 0) {
1047                                 level = -1;             /* exit the loop */
1048                         }
1049                         break;
1050                 case FDT_PROP:
1051                         fdt_prop = fdt_offset_ptr(working_fdt, nodeoffset,
1052                                         sizeof(*fdt_prop));
1053                         pathp    = fdt_string(working_fdt,
1054                                         fdt32_to_cpu(fdt_prop->nameoff));
1055                         len      = fdt32_to_cpu(fdt_prop->len);
1056                         nodep    = fdt_prop->data;
1057                         if (len < 0) {
1058                                 printf ("libfdt fdt_getprop(): %s\n",
1059                                         fdt_strerror(len));
1060                                 return 1;
1061                         } else if (len == 0) {
1062                                 /* the property has no value */
1063                                 if (level <= depth)
1064                                         printf("%s%s;\n",
1065                                                 &tabs[MAX_LEVEL - level],
1066                                                 pathp);
1067                         } else {
1068                                 if (level <= depth) {
1069                                         printf("%s%s = ",
1070                                                 &tabs[MAX_LEVEL - level],
1071                                                 pathp);
1072                                         print_data (nodep, len);
1073                                         printf(";\n");
1074                                 }
1075                         }
1076                         break;
1077                 case FDT_NOP:
1078                         printf("%s/* NOP */\n", &tabs[MAX_LEVEL - level]);
1079                         break;
1080                 case FDT_END:
1081                         return 1;
1082                 default:
1083                         if (level <= depth)
1084                                 printf("Unknown tag 0x%08X\n", tag);
1085                         return 1;
1086                 }
1087                 nodeoffset = nextoffset;
1088         }
1089         return 0;
1090 }
1091
1092 /********************************************************************/
1093 #ifdef CONFIG_SYS_LONGHELP
1094 static char fdt_help_text[] =
1095         "addr [-c] [-q] <addr> [<size>]  - Set the [control] fdt location to <addr>\n"
1096 #ifdef CONFIG_OF_LIBFDT_OVERLAY
1097         "fdt apply <addr>                    - Apply overlay to the DT\n"
1098 #endif
1099 #ifdef CONFIG_OF_BOARD_SETUP
1100         "fdt boardsetup                      - Do board-specific set up\n"
1101 #endif
1102 #ifdef CONFIG_OF_SYSTEM_SETUP
1103         "fdt systemsetup                     - Do system-specific set up\n"
1104 #endif
1105         "fdt move   <fdt> <newaddr> <length> - Copy the fdt to <addr> and make it active\n"
1106         "fdt resize [<extrasize>]            - Resize fdt to size + padding to 4k addr + some optional <extrasize> if needed\n"
1107         "fdt print  <path> [<prop>]          - Recursive print starting at <path>\n"
1108         "fdt list   <path> [<prop>]          - Print one level starting at <path>\n"
1109         "fdt get value <var> <path> <prop> [<index>] - Get <property> and store in <var>\n"
1110         "                                      In case of stringlist property, use optional <index>\n"
1111         "                                      to select string within the stringlist. Default is 0.\n"
1112         "fdt get name <var> <path> <index>   - Get name of node <index> and store in <var>\n"
1113         "fdt get addr <var> <path> <prop>    - Get start address of <property> and store in <var>\n"
1114         "fdt get size <var> <path> [<prop>]  - Get size of [<property>] or num nodes and store in <var>\n"
1115         "fdt set    <path> <prop> [<val>]    - Set <property> [to <val>]\n"
1116         "fdt mknode <path> <node>            - Create a new node after <path>\n"
1117         "fdt rm     <path> [<prop>]          - Delete the node or <property>\n"
1118         "fdt header [get <var> <member>]     - Display header info\n"
1119         "                                      get - get header member <member> and store it in <var>\n"
1120         "fdt bootcpu <id>                    - Set boot cpuid\n"
1121         "fdt memory <addr> <size>            - Add/Update memory node\n"
1122         "fdt rsvmem print                    - Show current mem reserves\n"
1123         "fdt rsvmem add <addr> <size>        - Add a mem reserve\n"
1124         "fdt rsvmem delete <index>           - Delete a mem reserves\n"
1125         "fdt chosen [<start> <size>]         - Add/update the /chosen branch in the tree\n"
1126         "                                        <start>/<size> - initrd start addr/size\n"
1127 #if defined(CONFIG_FIT_SIGNATURE)
1128         "fdt checksign [<addr>]              - check FIT signature\n"
1129         "                                        <start> - addr of key blob\n"
1130         "                                                  default gd->fdt_blob\n"
1131 #endif
1132         "NOTE: Dereference aliases by omitting the leading '/', "
1133                 "e.g. fdt print ethernet0.";
1134 #endif
1135
1136 U_BOOT_CMD(
1137         fdt,    255,    0,      do_fdt,
1138         "flattened device tree utility commands", fdt_help_text
1139 );