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