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