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