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