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