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