2 * (C) Copyright 2000-2010
3 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
6 * Guennadi Liakhovetski, DENX Software Engineering, lg@denx.de.
8 * SPDX-License-Identifier: GPL-2.0+
15 #include <env_flags.h>
17 #include <linux/stringify.h>
22 #include <sys/types.h>
23 #include <sys/ioctl.h>
29 # include <linux/mtd/mtd.h>
31 # define __user /* nothing */
32 # include <mtd/mtd-user.h>
39 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
41 #define WHITESPACE(c) ((c == '\t') || (c == ' '))
43 #define min(x, y) ({ \
44 typeof(x) _min1 = (x); \
45 typeof(y) _min2 = (y); \
46 (void) (&_min1 == &_min2); \
47 _min1 < _min2 ? _min1 : _min2; })
50 const char *devname; /* Device name */
51 ulong devoff; /* Device offset */
52 ulong env_size; /* environment size */
53 ulong erase_size; /* device erase size */
54 ulong env_sectors; /* number of environment sectors */
55 uint8_t mtd_type; /* type of the MTD device */
58 static struct envdev_s envdevices[2] =
61 .mtd_type = MTD_ABSENT,
63 .mtd_type = MTD_ABSENT,
66 static int dev_current;
68 #define DEVNAME(i) envdevices[(i)].devname
69 #define DEVOFFSET(i) envdevices[(i)].devoff
70 #define ENVSIZE(i) envdevices[(i)].env_size
71 #define DEVESIZE(i) envdevices[(i)].erase_size
72 #define ENVSECTORS(i) envdevices[(i)].env_sectors
73 #define DEVTYPE(i) envdevices[(i)].mtd_type
75 #define CUR_ENVSIZE ENVSIZE(dev_current)
77 #define ENV_SIZE getenvsize()
79 struct env_image_single {
80 uint32_t crc; /* CRC32 over data bytes */
84 struct env_image_redundant {
85 uint32_t crc; /* CRC32 over data bytes */
86 unsigned char flags; /* active or obsolete */
101 enum flag_scheme flag_scheme;
104 static struct environment environment = {
105 .flag_scheme = FLAG_NONE,
108 /* Is AES encryption used? */
110 static uint8_t aes_key[AES_KEY_LENGTH] = { 0 };
111 static int env_aes_cbc_crypt(char *data, const int enc);
113 static int HaveRedundEnv = 0;
115 static unsigned char active_flag = 1;
116 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
117 static unsigned char obsolete_flag = 0;
119 #define DEFAULT_ENV_INSTANCE_STATIC
120 #include <env_default.h>
122 static int flash_io (int mode);
123 static char *envmatch (char * s1, char * s2);
124 static int parse_config (void);
126 #if defined(CONFIG_FILE)
127 static int get_config (char *);
128 static char *config_file = CONFIG_FILE;
130 static inline ulong getenvsize (void)
132 ulong rc = CUR_ENVSIZE - sizeof(uint32_t);
138 rc &= ~(AES_KEY_LENGTH - 1);
143 static char *fw_string_blank(char *s, int noblank)
148 for (i = 0; i < len; i++, s++) {
149 if ((noblank && !WHITESPACE(*s)) ||
150 (!noblank && WHITESPACE(*s)))
160 * Search the environment for a variable.
161 * Return the value, if found, or NULL, if not found.
163 char *fw_getenv (char *name)
167 for (env = environment.data; *env; env = nxt + 1) {
170 for (nxt = env; *nxt; ++nxt) {
171 if (nxt >= &environment.data[ENV_SIZE]) {
172 fprintf (stderr, "## Error: "
173 "environment not terminated\n");
177 val = envmatch (name, env);
186 * Search the default environment for a variable.
187 * Return the value, if found, or NULL, if not found.
189 char *fw_getdefenv(char *name)
193 for (env = default_environment; *env; env = nxt + 1) {
196 for (nxt = env; *nxt; ++nxt) {
197 if (nxt >= &default_environment[ENV_SIZE]) {
198 fprintf(stderr, "## Error: "
199 "default environment not terminated\n");
203 val = envmatch(name, env);
211 static int parse_aes_key(char *key)
213 char tmp[5] = { '0', 'x', 0, 0, 0 };
217 if (strnlen(key, 64) != 32) {
219 "## Error: '-a' option requires 16-byte AES key\n");
223 for (i = 0; i < 16; i++) {
227 ul = strtoul(tmp, NULL, 16);
230 "## Error: '-a' option requires valid AES key\n");
233 aes_key[i] = ul & 0xff;
242 * Print the current definition of one, or more, or all
243 * environment variables
245 int fw_printenv (int argc, char *argv[])
252 if (argc >= 2 && strcmp(argv[1], "-c") == 0) {
255 "## Error: '-c' option requires the config file to use\n");
258 config_file = argv[2];
264 if (argc >= 2 && strcmp(argv[1], "-a") == 0) {
267 "## Error: '-a' option requires AES key\n");
270 rc = parse_aes_key(argv[2]);
280 if (argc == 1) { /* Print all env variables */
281 for (env = environment.data; *env; env = nxt + 1) {
282 for (nxt = env; *nxt; ++nxt) {
283 if (nxt >= &environment.data[ENV_SIZE]) {
284 fprintf (stderr, "## Error: "
285 "environment not terminated\n");
290 printf ("%s\n", env);
295 if (strcmp (argv[1], "-n") == 0) {
300 fprintf (stderr, "## Error: "
301 "`-n' option requires exactly one argument\n");
308 for (i = 1; i < argc; ++i) { /* print single env variables */
309 char *name = argv[i];
312 for (env = environment.data; *env; env = nxt + 1) {
314 for (nxt = env; *nxt; ++nxt) {
315 if (nxt >= &environment.data[ENV_SIZE]) {
316 fprintf (stderr, "## Error: "
317 "environment not terminated\n");
321 val = envmatch (name, env);
324 fputs (name, stdout);
332 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
340 int fw_env_close(void)
344 ret = env_aes_cbc_crypt(environment.data, 1);
347 "Error: can't encrypt env for flash\n");
355 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
357 /* write environment back to flash */
358 if (flash_io(O_RDWR)) {
360 "Error: can't write fw_env to flash\n");
369 * Set/Clear a single variable in the environment.
370 * This is called in sequence to update the environment
371 * in RAM without updating the copy in flash after each set
373 int fw_env_write(char *name, char *value)
378 int deleting, creating, overwriting;
381 * search if variable with this name already exists
383 for (nxt = env = environment.data; *env; env = nxt + 1) {
384 for (nxt = env; *nxt; ++nxt) {
385 if (nxt >= &environment.data[ENV_SIZE]) {
386 fprintf(stderr, "## Error: "
387 "environment not terminated\n");
392 if ((oldval = envmatch (name, env)) != NULL)
396 deleting = (oldval && !(value && strlen(value)));
397 creating = (!oldval && (value && strlen(value)));
398 overwriting = (oldval && (value && strlen(value)));
400 /* check for permission */
402 if (env_flags_validate_varaccess(name,
403 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
404 printf("Can't delete \"%s\"\n", name);
408 } else if (overwriting) {
409 if (env_flags_validate_varaccess(name,
410 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
411 printf("Can't overwrite \"%s\"\n", name);
414 } else if (env_flags_validate_varaccess(name,
415 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
416 const char *defval = fw_getdefenv(name);
420 if (strcmp(oldval, defval)
422 printf("Can't overwrite \"%s\"\n", name);
427 } else if (creating) {
428 if (env_flags_validate_varaccess(name,
429 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
430 printf("Can't create \"%s\"\n", name);
438 if (deleting || overwriting) {
439 if (*++nxt == '\0') {
444 if ((*env == '\0') && (*nxt == '\0'))
453 if (!value || !strlen(value))
457 * Append new definition at the end
459 for (env = environment.data; *env || *(env + 1); ++env);
460 if (env > environment.data)
464 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
466 len = strlen (name) + 2;
467 /* add '=' for first arg, ' ' for all others */
468 len += strlen(value) + 1;
470 if (len > (&environment.data[ENV_SIZE] - env)) {
472 "Error: environment overflow, \"%s\" deleted\n",
477 while ((*env = *name++) != '\0')
480 while ((*++env = *value++) != '\0')
483 /* end is marked with double '\0' */
490 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
492 * EINVAL - need at least 1 argument
493 * EROFS - certain variables ("ethaddr", "serial#") cannot be
494 * modified or deleted
497 int fw_setenv(int argc, char *argv[])
505 if (argc >= 2 && strcmp(argv[1], "-c") == 0) {
508 "## Error: '-c' option requires the config file to use\n");
511 config_file = argv[2];
522 if (strcmp(argv[1], "-a") == 0) {
525 "## Error: '-a' option requires AES key\n");
528 rc = parse_aes_key(argv[2]);
541 fprintf(stderr, "Error: environment not initialized\n");
547 if (env_flags_validate_env_set_params(argc, argv) < 0)
551 for (i = 2; i < argc; ++i) {
553 size_t val_len = strlen(val);
556 value[len - 1] = ' ';
557 value = realloc(value, len + val_len + 1);
560 "Cannot malloc %zu bytes: %s\n",
561 len, strerror(errno));
565 memcpy(value + len, val, val_len);
570 fw_env_write(name, value);
574 return fw_env_close();
578 * Parse a file and configure the u-boot variables.
579 * The script file has a very simple format, as follows:
581 * Each line has a couple with name, value:
582 * <white spaces>variable_name<white spaces>variable_value
584 * Both variable_name and variable_value are interpreted as strings.
585 * Any character after <white spaces> and before ending \r\n is interpreted
586 * as variable's value (no comment allowed on these lines !)
588 * Comments are allowed if the first character in the line is #
590 * Returns -1 and sets errno error codes:
594 int fw_parse_script(char *fname)
597 char dump[1024]; /* Maximum line length in the file */
605 fprintf(stderr, "Error: environment not initialized\n");
609 if (strcmp(fname, "-") == 0)
612 fp = fopen(fname, "r");
614 fprintf(stderr, "I cannot open %s for reading\n",
620 while (fgets(dump, sizeof(dump), fp)) {
625 * Read a whole line from the file. If the line is too long
626 * or is not terminated, reports an error and exit.
628 if (dump[len - 1] != '\n') {
630 "Line %d not corrected terminated or too long\n",
636 /* Drop ending line feed / carriage return */
637 while (len > 0 && (dump[len - 1] == '\n' ||
638 dump[len - 1] == '\r')) {
639 dump[len - 1] = '\0';
643 /* Skip comment or empty lines */
644 if ((len == 0) || dump[0] == '#')
648 * Search for variable's name,
649 * remove leading whitespaces
651 name = fw_string_blank(dump, 1);
655 /* The first white space is the end of variable name */
656 val = fw_string_blank(name, 0);
660 if ((val - name) < len)
661 val = fw_string_blank(val, 1);
667 fprintf(stderr, "Setting %s : %s\n",
668 name, val ? val : " removed");
671 if (env_flags_validate_type(name, val) < 0) {
677 * If there is an error setting a variable,
678 * try to save the environment and returns an error
680 if (fw_env_write(name, val)) {
682 "fw_env_write returns with error : %s\n",
690 /* Close file if not stdin */
691 if (strcmp(fname, "-") != 0)
694 ret |= fw_env_close();
701 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
704 * < 0 - failed to test
706 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
708 if (mtd_type == MTD_NANDFLASH) {
709 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
712 perror ("Cannot read bad block mark");
718 fprintf (stderr, "Bad block at 0x%llx, "
719 "skipping\n", *blockstart);
729 * Read data from flash at an offset into a provided buffer. On NAND it skips
730 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
731 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
733 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
734 off_t offset, uint8_t mtd_type)
736 size_t blocklen; /* erase / write length - one block on NAND,
738 size_t processed = 0; /* progress counter */
739 size_t readlen = count; /* current read length */
740 off_t top_of_range; /* end of the last block we may use */
741 off_t block_seek; /* offset inside the current block to the start
743 loff_t blockstart; /* running start of the current block -
744 MEMGETBADBLOCK needs 64 bits */
747 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
749 /* Offset inside a block */
750 block_seek = offset - blockstart;
752 if (mtd_type == MTD_NANDFLASH) {
754 * NAND: calculate which blocks we are reading. We have
755 * to read one block at a time to skip bad blocks.
757 blocklen = DEVESIZE (dev);
760 * To calculate the top of the range, we have to use the
761 * global DEVOFFSET (dev), which can be different from offset
763 top_of_range = ((DEVOFFSET(dev) / blocklen) +
764 ENVSECTORS (dev)) * blocklen;
766 /* Limit to one block for the first read */
767 if (readlen > blocklen - block_seek)
768 readlen = blocklen - block_seek;
771 top_of_range = offset + count;
774 /* This only runs once on NOR flash */
775 while (processed < count) {
776 rc = flash_bad_block (fd, mtd_type, &blockstart);
777 if (rc < 0) /* block test failed */
780 if (blockstart + block_seek + readlen > top_of_range) {
781 /* End of range is reached */
783 "Too few good blocks within range\n");
787 if (rc) { /* block is bad */
788 blockstart += blocklen;
793 * If a block is bad, we retry in the next block at the same
794 * offset - see common/env_nand.c::writeenv()
796 lseek (fd, blockstart + block_seek, SEEK_SET);
798 rc = read (fd, buf + processed, readlen);
800 fprintf (stderr, "Read error on %s: %s\n",
801 DEVNAME (dev), strerror (errno));
805 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
806 rc, blockstart + block_seek, DEVNAME(dev));
808 processed += readlen;
809 readlen = min (blocklen, count - processed);
811 blockstart += blocklen;
818 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
819 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
820 * erase and write the whole data at once.
822 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
823 off_t offset, uint8_t mtd_type)
826 struct erase_info_user erase;
827 size_t blocklen; /* length of NAND block / NOR erase sector */
828 size_t erase_len; /* whole area that can be erased - may include
830 size_t erasesize; /* erase / write length - one block on NAND,
832 size_t processed = 0; /* progress counter */
833 size_t write_total; /* total size to actually write - excluding
835 off_t erase_offset; /* offset to the first erase block (aligned)
837 off_t block_seek; /* offset inside the erase block to the start
839 off_t top_of_range; /* end of the last block we may use */
840 loff_t blockstart; /* running start of the current block -
841 MEMGETBADBLOCK needs 64 bits */
845 * For mtd devices only offset and size of the environment do matter
847 if (mtd_type == MTD_ABSENT) {
849 top_of_range = offset + count;
850 erase_len = blocklen;
853 write_total = blocklen;
855 blocklen = DEVESIZE(dev);
857 top_of_range = ((DEVOFFSET(dev) / blocklen) +
858 ENVSECTORS(dev)) * blocklen;
860 erase_offset = (offset / blocklen) * blocklen;
862 /* Maximum area we may use */
863 erase_len = top_of_range - erase_offset;
865 blockstart = erase_offset;
866 /* Offset inside a block */
867 block_seek = offset - erase_offset;
870 * Data size we actually write: from the start of the block
871 * to the start of the data, then count bytes of data, and
872 * to the end of the block
874 write_total = ((block_seek + count + blocklen - 1) /
875 blocklen) * blocklen;
879 * Support data anywhere within erase sectors: read out the complete
880 * area to be erased, replace the environment image, write the whole
883 if (write_total > count) {
884 data = malloc (erase_len);
887 "Cannot malloc %zu bytes: %s\n",
888 erase_len, strerror (errno));
892 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
894 if (write_total != rc)
898 fprintf(stderr, "Preserving data ");
900 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
901 if (block_seek + count != write_total) {
903 fprintf(stderr, " and ");
904 fprintf(stderr, "0x%lx - 0x%x",
905 block_seek + count, write_total - 1);
907 fprintf(stderr, "\n");
909 /* Overwrite the old environment */
910 memcpy (data + block_seek, buf, count);
913 * We get here, iff offset is block-aligned and count is a
914 * multiple of blocklen - see write_total calculation above
919 if (mtd_type == MTD_NANDFLASH) {
921 * NAND: calculate which blocks we are writing. We have
922 * to write one block at a time to skip bad blocks.
924 erasesize = blocklen;
926 erasesize = erase_len;
929 erase.length = erasesize;
931 /* This only runs once on NOR flash and SPI-dataflash */
932 while (processed < write_total) {
933 rc = flash_bad_block (fd, mtd_type, &blockstart);
934 if (rc < 0) /* block test failed */
937 if (blockstart + erasesize > top_of_range) {
938 fprintf (stderr, "End of range reached, aborting\n");
942 if (rc) { /* block is bad */
943 blockstart += blocklen;
947 if (mtd_type != MTD_ABSENT) {
948 erase.start = blockstart;
949 ioctl(fd, MEMUNLOCK, &erase);
950 /* These do not need an explicit erase cycle */
951 if (mtd_type != MTD_DATAFLASH)
952 if (ioctl(fd, MEMERASE, &erase) != 0) {
954 "MTD erase error on %s: %s\n",
955 DEVNAME(dev), strerror(errno));
960 if (lseek (fd, blockstart, SEEK_SET) == -1) {
962 "Seek error on %s: %s\n",
963 DEVNAME (dev), strerror (errno));
968 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
971 if (write (fd, data + processed, erasesize) != erasesize) {
972 fprintf (stderr, "Write error on %s: %s\n",
973 DEVNAME (dev), strerror (errno));
977 if (mtd_type != MTD_ABSENT)
978 ioctl(fd, MEMLOCK, &erase);
980 processed += erasesize;
982 blockstart += erasesize;
985 if (write_total > count)
992 * Set obsolete flag at offset - NOR flash only
994 static int flash_flag_obsolete (int dev, int fd, off_t offset)
997 struct erase_info_user erase;
999 erase.start = DEVOFFSET (dev);
1000 erase.length = DEVESIZE (dev);
1001 /* This relies on the fact, that obsolete_flag == 0 */
1002 rc = lseek (fd, offset, SEEK_SET);
1004 fprintf (stderr, "Cannot seek to set the flag on %s \n",
1008 ioctl (fd, MEMUNLOCK, &erase);
1009 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
1010 ioctl (fd, MEMLOCK, &erase);
1012 perror ("Could not set obsolete flag");
1017 /* Encrypt or decrypt the environment before writing or reading it. */
1018 static int env_aes_cbc_crypt(char *payload, const int enc)
1020 uint8_t *data = (uint8_t *)payload;
1021 const int len = getenvsize();
1022 uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
1023 uint32_t aes_blocks;
1025 /* First we expand the key. */
1026 aes_expand_key(aes_key, key_exp);
1028 /* Calculate the number of AES blocks to encrypt. */
1029 aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
1032 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
1034 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
1039 static int flash_write (int fd_current, int fd_target, int dev_target)
1043 switch (environment.flag_scheme) {
1046 case FLAG_INCREMENTAL:
1047 (*environment.flags)++;
1050 *environment.flags = active_flag;
1053 fprintf (stderr, "Unimplemented flash scheme %u \n",
1054 environment.flag_scheme);
1059 fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
1060 DEVOFFSET (dev_target), DEVNAME (dev_target));
1063 rc = flash_write_buf(dev_target, fd_target, environment.image,
1064 CUR_ENVSIZE, DEVOFFSET(dev_target),
1065 DEVTYPE(dev_target));
1069 if (environment.flag_scheme == FLAG_BOOLEAN) {
1070 /* Have to set obsolete flag */
1071 off_t offset = DEVOFFSET (dev_current) +
1072 offsetof (struct env_image_redundant, flags);
1075 "Setting obsolete flag in environment at 0x%lx on %s\n",
1076 DEVOFFSET (dev_current), DEVNAME (dev_current));
1078 flash_flag_obsolete (dev_current, fd_current, offset);
1084 static int flash_read (int fd)
1086 struct mtd_info_user mtdinfo;
1090 rc = fstat(fd, &st);
1092 fprintf(stderr, "Cannot stat the file %s\n",
1093 DEVNAME(dev_current));
1097 if (S_ISCHR(st.st_mode)) {
1098 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1100 fprintf(stderr, "Cannot get MTD information for %s\n",
1101 DEVNAME(dev_current));
1104 if (mtdinfo.type != MTD_NORFLASH &&
1105 mtdinfo.type != MTD_NANDFLASH &&
1106 mtdinfo.type != MTD_DATAFLASH &&
1107 mtdinfo.type != MTD_UBIVOLUME) {
1108 fprintf (stderr, "Unsupported flash type %u on %s\n",
1109 mtdinfo.type, DEVNAME(dev_current));
1113 memset(&mtdinfo, 0, sizeof(mtdinfo));
1114 mtdinfo.type = MTD_ABSENT;
1117 DEVTYPE(dev_current) = mtdinfo.type;
1119 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1120 DEVOFFSET (dev_current), mtdinfo.type);
1121 if (rc != CUR_ENVSIZE)
1127 static int flash_io (int mode)
1129 int fd_current, fd_target, rc, dev_target;
1131 /* dev_current: fd_current, erase_current */
1132 fd_current = open (DEVNAME (dev_current), mode);
1133 if (fd_current < 0) {
1135 "Can't open %s: %s\n",
1136 DEVNAME (dev_current), strerror (errno));
1140 if (mode == O_RDWR) {
1141 if (HaveRedundEnv) {
1142 /* switch to next partition for writing */
1143 dev_target = !dev_current;
1144 /* dev_target: fd_target, erase_target */
1145 fd_target = open (DEVNAME (dev_target), mode);
1146 if (fd_target < 0) {
1148 "Can't open %s: %s\n",
1149 DEVNAME (dev_target),
1155 dev_target = dev_current;
1156 fd_target = fd_current;
1159 rc = flash_write (fd_current, fd_target, dev_target);
1161 if (HaveRedundEnv) {
1162 if (close (fd_target)) {
1164 "I/O error on %s: %s\n",
1165 DEVNAME (dev_target),
1171 rc = flash_read (fd_current);
1175 if (close (fd_current)) {
1177 "I/O error on %s: %s\n",
1178 DEVNAME (dev_current), strerror (errno));
1186 * s1 is either a simple 'name', or a 'name=value' pair.
1187 * s2 is a 'name=value' pair.
1188 * If the names match, return the value of s2, else NULL.
1191 static char *envmatch (char * s1, char * s2)
1193 if (s1 == NULL || s2 == NULL)
1196 while (*s1 == *s2++)
1199 if (*s1 == '\0' && *(s2 - 1) == '=')
1205 * Prevent confusion if running from erased flash memory
1207 int fw_env_open(void)
1210 unsigned char flag0;
1214 unsigned char flag1;
1219 struct env_image_single *single;
1220 struct env_image_redundant *redundant;
1222 if (parse_config ()) /* should fill envdevices */
1225 addr0 = calloc(1, CUR_ENVSIZE);
1226 if (addr0 == NULL) {
1228 "Not enough memory for environment (%ld bytes)\n",
1233 /* read environment from FLASH to local buffer */
1234 environment.image = addr0;
1236 if (HaveRedundEnv) {
1238 environment.crc = &redundant->crc;
1239 environment.flags = &redundant->flags;
1240 environment.data = redundant->data;
1243 environment.crc = &single->crc;
1244 environment.flags = NULL;
1245 environment.data = single->data;
1249 if (flash_io (O_RDONLY))
1252 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1255 ret = env_aes_cbc_crypt(environment.data, 0);
1260 crc0_ok = (crc0 == *environment.crc);
1261 if (!HaveRedundEnv) {
1264 "Warning: Bad CRC, using default environment\n");
1265 memcpy(environment.data, default_environment, sizeof default_environment);
1268 flag0 = *environment.flags;
1271 addr1 = calloc(1, CUR_ENVSIZE);
1272 if (addr1 == NULL) {
1274 "Not enough memory for environment (%ld bytes)\n",
1281 * have to set environment.image for flash_read(), careful -
1282 * other pointers in environment still point inside addr0
1284 environment.image = addr1;
1285 if (flash_io (O_RDONLY))
1288 /* Check flag scheme compatibility */
1289 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1290 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1291 environment.flag_scheme = FLAG_BOOLEAN;
1292 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1293 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1294 environment.flag_scheme = FLAG_INCREMENTAL;
1295 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1296 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1297 environment.flag_scheme = FLAG_BOOLEAN;
1298 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1299 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1300 environment.flag_scheme = FLAG_INCREMENTAL;
1301 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1302 DEVTYPE(!dev_current) == MTD_ABSENT) {
1303 environment.flag_scheme = FLAG_INCREMENTAL;
1305 fprintf (stderr, "Incompatible flash types!\n");
1309 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1312 ret = env_aes_cbc_crypt(redundant->data, 0);
1317 crc1_ok = (crc1 == redundant->crc);
1318 flag1 = redundant->flags;
1320 if (crc0_ok && !crc1_ok) {
1322 } else if (!crc0_ok && crc1_ok) {
1324 } else if (!crc0_ok && !crc1_ok) {
1326 "Warning: Bad CRC, using default environment\n");
1327 memcpy (environment.data, default_environment,
1328 sizeof default_environment);
1331 switch (environment.flag_scheme) {
1333 if (flag0 == active_flag &&
1334 flag1 == obsolete_flag) {
1336 } else if (flag0 == obsolete_flag &&
1337 flag1 == active_flag) {
1339 } else if (flag0 == flag1) {
1341 } else if (flag0 == 0xFF) {
1343 } else if (flag1 == 0xFF) {
1349 case FLAG_INCREMENTAL:
1350 if (flag0 == 255 && flag1 == 0)
1352 else if ((flag1 == 255 && flag0 == 0) ||
1355 else /* flag1 > flag0 */
1359 fprintf (stderr, "Unknown flag scheme %u \n",
1360 environment.flag_scheme);
1366 * If we are reading, we don't need the flag and the CRC any
1367 * more, if we are writing, we will re-calculate CRC and update
1368 * flags before writing out
1371 environment.image = addr1;
1372 environment.crc = &redundant->crc;
1373 environment.flags = &redundant->flags;
1374 environment.data = redundant->data;
1377 environment.image = addr0;
1378 /* Other pointers are already set */
1382 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1389 static int parse_config ()
1393 #if defined(CONFIG_FILE)
1394 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1395 if (get_config (config_file)) {
1397 "Cannot parse config file '%s': %s\n", config_file, strerror (errno));
1401 DEVNAME (0) = DEVICE1_NAME;
1402 DEVOFFSET (0) = DEVICE1_OFFSET;
1403 ENVSIZE (0) = ENV1_SIZE;
1404 /* Default values are: erase-size=env-size */
1405 DEVESIZE (0) = ENVSIZE (0);
1406 /* #sectors=env-size/erase-size (rounded up) */
1407 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1408 #ifdef DEVICE1_ESIZE
1409 DEVESIZE (0) = DEVICE1_ESIZE;
1411 #ifdef DEVICE1_ENVSECTORS
1412 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1416 DEVNAME (1) = DEVICE2_NAME;
1417 DEVOFFSET (1) = DEVICE2_OFFSET;
1418 ENVSIZE (1) = ENV2_SIZE;
1419 /* Default values are: erase-size=env-size */
1420 DEVESIZE (1) = ENVSIZE (1);
1421 /* #sectors=env-size/erase-size (rounded up) */
1422 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1423 #ifdef DEVICE2_ESIZE
1424 DEVESIZE (1) = DEVICE2_ESIZE;
1426 #ifdef DEVICE2_ENVSECTORS
1427 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1432 if (stat (DEVNAME (0), &st)) {
1434 "Cannot access MTD device %s: %s\n",
1435 DEVNAME (0), strerror (errno));
1439 if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
1441 "Cannot access MTD device %s: %s\n",
1442 DEVNAME (1), strerror (errno));
1448 #if defined(CONFIG_FILE)
1449 static int get_config (char *fname)
1457 fp = fopen (fname, "r");
1461 while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1462 /* Skip incomplete conversions and comment strings */
1466 rc = sscanf (dump, "%ms %lx %lx %lx %lx",
1476 DEVNAME(i) = devname;
1479 /* Assume the erase size is the same as the env-size */
1480 DEVESIZE(i) = ENVSIZE(i);
1483 /* Assume enough env sectors to cover the environment */
1484 ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1490 HaveRedundEnv = i - 1;
1491 if (!i) { /* No valid entries found */