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+
12 #include <env_flags.h>
14 #include <linux/stringify.h>
19 #include <sys/types.h>
20 #include <sys/ioctl.h>
26 # include <linux/mtd/mtd.h>
28 # define __user /* nothing */
29 # include <mtd/mtd-user.h>
36 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
38 #define WHITESPACE(c) ((c == '\t') || (c == ' '))
40 #define min(x, y) ({ \
41 typeof(x) _min1 = (x); \
42 typeof(y) _min2 = (y); \
43 (void) (&_min1 == &_min2); \
44 _min1 < _min2 ? _min1 : _min2; })
47 const char *devname; /* Device name */
48 ulong devoff; /* Device offset */
49 ulong env_size; /* environment size */
50 ulong erase_size; /* device erase size */
51 ulong env_sectors; /* number of environment sectors */
52 uint8_t mtd_type; /* type of the MTD device */
55 static struct envdev_s envdevices[2] =
58 .mtd_type = MTD_ABSENT,
60 .mtd_type = MTD_ABSENT,
63 static int dev_current;
65 #define DEVNAME(i) envdevices[(i)].devname
66 #define DEVOFFSET(i) envdevices[(i)].devoff
67 #define ENVSIZE(i) envdevices[(i)].env_size
68 #define DEVESIZE(i) envdevices[(i)].erase_size
69 #define ENVSECTORS(i) envdevices[(i)].env_sectors
70 #define DEVTYPE(i) envdevices[(i)].mtd_type
72 #define CUR_ENVSIZE ENVSIZE(dev_current)
74 #define ENV_SIZE getenvsize()
76 struct env_image_single {
77 uint32_t crc; /* CRC32 over data bytes */
81 struct env_image_redundant {
82 uint32_t crc; /* CRC32 over data bytes */
83 unsigned char flags; /* active or obsolete */
98 enum flag_scheme flag_scheme;
101 static struct environment environment = {
102 .flag_scheme = FLAG_NONE,
105 /* Is AES encryption used? */
107 static uint8_t aes_key[AES_KEY_LENGTH] = { 0 };
108 static int env_aes_cbc_crypt(char *data, const int enc);
110 static int HaveRedundEnv = 0;
112 static unsigned char active_flag = 1;
113 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
114 static unsigned char obsolete_flag = 0;
116 #define DEFAULT_ENV_INSTANCE_STATIC
117 #include <env_default.h>
119 static int flash_io (int mode);
120 static char *envmatch (char * s1, char * s2);
121 static int parse_config (void);
123 #if defined(CONFIG_FILE)
124 static int get_config (char *);
126 static inline ulong getenvsize (void)
128 ulong rc = CUR_ENVSIZE - sizeof(long);
134 rc &= ~(AES_KEY_LENGTH - 1);
139 static char *fw_string_blank(char *s, int noblank)
144 for (i = 0; i < len; i++, s++) {
145 if ((noblank && !WHITESPACE(*s)) ||
146 (!noblank && WHITESPACE(*s)))
156 * Search the environment for a variable.
157 * Return the value, if found, or NULL, if not found.
159 char *fw_getenv (char *name)
163 for (env = environment.data; *env; env = nxt + 1) {
166 for (nxt = env; *nxt; ++nxt) {
167 if (nxt >= &environment.data[ENV_SIZE]) {
168 fprintf (stderr, "## Error: "
169 "environment not terminated\n");
173 val = envmatch (name, env);
182 * Search the default environment for a variable.
183 * Return the value, if found, or NULL, if not found.
185 char *fw_getdefenv(char *name)
189 for (env = default_environment; *env; env = nxt + 1) {
192 for (nxt = env; *nxt; ++nxt) {
193 if (nxt >= &default_environment[ENV_SIZE]) {
194 fprintf(stderr, "## Error: "
195 "default environment not terminated\n");
199 val = envmatch(name, env);
207 static int parse_aes_key(char *key)
209 char tmp[5] = { '0', 'x', 0, 0, 0 };
213 if (strnlen(key, 64) != 32) {
215 "## Error: '-a' option requires 16-byte AES key\n");
219 for (i = 0; i < 16; i++) {
223 ul = strtoul(tmp, NULL, 16);
226 "## Error: '-a' option requires valid AES key\n");
229 aes_key[i] = ul & 0xff;
238 * Print the current definition of one, or more, or all
239 * environment variables
241 int fw_printenv (int argc, char *argv[])
247 if (argc >= 2 && strcmp(argv[1], "-a") == 0) {
250 "## Error: '-a' option requires AES key\n");
253 rc = parse_aes_key(argv[2]);
263 if (argc == 1) { /* Print all env variables */
264 for (env = environment.data; *env; env = nxt + 1) {
265 for (nxt = env; *nxt; ++nxt) {
266 if (nxt >= &environment.data[ENV_SIZE]) {
267 fprintf (stderr, "## Error: "
268 "environment not terminated\n");
273 printf ("%s\n", env);
278 if (strcmp (argv[1], "-n") == 0) {
283 fprintf (stderr, "## Error: "
284 "`-n' option requires exactly one argument\n");
291 for (i = 1; i < argc; ++i) { /* print single env variables */
292 char *name = argv[i];
295 for (env = environment.data; *env; env = nxt + 1) {
297 for (nxt = env; *nxt; ++nxt) {
298 if (nxt >= &environment.data[ENV_SIZE]) {
299 fprintf (stderr, "## Error: "
300 "environment not terminated\n");
304 val = envmatch (name, env);
307 fputs (name, stdout);
315 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
323 int fw_env_close(void)
327 ret = env_aes_cbc_crypt(environment.data, 1);
330 "Error: can't encrypt env for flash\n");
338 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
340 /* write environment back to flash */
341 if (flash_io(O_RDWR)) {
343 "Error: can't write fw_env to flash\n");
352 * Set/Clear a single variable in the environment.
353 * This is called in sequence to update the environment
354 * in RAM without updating the copy in flash after each set
356 int fw_env_write(char *name, char *value)
361 int deleting, creating, overwriting;
364 * search if variable with this name already exists
366 for (nxt = env = environment.data; *env; env = nxt + 1) {
367 for (nxt = env; *nxt; ++nxt) {
368 if (nxt >= &environment.data[ENV_SIZE]) {
369 fprintf(stderr, "## Error: "
370 "environment not terminated\n");
375 if ((oldval = envmatch (name, env)) != NULL)
379 deleting = (oldval && !(value && strlen(value)));
380 creating = (!oldval && (value && strlen(value)));
381 overwriting = (oldval && (value && strlen(value)));
383 /* check for permission */
385 if (env_flags_validate_varaccess(name,
386 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
387 printf("Can't delete \"%s\"\n", name);
391 } else if (overwriting) {
392 if (env_flags_validate_varaccess(name,
393 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
394 printf("Can't overwrite \"%s\"\n", name);
397 } else if (env_flags_validate_varaccess(name,
398 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
399 const char *defval = fw_getdefenv(name);
403 if (strcmp(oldval, defval)
405 printf("Can't overwrite \"%s\"\n", name);
410 } else if (creating) {
411 if (env_flags_validate_varaccess(name,
412 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
413 printf("Can't create \"%s\"\n", name);
421 if (deleting || overwriting) {
422 if (*++nxt == '\0') {
427 if ((*env == '\0') && (*nxt == '\0'))
436 if (!value || !strlen(value))
440 * Append new definition at the end
442 for (env = environment.data; *env || *(env + 1); ++env);
443 if (env > environment.data)
447 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
449 len = strlen (name) + 2;
450 /* add '=' for first arg, ' ' for all others */
451 len += strlen(value) + 1;
453 if (len > (&environment.data[ENV_SIZE] - env)) {
455 "Error: environment overflow, \"%s\" deleted\n",
460 while ((*env = *name++) != '\0')
463 while ((*++env = *value++) != '\0')
466 /* end is marked with double '\0' */
473 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
475 * EINVAL - need at least 1 argument
476 * EROFS - certain variables ("ethaddr", "serial#") cannot be
477 * modified or deleted
480 int fw_setenv(int argc, char *argv[])
492 if (strcmp(argv[1], "-a") == 0) {
495 "## Error: '-a' option requires AES key\n");
498 rc = parse_aes_key(argv[2]);
511 fprintf(stderr, "Error: environment not initialized\n");
517 if (env_flags_validate_env_set_params(argc, argv) < 0)
521 for (i = 2; i < argc; ++i) {
523 size_t val_len = strlen(val);
526 value[len - 1] = ' ';
527 value = realloc(value, len + val_len + 1);
530 "Cannot malloc %zu bytes: %s\n",
531 len, strerror(errno));
535 memcpy(value + len, val, val_len);
540 fw_env_write(name, value);
544 return fw_env_close();
548 * Parse a file and configure the u-boot variables.
549 * The script file has a very simple format, as follows:
551 * Each line has a couple with name, value:
552 * <white spaces>variable_name<white spaces>variable_value
554 * Both variable_name and variable_value are interpreted as strings.
555 * Any character after <white spaces> and before ending \r\n is interpreted
556 * as variable's value (no comment allowed on these lines !)
558 * Comments are allowed if the first character in the line is #
560 * Returns -1 and sets errno error codes:
564 int fw_parse_script(char *fname)
567 char dump[1024]; /* Maximum line length in the file */
575 fprintf(stderr, "Error: environment not initialized\n");
579 if (strcmp(fname, "-") == 0)
582 fp = fopen(fname, "r");
584 fprintf(stderr, "I cannot open %s for reading\n",
590 while (fgets(dump, sizeof(dump), fp)) {
595 * Read a whole line from the file. If the line is too long
596 * or is not terminated, reports an error and exit.
598 if (dump[len - 1] != '\n') {
600 "Line %d not corrected terminated or too long\n",
606 /* Drop ending line feed / carriage return */
607 while (len > 0 && (dump[len - 1] == '\n' ||
608 dump[len - 1] == '\r')) {
609 dump[len - 1] = '\0';
613 /* Skip comment or empty lines */
614 if ((len == 0) || dump[0] == '#')
618 * Search for variable's name,
619 * remove leading whitespaces
621 name = fw_string_blank(dump, 1);
625 /* The first white space is the end of variable name */
626 val = fw_string_blank(name, 0);
630 if ((val - name) < len)
631 val = fw_string_blank(val, 1);
637 fprintf(stderr, "Setting %s : %s\n",
638 name, val ? val : " removed");
641 if (env_flags_validate_type(name, val) < 0) {
647 * If there is an error setting a variable,
648 * try to save the environment and returns an error
650 if (fw_env_write(name, val)) {
652 "fw_env_write returns with error : %s\n",
660 /* Close file if not stdin */
661 if (strcmp(fname, "-") != 0)
664 ret |= fw_env_close();
671 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
674 * < 0 - failed to test
676 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
678 if (mtd_type == MTD_NANDFLASH) {
679 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
682 perror ("Cannot read bad block mark");
688 fprintf (stderr, "Bad block at 0x%llx, "
689 "skipping\n", *blockstart);
699 * Read data from flash at an offset into a provided buffer. On NAND it skips
700 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
701 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
703 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
704 off_t offset, uint8_t mtd_type)
706 size_t blocklen; /* erase / write length - one block on NAND,
708 size_t processed = 0; /* progress counter */
709 size_t readlen = count; /* current read length */
710 off_t top_of_range; /* end of the last block we may use */
711 off_t block_seek; /* offset inside the current block to the start
713 loff_t blockstart; /* running start of the current block -
714 MEMGETBADBLOCK needs 64 bits */
717 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
719 /* Offset inside a block */
720 block_seek = offset - blockstart;
722 if (mtd_type == MTD_NANDFLASH) {
724 * NAND: calculate which blocks we are reading. We have
725 * to read one block at a time to skip bad blocks.
727 blocklen = DEVESIZE (dev);
730 * To calculate the top of the range, we have to use the
731 * global DEVOFFSET (dev), which can be different from offset
733 top_of_range = ((DEVOFFSET(dev) / blocklen) +
734 ENVSECTORS (dev)) * blocklen;
736 /* Limit to one block for the first read */
737 if (readlen > blocklen - block_seek)
738 readlen = blocklen - block_seek;
741 top_of_range = offset + count;
744 /* This only runs once on NOR flash */
745 while (processed < count) {
746 rc = flash_bad_block (fd, mtd_type, &blockstart);
747 if (rc < 0) /* block test failed */
750 if (blockstart + block_seek + readlen > top_of_range) {
751 /* End of range is reached */
753 "Too few good blocks within range\n");
757 if (rc) { /* block is bad */
758 blockstart += blocklen;
763 * If a block is bad, we retry in the next block at the same
764 * offset - see common/env_nand.c::writeenv()
766 lseek (fd, blockstart + block_seek, SEEK_SET);
768 rc = read (fd, buf + processed, readlen);
770 fprintf (stderr, "Read error on %s: %s\n",
771 DEVNAME (dev), strerror (errno));
775 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
776 rc, blockstart + block_seek, DEVNAME(dev));
778 processed += readlen;
779 readlen = min (blocklen, count - processed);
781 blockstart += blocklen;
788 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
789 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
790 * erase and write the whole data at once.
792 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
793 off_t offset, uint8_t mtd_type)
796 struct erase_info_user erase;
797 size_t blocklen; /* length of NAND block / NOR erase sector */
798 size_t erase_len; /* whole area that can be erased - may include
800 size_t erasesize; /* erase / write length - one block on NAND,
802 size_t processed = 0; /* progress counter */
803 size_t write_total; /* total size to actually write - excluding
805 off_t erase_offset; /* offset to the first erase block (aligned)
807 off_t block_seek; /* offset inside the erase block to the start
809 off_t top_of_range; /* end of the last block we may use */
810 loff_t blockstart; /* running start of the current block -
811 MEMGETBADBLOCK needs 64 bits */
815 * For mtd devices only offset and size of the environment do matter
817 if (mtd_type == MTD_ABSENT) {
819 top_of_range = offset + count;
820 erase_len = blocklen;
823 write_total = blocklen;
825 blocklen = DEVESIZE(dev);
827 top_of_range = ((DEVOFFSET(dev) / blocklen) +
828 ENVSECTORS(dev)) * blocklen;
830 erase_offset = (offset / blocklen) * blocklen;
832 /* Maximum area we may use */
833 erase_len = top_of_range - erase_offset;
835 blockstart = erase_offset;
836 /* Offset inside a block */
837 block_seek = offset - erase_offset;
840 * Data size we actually write: from the start of the block
841 * to the start of the data, then count bytes of data, and
842 * to the end of the block
844 write_total = ((block_seek + count + blocklen - 1) /
845 blocklen) * blocklen;
849 * Support data anywhere within erase sectors: read out the complete
850 * area to be erased, replace the environment image, write the whole
853 if (write_total > count) {
854 data = malloc (erase_len);
857 "Cannot malloc %zu bytes: %s\n",
858 erase_len, strerror (errno));
862 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
864 if (write_total != rc)
868 fprintf(stderr, "Preserving data ");
870 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
871 if (block_seek + count != write_total) {
873 fprintf(stderr, " and ");
874 fprintf(stderr, "0x%lx - 0x%x",
875 block_seek + count, write_total - 1);
877 fprintf(stderr, "\n");
879 /* Overwrite the old environment */
880 memcpy (data + block_seek, buf, count);
883 * We get here, iff offset is block-aligned and count is a
884 * multiple of blocklen - see write_total calculation above
889 if (mtd_type == MTD_NANDFLASH) {
891 * NAND: calculate which blocks we are writing. We have
892 * to write one block at a time to skip bad blocks.
894 erasesize = blocklen;
896 erasesize = erase_len;
899 erase.length = erasesize;
901 /* This only runs once on NOR flash and SPI-dataflash */
902 while (processed < write_total) {
903 rc = flash_bad_block (fd, mtd_type, &blockstart);
904 if (rc < 0) /* block test failed */
907 if (blockstart + erasesize > top_of_range) {
908 fprintf (stderr, "End of range reached, aborting\n");
912 if (rc) { /* block is bad */
913 blockstart += blocklen;
917 if (mtd_type != MTD_ABSENT) {
918 erase.start = blockstart;
919 ioctl(fd, MEMUNLOCK, &erase);
920 /* These do not need an explicit erase cycle */
921 if (mtd_type != MTD_DATAFLASH)
922 if (ioctl(fd, MEMERASE, &erase) != 0) {
924 "MTD erase error on %s: %s\n",
925 DEVNAME(dev), strerror(errno));
930 if (lseek (fd, blockstart, SEEK_SET) == -1) {
932 "Seek error on %s: %s\n",
933 DEVNAME (dev), strerror (errno));
938 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
941 if (write (fd, data + processed, erasesize) != erasesize) {
942 fprintf (stderr, "Write error on %s: %s\n",
943 DEVNAME (dev), strerror (errno));
947 if (mtd_type != MTD_ABSENT)
948 ioctl(fd, MEMLOCK, &erase);
950 processed += erasesize;
952 blockstart += erasesize;
955 if (write_total > count)
962 * Set obsolete flag at offset - NOR flash only
964 static int flash_flag_obsolete (int dev, int fd, off_t offset)
967 struct erase_info_user erase;
969 erase.start = DEVOFFSET (dev);
970 erase.length = DEVESIZE (dev);
971 /* This relies on the fact, that obsolete_flag == 0 */
972 rc = lseek (fd, offset, SEEK_SET);
974 fprintf (stderr, "Cannot seek to set the flag on %s \n",
978 ioctl (fd, MEMUNLOCK, &erase);
979 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
980 ioctl (fd, MEMLOCK, &erase);
982 perror ("Could not set obsolete flag");
987 /* Encrypt or decrypt the environment before writing or reading it. */
988 static int env_aes_cbc_crypt(char *payload, const int enc)
990 uint8_t *data = (uint8_t *)payload;
991 const int len = getenvsize();
992 uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
995 /* First we expand the key. */
996 aes_expand_key(aes_key, key_exp);
998 /* Calculate the number of AES blocks to encrypt. */
999 aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
1002 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
1004 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
1009 static int flash_write (int fd_current, int fd_target, int dev_target)
1013 switch (environment.flag_scheme) {
1016 case FLAG_INCREMENTAL:
1017 (*environment.flags)++;
1020 *environment.flags = active_flag;
1023 fprintf (stderr, "Unimplemented flash scheme %u \n",
1024 environment.flag_scheme);
1029 fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
1030 DEVOFFSET (dev_target), DEVNAME (dev_target));
1033 rc = flash_write_buf(dev_target, fd_target, environment.image,
1034 CUR_ENVSIZE, DEVOFFSET(dev_target),
1035 DEVTYPE(dev_target));
1039 if (environment.flag_scheme == FLAG_BOOLEAN) {
1040 /* Have to set obsolete flag */
1041 off_t offset = DEVOFFSET (dev_current) +
1042 offsetof (struct env_image_redundant, flags);
1045 "Setting obsolete flag in environment at 0x%lx on %s\n",
1046 DEVOFFSET (dev_current), DEVNAME (dev_current));
1048 flash_flag_obsolete (dev_current, fd_current, offset);
1054 static int flash_read (int fd)
1056 struct mtd_info_user mtdinfo;
1060 rc = fstat(fd, &st);
1062 fprintf(stderr, "Cannot stat the file %s\n",
1063 DEVNAME(dev_current));
1067 if (S_ISCHR(st.st_mode)) {
1068 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1070 fprintf(stderr, "Cannot get MTD information for %s\n",
1071 DEVNAME(dev_current));
1074 if (mtdinfo.type != MTD_NORFLASH &&
1075 mtdinfo.type != MTD_NANDFLASH &&
1076 mtdinfo.type != MTD_DATAFLASH &&
1077 mtdinfo.type != MTD_UBIVOLUME) {
1078 fprintf (stderr, "Unsupported flash type %u on %s\n",
1079 mtdinfo.type, DEVNAME(dev_current));
1083 memset(&mtdinfo, 0, sizeof(mtdinfo));
1084 mtdinfo.type = MTD_ABSENT;
1087 DEVTYPE(dev_current) = mtdinfo.type;
1089 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1090 DEVOFFSET (dev_current), mtdinfo.type);
1091 if (rc != CUR_ENVSIZE)
1097 static int flash_io (int mode)
1099 int fd_current, fd_target, rc, dev_target;
1101 /* dev_current: fd_current, erase_current */
1102 fd_current = open (DEVNAME (dev_current), mode);
1103 if (fd_current < 0) {
1105 "Can't open %s: %s\n",
1106 DEVNAME (dev_current), strerror (errno));
1110 if (mode == O_RDWR) {
1111 if (HaveRedundEnv) {
1112 /* switch to next partition for writing */
1113 dev_target = !dev_current;
1114 /* dev_target: fd_target, erase_target */
1115 fd_target = open (DEVNAME (dev_target), mode);
1116 if (fd_target < 0) {
1118 "Can't open %s: %s\n",
1119 DEVNAME (dev_target),
1125 dev_target = dev_current;
1126 fd_target = fd_current;
1129 rc = flash_write (fd_current, fd_target, dev_target);
1131 if (HaveRedundEnv) {
1132 if (close (fd_target)) {
1134 "I/O error on %s: %s\n",
1135 DEVNAME (dev_target),
1141 rc = flash_read (fd_current);
1145 if (close (fd_current)) {
1147 "I/O error on %s: %s\n",
1148 DEVNAME (dev_current), strerror (errno));
1156 * s1 is either a simple 'name', or a 'name=value' pair.
1157 * s2 is a 'name=value' pair.
1158 * If the names match, return the value of s2, else NULL.
1161 static char *envmatch (char * s1, char * s2)
1163 if (s1 == NULL || s2 == NULL)
1166 while (*s1 == *s2++)
1169 if (*s1 == '\0' && *(s2 - 1) == '=')
1175 * Prevent confusion if running from erased flash memory
1177 int fw_env_open(void)
1180 unsigned char flag0;
1184 unsigned char flag1;
1189 struct env_image_single *single;
1190 struct env_image_redundant *redundant;
1192 if (parse_config ()) /* should fill envdevices */
1195 addr0 = calloc(1, CUR_ENVSIZE);
1196 if (addr0 == NULL) {
1198 "Not enough memory for environment (%ld bytes)\n",
1203 /* read environment from FLASH to local buffer */
1204 environment.image = addr0;
1206 if (HaveRedundEnv) {
1208 environment.crc = &redundant->crc;
1209 environment.flags = &redundant->flags;
1210 environment.data = redundant->data;
1213 environment.crc = &single->crc;
1214 environment.flags = NULL;
1215 environment.data = single->data;
1219 if (flash_io (O_RDONLY))
1222 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1225 ret = env_aes_cbc_crypt(environment.data, 0);
1230 crc0_ok = (crc0 == *environment.crc);
1231 if (!HaveRedundEnv) {
1234 "Warning: Bad CRC, using default environment\n");
1235 memcpy(environment.data, default_environment, sizeof default_environment);
1238 flag0 = *environment.flags;
1241 addr1 = calloc(1, CUR_ENVSIZE);
1242 if (addr1 == NULL) {
1244 "Not enough memory for environment (%ld bytes)\n",
1251 * have to set environment.image for flash_read(), careful -
1252 * other pointers in environment still point inside addr0
1254 environment.image = addr1;
1255 if (flash_io (O_RDONLY))
1258 /* Check flag scheme compatibility */
1259 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1260 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1261 environment.flag_scheme = FLAG_BOOLEAN;
1262 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1263 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1264 environment.flag_scheme = FLAG_INCREMENTAL;
1265 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1266 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1267 environment.flag_scheme = FLAG_BOOLEAN;
1268 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1269 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1270 environment.flag_scheme = FLAG_INCREMENTAL;
1271 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1272 DEVTYPE(!dev_current) == MTD_ABSENT) {
1273 environment.flag_scheme = FLAG_INCREMENTAL;
1275 fprintf (stderr, "Incompatible flash types!\n");
1279 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1282 ret = env_aes_cbc_crypt(redundant->data, 0);
1287 crc1_ok = (crc1 == redundant->crc);
1288 flag1 = redundant->flags;
1290 if (crc0_ok && !crc1_ok) {
1292 } else if (!crc0_ok && crc1_ok) {
1294 } else if (!crc0_ok && !crc1_ok) {
1296 "Warning: Bad CRC, using default environment\n");
1297 memcpy (environment.data, default_environment,
1298 sizeof default_environment);
1301 switch (environment.flag_scheme) {
1303 if (flag0 == active_flag &&
1304 flag1 == obsolete_flag) {
1306 } else if (flag0 == obsolete_flag &&
1307 flag1 == active_flag) {
1309 } else if (flag0 == flag1) {
1311 } else if (flag0 == 0xFF) {
1313 } else if (flag1 == 0xFF) {
1319 case FLAG_INCREMENTAL:
1320 if (flag0 == 255 && flag1 == 0)
1322 else if ((flag1 == 255 && flag0 == 0) ||
1325 else /* flag1 > flag0 */
1329 fprintf (stderr, "Unknown flag scheme %u \n",
1330 environment.flag_scheme);
1336 * If we are reading, we don't need the flag and the CRC any
1337 * more, if we are writing, we will re-calculate CRC and update
1338 * flags before writing out
1341 environment.image = addr1;
1342 environment.crc = &redundant->crc;
1343 environment.flags = &redundant->flags;
1344 environment.data = redundant->data;
1347 environment.image = addr0;
1348 /* Other pointers are already set */
1352 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1359 static int parse_config ()
1363 #if defined(CONFIG_FILE)
1364 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1365 if (get_config (CONFIG_FILE)) {
1367 "Cannot parse config file: %s\n", strerror (errno));
1371 DEVNAME (0) = DEVICE1_NAME;
1372 DEVOFFSET (0) = DEVICE1_OFFSET;
1373 ENVSIZE (0) = ENV1_SIZE;
1374 /* Default values are: erase-size=env-size */
1375 DEVESIZE (0) = ENVSIZE (0);
1376 /* #sectors=env-size/erase-size (rounded up) */
1377 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1378 #ifdef DEVICE1_ESIZE
1379 DEVESIZE (0) = DEVICE1_ESIZE;
1381 #ifdef DEVICE1_ENVSECTORS
1382 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1386 DEVNAME (1) = DEVICE2_NAME;
1387 DEVOFFSET (1) = DEVICE2_OFFSET;
1388 ENVSIZE (1) = ENV2_SIZE;
1389 /* Default values are: erase-size=env-size */
1390 DEVESIZE (1) = ENVSIZE (1);
1391 /* #sectors=env-size/erase-size (rounded up) */
1392 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1393 #ifdef DEVICE2_ESIZE
1394 DEVESIZE (1) = DEVICE2_ESIZE;
1396 #ifdef DEVICE2_ENVSECTORS
1397 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1402 if (stat (DEVNAME (0), &st)) {
1404 "Cannot access MTD device %s: %s\n",
1405 DEVNAME (0), strerror (errno));
1409 if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
1411 "Cannot access MTD device %s: %s\n",
1412 DEVNAME (1), strerror (errno));
1418 #if defined(CONFIG_FILE)
1419 static int get_config (char *fname)
1427 fp = fopen (fname, "r");
1431 while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1432 /* Skip incomplete conversions and comment strings */
1436 rc = sscanf (dump, "%ms %lx %lx %lx %lx",
1446 DEVNAME(i) = devname;
1449 /* Assume the erase size is the same as the env-size */
1450 DEVESIZE(i) = ENVSIZE(i);
1453 /* Assume enough env sectors to cover the environment */
1454 ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1460 HaveRedundEnv = i - 1;
1461 if (!i) { /* No valid entries found */