]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - common/cmd_nvedit.c
"env grep" - add options to grep in name, value, or both.
[karo-tx-uboot.git] / common / cmd_nvedit.c
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  * See file CREDITS for list of people who contributed to this
11  * project.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License as
15  * published by the Free Software Foundation; either version 2 of
16  * the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
26  * MA 02111-1307 USA
27  */
28
29 /*
30  * Support for persistent environment data
31  *
32  * The "environment" is stored on external storage as a list of '\0'
33  * terminated "name=value" strings. The end of the list is marked by
34  * a double '\0'. The environment is preceeded by a 32 bit CRC over
35  * the data part and, in case of redundant environment, a byte of
36  * flags.
37  *
38  * This linearized representation will also be used before
39  * relocation, i. e. as long as we don't have a full C runtime
40  * environment. After that, we use a hash table.
41  */
42
43 #include <common.h>
44 #include <command.h>
45 #include <environment.h>
46 #include <search.h>
47 #include <errno.h>
48 #include <malloc.h>
49 #include <watchdog.h>
50 #include <linux/stddef.h>
51 #include <asm/byteorder.h>
52
53 DECLARE_GLOBAL_DATA_PTR;
54
55 #if     !defined(CONFIG_ENV_IS_IN_EEPROM)       && \
56         !defined(CONFIG_ENV_IS_IN_FLASH)        && \
57         !defined(CONFIG_ENV_IS_IN_DATAFLASH)    && \
58         !defined(CONFIG_ENV_IS_IN_MMC)          && \
59         !defined(CONFIG_ENV_IS_IN_FAT)          && \
60         !defined(CONFIG_ENV_IS_IN_NAND)         && \
61         !defined(CONFIG_ENV_IS_IN_NVRAM)        && \
62         !defined(CONFIG_ENV_IS_IN_ONENAND)      && \
63         !defined(CONFIG_ENV_IS_IN_SPI_FLASH)    && \
64         !defined(CONFIG_ENV_IS_IN_REMOTE)       && \
65         !defined(CONFIG_ENV_IS_IN_UBI)          && \
66         !defined(CONFIG_ENV_IS_NOWHERE)
67 # error Define one of CONFIG_ENV_IS_IN_{EEPROM|FLASH|DATAFLASH|ONENAND|\
68 SPI_FLASH|NVRAM|MMC|FAT|REMOTE|UBI} or CONFIG_ENV_IS_NOWHERE
69 #endif
70
71 /*
72  * Maximum expected input data size for import command
73  */
74 #define MAX_ENV_SIZE    (1 << 20)       /* 1 MiB */
75
76 /*
77  * This variable is incremented on each do_env_set(), so it can
78  * be used via get_env_id() as an indication, if the environment
79  * has changed or not. So it is possible to reread an environment
80  * variable only if the environment was changed ... done so for
81  * example in NetInitLoop()
82  */
83 static int env_id = 1;
84
85 int get_env_id(void)
86 {
87         return env_id;
88 }
89
90 #ifndef CONFIG_SPL_BUILD
91 /*
92  * Command interface: print one or all environment variables
93  *
94  * Returns 0 in case of error, or length of printed string
95  */
96 static int env_print(char *name, int flag)
97 {
98         char *res = NULL;
99         ssize_t len;
100
101         if (name) {             /* print a single name */
102                 ENTRY e, *ep;
103
104                 e.key = name;
105                 e.data = NULL;
106                 hsearch_r(e, FIND, &ep, &env_htab, flag);
107                 if (ep == NULL)
108                         return 0;
109                 len = printf("%s=%s\n", ep->key, ep->data);
110                 return len;
111         }
112
113         /* print whole list */
114         len = hexport_r(&env_htab, '\n', flag, &res, 0, 0, NULL);
115
116         if (len > 0) {
117                 puts(res);
118                 free(res);
119                 return len;
120         }
121
122         /* should never happen */
123         printf("## Error: cannot export environment\n");
124         return 0;
125 }
126
127 static int do_env_print(cmd_tbl_t *cmdtp, int flag, int argc,
128                         char * const argv[])
129 {
130         int i;
131         int rcode = 0;
132         int env_flag = H_HIDE_DOT;
133
134         if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'a') {
135                 argc--;
136                 argv++;
137                 env_flag &= ~H_HIDE_DOT;
138         }
139
140         if (argc == 1) {
141                 /* print all env vars */
142                 rcode = env_print(NULL, env_flag);
143                 if (!rcode)
144                         return 1;
145                 printf("\nEnvironment size: %d/%ld bytes\n",
146                         rcode, (ulong)ENV_SIZE);
147                 return 0;
148         }
149
150         /* print selected env vars */
151         env_flag &= ~H_HIDE_DOT;
152         for (i = 1; i < argc; ++i) {
153                 int rc = env_print(argv[i], env_flag);
154                 if (!rc) {
155                         printf("## Error: \"%s\" not defined\n", argv[i]);
156                         ++rcode;
157                 }
158         }
159
160         return rcode;
161 }
162
163 #ifdef CONFIG_CMD_GREPENV
164 static int do_env_grep(cmd_tbl_t *cmdtp, int flag,
165                        int argc, char * const argv[])
166 {
167         char *res = NULL;
168         int len, grep_flags;
169
170         if (argc < 2)
171                 return CMD_RET_USAGE;
172
173         grep_flags = H_MATCH_BOTH;
174
175         while (argc > 1 && **(argv + 1) == '-') {
176                 char *arg = *++argv;
177
178                 --argc;
179                 while (*++arg) {
180                         switch (*arg) {
181                         case 'n':               /* grep for name */
182                                 grep_flags = H_MATCH_KEY;
183                                 break;
184                         case 'v':               /* grep for value */
185                                 grep_flags = H_MATCH_DATA;
186                                 break;
187                         case 'b':               /* grep for both */
188                                 grep_flags = H_MATCH_BOTH;
189                                 break;
190                         case '-':
191                                 goto DONE;
192                         default:
193                                 return CMD_RET_USAGE;
194                         }
195                 }
196         }
197
198 DONE:
199         len = hexport_r(&env_htab, '\n',
200                         flag | grep_flags | H_MATCH_SUBSTR,
201                         &res, 0, argc, argv);
202
203         if (len > 0) {
204                 puts(res);
205                 free(res);
206         }
207
208         if (len < 2)
209                 return 1;
210
211         return 0;
212 }
213 #endif
214 #endif /* CONFIG_SPL_BUILD */
215
216 /*
217  * Set a new environment variable,
218  * or replace or delete an existing one.
219  */
220 static int _do_env_set(int flag, int argc, char * const argv[])
221 {
222         int   i, len;
223         char  *name, *value, *s;
224         ENTRY e, *ep;
225         int env_flag = H_INTERACTIVE;
226
227         debug("Initial value for argc=%d\n", argc);
228         while (argc > 1 && **(argv + 1) == '-') {
229                 char *arg = *++argv;
230
231                 --argc;
232                 while (*++arg) {
233                         switch (*arg) {
234                         case 'f':               /* force */
235                                 env_flag |= H_FORCE;
236                                 break;
237                         default:
238                                 return CMD_RET_USAGE;
239                         }
240                 }
241         }
242         debug("Final value for argc=%d\n", argc);
243         name = argv[1];
244         value = argv[2];
245
246         if (strchr(name, '=')) {
247                 printf("## Error: illegal character '='"
248                        "in variable name \"%s\"\n", name);
249                 return 1;
250         }
251
252         env_id++;
253
254         /* Delete only ? */
255         if (argc < 3 || argv[2] == NULL) {
256                 int rc = hdelete_r(name, &env_htab, env_flag);
257                 return !rc;
258         }
259
260         /*
261          * Insert / replace new value
262          */
263         for (i = 2, len = 0; i < argc; ++i)
264                 len += strlen(argv[i]) + 1;
265
266         value = malloc(len);
267         if (value == NULL) {
268                 printf("## Can't malloc %d bytes\n", len);
269                 return 1;
270         }
271         for (i = 2, s = value; i < argc; ++i) {
272                 char *v = argv[i];
273
274                 while ((*s++ = *v++) != '\0')
275                         ;
276                 *(s - 1) = ' ';
277         }
278         if (s != value)
279                 *--s = '\0';
280
281         e.key   = name;
282         e.data  = value;
283         hsearch_r(e, ENTER, &ep, &env_htab, env_flag);
284         free(value);
285         if (!ep) {
286                 printf("## Error inserting \"%s\" variable, errno=%d\n",
287                         name, errno);
288                 return 1;
289         }
290
291         return 0;
292 }
293
294 int setenv(const char *varname, const char *varvalue)
295 {
296         const char * const argv[4] = { "setenv", varname, varvalue, NULL };
297
298         /* before import into hashtable */
299         if (!(gd->flags & GD_FLG_ENV_READY))
300                 return 1;
301
302         if (varvalue == NULL || varvalue[0] == '\0')
303                 return _do_env_set(0, 2, (char * const *)argv);
304         else
305                 return _do_env_set(0, 3, (char * const *)argv);
306 }
307
308 /**
309  * Set an environment variable to an integer value
310  *
311  * @param varname       Environmet variable to set
312  * @param value         Value to set it to
313  * @return 0 if ok, 1 on error
314  */
315 int setenv_ulong(const char *varname, ulong value)
316 {
317         /* TODO: this should be unsigned */
318         char *str = simple_itoa(value);
319
320         return setenv(varname, str);
321 }
322
323 /**
324  * Set an environment variable to an value in hex
325  *
326  * @param varname       Environmet variable to set
327  * @param value         Value to set it to
328  * @return 0 if ok, 1 on error
329  */
330 int setenv_hex(const char *varname, ulong value)
331 {
332         char str[17];
333
334         sprintf(str, "%lx", value);
335         return setenv(varname, str);
336 }
337
338 ulong getenv_hex(const char *varname, ulong default_val)
339 {
340         const char *s;
341         ulong value;
342         char *endp;
343
344         s = getenv(varname);
345         if (s)
346                 value = simple_strtoul(s, &endp, 16);
347         if (!s || endp == s)
348                 return default_val;
349
350         return value;
351 }
352
353 #ifndef CONFIG_SPL_BUILD
354 static int do_env_set(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
355 {
356         if (argc < 2)
357                 return CMD_RET_USAGE;
358
359         return _do_env_set(flag, argc, argv);
360 }
361
362 /*
363  * Prompt for environment variable
364  */
365 #if defined(CONFIG_CMD_ASKENV)
366 int do_env_ask(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
367 {
368         char message[CONFIG_SYS_CBSIZE];
369         int i, len, pos, size;
370         char *local_args[4];
371         char *endptr;
372
373         local_args[0] = argv[0];
374         local_args[1] = argv[1];
375         local_args[2] = NULL;
376         local_args[3] = NULL;
377
378         /*
379          * Check the syntax:
380          *
381          * env_ask envname [message1 ...] [size]
382          */
383         if (argc == 1)
384                 return CMD_RET_USAGE;
385
386         /*
387          * We test the last argument if it can be converted
388          * into a decimal number.  If yes, we assume it's
389          * the size.  Otherwise we echo it as part of the
390          * message.
391          */
392         i = simple_strtoul(argv[argc - 1], &endptr, 10);
393         if (*endptr != '\0') {                  /* no size */
394                 size = CONFIG_SYS_CBSIZE - 1;
395         } else {                                /* size given */
396                 size = i;
397                 --argc;
398         }
399
400         if (argc <= 2) {
401                 sprintf(message, "Please enter '%s': ", argv[1]);
402         } else {
403                 /* env_ask envname message1 ... messagen [size] */
404                 for (i = 2, pos = 0; i < argc; i++) {
405                         if (pos)
406                                 message[pos++] = ' ';
407
408                         strcpy(message + pos, argv[i]);
409                         pos += strlen(argv[i]);
410                 }
411                 message[pos++] = ' ';
412                 message[pos] = '\0';
413         }
414
415         if (size >= CONFIG_SYS_CBSIZE)
416                 size = CONFIG_SYS_CBSIZE - 1;
417
418         if (size <= 0)
419                 return 1;
420
421         /* prompt for input */
422         len = readline(message);
423
424         if (size < len)
425                 console_buffer[size] = '\0';
426
427         len = 2;
428         if (console_buffer[0] != '\0') {
429                 local_args[2] = console_buffer;
430                 len = 3;
431         }
432
433         /* Continue calling setenv code */
434         return _do_env_set(flag, len, local_args);
435 }
436 #endif
437
438 #if defined(CONFIG_CMD_ENV_CALLBACK)
439 static int print_static_binding(const char *var_name, const char *callback_name)
440 {
441         printf("\t%-20s %-20s\n", var_name, callback_name);
442
443         return 0;
444 }
445
446 static int print_active_callback(ENTRY *entry)
447 {
448         struct env_clbk_tbl *clbkp;
449         int i;
450         int num_callbacks;
451
452         if (entry->callback == NULL)
453                 return 0;
454
455         /* look up the callback in the linker-list */
456         num_callbacks = ll_entry_count(struct env_clbk_tbl, env_clbk);
457         for (i = 0, clbkp = ll_entry_start(struct env_clbk_tbl, env_clbk);
458              i < num_callbacks;
459              i++, clbkp++) {
460 #if defined(CONFIG_NEEDS_MANUAL_RELOC)
461                 if (entry->callback == clbkp->callback + gd->reloc_off)
462 #else
463                 if (entry->callback == clbkp->callback)
464 #endif
465                         break;
466         }
467
468         if (i == num_callbacks)
469                 /* this should probably never happen, but just in case... */
470                 printf("\t%-20s %p\n", entry->key, entry->callback);
471         else
472                 printf("\t%-20s %-20s\n", entry->key, clbkp->name);
473
474         return 0;
475 }
476
477 /*
478  * Print the callbacks available and what they are bound to
479  */
480 int do_env_callback(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
481 {
482         struct env_clbk_tbl *clbkp;
483         int i;
484         int num_callbacks;
485
486         /* Print the available callbacks */
487         puts("Available callbacks:\n");
488         puts("\tCallback Name\n");
489         puts("\t-------------\n");
490         num_callbacks = ll_entry_count(struct env_clbk_tbl, env_clbk);
491         for (i = 0, clbkp = ll_entry_start(struct env_clbk_tbl, env_clbk);
492              i < num_callbacks;
493              i++, clbkp++)
494                 printf("\t%s\n", clbkp->name);
495         puts("\n");
496
497         /* Print the static bindings that may exist */
498         puts("Static callback bindings:\n");
499         printf("\t%-20s %-20s\n", "Variable Name", "Callback Name");
500         printf("\t%-20s %-20s\n", "-------------", "-------------");
501         env_attr_walk(ENV_CALLBACK_LIST_STATIC, print_static_binding);
502         puts("\n");
503
504         /* walk through each variable and print the callback if it has one */
505         puts("Active callback bindings:\n");
506         printf("\t%-20s %-20s\n", "Variable Name", "Callback Name");
507         printf("\t%-20s %-20s\n", "-------------", "-------------");
508         hwalk_r(&env_htab, print_active_callback);
509         return 0;
510 }
511 #endif
512
513 #if defined(CONFIG_CMD_ENV_FLAGS)
514 static int print_static_flags(const char *var_name, const char *flags)
515 {
516         enum env_flags_vartype type = env_flags_parse_vartype(flags);
517         enum env_flags_varaccess access = env_flags_parse_varaccess(flags);
518
519         printf("\t%-20s %-20s %-20s\n", var_name,
520                 env_flags_get_vartype_name(type),
521                 env_flags_get_varaccess_name(access));
522
523         return 0;
524 }
525
526 static int print_active_flags(ENTRY *entry)
527 {
528         enum env_flags_vartype type;
529         enum env_flags_varaccess access;
530
531         if (entry->flags == 0)
532                 return 0;
533
534         type = (enum env_flags_vartype)
535                 (entry->flags & ENV_FLAGS_VARTYPE_BIN_MASK);
536         access = env_flags_parse_varaccess_from_binflags(entry->flags);
537         printf("\t%-20s %-20s %-20s\n", entry->key,
538                 env_flags_get_vartype_name(type),
539                 env_flags_get_varaccess_name(access));
540
541         return 0;
542 }
543
544 /*
545  * Print the flags available and what variables have flags
546  */
547 int do_env_flags(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
548 {
549         /* Print the available variable types */
550         printf("Available variable type flags (position %d):\n",
551                 ENV_FLAGS_VARTYPE_LOC);
552         puts("\tFlag\tVariable Type Name\n");
553         puts("\t----\t------------------\n");
554         env_flags_print_vartypes();
555         puts("\n");
556
557         /* Print the available variable access types */
558         printf("Available variable access flags (position %d):\n",
559                 ENV_FLAGS_VARACCESS_LOC);
560         puts("\tFlag\tVariable Access Name\n");
561         puts("\t----\t--------------------\n");
562         env_flags_print_varaccess();
563         puts("\n");
564
565         /* Print the static flags that may exist */
566         puts("Static flags:\n");
567         printf("\t%-20s %-20s %-20s\n", "Variable Name", "Variable Type",
568                 "Variable Access");
569         printf("\t%-20s %-20s %-20s\n", "-------------", "-------------",
570                 "---------------");
571         env_attr_walk(ENV_FLAGS_LIST_STATIC, print_static_flags);
572         puts("\n");
573
574         /* walk through each variable and print the flags if non-default */
575         puts("Active flags:\n");
576         printf("\t%-20s %-20s %-20s\n", "Variable Name", "Variable Type",
577                 "Variable Access");
578         printf("\t%-20s %-20s %-20s\n", "-------------", "-------------",
579                 "---------------");
580         hwalk_r(&env_htab, print_active_flags);
581         return 0;
582 }
583 #endif
584
585 /*
586  * Interactively edit an environment variable
587  */
588 #if defined(CONFIG_CMD_EDITENV)
589 static int do_env_edit(cmd_tbl_t *cmdtp, int flag, int argc,
590                        char * const argv[])
591 {
592         char buffer[CONFIG_SYS_CBSIZE];
593         char *init_val;
594
595         if (argc < 2)
596                 return CMD_RET_USAGE;
597
598         /* Set read buffer to initial value or empty sting */
599         init_val = getenv(argv[1]);
600         if (init_val)
601                 sprintf(buffer, "%s", init_val);
602         else
603                 buffer[0] = '\0';
604
605         if (readline_into_buffer("edit: ", buffer, 0) < 0)
606                 return 1;
607
608         return setenv(argv[1], buffer);
609 }
610 #endif /* CONFIG_CMD_EDITENV */
611 #endif /* CONFIG_SPL_BUILD */
612
613 /*
614  * Look up variable from environment,
615  * return address of storage for that variable,
616  * or NULL if not found
617  */
618 char *getenv(const char *name)
619 {
620         if (gd->flags & GD_FLG_ENV_READY) { /* after import into hashtable */
621                 ENTRY e, *ep;
622
623                 WATCHDOG_RESET();
624
625                 e.key   = name;
626                 e.data  = NULL;
627                 hsearch_r(e, FIND, &ep, &env_htab, 0);
628
629                 return ep ? ep->data : NULL;
630         }
631
632         /* restricted capabilities before import */
633         if (getenv_f(name, (char *)(gd->env_buf), sizeof(gd->env_buf)) > 0)
634                 return (char *)(gd->env_buf);
635
636         return NULL;
637 }
638
639 /*
640  * Look up variable from environment for restricted C runtime env.
641  */
642 int getenv_f(const char *name, char *buf, unsigned len)
643 {
644         int i, nxt;
645
646         for (i = 0; env_get_char(i) != '\0'; i = nxt + 1) {
647                 int val, n;
648
649                 for (nxt = i; env_get_char(nxt) != '\0'; ++nxt) {
650                         if (nxt >= CONFIG_ENV_SIZE)
651                                 return -1;
652                 }
653
654                 val = envmatch((uchar *)name, i);
655                 if (val < 0)
656                         continue;
657
658                 /* found; copy out */
659                 for (n = 0; n < len; ++n, ++buf) {
660                         *buf = env_get_char(val++);
661                         if (*buf == '\0')
662                                 return n;
663                 }
664
665                 if (n)
666                         *--buf = '\0';
667
668                 printf("env_buf [%d bytes] too small for value of \"%s\"\n",
669                         len, name);
670
671                 return n;
672         }
673
674         return -1;
675 }
676
677 /**
678  * Decode the integer value of an environment variable and return it.
679  *
680  * @param name          Name of environemnt variable
681  * @param base          Number base to use (normally 10, or 16 for hex)
682  * @param default_val   Default value to return if the variable is not
683  *                      found
684  * @return the decoded value, or default_val if not found
685  */
686 ulong getenv_ulong(const char *name, int base, ulong default_val)
687 {
688         /*
689          * We can use getenv() here, even before relocation, since the
690          * environment variable value is an integer and thus short.
691          */
692         const char *str = getenv(name);
693
694         return str ? simple_strtoul(str, NULL, base) : default_val;
695 }
696
697 #ifndef CONFIG_SPL_BUILD
698 #if defined(CONFIG_CMD_SAVEENV) && !defined(CONFIG_ENV_IS_NOWHERE)
699 static int do_env_save(cmd_tbl_t *cmdtp, int flag, int argc,
700                        char * const argv[])
701 {
702         printf("Saving Environment to %s...\n", env_name_spec);
703
704         return saveenv() ? 1 : 0;
705 }
706
707 U_BOOT_CMD(
708         saveenv, 1, 0,  do_env_save,
709         "save environment variables to persistent storage",
710         ""
711 );
712 #endif
713 #endif /* CONFIG_SPL_BUILD */
714
715
716 /*
717  * Match a name / name=value pair
718  *
719  * s1 is either a simple 'name', or a 'name=value' pair.
720  * i2 is the environment index for a 'name2=value2' pair.
721  * If the names match, return the index for the value2, else -1.
722  */
723 int envmatch(uchar *s1, int i2)
724 {
725         if (s1 == NULL)
726                 return -1;
727
728         while (*s1 == env_get_char(i2++))
729                 if (*s1++ == '=')
730                         return i2;
731
732         if (*s1 == '\0' && env_get_char(i2-1) == '=')
733                 return i2;
734
735         return -1;
736 }
737
738 #ifndef CONFIG_SPL_BUILD
739 static int do_env_default(cmd_tbl_t *cmdtp, int __flag,
740                           int argc, char * const argv[])
741 {
742         int all = 0, flag = 0;
743
744         debug("Initial value for argc=%d\n", argc);
745         while (--argc > 0 && **++argv == '-') {
746                 char *arg = *argv;
747
748                 while (*++arg) {
749                         switch (*arg) {
750                         case 'a':               /* default all */
751                                 all = 1;
752                                 break;
753                         case 'f':               /* force */
754                                 flag |= H_FORCE;
755                                 break;
756                         default:
757                                 return cmd_usage(cmdtp);
758                         }
759                 }
760         }
761         debug("Final value for argc=%d\n", argc);
762         if (all && (argc == 0)) {
763                 /* Reset the whole environment */
764                 set_default_env("## Resetting to default environment\n");
765                 return 0;
766         }
767         if (!all && (argc > 0)) {
768                 /* Reset individual variables */
769                 set_default_vars(argc, argv);
770                 return 0;
771         }
772
773         return cmd_usage(cmdtp);
774 }
775
776 static int do_env_delete(cmd_tbl_t *cmdtp, int flag,
777                          int argc, char * const argv[])
778 {
779         int env_flag = H_INTERACTIVE;
780         int ret = 0;
781
782         debug("Initial value for argc=%d\n", argc);
783         while (argc > 1 && **(argv + 1) == '-') {
784                 char *arg = *++argv;
785
786                 --argc;
787                 while (*++arg) {
788                         switch (*arg) {
789                         case 'f':               /* force */
790                                 env_flag |= H_FORCE;
791                                 break;
792                         default:
793                                 return CMD_RET_USAGE;
794                         }
795                 }
796         }
797         debug("Final value for argc=%d\n", argc);
798
799         env_id++;
800
801         while (--argc > 0) {
802                 char *name = *++argv;
803
804                 if (!hdelete_r(name, &env_htab, env_flag))
805                         ret = 1;
806         }
807
808         return ret;
809 }
810
811 #ifdef CONFIG_CMD_EXPORTENV
812 /*
813  * env export [-t | -b | -c] [-s size] addr [var ...]
814  *      -t:     export as text format; if size is given, data will be
815  *              padded with '\0' bytes; if not, one terminating '\0'
816  *              will be added (which is included in the "filesize"
817  *              setting so you can for exmple copy this to flash and
818  *              keep the termination).
819  *      -b:     export as binary format (name=value pairs separated by
820  *              '\0', list end marked by double "\0\0")
821  *      -c:     export as checksum protected environment format as
822  *              used for example by "saveenv" command
823  *      -s size:
824  *              size of output buffer
825  *      addr:   memory address where environment gets stored
826  *      var...  List of variable names that get included into the
827  *              export. Without arguments, the whole environment gets
828  *              exported.
829  *
830  * With "-c" and size is NOT given, then the export command will
831  * format the data as currently used for the persistent storage,
832  * i. e. it will use CONFIG_ENV_SECT_SIZE as output block size and
833  * prepend a valid CRC32 checksum and, in case of resundant
834  * environment, a "current" redundancy flag. If size is given, this
835  * value will be used instead of CONFIG_ENV_SECT_SIZE; again, CRC32
836  * checksum and redundancy flag will be inserted.
837  *
838  * With "-b" and "-t", always only the real data (including a
839  * terminating '\0' byte) will be written; here the optional size
840  * argument will be used to make sure not to overflow the user
841  * provided buffer; the command will abort if the size is not
842  * sufficient. Any remainign space will be '\0' padded.
843  *
844  * On successful return, the variable "filesize" will be set.
845  * Note that filesize includes the trailing/terminating '\0' byte(s).
846  *
847  * Usage szenario:  create a text snapshot/backup of the current settings:
848  *
849  *      => env export -t 100000
850  *      => era ${backup_addr} +${filesize}
851  *      => cp.b 100000 ${backup_addr} ${filesize}
852  *
853  * Re-import this snapshot, deleting all other settings:
854  *
855  *      => env import -d -t ${backup_addr}
856  */
857 static int do_env_export(cmd_tbl_t *cmdtp, int flag,
858                          int argc, char * const argv[])
859 {
860         char    buf[32];
861         char    *addr, *cmd, *res;
862         size_t  size = 0;
863         ssize_t len;
864         env_t   *envp;
865         char    sep = '\n';
866         int     chk = 0;
867         int     fmt = 0;
868
869         cmd = *argv;
870
871         while (--argc > 0 && **++argv == '-') {
872                 char *arg = *argv;
873                 while (*++arg) {
874                         switch (*arg) {
875                         case 'b':               /* raw binary format */
876                                 if (fmt++)
877                                         goto sep_err;
878                                 sep = '\0';
879                                 break;
880                         case 'c':               /* external checksum format */
881                                 if (fmt++)
882                                         goto sep_err;
883                                 sep = '\0';
884                                 chk = 1;
885                                 break;
886                         case 's':               /* size given */
887                                 if (--argc <= 0)
888                                         return cmd_usage(cmdtp);
889                                 size = simple_strtoul(*++argv, NULL, 16);
890                                 goto NXTARG;
891                         case 't':               /* text format */
892                                 if (fmt++)
893                                         goto sep_err;
894                                 sep = '\n';
895                                 break;
896                         default:
897                                 return CMD_RET_USAGE;
898                         }
899                 }
900 NXTARG:         ;
901         }
902
903         if (argc < 1)
904                 return CMD_RET_USAGE;
905
906         addr = (char *)simple_strtoul(argv[0], NULL, 16);
907
908         if (size)
909                 memset(addr, '\0', size);
910
911         argc--;
912         argv++;
913
914         if (sep) {              /* export as text file */
915                 len = hexport_r(&env_htab, sep,
916                                 H_MATCH_KEY | H_MATCH_IDENT,
917                                 &addr, size, argc, argv);
918                 if (len < 0) {
919                         error("Cannot export environment: errno = %d\n", errno);
920                         return 1;
921                 }
922                 sprintf(buf, "%zX", (size_t)len);
923                 setenv("filesize", buf);
924
925                 return 0;
926         }
927
928         envp = (env_t *)addr;
929
930         if (chk)                /* export as checksum protected block */
931                 res = (char *)envp->data;
932         else                    /* export as raw binary data */
933                 res = addr;
934
935         len = hexport_r(&env_htab, '\0',
936                         H_MATCH_KEY | H_MATCH_IDENT,
937                         &res, ENV_SIZE, argc, argv);
938         if (len < 0) {
939                 error("Cannot export environment: errno = %d\n", errno);
940                 return 1;
941         }
942
943         if (chk) {
944                 envp->crc = crc32(0, envp->data, ENV_SIZE);
945 #ifdef CONFIG_ENV_ADDR_REDUND
946                 envp->flags = ACTIVE_FLAG;
947 #endif
948         }
949         setenv_hex("filesize", len + offsetof(env_t, data));
950
951         return 0;
952
953 sep_err:
954         printf("## %s: only one of \"-b\", \"-c\" or \"-t\" allowed\n", cmd);
955         return 1;
956 }
957 #endif
958
959 #ifdef CONFIG_CMD_IMPORTENV
960 /*
961  * env import [-d] [-t | -b | -c] addr [size]
962  *      -d:     delete existing environment before importing;
963  *              otherwise overwrite / append to existion definitions
964  *      -t:     assume text format; either "size" must be given or the
965  *              text data must be '\0' terminated
966  *      -b:     assume binary format ('\0' separated, "\0\0" terminated)
967  *      -c:     assume checksum protected environment format
968  *      addr:   memory address to read from
969  *      size:   length of input data; if missing, proper '\0'
970  *              termination is mandatory
971  */
972 static int do_env_import(cmd_tbl_t *cmdtp, int flag,
973                          int argc, char * const argv[])
974 {
975         char    *cmd, *addr;
976         char    sep = '\n';
977         int     chk = 0;
978         int     fmt = 0;
979         int     del = 0;
980         size_t  size;
981
982         cmd = *argv;
983
984         while (--argc > 0 && **++argv == '-') {
985                 char *arg = *argv;
986                 while (*++arg) {
987                         switch (*arg) {
988                         case 'b':               /* raw binary format */
989                                 if (fmt++)
990                                         goto sep_err;
991                                 sep = '\0';
992                                 break;
993                         case 'c':               /* external checksum format */
994                                 if (fmt++)
995                                         goto sep_err;
996                                 sep = '\0';
997                                 chk = 1;
998                                 break;
999                         case 't':               /* text format */
1000                                 if (fmt++)
1001                                         goto sep_err;
1002                                 sep = '\n';
1003                                 break;
1004                         case 'd':
1005                                 del = 1;
1006                                 break;
1007                         default:
1008                                 return CMD_RET_USAGE;
1009                         }
1010                 }
1011         }
1012
1013         if (argc < 1)
1014                 return CMD_RET_USAGE;
1015
1016         if (!fmt)
1017                 printf("## Warning: defaulting to text format\n");
1018
1019         addr = (char *)simple_strtoul(argv[0], NULL, 16);
1020
1021         if (argc == 2) {
1022                 size = simple_strtoul(argv[1], NULL, 16);
1023         } else {
1024                 char *s = addr;
1025
1026                 size = 0;
1027
1028                 while (size < MAX_ENV_SIZE) {
1029                         if ((*s == sep) && (*(s+1) == '\0'))
1030                                 break;
1031                         ++s;
1032                         ++size;
1033                 }
1034                 if (size == MAX_ENV_SIZE) {
1035                         printf("## Warning: Input data exceeds %d bytes"
1036                                 " - truncated\n", MAX_ENV_SIZE);
1037                 }
1038                 size += 2;
1039                 printf("## Info: input data size = %zu = 0x%zX\n", size, size);
1040         }
1041
1042         if (chk) {
1043                 uint32_t crc;
1044                 env_t *ep = (env_t *)addr;
1045
1046                 size -= offsetof(env_t, data);
1047                 memcpy(&crc, &ep->crc, sizeof(crc));
1048
1049                 if (crc32(0, ep->data, size) != crc) {
1050                         puts("## Error: bad CRC, import failed\n");
1051                         return 1;
1052                 }
1053                 addr = (char *)ep->data;
1054         }
1055
1056         if (himport_r(&env_htab, addr, size, sep, del ? 0 : H_NOCLEAR,
1057                         0, NULL) == 0) {
1058                 error("Environment import failed: errno = %d\n", errno);
1059                 return 1;
1060         }
1061         gd->flags |= GD_FLG_ENV_READY;
1062
1063         return 0;
1064
1065 sep_err:
1066         printf("## %s: only one of \"-b\", \"-c\" or \"-t\" allowed\n",
1067                 cmd);
1068         return 1;
1069 }
1070 #endif
1071
1072 /*
1073  * New command line interface: "env" command with subcommands
1074  */
1075 static cmd_tbl_t cmd_env_sub[] = {
1076 #if defined(CONFIG_CMD_ASKENV)
1077         U_BOOT_CMD_MKENT(ask, CONFIG_SYS_MAXARGS, 1, do_env_ask, "", ""),
1078 #endif
1079         U_BOOT_CMD_MKENT(default, 1, 0, do_env_default, "", ""),
1080         U_BOOT_CMD_MKENT(delete, CONFIG_SYS_MAXARGS, 0, do_env_delete, "", ""),
1081 #if defined(CONFIG_CMD_EDITENV)
1082         U_BOOT_CMD_MKENT(edit, 2, 0, do_env_edit, "", ""),
1083 #endif
1084 #if defined(CONFIG_CMD_ENV_CALLBACK)
1085         U_BOOT_CMD_MKENT(callbacks, 1, 0, do_env_callback, "", ""),
1086 #endif
1087 #if defined(CONFIG_CMD_ENV_FLAGS)
1088         U_BOOT_CMD_MKENT(flags, 1, 0, do_env_flags, "", ""),
1089 #endif
1090 #if defined(CONFIG_CMD_EXPORTENV)
1091         U_BOOT_CMD_MKENT(export, 4, 0, do_env_export, "", ""),
1092 #endif
1093 #if defined(CONFIG_CMD_GREPENV)
1094         U_BOOT_CMD_MKENT(grep, CONFIG_SYS_MAXARGS, 1, do_env_grep, "", ""),
1095 #endif
1096 #if defined(CONFIG_CMD_IMPORTENV)
1097         U_BOOT_CMD_MKENT(import, 5, 0, do_env_import, "", ""),
1098 #endif
1099         U_BOOT_CMD_MKENT(print, CONFIG_SYS_MAXARGS, 1, do_env_print, "", ""),
1100 #if defined(CONFIG_CMD_RUN)
1101         U_BOOT_CMD_MKENT(run, CONFIG_SYS_MAXARGS, 1, do_run, "", ""),
1102 #endif
1103 #if defined(CONFIG_CMD_SAVEENV) && !defined(CONFIG_ENV_IS_NOWHERE)
1104         U_BOOT_CMD_MKENT(save, 1, 0, do_env_save, "", ""),
1105 #endif
1106         U_BOOT_CMD_MKENT(set, CONFIG_SYS_MAXARGS, 0, do_env_set, "", ""),
1107 };
1108
1109 #if defined(CONFIG_NEEDS_MANUAL_RELOC)
1110 void env_reloc(void)
1111 {
1112         fixup_cmdtable(cmd_env_sub, ARRAY_SIZE(cmd_env_sub));
1113 }
1114 #endif
1115
1116 static int do_env(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1117 {
1118         cmd_tbl_t *cp;
1119
1120         if (argc < 2)
1121                 return CMD_RET_USAGE;
1122
1123         /* drop initial "env" arg */
1124         argc--;
1125         argv++;
1126
1127         cp = find_cmd_tbl(argv[0], cmd_env_sub, ARRAY_SIZE(cmd_env_sub));
1128
1129         if (cp)
1130                 return cp->cmd(cmdtp, flag, argc, argv);
1131
1132         return CMD_RET_USAGE;
1133 }
1134
1135 #ifdef CONFIG_SYS_LONGHELP
1136 static char env_help_text[] =
1137 #if defined(CONFIG_CMD_ASKENV)
1138         "ask name [message] [size] - ask for environment variable\nenv "
1139 #endif
1140 #if defined(CONFIG_CMD_ENV_CALLBACK)
1141         "callbacks - print callbacks and their associated variables\nenv "
1142 #endif
1143         "default [-f] -a - [forcibly] reset default environment\n"
1144         "env default [-f] var [...] - [forcibly] reset variable(s) to their default values\n"
1145         "env delete [-f] var [...] - [forcibly] delete variable(s)\n"
1146 #if defined(CONFIG_CMD_EDITENV)
1147         "env edit name - edit environment variable\n"
1148 #endif
1149 #if defined(CONFIG_CMD_EXPORTENV)
1150         "env export [-t | -b | -c] [-s size] addr [var ...] - export environment\n"
1151 #endif
1152 #if defined(CONFIG_CMD_ENV_FLAGS)
1153         "env flags - print variables that have non-default flags\n"
1154 #endif
1155 #if defined(CONFIG_CMD_GREPENV)
1156         "env grep [-n | -v | -b] string [...] - search environment\n"
1157 #endif
1158 #if defined(CONFIG_CMD_IMPORTENV)
1159         "env import [-d] [-t | -b | -c] addr [size] - import environment\n"
1160 #endif
1161         "env print [-a | name ...] - print environment\n"
1162 #if defined(CONFIG_CMD_RUN)
1163         "env run var [...] - run commands in an environment variable\n"
1164 #endif
1165 #if defined(CONFIG_CMD_SAVEENV) && !defined(CONFIG_ENV_IS_NOWHERE)
1166         "env save - save environment\n"
1167 #endif
1168         "env set [-f] name [arg ...]\n";
1169 #endif
1170
1171 U_BOOT_CMD(
1172         env, CONFIG_SYS_MAXARGS, 1, do_env,
1173         "environment handling commands", env_help_text
1174 );
1175
1176 /*
1177  * Old command line interface, kept for compatibility
1178  */
1179
1180 #if defined(CONFIG_CMD_EDITENV)
1181 U_BOOT_CMD_COMPLETE(
1182         editenv, 2, 0,  do_env_edit,
1183         "edit environment variable",
1184         "name\n"
1185         "    - edit environment variable 'name'",
1186         var_complete
1187 );
1188 #endif
1189
1190 U_BOOT_CMD_COMPLETE(
1191         printenv, CONFIG_SYS_MAXARGS, 1,        do_env_print,
1192         "print environment variables",
1193         "[-a]\n    - print [all] values of all environment variables\n"
1194         "printenv name ...\n"
1195         "    - print value of environment variable 'name'",
1196         var_complete
1197 );
1198
1199 #ifdef CONFIG_CMD_GREPENV
1200 U_BOOT_CMD_COMPLETE(
1201         grepenv, CONFIG_SYS_MAXARGS, 0,  do_env_grep,
1202         "search environment variables",
1203         "[-n | -v | -b] string ...\n"
1204         "    - list environment name=value pairs matching 'string'\n"
1205         "      \"-n\": search variable names; \"-v\": search values;\n"
1206         "      \"-b\": search both names and values (default)",
1207         var_complete
1208 );
1209 #endif
1210
1211 U_BOOT_CMD_COMPLETE(
1212         setenv, CONFIG_SYS_MAXARGS, 0,  do_env_set,
1213         "set environment variables",
1214         "[-f] name value ...\n"
1215         "    - [forcibly] set environment variable 'name' to 'value ...'\n"
1216         "setenv [-f] name\n"
1217         "    - [forcibly] delete environment variable 'name'",
1218         var_complete
1219 );
1220
1221 #if defined(CONFIG_CMD_ASKENV)
1222
1223 U_BOOT_CMD(
1224         askenv, CONFIG_SYS_MAXARGS,     1,      do_env_ask,
1225         "get environment variables from stdin",
1226         "name [message] [size]\n"
1227         "    - get environment variable 'name' from stdin (max 'size' chars)"
1228 );
1229 #endif
1230
1231 #if defined(CONFIG_CMD_RUN)
1232 U_BOOT_CMD_COMPLETE(
1233         run,    CONFIG_SYS_MAXARGS,     1,      do_run,
1234         "run commands in an environment variable",
1235         "var [...]\n"
1236         "    - run the commands in the environment variable(s) 'var'",
1237         var_complete
1238 );
1239 #endif
1240 #endif /* CONFIG_SPL_BUILD */