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