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