• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2000-2013
4  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
5  *
6  * (C) Copyright 2001 Sysgo Real-Time Solutions, GmbH <www.elinos.com>
7  * Andreas Heppel <aheppel@sysgo.de>
8  *
9  * Copyright 2011 Freescale Semiconductor, Inc.
10  */
11 
12 /*
13  * Support for persistent environment data
14  *
15  * The "environment" is stored on external storage as a list of '\0'
16  * terminated "name=value" strings. The end of the list is marked by
17  * a double '\0'. The environment is preceded by a 32 bit CRC over
18  * the data part and, in case of redundant environment, a byte of
19  * flags.
20  *
21  * This linearized representation will also be used before
22  * relocation, i. e. as long as we don't have a full C runtime
23  * environment. After that, we use a hash table.
24  */
25 
26 #include <common.h>
27 #include <cli.h>
28 #include <command.h>
29 #include <console.h>
30 #include <env.h>
31 #include <env_internal.h>
32 #include <search.h>
33 #include <errno.h>
34 #include <malloc.h>
35 #include <mapmem.h>
36 #include <u-boot/crc.h>
37 #include <watchdog.h>
38 #include <linux/stddef.h>
39 #include <asm/byteorder.h>
40 #include <asm/io.h>
41 
42 DECLARE_GLOBAL_DATA_PTR;
43 
44 #if	defined(CONFIG_ENV_IS_IN_EEPROM)	|| \
45 	defined(CONFIG_ENV_IS_IN_FLASH)		|| \
46 	defined(CONFIG_ENV_IS_IN_MMC)		|| \
47 	defined(CONFIG_ENV_IS_IN_FAT)		|| \
48 	defined(CONFIG_ENV_IS_IN_EXT4)		|| \
49 	defined(CONFIG_ENV_IS_IN_NAND)		|| \
50 	defined(CONFIG_ENV_IS_IN_NVRAM)		|| \
51 	defined(CONFIG_ENV_IS_IN_ONENAND)	|| \
52 	defined(CONFIG_ENV_IS_IN_SATA)		|| \
53 	defined(CONFIG_ENV_IS_IN_SPI_FLASH)	|| \
54 	defined(CONFIG_ENV_IS_IN_REMOTE)	|| \
55 	defined(CONFIG_ENV_IS_IN_UFS)		|| \
56 	defined(CONFIG_ENV_IS_IN_UBI)
57 
58 #define ENV_IS_IN_DEVICE
59 
60 #endif
61 
62 #if	!defined(ENV_IS_IN_DEVICE)		&& \
63 	!defined(CONFIG_ENV_IS_NOWHERE)
64 # error Define one of CONFIG_ENV_IS_IN_{EEPROM|FLASH|MMC|FAT|EXT4|\
65 NAND|NVRAM|ONENAND|SATA|SPI_FLASH|REMOTE|UBI|UFS} or CONFIG_ENV_IS_NOWHERE
66 #endif
67 
68 /*
69  * Maximum expected input data size for import command
70  */
71 #define	MAX_ENV_SIZE	(1 << 20)	/* 1 MiB */
72 
73 /*
74  * This variable is incremented on each do_env_set(), so it can
75  * be used via env_get_id() as an indication, if the environment
76  * has changed or not. So it is possible to reread an environment
77  * variable only if the environment was changed ... done so for
78  * example in NetInitLoop()
79  */
80 static int env_id = 1;
81 
env_get_id(void)82 int env_get_id(void)
83 {
84 	return env_id;
85 }
86 
87 #ifndef CONFIG_SPL_BUILD
88 /*
89  * Command interface: print one or all environment variables
90  *
91  * Returns 0 in case of error, or length of printed string
92  */
env_print(char * name,int flag)93 static int env_print(char *name, int flag)
94 {
95 	char *res = NULL;
96 	ssize_t len;
97 
98 	if (name) {		/* print a single name */
99 		struct env_entry e, *ep;
100 
101 		e.key = name;
102 		e.data = NULL;
103 		hsearch_r(e, ENV_FIND, &ep, &env_htab, flag);
104 		if (ep == NULL)
105 			return 0;
106 		len = printf("%s=%s\n", ep->key, ep->data);
107 		return len;
108 	}
109 
110 	/* print whole list */
111 	len = hexport_r(&env_htab, '\n', flag, &res, 0, 0, NULL);
112 
113 	if (len > 0) {
114 		puts(res);
115 		free(res);
116 		return len;
117 	}
118 
119 	/* should never happen */
120 	printf("## Error: cannot export environment\n");
121 	return 0;
122 }
123 
do_env_print(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])124 static int do_env_print(cmd_tbl_t *cmdtp, int flag, int argc,
125 			char * const argv[])
126 {
127 	int i;
128 	int rcode = 0;
129 	int env_flag = H_HIDE_DOT;
130 
131 #if defined(CONFIG_CMD_NVEDIT_EFI)
132 	if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'e')
133 		return do_env_print_efi(cmdtp, flag, --argc, ++argv);
134 #endif
135 
136 	if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'a') {
137 		argc--;
138 		argv++;
139 		env_flag &= ~H_HIDE_DOT;
140 	}
141 
142 	if (argc == 1) {
143 		/* print all env vars */
144 		rcode = env_print(NULL, env_flag);
145 		if (!rcode)
146 			return 1;
147 		printf("\nEnvironment size: %d/%ld bytes\n",
148 			rcode, (ulong)ENV_SIZE);
149 		return 0;
150 	}
151 
152 	/* print selected env vars */
153 	env_flag &= ~H_HIDE_DOT;
154 	for (i = 1; i < argc; ++i) {
155 		int rc = env_print(argv[i], env_flag);
156 		if (!rc) {
157 			printf("## Error: \"%s\" not defined\n", argv[i]);
158 			++rcode;
159 		}
160 	}
161 
162 	return rcode;
163 }
164 
165 #ifdef CONFIG_CMD_GREPENV
do_env_grep(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])166 static int do_env_grep(cmd_tbl_t *cmdtp, int flag,
167 		       int argc, char * const argv[])
168 {
169 	char *res = NULL;
170 	int len, grep_how, grep_what;
171 
172 	if (argc < 2)
173 		return CMD_RET_USAGE;
174 
175 	grep_how  = H_MATCH_SUBSTR;	/* default: substring search	*/
176 	grep_what = H_MATCH_BOTH;	/* default: grep names and values */
177 
178 	while (--argc > 0 && **++argv == '-') {
179 		char *arg = *argv;
180 		while (*++arg) {
181 			switch (*arg) {
182 #ifdef CONFIG_REGEX
183 			case 'e':		/* use regex matching */
184 				grep_how  = H_MATCH_REGEX;
185 				break;
186 #endif
187 			case 'n':		/* grep for name */
188 				grep_what = H_MATCH_KEY;
189 				break;
190 			case 'v':		/* grep for value */
191 				grep_what = H_MATCH_DATA;
192 				break;
193 			case 'b':		/* grep for both */
194 				grep_what = H_MATCH_BOTH;
195 				break;
196 			case '-':
197 				goto DONE;
198 			default:
199 				return CMD_RET_USAGE;
200 			}
201 		}
202 	}
203 
204 DONE:
205 	len = hexport_r(&env_htab, '\n',
206 			flag | grep_what | grep_how,
207 			&res, 0, argc, argv);
208 
209 	if (len > 0) {
210 		puts(res);
211 		free(res);
212 	}
213 
214 	if (len < 2)
215 		return 1;
216 
217 	return 0;
218 }
219 #endif
220 #endif /* CONFIG_SPL_BUILD */
221 
222 /*
223  * Set a new environment variable,
224  * or replace or delete an existing one.
225  */
_do_env_set(int flag,int argc,char * const argv[],int env_flag)226 static int _do_env_set(int flag, int argc, char * const argv[], int env_flag)
227 {
228 	int   i, len;
229 	char  *name, *value, *s;
230 	struct env_entry e, *ep;
231 
232 	debug("Initial value for argc=%d\n", argc);
233 
234 #if CONFIG_IS_ENABLED(CMD_NVEDIT_EFI)
235 	if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'e')
236 		return do_env_set_efi(NULL, flag, --argc, ++argv);
237 #endif
238 
239 	while (argc > 1 && **(argv + 1) == '-') {
240 		char *arg = *++argv;
241 
242 		--argc;
243 		while (*++arg) {
244 			switch (*arg) {
245 			case 'f':		/* force */
246 				env_flag |= H_FORCE;
247 				break;
248 			default:
249 				return CMD_RET_USAGE;
250 			}
251 		}
252 	}
253 	debug("Final value for argc=%d\n", argc);
254 	name = argv[1];
255 
256 	if (strchr(name, '=')) {
257 		printf("## Error: illegal character '='"
258 		       "in variable name \"%s\"\n", name);
259 		return 1;
260 	}
261 
262 	env_id++;
263 
264 	/* Delete only ? */
265 	if (argc < 3 || argv[2] == NULL) {
266 		int rc = hdelete_r(name, &env_htab, env_flag);
267 		return !rc;
268 	}
269 
270 	/*
271 	 * Insert / replace new value
272 	 */
273 	for (i = 2, len = 0; i < argc; ++i)
274 		len += strlen(argv[i]) + 1;
275 
276 	value = malloc(len);
277 	if (value == NULL) {
278 		printf("## Can't malloc %d bytes\n", len);
279 		return 1;
280 	}
281 	for (i = 2, s = value; i < argc; ++i) {
282 		char *v = argv[i];
283 
284 		while ((*s++ = *v++) != '\0')
285 			;
286 		*(s - 1) = ' ';
287 	}
288 	if (s != value)
289 		*--s = '\0';
290 
291 	e.key	= name;
292 	e.data	= value;
293 	hsearch_r(e, ENV_ENTER, &ep, &env_htab, env_flag);
294 	free(value);
295 	if (!ep) {
296 		printf("## Error inserting \"%s\" variable, errno=%d\n",
297 			name, errno);
298 		return 1;
299 	}
300 
301 	return 0;
302 }
303 
env_set(const char * varname,const char * varvalue)304 int env_set(const char *varname, const char *varvalue)
305 {
306 	const char * const argv[4] = { "setenv", varname, varvalue, NULL };
307 
308 	/* before import into hashtable */
309 	if (!(gd->flags & GD_FLG_ENV_READY))
310 		return 1;
311 
312 	if (varvalue == NULL || varvalue[0] == '\0')
313 		return _do_env_set(0, 2, (char * const *)argv, H_PROGRAMMATIC);
314 	else
315 		return _do_env_set(0, 3, (char * const *)argv, H_PROGRAMMATIC);
316 }
317 
318 /**
319  * Set an environment variable to an integer value
320  *
321  * @param varname	Environment variable to set
322  * @param value		Value to set it to
323  * @return 0 if ok, 1 on error
324  */
env_set_ulong(const char * varname,ulong value)325 int env_set_ulong(const char *varname, ulong value)
326 {
327 	/* TODO: this should be unsigned */
328 	char *str = simple_itoa(value);
329 
330 	return env_set(varname, str);
331 }
332 
333 /**
334  * Set an environment variable to an value in hex
335  *
336  * @param varname	Environment variable to set
337  * @param value		Value to set it to
338  * @return 0 if ok, 1 on error
339  */
env_set_hex(const char * varname,ulong value)340 int env_set_hex(const char *varname, ulong value)
341 {
342 	char str[17];
343 
344 	sprintf(str, "%lx", value);
345 	return env_set(varname, str);
346 }
347 
env_get_hex(const char * varname,ulong default_val)348 ulong env_get_hex(const char *varname, ulong default_val)
349 {
350 	const char *s;
351 	ulong value;
352 	char *endp;
353 
354 	s = env_get(varname);
355 	if (s)
356 		value = simple_strtoul(s, &endp, 16);
357 	if (!s || endp == s)
358 		return default_val;
359 
360 	return value;
361 }
362 
eth_env_get_enetaddr(const char * name,uint8_t * enetaddr)363 int eth_env_get_enetaddr(const char *name, uint8_t *enetaddr)
364 {
365 	string_to_enetaddr(env_get(name), enetaddr);
366 	return is_valid_ethaddr(enetaddr);
367 }
368 
eth_env_set_enetaddr(const char * name,const uint8_t * enetaddr)369 int eth_env_set_enetaddr(const char *name, const uint8_t *enetaddr)
370 {
371 	char buf[ARP_HLEN_ASCII + 1];
372 
373 	if (eth_env_get_enetaddr(name, (uint8_t *)buf))
374 		return -EEXIST;
375 
376 	sprintf(buf, "%pM", enetaddr);
377 
378 	return env_set(name, buf);
379 }
380 
381 #ifndef CONFIG_SPL_BUILD
do_env_set(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])382 static int do_env_set(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
383 {
384 	if (argc < 2)
385 		return CMD_RET_USAGE;
386 
387 	return _do_env_set(flag, argc, argv, H_INTERACTIVE);
388 }
389 
390 /*
391  * Prompt for environment variable
392  */
393 #if defined(CONFIG_CMD_ASKENV)
do_env_ask(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])394 int do_env_ask(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
395 {
396 	char message[CONFIG_SYS_CBSIZE];
397 	int i, len, pos, size;
398 	char *local_args[4];
399 	char *endptr;
400 
401 	local_args[0] = argv[0];
402 	local_args[1] = argv[1];
403 	local_args[2] = NULL;
404 	local_args[3] = NULL;
405 
406 	/*
407 	 * Check the syntax:
408 	 *
409 	 * env_ask envname [message1 ...] [size]
410 	 */
411 	if (argc == 1)
412 		return CMD_RET_USAGE;
413 
414 	/*
415 	 * We test the last argument if it can be converted
416 	 * into a decimal number.  If yes, we assume it's
417 	 * the size.  Otherwise we echo it as part of the
418 	 * message.
419 	 */
420 	i = simple_strtoul(argv[argc - 1], &endptr, 10);
421 	if (*endptr != '\0') {			/* no size */
422 		size = CONFIG_SYS_CBSIZE - 1;
423 	} else {				/* size given */
424 		size = i;
425 		--argc;
426 	}
427 
428 	if (argc <= 2) {
429 		sprintf(message, "Please enter '%s': ", argv[1]);
430 	} else {
431 		/* env_ask envname message1 ... messagen [size] */
432 		for (i = 2, pos = 0; i < argc && pos+1 < sizeof(message); i++) {
433 			if (pos)
434 				message[pos++] = ' ';
435 
436 			strncpy(message + pos, argv[i], sizeof(message) - pos);
437 			pos += strlen(argv[i]);
438 		}
439 		if (pos < sizeof(message) - 1) {
440 			message[pos++] = ' ';
441 			message[pos] = '\0';
442 		} else
443 			message[CONFIG_SYS_CBSIZE - 1] = '\0';
444 	}
445 
446 	if (size >= CONFIG_SYS_CBSIZE)
447 		size = CONFIG_SYS_CBSIZE - 1;
448 
449 	if (size <= 0)
450 		return 1;
451 
452 	/* prompt for input */
453 	len = cli_readline(message);
454 
455 	if (size < len)
456 		console_buffer[size] = '\0';
457 
458 	len = 2;
459 	if (console_buffer[0] != '\0') {
460 		local_args[2] = console_buffer;
461 		len = 3;
462 	}
463 
464 	/* Continue calling setenv code */
465 	return _do_env_set(flag, len, local_args, H_INTERACTIVE);
466 }
467 #endif
468 
469 #if defined(CONFIG_CMD_ENV_CALLBACK)
print_static_binding(const char * var_name,const char * callback_name,void * priv)470 static int print_static_binding(const char *var_name, const char *callback_name,
471 				void *priv)
472 {
473 	printf("\t%-20s %-20s\n", var_name, callback_name);
474 
475 	return 0;
476 }
477 
print_active_callback(struct env_entry * entry)478 static int print_active_callback(struct env_entry *entry)
479 {
480 	struct env_clbk_tbl *clbkp;
481 	int i;
482 	int num_callbacks;
483 
484 	if (entry->callback == NULL)
485 		return 0;
486 
487 	/* look up the callback in the linker-list */
488 	num_callbacks = ll_entry_count(struct env_clbk_tbl, env_clbk);
489 	for (i = 0, clbkp = ll_entry_start(struct env_clbk_tbl, env_clbk);
490 	     i < num_callbacks;
491 	     i++, clbkp++) {
492 #if defined(CONFIG_NEEDS_MANUAL_RELOC)
493 		if (entry->callback == clbkp->callback + gd->reloc_off)
494 #else
495 		if (entry->callback == clbkp->callback)
496 #endif
497 			break;
498 	}
499 
500 	if (i == num_callbacks)
501 		/* this should probably never happen, but just in case... */
502 		printf("\t%-20s %p\n", entry->key, entry->callback);
503 	else
504 		printf("\t%-20s %-20s\n", entry->key, clbkp->name);
505 
506 	return 0;
507 }
508 
509 /*
510  * Print the callbacks available and what they are bound to
511  */
do_env_callback(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])512 int do_env_callback(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
513 {
514 	struct env_clbk_tbl *clbkp;
515 	int i;
516 	int num_callbacks;
517 
518 	/* Print the available callbacks */
519 	puts("Available callbacks:\n");
520 	puts("\tCallback Name\n");
521 	puts("\t-------------\n");
522 	num_callbacks = ll_entry_count(struct env_clbk_tbl, env_clbk);
523 	for (i = 0, clbkp = ll_entry_start(struct env_clbk_tbl, env_clbk);
524 	     i < num_callbacks;
525 	     i++, clbkp++)
526 		printf("\t%s\n", clbkp->name);
527 	puts("\n");
528 
529 	/* Print the static bindings that may exist */
530 	puts("Static callback bindings:\n");
531 	printf("\t%-20s %-20s\n", "Variable Name", "Callback Name");
532 	printf("\t%-20s %-20s\n", "-------------", "-------------");
533 	env_attr_walk(ENV_CALLBACK_LIST_STATIC, print_static_binding, NULL);
534 	puts("\n");
535 
536 	/* walk through each variable and print the callback if it has one */
537 	puts("Active callback bindings:\n");
538 	printf("\t%-20s %-20s\n", "Variable Name", "Callback Name");
539 	printf("\t%-20s %-20s\n", "-------------", "-------------");
540 	hwalk_r(&env_htab, print_active_callback);
541 	return 0;
542 }
543 #endif
544 
545 #if defined(CONFIG_CMD_ENV_FLAGS)
print_static_flags(const char * var_name,const char * flags,void * priv)546 static int print_static_flags(const char *var_name, const char *flags,
547 			      void *priv)
548 {
549 	enum env_flags_vartype type = env_flags_parse_vartype(flags);
550 	enum env_flags_varaccess access = env_flags_parse_varaccess(flags);
551 
552 	printf("\t%-20s %-20s %-20s\n", var_name,
553 		env_flags_get_vartype_name(type),
554 		env_flags_get_varaccess_name(access));
555 
556 	return 0;
557 }
558 
print_active_flags(struct env_entry * entry)559 static int print_active_flags(struct env_entry *entry)
560 {
561 	enum env_flags_vartype type;
562 	enum env_flags_varaccess access;
563 
564 	if (entry->flags == 0)
565 		return 0;
566 
567 	type = (enum env_flags_vartype)
568 		(entry->flags & ENV_FLAGS_VARTYPE_BIN_MASK);
569 	access = env_flags_parse_varaccess_from_binflags(entry->flags);
570 	printf("\t%-20s %-20s %-20s\n", entry->key,
571 		env_flags_get_vartype_name(type),
572 		env_flags_get_varaccess_name(access));
573 
574 	return 0;
575 }
576 
577 /*
578  * Print the flags available and what variables have flags
579  */
do_env_flags(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])580 int do_env_flags(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
581 {
582 	/* Print the available variable types */
583 	printf("Available variable type flags (position %d):\n",
584 		ENV_FLAGS_VARTYPE_LOC);
585 	puts("\tFlag\tVariable Type Name\n");
586 	puts("\t----\t------------------\n");
587 	env_flags_print_vartypes();
588 	puts("\n");
589 
590 	/* Print the available variable access types */
591 	printf("Available variable access flags (position %d):\n",
592 		ENV_FLAGS_VARACCESS_LOC);
593 	puts("\tFlag\tVariable Access Name\n");
594 	puts("\t----\t--------------------\n");
595 	env_flags_print_varaccess();
596 	puts("\n");
597 
598 	/* Print the static flags that may exist */
599 	puts("Static flags:\n");
600 	printf("\t%-20s %-20s %-20s\n", "Variable Name", "Variable Type",
601 		"Variable Access");
602 	printf("\t%-20s %-20s %-20s\n", "-------------", "-------------",
603 		"---------------");
604 	env_attr_walk(ENV_FLAGS_LIST_STATIC, print_static_flags, NULL);
605 	puts("\n");
606 
607 	/* walk through each variable and print the flags if non-default */
608 	puts("Active flags:\n");
609 	printf("\t%-20s %-20s %-20s\n", "Variable Name", "Variable Type",
610 		"Variable Access");
611 	printf("\t%-20s %-20s %-20s\n", "-------------", "-------------",
612 		"---------------");
613 	hwalk_r(&env_htab, print_active_flags);
614 	return 0;
615 }
616 #endif
617 
618 /*
619  * Interactively edit an environment variable
620  */
621 #if defined(CONFIG_CMD_EDITENV)
do_env_edit(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])622 static int do_env_edit(cmd_tbl_t *cmdtp, int flag, int argc,
623 		       char * const argv[])
624 {
625 	char buffer[CONFIG_SYS_CBSIZE];
626 	char *init_val;
627 
628 	if (argc < 2)
629 		return CMD_RET_USAGE;
630 
631 	/* before import into hashtable */
632 	if (!(gd->flags & GD_FLG_ENV_READY))
633 		return 1;
634 
635 	/* Set read buffer to initial value or empty sting */
636 	init_val = env_get(argv[1]);
637 	if (init_val)
638 		snprintf(buffer, CONFIG_SYS_CBSIZE, "%s", init_val);
639 	else
640 		buffer[0] = '\0';
641 
642 	if (cli_readline_into_buffer("edit: ", buffer, 0) < 0)
643 		return 1;
644 
645 	if (buffer[0] == '\0') {
646 		const char * const _argv[3] = { "setenv", argv[1], NULL };
647 
648 		return _do_env_set(0, 2, (char * const *)_argv, H_INTERACTIVE);
649 	} else {
650 		const char * const _argv[4] = { "setenv", argv[1], buffer,
651 			NULL };
652 
653 		return _do_env_set(0, 3, (char * const *)_argv, H_INTERACTIVE);
654 	}
655 }
656 #endif /* CONFIG_CMD_EDITENV */
657 #endif /* CONFIG_SPL_BUILD */
658 
659 /*
660  * Look up variable from environment,
661  * return address of storage for that variable,
662  * or NULL if not found
663  */
env_get(const char * name)664 char *env_get(const char *name)
665 {
666 	if (gd->flags & GD_FLG_ENV_READY) { /* after import into hashtable */
667 		struct env_entry e, *ep;
668 
669 		WATCHDOG_RESET();
670 
671 		e.key	= name;
672 		e.data	= NULL;
673 		hsearch_r(e, ENV_FIND, &ep, &env_htab, 0);
674 
675 		return ep ? ep->data : NULL;
676 	}
677 
678 	/* restricted capabilities before import */
679 	if (env_get_f(name, (char *)(gd->env_buf), sizeof(gd->env_buf)) > 0)
680 		return (char *)(gd->env_buf);
681 
682 	return NULL;
683 }
684 
685 /*
686  * Like env_get, but prints an error if envvar isn't defined in the
687  * environment.  It always returns what env_get does, so it can be used in
688  * place of env_get without changing error handling otherwise.
689  */
from_env(const char * envvar)690 char *from_env(const char *envvar)
691 {
692 	char *ret;
693 
694 	ret = env_get(envvar);
695 
696 	if (!ret)
697 		printf("missing environment variable: %s\n", envvar);
698 
699 	return ret;
700 }
701 
702 /*
703  * Look up variable from environment for restricted C runtime env.
704  */
env_get_f(const char * name,char * buf,unsigned len)705 int env_get_f(const char *name, char *buf, unsigned len)
706 {
707 	int i, nxt, c;
708 
709 	for (i = 0; env_get_char(i) != '\0'; i = nxt + 1) {
710 		int val, n;
711 
712 		for (nxt = i; (c = env_get_char(nxt)) != '\0'; ++nxt) {
713 			if (c < 0)
714 				return c;
715 			if (nxt >= CONFIG_ENV_SIZE)
716 				return -1;
717 		}
718 
719 		val = env_match((uchar *)name, i);
720 		if (val < 0)
721 			continue;
722 
723 		/* found; copy out */
724 		for (n = 0; n < len; ++n, ++buf) {
725 			c = env_get_char(val++);
726 			if (c < 0)
727 				return c;
728 			*buf = c;
729 			if (*buf == '\0')
730 				return n;
731 		}
732 
733 		if (n)
734 			*--buf = '\0';
735 
736 		printf("env_buf [%u bytes] too small for value of \"%s\"\n",
737 		       len, name);
738 
739 		return n;
740 	}
741 
742 	return -1;
743 }
744 
745 /**
746  * Decode the integer value of an environment variable and return it.
747  *
748  * @param name		Name of environment variable
749  * @param base		Number base to use (normally 10, or 16 for hex)
750  * @param default_val	Default value to return if the variable is not
751  *			found
752  * @return the decoded value, or default_val if not found
753  */
env_get_ulong(const char * name,int base,ulong default_val)754 ulong env_get_ulong(const char *name, int base, ulong default_val)
755 {
756 	/*
757 	 * We can use env_get() here, even before relocation, since the
758 	 * environment variable value is an integer and thus short.
759 	 */
760 	const char *str = env_get(name);
761 
762 	return str ? simple_strtoul(str, NULL, base) : default_val;
763 }
764 
765 #ifndef CONFIG_SPL_BUILD
766 #if defined(CONFIG_CMD_SAVEENV) && defined(ENV_IS_IN_DEVICE)
do_env_save(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])767 static int do_env_save(cmd_tbl_t *cmdtp, int flag, int argc,
768 		       char * const argv[])
769 {
770 	return env_save() ? 1 : 0;
771 }
772 
773 U_BOOT_CMD(
774 	saveenv, 1, 0,	do_env_save,
775 	"save environment variables to persistent storage",
776 	""
777 );
778 
779 #if defined(CONFIG_CMD_ERASEENV)
do_env_erase(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])780 static int do_env_erase(cmd_tbl_t *cmdtp, int flag, int argc,
781 			char * const argv[])
782 {
783 	return env_erase() ? 1 : 0;
784 }
785 
786 U_BOOT_CMD(
787 	eraseenv, 1, 0,	do_env_erase,
788 	"erase environment variables from persistent storage",
789 	""
790 );
791 #endif
792 #endif
793 #endif /* CONFIG_SPL_BUILD */
794 
env_match(uchar * s1,int i2)795 int env_match(uchar *s1, int i2)
796 {
797 	if (s1 == NULL)
798 		return -1;
799 
800 	while (*s1 == env_get_char(i2++))
801 		if (*s1++ == '=')
802 			return i2;
803 
804 	if (*s1 == '\0' && env_get_char(i2-1) == '=')
805 		return i2;
806 
807 	return -1;
808 }
809 
810 #ifndef CONFIG_SPL_BUILD
811 #ifndef CONFIG_MINI_BOOT
do_env_default(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])812 static int do_env_default(cmd_tbl_t *cmdtp, int flag,
813 			  int argc, char * const argv[])
814 {
815 	int all = 0, env_flag = H_INTERACTIVE;
816 
817 	debug("Initial value for argc=%d\n", argc);
818 	while (--argc > 0 && **++argv == '-') {
819 		char *arg = *argv;
820 
821 		while (*++arg) {
822 			switch (*arg) {
823 			case 'a':		/* default all */
824 				all = 1;
825 				break;
826 			case 'f':		/* force */
827 				env_flag |= H_FORCE;
828 				break;
829 			default:
830 				return cmd_usage(cmdtp);
831 			}
832 		}
833 	}
834 	debug("Final value for argc=%d\n", argc);
835 	if (all && (argc == 0)) {
836 		/* Reset the whole environment */
837 		env_set_default("## Resetting to default environment\n",
838 				env_flag);
839 		return 0;
840 	}
841 	if (!all && (argc > 0)) {
842 		/* Reset individual variables */
843 		env_set_default_vars(argc, argv, env_flag);
844 		return 0;
845 	}
846 
847 	return cmd_usage(cmdtp);
848 }
849 
do_env_delete(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])850 static int do_env_delete(cmd_tbl_t *cmdtp, int flag,
851 			 int argc, char * const argv[])
852 {
853 	int env_flag = H_INTERACTIVE;
854 	int ret = 0;
855 
856 	debug("Initial value for argc=%d\n", argc);
857 	while (argc > 1 && **(argv + 1) == '-') {
858 		char *arg = *++argv;
859 
860 		--argc;
861 		while (*++arg) {
862 			switch (*arg) {
863 			case 'f':		/* force */
864 				env_flag |= H_FORCE;
865 				break;
866 			default:
867 				return CMD_RET_USAGE;
868 			}
869 		}
870 	}
871 	debug("Final value for argc=%d\n", argc);
872 
873 	env_id++;
874 
875 	while (--argc > 0) {
876 		char *name = *++argv;
877 
878 		if (!hdelete_r(name, &env_htab, env_flag))
879 			ret = 1;
880 	}
881 
882 	return ret;
883 }
884 #endif /* CONFIG_MINI_BOOT */
885 
886 #ifdef CONFIG_CMD_EXPORTENV
887 /*
888  * env export [-t | -b | -c] [-s size] addr [var ...]
889  *	-t:	export as text format; if size is given, data will be
890  *		padded with '\0' bytes; if not, one terminating '\0'
891  *		will be added (which is included in the "filesize"
892  *		setting so you can for exmple copy this to flash and
893  *		keep the termination).
894  *	-b:	export as binary format (name=value pairs separated by
895  *		'\0', list end marked by double "\0\0")
896  *	-c:	export as checksum protected environment format as
897  *		used for example by "saveenv" command
898  *	-s size:
899  *		size of output buffer
900  *	addr:	memory address where environment gets stored
901  *	var...	List of variable names that get included into the
902  *		export. Without arguments, the whole environment gets
903  *		exported.
904  *
905  * With "-c" and size is NOT given, then the export command will
906  * format the data as currently used for the persistent storage,
907  * i. e. it will use CONFIG_ENV_SECT_SIZE as output block size and
908  * prepend a valid CRC32 checksum and, in case of redundant
909  * environment, a "current" redundancy flag. If size is given, this
910  * value will be used instead of CONFIG_ENV_SECT_SIZE; again, CRC32
911  * checksum and redundancy flag will be inserted.
912  *
913  * With "-b" and "-t", always only the real data (including a
914  * terminating '\0' byte) will be written; here the optional size
915  * argument will be used to make sure not to overflow the user
916  * provided buffer; the command will abort if the size is not
917  * sufficient. Any remaining space will be '\0' padded.
918  *
919  * On successful return, the variable "filesize" will be set.
920  * Note that filesize includes the trailing/terminating '\0' byte(s).
921  *
922  * Usage scenario:  create a text snapshot/backup of the current settings:
923  *
924  *	=> env export -t 100000
925  *	=> era ${backup_addr} +${filesize}
926  *	=> cp.b 100000 ${backup_addr} ${filesize}
927  *
928  * Re-import this snapshot, deleting all other settings:
929  *
930  *	=> env import -d -t ${backup_addr}
931  */
do_env_export(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])932 static int do_env_export(cmd_tbl_t *cmdtp, int flag,
933 			 int argc, char * const argv[])
934 {
935 	char	buf[32];
936 	ulong	addr;
937 	char	*ptr, *cmd, *res;
938 	size_t	size = 0;
939 	ssize_t	len;
940 	env_t	*envp;
941 	char	sep = '\n';
942 	int	chk = 0;
943 	int	fmt = 0;
944 
945 	cmd = *argv;
946 
947 	while (--argc > 0 && **++argv == '-') {
948 		char *arg = *argv;
949 		while (*++arg) {
950 			switch (*arg) {
951 			case 'b':		/* raw binary format */
952 				if (fmt++)
953 					goto sep_err;
954 				sep = '\0';
955 				break;
956 			case 'c':		/* external checksum format */
957 				if (fmt++)
958 					goto sep_err;
959 				sep = '\0';
960 				chk = 1;
961 				break;
962 			case 's':		/* size given */
963 				if (--argc <= 0)
964 					return cmd_usage(cmdtp);
965 				size = simple_strtoul(*++argv, NULL, 16);
966 				goto NXTARG;
967 			case 't':		/* text format */
968 				if (fmt++)
969 					goto sep_err;
970 				sep = '\n';
971 				break;
972 			default:
973 				return CMD_RET_USAGE;
974 			}
975 		}
976 NXTARG:		;
977 	}
978 
979 	if (argc < 1)
980 		return CMD_RET_USAGE;
981 
982 	addr = simple_strtoul(argv[0], NULL, 16);
983 	ptr = map_sysmem(addr, size);
984 
985 	if (size)
986 		memset(ptr, '\0', size);
987 
988 	argc--;
989 	argv++;
990 
991 	if (sep) {		/* export as text file */
992 		len = hexport_r(&env_htab, sep,
993 				H_MATCH_KEY | H_MATCH_IDENT,
994 				&ptr, size, argc, argv);
995 		if (len < 0) {
996 			pr_err("## Error: Cannot export environment: errno = %d\n",
997 			       errno);
998 			return 1;
999 		}
1000 		sprintf(buf, "%zX", (size_t)len);
1001 		env_set("filesize", buf);
1002 
1003 		return 0;
1004 	}
1005 
1006 	envp = (env_t *)ptr;
1007 
1008 	if (chk)		/* export as checksum protected block */
1009 		res = (char *)envp->data;
1010 	else			/* export as raw binary data */
1011 		res = ptr;
1012 
1013 	len = hexport_r(&env_htab, '\0',
1014 			H_MATCH_KEY | H_MATCH_IDENT,
1015 			&res, ENV_SIZE, argc, argv);
1016 	if (len < 0) {
1017 		pr_err("## Error: Cannot export environment: errno = %d\n",
1018 		       errno);
1019 		return 1;
1020 	}
1021 
1022 	if (chk) {
1023 		envp->crc = crc32(0, envp->data,
1024 				size ? size - offsetof(env_t, data) : ENV_SIZE);
1025 #ifdef CONFIG_ENV_ADDR_REDUND
1026 		envp->flags = ENV_REDUND_ACTIVE;
1027 #endif
1028 	}
1029 	env_set_hex("filesize", len + offsetof(env_t, data));
1030 
1031 	return 0;
1032 
1033 sep_err:
1034 	printf("## Error: %s: only one of \"-b\", \"-c\" or \"-t\" allowed\n",
1035 	       cmd);
1036 	return 1;
1037 }
1038 #endif
1039 
1040 #ifdef CONFIG_CMD_IMPORTENV
1041 /*
1042  * env import [-d] [-t [-r] | -b | -c] addr [size] [var ...]
1043  *	-d:	delete existing environment before importing if no var is
1044  *		passed; if vars are passed, if one var is in the current
1045  *		environment but not in the environment at addr, delete var from
1046  *		current environment;
1047  *		otherwise overwrite / append to existing definitions
1048  *	-t:	assume text format; either "size" must be given or the
1049  *		text data must be '\0' terminated
1050  *	-r:	handle CRLF like LF, that means exported variables with
1051  *		a content which ends with \r won't get imported. Used
1052  *		to import text files created with editors which are using CRLF
1053  *		for line endings. Only effective in addition to -t.
1054  *	-b:	assume binary format ('\0' separated, "\0\0" terminated)
1055  *	-c:	assume checksum protected environment format
1056  *	addr:	memory address to read from
1057  *	size:	length of input data; if missing, proper '\0'
1058  *		termination is mandatory
1059  *		if var is set and size should be missing (i.e. '\0'
1060  *		termination), set size to '-'
1061  *	var...	List of the names of the only variables that get imported from
1062  *		the environment at address 'addr'. Without arguments, the whole
1063  *		environment gets imported.
1064  */
do_env_import(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])1065 static int do_env_import(cmd_tbl_t *cmdtp, int flag,
1066 			 int argc, char * const argv[])
1067 {
1068 	ulong	addr;
1069 	char	*cmd, *ptr;
1070 	char	sep = '\n';
1071 	int	chk = 0;
1072 	int	fmt = 0;
1073 	int	del = 0;
1074 	int	crlf_is_lf = 0;
1075 	int	wl = 0;
1076 	size_t	size;
1077 
1078 	cmd = *argv;
1079 
1080 	while (--argc > 0 && **++argv == '-') {
1081 		char *arg = *argv;
1082 		while (*++arg) {
1083 			switch (*arg) {
1084 			case 'b':		/* raw binary format */
1085 				if (fmt++)
1086 					goto sep_err;
1087 				sep = '\0';
1088 				break;
1089 			case 'c':		/* external checksum format */
1090 				if (fmt++)
1091 					goto sep_err;
1092 				sep = '\0';
1093 				chk = 1;
1094 				break;
1095 			case 't':		/* text format */
1096 				if (fmt++)
1097 					goto sep_err;
1098 				sep = '\n';
1099 				break;
1100 			case 'r':		/* handle CRLF like LF */
1101 				crlf_is_lf = 1;
1102 				break;
1103 			case 'd':
1104 				del = 1;
1105 				break;
1106 			default:
1107 				return CMD_RET_USAGE;
1108 			}
1109 		}
1110 	}
1111 
1112 	if (argc < 1)
1113 		return CMD_RET_USAGE;
1114 
1115 	if (!fmt)
1116 		printf("## Warning: defaulting to text format\n");
1117 
1118 	if (sep != '\n' && crlf_is_lf )
1119 		crlf_is_lf = 0;
1120 
1121 	addr = simple_strtoul(argv[0], NULL, 16);
1122 	ptr = map_sysmem(addr, 0);
1123 
1124 	if (argc >= 2 && strcmp(argv[1], "-")) {
1125 		size = simple_strtoul(argv[1], NULL, 16);
1126 	} else if (chk) {
1127 		puts("## Error: external checksum format must pass size\n");
1128 		return CMD_RET_FAILURE;
1129 	} else {
1130 		char *s = ptr;
1131 
1132 		size = 0;
1133 
1134 		while (size < MAX_ENV_SIZE) {
1135 			if ((*s == sep) && (*(s+1) == '\0'))
1136 				break;
1137 			++s;
1138 			++size;
1139 		}
1140 		if (size == MAX_ENV_SIZE) {
1141 			printf("## Warning: Input data exceeds %d bytes"
1142 				" - truncated\n", MAX_ENV_SIZE);
1143 		}
1144 		size += 2;
1145 		printf("## Info: input data size = %zu = 0x%zX\n", size, size);
1146 	}
1147 
1148 	if (argc > 2)
1149 		wl = 1;
1150 
1151 	if (chk) {
1152 		uint32_t crc;
1153 		env_t *ep = (env_t *)ptr;
1154 
1155 		size -= offsetof(env_t, data);
1156 		memcpy(&crc, &ep->crc, sizeof(crc));
1157 
1158 		if (crc32(0, ep->data, size) != crc) {
1159 			puts("## Error: bad CRC, import failed\n");
1160 			return 1;
1161 		}
1162 		ptr = (char *)ep->data;
1163 	}
1164 
1165 	if (!himport_r(&env_htab, ptr, size, sep, del ? 0 : H_NOCLEAR,
1166 		       crlf_is_lf, wl ? argc - 2 : 0, wl ? &argv[2] : NULL)) {
1167 		pr_err("## Error: Environment import failed: errno = %d\n",
1168 		       errno);
1169 		return 1;
1170 	}
1171 	gd->flags |= GD_FLG_ENV_READY;
1172 
1173 	return 0;
1174 
1175 sep_err:
1176 	printf("## %s: only one of \"-b\", \"-c\" or \"-t\" allowed\n",
1177 		cmd);
1178 	return 1;
1179 }
1180 #endif
1181 
1182 #if defined(CONFIG_CMD_NVEDIT_INFO)
1183 /*
1184  * print_env_info - print environment information
1185  */
print_env_info(void)1186 static int print_env_info(void)
1187 {
1188 	const char *value;
1189 
1190 	/* print environment validity value */
1191 	switch (gd->env_valid) {
1192 	case ENV_INVALID:
1193 		value = "invalid";
1194 		break;
1195 	case ENV_VALID:
1196 		value = "valid";
1197 		break;
1198 	case ENV_REDUND:
1199 		value = "redundant";
1200 		break;
1201 	default:
1202 		value = "unknown";
1203 		break;
1204 	}
1205 	printf("env_valid = %s\n", value);
1206 
1207 	/* print environment ready flag */
1208 	value = gd->flags & GD_FLG_ENV_READY ? "true" : "false";
1209 	printf("env_ready = %s\n", value);
1210 
1211 	/* print environment using default flag */
1212 	value = gd->flags & GD_FLG_ENV_DEFAULT ? "true" : "false";
1213 	printf("env_use_default = %s\n", value);
1214 
1215 	return CMD_RET_SUCCESS;
1216 }
1217 
1218 #define ENV_INFO_IS_DEFAULT	BIT(0) /* default environment bit mask */
1219 #define ENV_INFO_IS_PERSISTED	BIT(1) /* environment persistence bit mask */
1220 
1221 /*
1222  * env info - display environment information
1223  * env info [-d] - evaluate whether default environment is used
1224  * env info [-p] - evaluate whether environment can be persisted
1225  */
do_env_info(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])1226 static int do_env_info(cmd_tbl_t *cmdtp, int flag,
1227 		       int argc, char * const argv[])
1228 {
1229 	int eval_flags = 0;
1230 	int eval_results = 0;
1231 
1232 	/* display environment information */
1233 	if (argc <= 1)
1234 		return print_env_info();
1235 
1236 	/* process options */
1237 	while (--argc > 0 && **++argv == '-') {
1238 		char *arg = *argv;
1239 
1240 		while (*++arg) {
1241 			switch (*arg) {
1242 			case 'd':
1243 				eval_flags |= ENV_INFO_IS_DEFAULT;
1244 				break;
1245 			case 'p':
1246 				eval_flags |= ENV_INFO_IS_PERSISTED;
1247 				break;
1248 			default:
1249 				return CMD_RET_USAGE;
1250 			}
1251 		}
1252 	}
1253 
1254 	/* evaluate whether default environment is used */
1255 	if (eval_flags & ENV_INFO_IS_DEFAULT) {
1256 		if (gd->flags & GD_FLG_ENV_DEFAULT) {
1257 			printf("Default environment is used\n");
1258 			eval_results |= ENV_INFO_IS_DEFAULT;
1259 		} else {
1260 			printf("Environment was loaded from persistent storage\n");
1261 		}
1262 	}
1263 
1264 	/* evaluate whether environment can be persisted */
1265 	if (eval_flags & ENV_INFO_IS_PERSISTED) {
1266 #if defined(CONFIG_CMD_SAVEENV) && !defined(CONFIG_ENV_IS_NOWHERE)
1267 		printf("Environment can be persisted\n");
1268 		eval_results |= ENV_INFO_IS_PERSISTED;
1269 #else
1270 		printf("Environment cannot be persisted\n");
1271 #endif
1272 	}
1273 
1274 	/* The result of evaluations is combined with AND */
1275 	if (eval_flags != eval_results)
1276 		return CMD_RET_FAILURE;
1277 
1278 	return CMD_RET_SUCCESS;
1279 }
1280 #endif
1281 
1282 #if defined(CONFIG_CMD_ENV_EXISTS)
do_env_exists(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])1283 static int do_env_exists(cmd_tbl_t *cmdtp, int flag, int argc,
1284 		       char * const argv[])
1285 {
1286 	struct env_entry e, *ep;
1287 
1288 	if (argc < 2)
1289 		return CMD_RET_USAGE;
1290 
1291 	e.key = argv[1];
1292 	e.data = NULL;
1293 	hsearch_r(e, ENV_FIND, &ep, &env_htab, 0);
1294 
1295 	return (ep == NULL) ? 1 : 0;
1296 }
1297 #endif
1298 
1299 /*
1300  * New command line interface: "env" command with subcommands
1301  */
1302 static cmd_tbl_t cmd_env_sub[] = {
1303 #if defined(CONFIG_CMD_ASKENV)
1304 	U_BOOT_CMD_MKENT(ask, CONFIG_SYS_MAXARGS, 1, do_env_ask, "", ""),
1305 #endif
1306 
1307 #ifndef CONFIG_MINI_BOOT
1308 	U_BOOT_CMD_MKENT(default, 1, 0, do_env_default, "", ""),
1309 	U_BOOT_CMD_MKENT(delete, CONFIG_SYS_MAXARGS, 0, do_env_delete, "", ""),
1310 #endif /* CONFIG_MINI_BOOT */
1311 #if defined(CONFIG_CMD_EDITENV)
1312 	U_BOOT_CMD_MKENT(edit, 2, 0, do_env_edit, "", ""),
1313 #endif
1314 #if defined(CONFIG_CMD_ENV_CALLBACK)
1315 	U_BOOT_CMD_MKENT(callbacks, 1, 0, do_env_callback, "", ""),
1316 #endif
1317 #if defined(CONFIG_CMD_ENV_FLAGS)
1318 	U_BOOT_CMD_MKENT(flags, 1, 0, do_env_flags, "", ""),
1319 #endif
1320 #if defined(CONFIG_CMD_EXPORTENV)
1321 	U_BOOT_CMD_MKENT(export, 4, 0, do_env_export, "", ""),
1322 #endif
1323 #if defined(CONFIG_CMD_GREPENV)
1324 	U_BOOT_CMD_MKENT(grep, CONFIG_SYS_MAXARGS, 1, do_env_grep, "", ""),
1325 #endif
1326 #if defined(CONFIG_CMD_IMPORTENV)
1327 	U_BOOT_CMD_MKENT(import, 5, 0, do_env_import, "", ""),
1328 #endif
1329 #if defined(CONFIG_CMD_NVEDIT_INFO)
1330 	U_BOOT_CMD_MKENT(info, 2, 0, do_env_info, "", ""),
1331 #endif
1332 	U_BOOT_CMD_MKENT(print, CONFIG_SYS_MAXARGS, 1, do_env_print, "", ""),
1333 #if defined(CONFIG_CMD_RUN)
1334 	U_BOOT_CMD_MKENT(run, CONFIG_SYS_MAXARGS, 1, do_run, "", ""),
1335 #endif
1336 #if defined(CONFIG_CMD_SAVEENV) && defined(ENV_IS_IN_DEVICE)
1337 	U_BOOT_CMD_MKENT(save, 1, 0, do_env_save, "", ""),
1338 #if defined(CONFIG_CMD_ERASEENV)
1339 	U_BOOT_CMD_MKENT(erase, 1, 0, do_env_erase, "", ""),
1340 #endif
1341 #endif
1342 	U_BOOT_CMD_MKENT(set, CONFIG_SYS_MAXARGS, 0, do_env_set, "", ""),
1343 #if defined(CONFIG_CMD_ENV_EXISTS)
1344 	U_BOOT_CMD_MKENT(exists, 2, 0, do_env_exists, "", ""),
1345 #endif
1346 };
1347 
1348 #if defined(CONFIG_NEEDS_MANUAL_RELOC)
env_reloc(void)1349 void env_reloc(void)
1350 {
1351 	fixup_cmdtable(cmd_env_sub, ARRAY_SIZE(cmd_env_sub));
1352 }
1353 #endif
1354 
do_env(cmd_tbl_t * cmdtp,int flag,int argc,char * const argv[])1355 static int do_env(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1356 {
1357 	cmd_tbl_t *cp;
1358 
1359 	if (argc < 2)
1360 		return CMD_RET_USAGE;
1361 
1362 	/* drop initial "env" arg */
1363 	argc--;
1364 	argv++;
1365 
1366 	cp = find_cmd_tbl(argv[0], cmd_env_sub, ARRAY_SIZE(cmd_env_sub));
1367 
1368 	if (cp)
1369 		return cp->cmd(cmdtp, flag, argc, argv);
1370 
1371 	return CMD_RET_USAGE;
1372 }
1373 
1374 #ifdef CONFIG_SYS_LONGHELP
1375 static char env_help_text[] =
1376 #if defined(CONFIG_CMD_ASKENV)
1377 	"ask name [message] [size] - ask for environment variable\nenv "
1378 #endif
1379 #if defined(CONFIG_CMD_ENV_CALLBACK)
1380 	"callbacks - print callbacks and their associated variables\nenv "
1381 #endif
1382 	"default [-f] -a - [forcibly] reset default environment\n"
1383 	"env default [-f] var [...] - [forcibly] reset variable(s) to their default values\n"
1384 	"env delete [-f] var [...] - [forcibly] delete variable(s)\n"
1385 #if defined(CONFIG_CMD_EDITENV)
1386 	"env edit name - edit environment variable\n"
1387 #endif
1388 #if defined(CONFIG_CMD_ENV_EXISTS)
1389 	"env exists name - tests for existence of variable\n"
1390 #endif
1391 #if defined(CONFIG_CMD_EXPORTENV)
1392 	"env export [-t | -b | -c] [-s size] addr [var ...] - export environment\n"
1393 #endif
1394 #if defined(CONFIG_CMD_ENV_FLAGS)
1395 	"env flags - print variables that have non-default flags\n"
1396 #endif
1397 #if defined(CONFIG_CMD_GREPENV)
1398 #ifdef CONFIG_REGEX
1399 	"env grep [-e] [-n | -v | -b] string [...] - search environment\n"
1400 #else
1401 	"env grep [-n | -v | -b] string [...] - search environment\n"
1402 #endif
1403 #endif
1404 #if defined(CONFIG_CMD_IMPORTENV)
1405 	"env import [-d] [-t [-r] | -b | -c] addr [size] [var ...] - import environment\n"
1406 #endif
1407 #if defined(CONFIG_CMD_NVEDIT_INFO)
1408 	"env info - display environment information\n"
1409 	"env info [-d] - whether default environment is used\n"
1410 	"env info [-p] - whether environment can be persisted\n"
1411 #endif
1412 	"env print [-a | name ...] - print environment\n"
1413 #if defined(CONFIG_CMD_NVEDIT_EFI)
1414 	"env print -e [-guid guid|-all][-n] [name ...] - print UEFI environment\n"
1415 #endif
1416 #if defined(CONFIG_CMD_RUN)
1417 	"env run var [...] - run commands in an environment variable\n"
1418 #endif
1419 #if defined(CONFIG_CMD_SAVEENV) && defined(ENV_IS_IN_DEVICE)
1420 	"env save - save environment\n"
1421 #if defined(CONFIG_CMD_ERASEENV)
1422 	"env erase - erase environment\n"
1423 #endif
1424 #endif
1425 #if defined(CONFIG_CMD_NVEDIT_EFI)
1426 	"env set -e [-nv][-bs][-rt][-a][-i addr,size][-v] name [arg ...]\n"
1427 	"    - set UEFI variable; unset if '-i' or 'arg' not specified\n"
1428 #endif
1429 	"env set [-f] name [arg ...]\n";
1430 #endif
1431 
1432 U_BOOT_CMD(
1433 	env, CONFIG_SYS_MAXARGS, 1, do_env,
1434 	"environment handling commands", env_help_text
1435 );
1436 
1437 /*
1438  * Old command line interface, kept for compatibility
1439  */
1440 
1441 #if defined(CONFIG_CMD_EDITENV)
1442 U_BOOT_CMD_COMPLETE(
1443 	editenv, 2, 0,	do_env_edit,
1444 	"edit environment variable",
1445 	"name\n"
1446 	"    - edit environment variable 'name'",
1447 	var_complete
1448 );
1449 #endif
1450 
1451 U_BOOT_CMD_COMPLETE(
1452 	printenv, CONFIG_SYS_MAXARGS, 1,	do_env_print,
1453 	"print environment variables",
1454 	"[-a]\n    - print [all] values of all environment variables\n"
1455 #if defined(CONFIG_CMD_NVEDIT_EFI)
1456 	"printenv -e [-guid guid|-all][-n] [name ...]\n"
1457 	"    - print UEFI variable 'name' or all the variables\n"
1458 	"      \"-n\": suppress dumping variable's value\n"
1459 #endif
1460 	"printenv name ...\n"
1461 	"    - print value of environment variable 'name'",
1462 	var_complete
1463 );
1464 
1465 #ifdef CONFIG_CMD_GREPENV
1466 U_BOOT_CMD_COMPLETE(
1467 	grepenv, CONFIG_SYS_MAXARGS, 0,  do_env_grep,
1468 	"search environment variables",
1469 #ifdef CONFIG_REGEX
1470 	"[-e] [-n | -v | -b] string ...\n"
1471 #else
1472 	"[-n | -v | -b] string ...\n"
1473 #endif
1474 	"    - list environment name=value pairs matching 'string'\n"
1475 #ifdef CONFIG_REGEX
1476 	"      \"-e\": enable regular expressions;\n"
1477 #endif
1478 	"      \"-n\": search variable names; \"-v\": search values;\n"
1479 	"      \"-b\": search both names and values (default)",
1480 	var_complete
1481 );
1482 #endif
1483 
1484 U_BOOT_CMD_COMPLETE(
1485 	setenv, CONFIG_SYS_MAXARGS, 0,	do_env_set,
1486 	"set environment variables",
1487 #if defined(CONFIG_CMD_NVEDIT_EFI)
1488 	"-e [-guid guid][-nv][-bs][-rt][-a][-v]\n"
1489 	"        [-i addr,size name], or [name [value ...]]\n"
1490 	"    - set UEFI variable 'name' to 'value' ...'\n"
1491 	"      \"-guid\": set vendor guid\n"
1492 	"      \"-nv\": set non-volatile attribute\n"
1493 	"      \"-bs\": set boot-service attribute\n"
1494 	"      \"-rt\": set runtime attribute\n"
1495 	"      \"-a\": append-write\n"
1496 	"      \"-i addr,size\": use <addr,size> as variable's value\n"
1497 	"      \"-v\": verbose message\n"
1498 	"    - delete UEFI variable 'name' if 'value' not specified\n"
1499 #endif
1500 	"setenv [-f] name value ...\n"
1501 	"    - [forcibly] set environment variable 'name' to 'value ...'\n"
1502 	"setenv [-f] name\n"
1503 	"    - [forcibly] delete environment variable 'name'",
1504 	var_complete
1505 );
1506 
1507 #if defined(CONFIG_CMD_ASKENV)
1508 
1509 U_BOOT_CMD(
1510 	askenv,	CONFIG_SYS_MAXARGS,	1,	do_env_ask,
1511 	"get environment variables from stdin",
1512 	"name [message] [size]\n"
1513 	"    - get environment variable 'name' from stdin (max 'size' chars)"
1514 );
1515 #endif
1516 
1517 #if defined(CONFIG_CMD_RUN)
1518 U_BOOT_CMD_COMPLETE(
1519 	run,	CONFIG_SYS_MAXARGS,	1,	do_run,
1520 	"run commands in an environment variable",
1521 	"var [...]\n"
1522 	"    - run the commands in the environment variable(s) 'var'",
1523 	var_complete
1524 );
1525 #endif
1526 #endif /* CONFIG_SPL_BUILD */
1527