1 // SPDX-License-Identifier: GPL-2.0+
3 * (C) Copyright 2000-2013
4 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
6 * (C) Copyright 2001 Sysgo Real-Time Solutions, GmbH <www.elinos.com>
7 * Andreas Heppel <aheppel@sysgo.de>
9 * Copyright 2011 Freescale Semiconductor, Inc.
13 * Support for persistent environment data
15 * The "environment" is stored on external storage as a list of '\0'
16 * terminated "name=value" strings. The end of the list is marked by
17 * a double '\0'. The environment is preceded by a 32 bit CRC over
18 * the data part and, in case of redundant environment, a byte of
21 * This linearized representation will also be used before
22 * relocation, i. e. as long as we don't have a full C runtime
23 * environment. After that, we use a hash table.
31 #include <env_internal.h>
38 #include <asm/global_data.h>
39 #include <linux/bitops.h>
40 #include <u-boot/crc.h>
42 #include <linux/stddef.h>
43 #include <asm/byteorder.h>
46 DECLARE_GLOBAL_DATA_PTR;
48 #if defined(CONFIG_ENV_IS_IN_EEPROM) || \
49 defined(CONFIG_ENV_IS_IN_FLASH) || \
50 defined(CONFIG_ENV_IS_IN_MMC) || \
51 defined(CONFIG_ENV_IS_IN_FAT) || \
52 defined(CONFIG_ENV_IS_IN_EXT4) || \
53 defined(CONFIG_ENV_IS_IN_NAND) || \
54 defined(CONFIG_ENV_IS_IN_NVRAM) || \
55 defined(CONFIG_ENV_IS_IN_ONENAND) || \
56 defined(CONFIG_ENV_IS_IN_SATA) || \
57 defined(CONFIG_ENV_IS_IN_SPI_FLASH) || \
58 defined(CONFIG_ENV_IS_IN_REMOTE) || \
59 defined(CONFIG_ENV_IS_IN_UBI)
61 #define ENV_IS_IN_DEVICE
65 #if !defined(ENV_IS_IN_DEVICE) && \
66 !defined(CONFIG_ENV_IS_NOWHERE)
67 # error Define one of CONFIG_ENV_IS_IN_{EEPROM|FLASH|MMC|FAT|EXT4|\
68 NAND|NVRAM|ONENAND|SATA|SPI_FLASH|REMOTE|UBI} or CONFIG_ENV_IS_NOWHERE
72 * Maximum expected input data size for import command
74 #define MAX_ENV_SIZE (1 << 20) /* 1 MiB */
77 * This variable is incremented on each do_env_set(), so it can
78 * be used via env_get_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()
83 static int env_id = 1;
90 #ifndef CONFIG_SPL_BUILD
92 * Command interface: print one or all environment variables
94 * Returns 0 in case of error, or length of printed string
96 static int env_print(char *name, int flag)
101 if (name) { /* print a single name */
102 struct env_entry e, *ep;
106 hsearch_r(e, ENV_FIND, &ep, &env_htab, flag);
109 len = printf("%s=%s\n", ep->key, ep->data);
113 /* print whole list */
114 len = hexport_r(&env_htab, '\n', flag, &res, 0, 0, NULL);
122 /* should never happen */
123 printf("## Error: cannot export environment\n");
127 static int do_env_print(struct cmd_tbl *cmdtp, int flag, int argc,
132 int env_flag = H_HIDE_DOT;
134 #if defined(CONFIG_CMD_NVEDIT_EFI)
135 if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'e')
136 return do_env_print_efi(cmdtp, flag, --argc, ++argv);
139 if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'a') {
142 env_flag &= ~H_HIDE_DOT;
146 /* print all env vars */
147 rcode = env_print(NULL, env_flag);
150 printf("\nEnvironment size: %d/%ld bytes\n",
151 rcode, (ulong)ENV_SIZE);
155 /* print selected env vars */
156 env_flag &= ~H_HIDE_DOT;
157 for (i = 1; i < argc; ++i) {
158 int rc = env_print(argv[i], env_flag);
160 printf("## Error: \"%s\" not defined\n", argv[i]);
168 #ifdef CONFIG_CMD_GREPENV
169 static int do_env_grep(struct cmd_tbl *cmdtp, int flag,
170 int argc, char *const argv[])
173 int len, grep_how, grep_what;
176 return CMD_RET_USAGE;
178 grep_how = H_MATCH_SUBSTR; /* default: substring search */
179 grep_what = H_MATCH_BOTH; /* default: grep names and values */
181 while (--argc > 0 && **++argv == '-') {
186 case 'e': /* use regex matching */
187 grep_how = H_MATCH_REGEX;
190 case 'n': /* grep for name */
191 grep_what = H_MATCH_KEY;
193 case 'v': /* grep for value */
194 grep_what = H_MATCH_DATA;
196 case 'b': /* grep for both */
197 grep_what = H_MATCH_BOTH;
202 return CMD_RET_USAGE;
208 len = hexport_r(&env_htab, '\n',
209 flag | grep_what | grep_how,
210 &res, 0, argc, argv);
223 #endif /* CONFIG_SPL_BUILD */
226 * Set a new environment variable,
227 * or replace or delete an existing one.
229 static int _do_env_set(int flag, int argc, char *const argv[], int env_flag)
232 char *name, *value, *s;
233 struct env_entry e, *ep;
235 debug("Initial value for argc=%d\n", argc);
237 #if CONFIG_IS_ENABLED(CMD_NVEDIT_EFI)
238 if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'e')
239 return do_env_set_efi(NULL, flag, --argc, ++argv);
242 while (argc > 1 && **(argv + 1) == '-') {
248 case 'f': /* force */
252 return CMD_RET_USAGE;
256 debug("Final value for argc=%d\n", argc);
259 if (strchr(name, '=')) {
260 printf("## Error: illegal character '='"
261 "in variable name \"%s\"\n", name);
268 if (argc < 3 || argv[2] == NULL) {
269 int rc = hdelete_r(name, &env_htab, env_flag);
271 /* If the variable didn't exist, don't report an error */
272 return rc && rc != -ENOENT ? 1 : 0;
276 * Insert / replace new value
278 for (i = 2, len = 0; i < argc; ++i)
279 len += strlen(argv[i]) + 1;
283 printf("## Can't malloc %d bytes\n", len);
286 for (i = 2, s = value; i < argc; ++i) {
289 while ((*s++ = *v++) != '\0')
298 hsearch_r(e, ENV_ENTER, &ep, &env_htab, env_flag);
301 printf("## Error inserting \"%s\" variable, errno=%d\n",
309 int env_set(const char *varname, const char *varvalue)
311 const char * const argv[4] = { "setenv", varname, varvalue, NULL };
313 /* before import into hashtable */
314 if (!(gd->flags & GD_FLG_ENV_READY))
317 if (varvalue == NULL || varvalue[0] == '\0')
318 return _do_env_set(0, 2, (char * const *)argv, H_PROGRAMMATIC);
320 return _do_env_set(0, 3, (char * const *)argv, H_PROGRAMMATIC);
324 * Set an environment variable to an integer value
326 * @param varname Environment variable to set
327 * @param value Value to set it to
328 * @return 0 if ok, 1 on error
330 int env_set_ulong(const char *varname, ulong value)
332 /* TODO: this should be unsigned */
333 char *str = simple_itoa(value);
335 return env_set(varname, str);
339 * Set an environment variable to an value in hex
341 * @param varname Environment variable to set
342 * @param value Value to set it to
343 * @return 0 if ok, 1 on error
345 int env_set_hex(const char *varname, ulong value)
349 sprintf(str, "%lx", value);
350 return env_set(varname, str);
353 ulong env_get_hex(const char *varname, ulong default_val)
359 s = env_get(varname);
361 value = hextoul(s, &endp);
368 int eth_env_get_enetaddr(const char *name, uint8_t *enetaddr)
370 string_to_enetaddr(env_get(name), enetaddr);
371 return is_valid_ethaddr(enetaddr);
374 int eth_env_set_enetaddr(const char *name, const uint8_t *enetaddr)
376 char buf[ARP_HLEN_ASCII + 1];
378 if (eth_env_get_enetaddr(name, (uint8_t *)buf))
381 sprintf(buf, "%pM", enetaddr);
383 return env_set(name, buf);
386 #ifndef CONFIG_SPL_BUILD
387 static int do_env_set(struct cmd_tbl *cmdtp, int flag, int argc,
391 return CMD_RET_USAGE;
393 return _do_env_set(flag, argc, argv, H_INTERACTIVE);
397 * Prompt for environment variable
399 #if defined(CONFIG_CMD_ASKENV)
400 int do_env_ask(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
402 char message[CONFIG_SYS_CBSIZE];
403 int i, len, pos, size;
407 local_args[0] = argv[0];
408 local_args[1] = argv[1];
409 local_args[2] = NULL;
410 local_args[3] = NULL;
415 * env_ask envname [message1 ...] [size]
418 return CMD_RET_USAGE;
421 * We test the last argument if it can be converted
422 * into a decimal number. If yes, we assume it's
423 * the size. Otherwise we echo it as part of the
426 i = dectoul(argv[argc - 1], &endptr);
427 if (*endptr != '\0') { /* no size */
428 size = CONFIG_SYS_CBSIZE - 1;
429 } else { /* size given */
435 sprintf(message, "Please enter '%s': ", argv[1]);
437 /* env_ask envname message1 ... messagen [size] */
438 for (i = 2, pos = 0; i < argc && pos+1 < sizeof(message); i++) {
440 message[pos++] = ' ';
442 strncpy(message + pos, argv[i], sizeof(message) - pos);
443 pos += strlen(argv[i]);
445 if (pos < sizeof(message) - 1) {
446 message[pos++] = ' ';
449 message[CONFIG_SYS_CBSIZE - 1] = '\0';
452 if (size >= CONFIG_SYS_CBSIZE)
453 size = CONFIG_SYS_CBSIZE - 1;
458 /* prompt for input */
459 len = cli_readline(message);
462 console_buffer[size] = '\0';
465 if (console_buffer[0] != '\0') {
466 local_args[2] = console_buffer;
470 /* Continue calling setenv code */
471 return _do_env_set(flag, len, local_args, H_INTERACTIVE);
475 #if defined(CONFIG_CMD_ENV_CALLBACK)
476 static int print_static_binding(const char *var_name, const char *callback_name,
479 printf("\t%-20s %-20s\n", var_name, callback_name);
484 static int print_active_callback(struct env_entry *entry)
486 struct env_clbk_tbl *clbkp;
490 if (entry->callback == NULL)
493 /* look up the callback in the linker-list */
494 num_callbacks = ll_entry_count(struct env_clbk_tbl, env_clbk);
495 for (i = 0, clbkp = ll_entry_start(struct env_clbk_tbl, env_clbk);
498 #if defined(CONFIG_NEEDS_MANUAL_RELOC)
499 if (entry->callback == clbkp->callback + gd->reloc_off)
501 if (entry->callback == clbkp->callback)
506 if (i == num_callbacks)
507 /* this should probably never happen, but just in case... */
508 printf("\t%-20s %p\n", entry->key, entry->callback);
510 printf("\t%-20s %-20s\n", entry->key, clbkp->name);
516 * Print the callbacks available and what they are bound to
518 int do_env_callback(struct cmd_tbl *cmdtp, int flag, int argc,
521 struct env_clbk_tbl *clbkp;
525 /* Print the available callbacks */
526 puts("Available callbacks:\n");
527 puts("\tCallback Name\n");
528 puts("\t-------------\n");
529 num_callbacks = ll_entry_count(struct env_clbk_tbl, env_clbk);
530 for (i = 0, clbkp = ll_entry_start(struct env_clbk_tbl, env_clbk);
533 printf("\t%s\n", clbkp->name);
536 /* Print the static bindings that may exist */
537 puts("Static callback bindings:\n");
538 printf("\t%-20s %-20s\n", "Variable Name", "Callback Name");
539 printf("\t%-20s %-20s\n", "-------------", "-------------");
540 env_attr_walk(ENV_CALLBACK_LIST_STATIC, print_static_binding, NULL);
543 /* walk through each variable and print the callback if it has one */
544 puts("Active callback bindings:\n");
545 printf("\t%-20s %-20s\n", "Variable Name", "Callback Name");
546 printf("\t%-20s %-20s\n", "-------------", "-------------");
547 hwalk_r(&env_htab, print_active_callback);
552 #if defined(CONFIG_CMD_ENV_FLAGS)
553 static int print_static_flags(const char *var_name, const char *flags,
556 enum env_flags_vartype type = env_flags_parse_vartype(flags);
557 enum env_flags_varaccess access = env_flags_parse_varaccess(flags);
559 printf("\t%-20s %-20s %-20s\n", var_name,
560 env_flags_get_vartype_name(type),
561 env_flags_get_varaccess_name(access));
566 static int print_active_flags(struct env_entry *entry)
568 enum env_flags_vartype type;
569 enum env_flags_varaccess access;
571 if (entry->flags == 0)
574 type = (enum env_flags_vartype)
575 (entry->flags & ENV_FLAGS_VARTYPE_BIN_MASK);
576 access = env_flags_parse_varaccess_from_binflags(entry->flags);
577 printf("\t%-20s %-20s %-20s\n", entry->key,
578 env_flags_get_vartype_name(type),
579 env_flags_get_varaccess_name(access));
585 * Print the flags available and what variables have flags
587 int do_env_flags(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
589 /* Print the available variable types */
590 printf("Available variable type flags (position %d):\n",
591 ENV_FLAGS_VARTYPE_LOC);
592 puts("\tFlag\tVariable Type Name\n");
593 puts("\t----\t------------------\n");
594 env_flags_print_vartypes();
597 /* Print the available variable access types */
598 printf("Available variable access flags (position %d):\n",
599 ENV_FLAGS_VARACCESS_LOC);
600 puts("\tFlag\tVariable Access Name\n");
601 puts("\t----\t--------------------\n");
602 env_flags_print_varaccess();
605 /* Print the static flags that may exist */
606 puts("Static flags:\n");
607 printf("\t%-20s %-20s %-20s\n", "Variable Name", "Variable Type",
609 printf("\t%-20s %-20s %-20s\n", "-------------", "-------------",
611 env_attr_walk(ENV_FLAGS_LIST_STATIC, print_static_flags, NULL);
614 /* walk through each variable and print the flags if non-default */
615 puts("Active flags:\n");
616 printf("\t%-20s %-20s %-20s\n", "Variable Name", "Variable Type",
618 printf("\t%-20s %-20s %-20s\n", "-------------", "-------------",
620 hwalk_r(&env_htab, print_active_flags);
626 * Interactively edit an environment variable
628 #if defined(CONFIG_CMD_EDITENV)
629 static int do_env_edit(struct cmd_tbl *cmdtp, int flag, int argc,
632 char buffer[CONFIG_SYS_CBSIZE];
636 return CMD_RET_USAGE;
638 /* before import into hashtable */
639 if (!(gd->flags & GD_FLG_ENV_READY))
642 /* Set read buffer to initial value or empty sting */
643 init_val = env_get(argv[1]);
645 snprintf(buffer, CONFIG_SYS_CBSIZE, "%s", init_val);
649 if (cli_readline_into_buffer("edit: ", buffer, 0) < 0)
652 if (buffer[0] == '\0') {
653 const char * const _argv[3] = { "setenv", argv[1], NULL };
655 return _do_env_set(0, 2, (char * const *)_argv, H_INTERACTIVE);
657 const char * const _argv[4] = { "setenv", argv[1], buffer,
660 return _do_env_set(0, 3, (char * const *)_argv, H_INTERACTIVE);
663 #endif /* CONFIG_CMD_EDITENV */
664 #endif /* CONFIG_SPL_BUILD */
667 * Look up variable from environment,
668 * return address of storage for that variable,
669 * or NULL if not found
671 char *env_get(const char *name)
673 if (gd->flags & GD_FLG_ENV_READY) { /* after import into hashtable */
674 struct env_entry e, *ep;
680 hsearch_r(e, ENV_FIND, &ep, &env_htab, 0);
682 return ep ? ep->data : NULL;
685 /* restricted capabilities before import */
686 if (env_get_f(name, (char *)(gd->env_buf), sizeof(gd->env_buf)) > 0)
687 return (char *)(gd->env_buf);
693 * Like env_get, but prints an error if envvar isn't defined in the
694 * environment. It always returns what env_get does, so it can be used in
695 * place of env_get without changing error handling otherwise.
697 char *from_env(const char *envvar)
701 ret = env_get(envvar);
704 printf("missing environment variable: %s\n", envvar);
710 * Look up variable from environment for restricted C runtime env.
712 int env_get_f(const char *name, char *buf, unsigned len)
714 const char *env, *p, *end;
717 if (name == NULL || *name == '\0')
720 name_len = strlen(name);
722 if (gd->env_valid == ENV_INVALID)
723 env = (const char *)default_environment;
725 env = (const char *)gd->env_addr;
727 for (p = env; *p != '\0'; p = end + 1) {
731 for (end = p; *end != '\0'; ++end)
732 if (end - env >= CONFIG_ENV_SIZE)
735 if (strncmp(name, p, name_len) || p[name_len] != '=')
737 value = &p[name_len + 1];
740 memcpy(buf, value, min(len, res + 1));
744 printf("env_buf [%u bytes] too small for value of \"%s\"\n",
755 * Decode the integer value of an environment variable and return it.
757 * @param name Name of environment variable
758 * @param base Number base to use (normally 10, or 16 for hex)
759 * @param default_val Default value to return if the variable is not
761 * @return the decoded value, or default_val if not found
763 ulong env_get_ulong(const char *name, int base, ulong default_val)
766 * We can use env_get() here, even before relocation, since the
767 * environment variable value is an integer and thus short.
769 const char *str = env_get(name);
771 return str ? simple_strtoul(str, NULL, base) : default_val;
774 #ifndef CONFIG_SPL_BUILD
775 #if defined(CONFIG_CMD_SAVEENV) && defined(ENV_IS_IN_DEVICE)
776 static int do_env_save(struct cmd_tbl *cmdtp, int flag, int argc,
779 return env_save() ? 1 : 0;
783 saveenv, 1, 0, do_env_save,
784 "save environment variables to persistent storage",
788 #if defined(CONFIG_CMD_ERASEENV)
789 static int do_env_erase(struct cmd_tbl *cmdtp, int flag, int argc,
792 return env_erase() ? 1 : 0;
796 eraseenv, 1, 0, do_env_erase,
797 "erase environment variables from persistent storage",
803 #if defined(CONFIG_CMD_NVEDIT_LOAD)
804 static int do_env_load(struct cmd_tbl *cmdtp, int flag, int argc,
807 return env_reload() ? 1 : 0;
811 #if defined(CONFIG_CMD_NVEDIT_SELECT)
812 static int do_env_select(struct cmd_tbl *cmdtp, int flag, int argc,
815 return env_select(argv[1]) ? 1 : 0;
819 #endif /* CONFIG_SPL_BUILD */
821 #ifndef CONFIG_SPL_BUILD
822 static int do_env_default(struct cmd_tbl *cmdtp, int flag,
823 int argc, char *const argv[])
825 int all = 0, env_flag = H_INTERACTIVE;
827 debug("Initial value for argc=%d\n", argc);
828 while (--argc > 0 && **++argv == '-') {
833 case 'a': /* default all */
836 case 'f': /* force */
840 return cmd_usage(cmdtp);
844 debug("Final value for argc=%d\n", argc);
845 if (all && (argc == 0)) {
846 /* Reset the whole environment */
847 env_set_default("## Resetting to default environment\n",
851 if (!all && (argc > 0)) {
852 /* Reset individual variables */
853 env_set_default_vars(argc, argv, env_flag);
857 return cmd_usage(cmdtp);
860 static int do_env_delete(struct cmd_tbl *cmdtp, int flag,
861 int argc, char *const argv[])
863 int env_flag = H_INTERACTIVE;
866 debug("Initial value for argc=%d\n", argc);
867 while (argc > 1 && **(argv + 1) == '-') {
873 case 'f': /* force */
877 return CMD_RET_USAGE;
881 debug("Final value for argc=%d\n", argc);
886 char *name = *++argv;
888 if (hdelete_r(name, &env_htab, env_flag))
895 #ifdef CONFIG_CMD_EXPORTENV
897 * env export [-t | -b | -c] [-s size] addr [var ...]
898 * -t: export as text format; if size is given, data will be
899 * padded with '\0' bytes; if not, one terminating '\0'
900 * will be added (which is included in the "filesize"
901 * setting so you can for exmple copy this to flash and
902 * keep the termination).
903 * -b: export as binary format (name=value pairs separated by
904 * '\0', list end marked by double "\0\0")
905 * -c: export as checksum protected environment format as
906 * used for example by "saveenv" command
908 * size of output buffer
909 * addr: memory address where environment gets stored
910 * var... List of variable names that get included into the
911 * export. Without arguments, the whole environment gets
914 * With "-c" and size is NOT given, then the export command will
915 * format the data as currently used for the persistent storage,
916 * i. e. it will use CONFIG_ENV_SECT_SIZE as output block size and
917 * prepend a valid CRC32 checksum and, in case of redundant
918 * environment, a "current" redundancy flag. If size is given, this
919 * value will be used instead of CONFIG_ENV_SECT_SIZE; again, CRC32
920 * checksum and redundancy flag will be inserted.
922 * With "-b" and "-t", always only the real data (including a
923 * terminating '\0' byte) will be written; here the optional size
924 * argument will be used to make sure not to overflow the user
925 * provided buffer; the command will abort if the size is not
926 * sufficient. Any remaining space will be '\0' padded.
928 * On successful return, the variable "filesize" will be set.
929 * Note that filesize includes the trailing/terminating '\0' byte(s).
931 * Usage scenario: create a text snapshot/backup of the current settings:
933 * => env export -t 100000
934 * => era ${backup_addr} +${filesize}
935 * => cp.b 100000 ${backup_addr} ${filesize}
937 * Re-import this snapshot, deleting all other settings:
939 * => env import -d -t ${backup_addr}
941 static int do_env_export(struct cmd_tbl *cmdtp, int flag,
942 int argc, char *const argv[])
946 char *ptr, *cmd, *res;
956 while (--argc > 0 && **++argv == '-') {
960 case 'b': /* raw binary format */
965 case 'c': /* external checksum format */
971 case 's': /* size given */
973 return cmd_usage(cmdtp);
974 size = hextoul(*++argv, NULL);
976 case 't': /* text format */
982 return CMD_RET_USAGE;
989 return CMD_RET_USAGE;
991 addr = hextoul(argv[0], NULL);
992 ptr = map_sysmem(addr, size);
995 memset(ptr, '\0', size);
1000 if (sep) { /* export as text file */
1001 len = hexport_r(&env_htab, sep,
1002 H_MATCH_KEY | H_MATCH_IDENT,
1003 &ptr, size, argc, argv);
1005 pr_err("## Error: Cannot export environment: errno = %d\n",
1009 sprintf(buf, "%zX", (size_t)len);
1010 env_set("filesize", buf);
1015 envp = (env_t *)ptr;
1017 if (chk) /* export as checksum protected block */
1018 res = (char *)envp->data;
1019 else /* export as raw binary data */
1022 len = hexport_r(&env_htab, '\0',
1023 H_MATCH_KEY | H_MATCH_IDENT,
1024 &res, ENV_SIZE, argc, argv);
1026 pr_err("## Error: Cannot export environment: errno = %d\n",
1032 envp->crc = crc32(0, envp->data,
1033 size ? size - offsetof(env_t, data) : ENV_SIZE);
1034 #ifdef CONFIG_ENV_ADDR_REDUND
1035 envp->flags = ENV_REDUND_ACTIVE;
1038 env_set_hex("filesize", len + offsetof(env_t, data));
1043 printf("## Error: %s: only one of \"-b\", \"-c\" or \"-t\" allowed\n",
1049 #ifdef CONFIG_CMD_IMPORTENV
1051 * env import [-d] [-t [-r] | -b | -c] addr [size] [var ...]
1052 * -d: delete existing environment before importing if no var is
1053 * passed; if vars are passed, if one var is in the current
1054 * environment but not in the environment at addr, delete var from
1055 * current environment;
1056 * otherwise overwrite / append to existing definitions
1057 * -t: assume text format; either "size" must be given or the
1058 * text data must be '\0' terminated
1059 * -r: handle CRLF like LF, that means exported variables with
1060 * a content which ends with \r won't get imported. Used
1061 * to import text files created with editors which are using CRLF
1062 * for line endings. Only effective in addition to -t.
1063 * -b: assume binary format ('\0' separated, "\0\0" terminated)
1064 * -c: assume checksum protected environment format
1065 * addr: memory address to read from
1066 * size: length of input data; if missing, proper '\0'
1067 * termination is mandatory
1068 * if var is set and size should be missing (i.e. '\0'
1069 * termination), set size to '-'
1070 * var... List of the names of the only variables that get imported from
1071 * the environment at address 'addr'. Without arguments, the whole
1072 * environment gets imported.
1074 static int do_env_import(struct cmd_tbl *cmdtp, int flag,
1075 int argc, char *const argv[])
1089 while (--argc > 0 && **++argv == '-') {
1093 case 'b': /* raw binary format */
1098 case 'c': /* external checksum format */
1104 case 't': /* text format */
1109 case 'r': /* handle CRLF like LF */
1116 return CMD_RET_USAGE;
1122 return CMD_RET_USAGE;
1125 printf("## Warning: defaulting to text format\n");
1127 if (sep != '\n' && crlf_is_lf )
1130 addr = hextoul(argv[0], NULL);
1131 ptr = map_sysmem(addr, 0);
1133 if (argc >= 2 && strcmp(argv[1], "-")) {
1134 size = hextoul(argv[1], NULL);
1136 puts("## Error: external checksum format must pass size\n");
1137 return CMD_RET_FAILURE;
1143 while (size < MAX_ENV_SIZE) {
1144 if ((*s == sep) && (*(s+1) == '\0'))
1149 if (size == MAX_ENV_SIZE) {
1150 printf("## Warning: Input data exceeds %d bytes"
1151 " - truncated\n", MAX_ENV_SIZE);
1154 printf("## Info: input data size = %zu = 0x%zX\n", size, size);
1162 env_t *ep = (env_t *)ptr;
1164 if (size <= offsetof(env_t, data)) {
1165 printf("## Error: Invalid size 0x%zX\n", size);
1169 size -= offsetof(env_t, data);
1170 memcpy(&crc, &ep->crc, sizeof(crc));
1172 if (crc32(0, ep->data, size) != crc) {
1173 puts("## Error: bad CRC, import failed\n");
1176 ptr = (char *)ep->data;
1179 if (!himport_r(&env_htab, ptr, size, sep, del ? 0 : H_NOCLEAR,
1180 crlf_is_lf, wl ? argc - 2 : 0, wl ? &argv[2] : NULL)) {
1181 pr_err("## Error: Environment import failed: errno = %d\n",
1185 gd->flags |= GD_FLG_ENV_READY;
1190 printf("## %s: only one of \"-b\", \"-c\" or \"-t\" allowed\n",
1196 #if defined(CONFIG_CMD_NVEDIT_INFO)
1198 * print_env_info - print environment information
1200 static int print_env_info(void)
1204 /* print environment validity value */
1205 switch (gd->env_valid) {
1213 value = "redundant";
1219 printf("env_valid = %s\n", value);
1221 /* print environment ready flag */
1222 value = gd->flags & GD_FLG_ENV_READY ? "true" : "false";
1223 printf("env_ready = %s\n", value);
1225 /* print environment using default flag */
1226 value = gd->flags & GD_FLG_ENV_DEFAULT ? "true" : "false";
1227 printf("env_use_default = %s\n", value);
1229 return CMD_RET_SUCCESS;
1232 #define ENV_INFO_IS_DEFAULT BIT(0) /* default environment bit mask */
1233 #define ENV_INFO_IS_PERSISTED BIT(1) /* environment persistence bit mask */
1236 * env info - display environment information
1237 * env info [-d] - evaluate whether default environment is used
1238 * env info [-p] - evaluate whether environment can be persisted
1239 * Add [-q] - quiet mode, use only for command result, for test by example:
1240 * test env info -p -d -q
1242 static int do_env_info(struct cmd_tbl *cmdtp, int flag,
1243 int argc, char *const argv[])
1246 int eval_results = 0;
1248 #if defined(CONFIG_CMD_SAVEENV) && defined(ENV_IS_IN_DEVICE)
1249 enum env_location loc;
1252 /* display environment information */
1254 return print_env_info();
1256 /* process options */
1257 while (--argc > 0 && **++argv == '-') {
1263 eval_flags |= ENV_INFO_IS_DEFAULT;
1266 eval_flags |= ENV_INFO_IS_PERSISTED;
1272 return CMD_RET_USAGE;
1277 /* evaluate whether default environment is used */
1278 if (eval_flags & ENV_INFO_IS_DEFAULT) {
1279 if (gd->flags & GD_FLG_ENV_DEFAULT) {
1281 printf("Default environment is used\n");
1282 eval_results |= ENV_INFO_IS_DEFAULT;
1285 printf("Environment was loaded from persistent storage\n");
1289 /* evaluate whether environment can be persisted */
1290 if (eval_flags & ENV_INFO_IS_PERSISTED) {
1291 #if defined(CONFIG_CMD_SAVEENV) && defined(ENV_IS_IN_DEVICE)
1292 loc = env_get_location(ENVOP_SAVE, gd->env_load_prio);
1293 if (ENVL_NOWHERE != loc && ENVL_UNKNOWN != loc) {
1295 printf("Environment can be persisted\n");
1296 eval_results |= ENV_INFO_IS_PERSISTED;
1299 printf("Environment cannot be persisted\n");
1303 printf("Environment cannot be persisted\n");
1307 /* The result of evaluations is combined with AND */
1308 if (eval_flags != eval_results)
1309 return CMD_RET_FAILURE;
1311 return CMD_RET_SUCCESS;
1315 #if defined(CONFIG_CMD_ENV_EXISTS)
1316 static int do_env_exists(struct cmd_tbl *cmdtp, int flag, int argc,
1319 struct env_entry e, *ep;
1322 return CMD_RET_USAGE;
1326 hsearch_r(e, ENV_FIND, &ep, &env_htab, 0);
1328 return (ep == NULL) ? 1 : 0;
1333 * New command line interface: "env" command with subcommands
1335 static struct cmd_tbl cmd_env_sub[] = {
1336 #if defined(CONFIG_CMD_ASKENV)
1337 U_BOOT_CMD_MKENT(ask, CONFIG_SYS_MAXARGS, 1, do_env_ask, "", ""),
1339 U_BOOT_CMD_MKENT(default, 1, 0, do_env_default, "", ""),
1340 U_BOOT_CMD_MKENT(delete, CONFIG_SYS_MAXARGS, 0, do_env_delete, "", ""),
1341 #if defined(CONFIG_CMD_EDITENV)
1342 U_BOOT_CMD_MKENT(edit, 2, 0, do_env_edit, "", ""),
1344 #if defined(CONFIG_CMD_ENV_CALLBACK)
1345 U_BOOT_CMD_MKENT(callbacks, 1, 0, do_env_callback, "", ""),
1347 #if defined(CONFIG_CMD_ENV_FLAGS)
1348 U_BOOT_CMD_MKENT(flags, 1, 0, do_env_flags, "", ""),
1350 #if defined(CONFIG_CMD_EXPORTENV)
1351 U_BOOT_CMD_MKENT(export, 4, 0, do_env_export, "", ""),
1353 #if defined(CONFIG_CMD_GREPENV)
1354 U_BOOT_CMD_MKENT(grep, CONFIG_SYS_MAXARGS, 1, do_env_grep, "", ""),
1356 #if defined(CONFIG_CMD_IMPORTENV)
1357 U_BOOT_CMD_MKENT(import, 5, 0, do_env_import, "", ""),
1359 #if defined(CONFIG_CMD_NVEDIT_INFO)
1360 U_BOOT_CMD_MKENT(info, 3, 0, do_env_info, "", ""),
1362 #if defined(CONFIG_CMD_NVEDIT_LOAD)
1363 U_BOOT_CMD_MKENT(load, 1, 0, do_env_load, "", ""),
1365 U_BOOT_CMD_MKENT(print, CONFIG_SYS_MAXARGS, 1, do_env_print, "", ""),
1366 #if defined(CONFIG_CMD_RUN)
1367 U_BOOT_CMD_MKENT(run, CONFIG_SYS_MAXARGS, 1, do_run, "", ""),
1369 #if defined(CONFIG_CMD_SAVEENV) && defined(ENV_IS_IN_DEVICE)
1370 U_BOOT_CMD_MKENT(save, 1, 0, do_env_save, "", ""),
1371 #if defined(CONFIG_CMD_ERASEENV)
1372 U_BOOT_CMD_MKENT(erase, 1, 0, do_env_erase, "", ""),
1375 #if defined(CONFIG_CMD_NVEDIT_SELECT)
1376 U_BOOT_CMD_MKENT(select, 2, 0, do_env_select, "", ""),
1378 U_BOOT_CMD_MKENT(set, CONFIG_SYS_MAXARGS, 0, do_env_set, "", ""),
1379 #if defined(CONFIG_CMD_ENV_EXISTS)
1380 U_BOOT_CMD_MKENT(exists, 2, 0, do_env_exists, "", ""),
1384 #if defined(CONFIG_NEEDS_MANUAL_RELOC)
1385 void env_reloc(void)
1387 fixup_cmdtable(cmd_env_sub, ARRAY_SIZE(cmd_env_sub));
1391 static int do_env(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
1396 return CMD_RET_USAGE;
1398 /* drop initial "env" arg */
1402 cp = find_cmd_tbl(argv[0], cmd_env_sub, ARRAY_SIZE(cmd_env_sub));
1405 return cp->cmd(cmdtp, flag, argc, argv);
1407 return CMD_RET_USAGE;
1410 #ifdef CONFIG_SYS_LONGHELP
1411 static char env_help_text[] =
1412 #if defined(CONFIG_CMD_ASKENV)
1413 "ask name [message] [size] - ask for environment variable\nenv "
1415 #if defined(CONFIG_CMD_ENV_CALLBACK)
1416 "callbacks - print callbacks and their associated variables\nenv "
1418 "default [-f] -a - [forcibly] reset default environment\n"
1419 "env default [-f] var [...] - [forcibly] reset variable(s) to their default values\n"
1420 "env delete [-f] var [...] - [forcibly] delete variable(s)\n"
1421 #if defined(CONFIG_CMD_EDITENV)
1422 "env edit name - edit environment variable\n"
1424 #if defined(CONFIG_CMD_ENV_EXISTS)
1425 "env exists name - tests for existence of variable\n"
1427 #if defined(CONFIG_CMD_EXPORTENV)
1428 "env export [-t | -b | -c] [-s size] addr [var ...] - export environment\n"
1430 #if defined(CONFIG_CMD_ENV_FLAGS)
1431 "env flags - print variables that have non-default flags\n"
1433 #if defined(CONFIG_CMD_GREPENV)
1435 "env grep [-e] [-n | -v | -b] string [...] - search environment\n"
1437 "env grep [-n | -v | -b] string [...] - search environment\n"
1440 #if defined(CONFIG_CMD_IMPORTENV)
1441 "env import [-d] [-t [-r] | -b | -c] addr [size] [var ...] - import environment\n"
1443 #if defined(CONFIG_CMD_NVEDIT_INFO)
1444 "env info - display environment information\n"
1445 "env info [-d] [-p] [-q] - evaluate environment information\n"
1446 " \"-d\": default environment is used\n"
1447 " \"-p\": environment can be persisted\n"
1448 " \"-q\": quiet output\n"
1450 "env print [-a | name ...] - print environment\n"
1451 #if defined(CONFIG_CMD_NVEDIT_EFI)
1452 "env print -e [-guid guid] [-n] [name ...] - print UEFI environment\n"
1454 #if defined(CONFIG_CMD_RUN)
1455 "env run var [...] - run commands in an environment variable\n"
1457 #if defined(CONFIG_CMD_SAVEENV) && defined(ENV_IS_IN_DEVICE)
1458 "env save - save environment\n"
1459 #if defined(CONFIG_CMD_ERASEENV)
1460 "env erase - erase environment\n"
1463 #if defined(CONFIG_CMD_NVEDIT_LOAD)
1464 "env load - load environment\n"
1466 #if defined(CONFIG_CMD_NVEDIT_SELECT)
1467 "env select [target] - select environment target\n"
1469 #if defined(CONFIG_CMD_NVEDIT_EFI)
1470 "env set -e [-nv][-bs][-rt][-at][-a][-i addr:size][-v] name [arg ...]\n"
1471 " - set UEFI variable; unset if '-i' or 'arg' not specified\n"
1473 "env set [-f] name [arg ...]\n";
1477 env, CONFIG_SYS_MAXARGS, 1, do_env,
1478 "environment handling commands", env_help_text
1482 * Old command line interface, kept for compatibility
1485 #if defined(CONFIG_CMD_EDITENV)
1486 U_BOOT_CMD_COMPLETE(
1487 editenv, 2, 0, do_env_edit,
1488 "edit environment variable",
1490 " - edit environment variable 'name'",
1495 U_BOOT_CMD_COMPLETE(
1496 printenv, CONFIG_SYS_MAXARGS, 1, do_env_print,
1497 "print environment variables",
1498 "[-a]\n - print [all] values of all environment variables\n"
1499 #if defined(CONFIG_CMD_NVEDIT_EFI)
1500 "printenv -e [-guid guid][-n] [name ...]\n"
1501 " - print UEFI variable 'name' or all the variables\n"
1502 " \"-guid\": GUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n"
1503 " \"-n\": suppress dumping variable's value\n"
1505 "printenv name ...\n"
1506 " - print value of environment variable 'name'",
1510 #ifdef CONFIG_CMD_GREPENV
1511 U_BOOT_CMD_COMPLETE(
1512 grepenv, CONFIG_SYS_MAXARGS, 0, do_env_grep,
1513 "search environment variables",
1515 "[-e] [-n | -v | -b] string ...\n"
1517 "[-n | -v | -b] string ...\n"
1519 " - list environment name=value pairs matching 'string'\n"
1521 " \"-e\": enable regular expressions;\n"
1523 " \"-n\": search variable names; \"-v\": search values;\n"
1524 " \"-b\": search both names and values (default)",
1529 U_BOOT_CMD_COMPLETE(
1530 setenv, CONFIG_SYS_MAXARGS, 0, do_env_set,
1531 "set environment variables",
1532 #if defined(CONFIG_CMD_NVEDIT_EFI)
1533 "-e [-guid guid][-nv][-bs][-rt][-at][-a][-v]\n"
1534 " [-i addr:size name], or [name [value ...]]\n"
1535 " - set UEFI variable 'name' to 'value' ...'\n"
1536 " \"-guid\": GUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n"
1537 " \"-nv\": set non-volatile attribute\n"
1538 " \"-bs\": set boot-service attribute\n"
1539 " \"-rt\": set runtime attribute\n"
1540 " \"-at\": set time-based authentication attribute\n"
1541 " \"-a\": append-write\n"
1542 " \"-i addr,size\": use <addr,size> as variable's value\n"
1543 " \"-v\": verbose message\n"
1544 " - delete UEFI variable 'name' if 'value' not specified\n"
1546 "setenv [-f] name value ...\n"
1547 " - [forcibly] set environment variable 'name' to 'value ...'\n"
1548 "setenv [-f] name\n"
1549 " - [forcibly] delete environment variable 'name'",
1553 #if defined(CONFIG_CMD_ASKENV)
1556 askenv, CONFIG_SYS_MAXARGS, 1, do_env_ask,
1557 "get environment variables from stdin",
1558 "name [message] [size]\n"
1559 " - get environment variable 'name' from stdin (max 'size' chars)"
1563 #if defined(CONFIG_CMD_RUN)
1564 U_BOOT_CMD_COMPLETE(
1565 run, CONFIG_SYS_MAXARGS, 1, do_run,
1566 "run commands in an environment variable",
1568 " - run the commands in the environment variable(s) 'var'",
1572 #endif /* CONFIG_SPL_BUILD */