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