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