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