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