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>
37 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
39 #define WHITESPACE(c) ((c == '\t') || (c == ' '))
41 #define min(x, y) ({ \
42 typeof(x) _min1 = (x); \
43 typeof(y) _min2 = (y); \
44 (void) (&_min1 == &_min2); \
45 _min1 < _min2 ? _min1 : _min2; })
48 const char *devname; /* Device name */
49 ulong devoff; /* Device offset */
50 ulong env_size; /* environment size */
51 ulong erase_size; /* device erase size */
52 ulong env_sectors; /* number of environment sectors */
53 uint8_t mtd_type; /* type of the MTD device */
56 static struct envdev_s envdevices[2] =
59 .mtd_type = MTD_ABSENT,
61 .mtd_type = MTD_ABSENT,
64 static int dev_current;
66 #define DEVNAME(i) envdevices[(i)].devname
67 #define DEVOFFSET(i) envdevices[(i)].devoff
68 #define ENVSIZE(i) envdevices[(i)].env_size
69 #define DEVESIZE(i) envdevices[(i)].erase_size
70 #define ENVSECTORS(i) envdevices[(i)].env_sectors
71 #define DEVTYPE(i) envdevices[(i)].mtd_type
73 #define CUR_ENVSIZE ENVSIZE(dev_current)
75 #define ENV_SIZE getenvsize()
77 struct env_image_single {
78 uint32_t crc; /* CRC32 over data bytes */
82 struct env_image_redundant {
83 uint32_t crc; /* CRC32 over data bytes */
84 unsigned char flags; /* active or obsolete */
99 enum flag_scheme flag_scheme;
102 static struct environment environment = {
103 .flag_scheme = FLAG_NONE,
106 static int env_aes_cbc_crypt(char *data, const int enc);
108 static int HaveRedundEnv = 0;
110 static unsigned char active_flag = 1;
111 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
112 static unsigned char obsolete_flag = 0;
114 #define DEFAULT_ENV_INSTANCE_STATIC
115 #include <env_default.h>
117 static int flash_io (int mode);
118 static char *envmatch (char * s1, char * s2);
119 static int parse_config (void);
121 #if defined(CONFIG_FILE)
122 static int get_config (char *);
124 static inline ulong getenvsize (void)
126 ulong rc = CUR_ENVSIZE - sizeof(uint32_t);
131 if (common_args.aes_flag)
132 rc &= ~(AES_KEY_LENGTH - 1);
137 static char *fw_string_blank(char *s, int noblank)
142 for (i = 0; i < len; i++, s++) {
143 if ((noblank && !WHITESPACE(*s)) ||
144 (!noblank && WHITESPACE(*s)))
154 * Search the environment for a variable.
155 * Return the value, if found, or NULL, if not found.
157 char *fw_getenv (char *name)
161 for (env = environment.data; *env; env = nxt + 1) {
164 for (nxt = env; *nxt; ++nxt) {
165 if (nxt >= &environment.data[ENV_SIZE]) {
166 fprintf (stderr, "## Error: "
167 "environment not terminated\n");
171 val = envmatch (name, env);
180 * Search the default environment for a variable.
181 * Return the value, if found, or NULL, if not found.
183 char *fw_getdefenv(char *name)
187 for (env = default_environment; *env; env = nxt + 1) {
190 for (nxt = env; *nxt; ++nxt) {
191 if (nxt >= &default_environment[ENV_SIZE]) {
192 fprintf(stderr, "## Error: "
193 "default environment not terminated\n");
197 val = envmatch(name, env);
205 int parse_aes_key(char *key, uint8_t *bin_key)
207 char tmp[5] = { '0', 'x', 0, 0, 0 };
211 if (strnlen(key, 64) != 32) {
213 "## Error: '-a' option requires 16-byte AES key\n");
217 for (i = 0; i < 16; i++) {
221 ul = strtoul(tmp, NULL, 16);
224 "## Error: '-a' option requires valid AES key\n");
227 bin_key[i] = ul & 0xff;
234 * Print the current definition of one, or more, or all
235 * environment variables
237 int fw_printenv (int argc, char *argv[])
245 if (argc == 0) { /* Print all env variables */
246 for (env = environment.data; *env; env = nxt + 1) {
247 for (nxt = env; *nxt; ++nxt) {
248 if (nxt >= &environment.data[ENV_SIZE]) {
249 fprintf (stderr, "## Error: "
250 "environment not terminated\n");
255 printf ("%s\n", env);
260 if (printenv_args.name_suppress && argc != 1) {
262 "## Error: `-n' option requires exactly one argument\n");
266 for (i = 0; i < argc; ++i) { /* print single env variables */
267 char *name = argv[i];
270 for (env = environment.data; *env; env = nxt + 1) {
272 for (nxt = env; *nxt; ++nxt) {
273 if (nxt >= &environment.data[ENV_SIZE]) {
274 fprintf (stderr, "## Error: "
275 "environment not terminated\n");
279 val = envmatch (name, env);
281 if (!printenv_args.name_suppress) {
282 fputs (name, stdout);
290 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
298 int fw_env_close(void)
301 if (common_args.aes_flag) {
302 ret = env_aes_cbc_crypt(environment.data, 1);
305 "Error: can't encrypt env for flash\n");
313 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
315 /* write environment back to flash */
316 if (flash_io(O_RDWR)) {
318 "Error: can't write fw_env to flash\n");
327 * Set/Clear a single variable in the environment.
328 * This is called in sequence to update the environment
329 * in RAM without updating the copy in flash after each set
331 int fw_env_write(char *name, char *value)
336 int deleting, creating, overwriting;
339 * search if variable with this name already exists
341 for (nxt = env = environment.data; *env; env = nxt + 1) {
342 for (nxt = env; *nxt; ++nxt) {
343 if (nxt >= &environment.data[ENV_SIZE]) {
344 fprintf(stderr, "## Error: "
345 "environment not terminated\n");
350 if ((oldval = envmatch (name, env)) != NULL)
354 deleting = (oldval && !(value && strlen(value)));
355 creating = (!oldval && (value && strlen(value)));
356 overwriting = (oldval && (value && strlen(value)));
358 /* check for permission */
360 if (env_flags_validate_varaccess(name,
361 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
362 printf("Can't delete \"%s\"\n", name);
366 } else if (overwriting) {
367 if (env_flags_validate_varaccess(name,
368 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
369 printf("Can't overwrite \"%s\"\n", name);
372 } else if (env_flags_validate_varaccess(name,
373 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
374 const char *defval = fw_getdefenv(name);
378 if (strcmp(oldval, defval)
380 printf("Can't overwrite \"%s\"\n", name);
385 } else if (creating) {
386 if (env_flags_validate_varaccess(name,
387 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
388 printf("Can't create \"%s\"\n", name);
396 if (deleting || overwriting) {
397 if (*++nxt == '\0') {
402 if ((*env == '\0') && (*nxt == '\0'))
411 if (!value || !strlen(value))
415 * Append new definition at the end
417 for (env = environment.data; *env || *(env + 1); ++env);
418 if (env > environment.data)
422 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
424 len = strlen (name) + 2;
425 /* add '=' for first arg, ' ' for all others */
426 len += strlen(value) + 1;
428 if (len > (&environment.data[ENV_SIZE] - env)) {
430 "Error: environment overflow, \"%s\" deleted\n",
435 while ((*env = *name++) != '\0')
438 while ((*++env = *value++) != '\0')
441 /* end is marked with double '\0' */
448 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
450 * EINVAL - need at least 1 argument
451 * EROFS - certain variables ("ethaddr", "serial#") cannot be
452 * modified or deleted
455 int fw_setenv(int argc, char *argv[])
464 fprintf(stderr, "## Error: variable name missing\n");
470 fprintf(stderr, "Error: environment not initialized\n");
478 if (env_flags_validate_env_set_params(name, valv, valc) < 0)
482 for (i = 0; i < valc; ++i) {
484 size_t val_len = strlen(val);
487 value[len - 1] = ' ';
488 value = realloc(value, len + val_len + 1);
491 "Cannot malloc %zu bytes: %s\n",
492 len, strerror(errno));
496 memcpy(value + len, val, val_len);
501 fw_env_write(name, value);
505 return fw_env_close();
509 * Parse a file and configure the u-boot variables.
510 * The script file has a very simple format, as follows:
512 * Each line has a couple with name, value:
513 * <white spaces>variable_name<white spaces>variable_value
515 * Both variable_name and variable_value are interpreted as strings.
516 * Any character after <white spaces> and before ending \r\n is interpreted
517 * as variable's value (no comment allowed on these lines !)
519 * Comments are allowed if the first character in the line is #
521 * Returns -1 and sets errno error codes:
525 int fw_parse_script(char *fname)
528 char dump[1024]; /* Maximum line length in the file */
536 fprintf(stderr, "Error: environment not initialized\n");
540 if (strcmp(fname, "-") == 0)
543 fp = fopen(fname, "r");
545 fprintf(stderr, "I cannot open %s for reading\n",
551 while (fgets(dump, sizeof(dump), fp)) {
556 * Read a whole line from the file. If the line is too long
557 * or is not terminated, reports an error and exit.
559 if (dump[len - 1] != '\n') {
561 "Line %d not corrected terminated or too long\n",
567 /* Drop ending line feed / carriage return */
568 while (len > 0 && (dump[len - 1] == '\n' ||
569 dump[len - 1] == '\r')) {
570 dump[len - 1] = '\0';
574 /* Skip comment or empty lines */
575 if ((len == 0) || dump[0] == '#')
579 * Search for variable's name,
580 * remove leading whitespaces
582 name = fw_string_blank(dump, 1);
586 /* The first white space is the end of variable name */
587 val = fw_string_blank(name, 0);
591 if ((val - name) < len)
592 val = fw_string_blank(val, 1);
598 fprintf(stderr, "Setting %s : %s\n",
599 name, val ? val : " removed");
602 if (env_flags_validate_type(name, val) < 0) {
608 * If there is an error setting a variable,
609 * try to save the environment and returns an error
611 if (fw_env_write(name, val)) {
613 "fw_env_write returns with error : %s\n",
621 /* Close file if not stdin */
622 if (strcmp(fname, "-") != 0)
625 ret |= fw_env_close();
632 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
635 * < 0 - failed to test
637 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
639 if (mtd_type == MTD_NANDFLASH) {
640 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
643 perror ("Cannot read bad block mark");
649 fprintf (stderr, "Bad block at 0x%llx, "
650 "skipping\n", *blockstart);
660 * Read data from flash at an offset into a provided buffer. On NAND it skips
661 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
662 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
664 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
665 off_t offset, uint8_t mtd_type)
667 size_t blocklen; /* erase / write length - one block on NAND,
669 size_t processed = 0; /* progress counter */
670 size_t readlen = count; /* current read length */
671 off_t top_of_range; /* end of the last block we may use */
672 off_t block_seek; /* offset inside the current block to the start
674 loff_t blockstart; /* running start of the current block -
675 MEMGETBADBLOCK needs 64 bits */
678 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
680 /* Offset inside a block */
681 block_seek = offset - blockstart;
683 if (mtd_type == MTD_NANDFLASH) {
685 * NAND: calculate which blocks we are reading. We have
686 * to read one block at a time to skip bad blocks.
688 blocklen = DEVESIZE (dev);
691 * To calculate the top of the range, we have to use the
692 * global DEVOFFSET (dev), which can be different from offset
694 top_of_range = ((DEVOFFSET(dev) / blocklen) +
695 ENVSECTORS (dev)) * blocklen;
697 /* Limit to one block for the first read */
698 if (readlen > blocklen - block_seek)
699 readlen = blocklen - block_seek;
702 top_of_range = offset + count;
705 /* This only runs once on NOR flash */
706 while (processed < count) {
707 rc = flash_bad_block (fd, mtd_type, &blockstart);
708 if (rc < 0) /* block test failed */
711 if (blockstart + block_seek + readlen > top_of_range) {
712 /* End of range is reached */
714 "Too few good blocks within range\n");
718 if (rc) { /* block is bad */
719 blockstart += blocklen;
724 * If a block is bad, we retry in the next block at the same
725 * offset - see common/env_nand.c::writeenv()
727 lseek (fd, blockstart + block_seek, SEEK_SET);
729 rc = read (fd, buf + processed, readlen);
731 fprintf (stderr, "Read error on %s: %s\n",
732 DEVNAME (dev), strerror (errno));
736 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
737 rc, blockstart + block_seek, DEVNAME(dev));
739 processed += readlen;
740 readlen = min (blocklen, count - processed);
742 blockstart += blocklen;
749 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
750 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
751 * erase and write the whole data at once.
753 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
754 off_t offset, uint8_t mtd_type)
757 struct erase_info_user erase;
758 size_t blocklen; /* length of NAND block / NOR erase sector */
759 size_t erase_len; /* whole area that can be erased - may include
761 size_t erasesize; /* erase / write length - one block on NAND,
763 size_t processed = 0; /* progress counter */
764 size_t write_total; /* total size to actually write - excluding
766 off_t erase_offset; /* offset to the first erase block (aligned)
768 off_t block_seek; /* offset inside the erase block to the start
770 off_t top_of_range; /* end of the last block we may use */
771 loff_t blockstart; /* running start of the current block -
772 MEMGETBADBLOCK needs 64 bits */
776 * For mtd devices only offset and size of the environment do matter
778 if (mtd_type == MTD_ABSENT) {
780 top_of_range = offset + count;
781 erase_len = blocklen;
784 write_total = blocklen;
786 blocklen = DEVESIZE(dev);
788 top_of_range = ((DEVOFFSET(dev) / blocklen) +
789 ENVSECTORS(dev)) * blocklen;
791 erase_offset = (offset / blocklen) * blocklen;
793 /* Maximum area we may use */
794 erase_len = top_of_range - erase_offset;
796 blockstart = erase_offset;
797 /* Offset inside a block */
798 block_seek = offset - erase_offset;
801 * Data size we actually write: from the start of the block
802 * to the start of the data, then count bytes of data, and
803 * to the end of the block
805 write_total = ((block_seek + count + blocklen - 1) /
806 blocklen) * blocklen;
810 * Support data anywhere within erase sectors: read out the complete
811 * area to be erased, replace the environment image, write the whole
814 if (write_total > count) {
815 data = malloc (erase_len);
818 "Cannot malloc %zu bytes: %s\n",
819 erase_len, strerror (errno));
823 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
825 if (write_total != rc)
829 fprintf(stderr, "Preserving data ");
831 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
832 if (block_seek + count != write_total) {
834 fprintf(stderr, " and ");
835 fprintf(stderr, "0x%lx - 0x%x",
836 block_seek + count, write_total - 1);
838 fprintf(stderr, "\n");
840 /* Overwrite the old environment */
841 memcpy (data + block_seek, buf, count);
844 * We get here, iff offset is block-aligned and count is a
845 * multiple of blocklen - see write_total calculation above
850 if (mtd_type == MTD_NANDFLASH) {
852 * NAND: calculate which blocks we are writing. We have
853 * to write one block at a time to skip bad blocks.
855 erasesize = blocklen;
857 erasesize = erase_len;
860 erase.length = erasesize;
862 /* This only runs once on NOR flash and SPI-dataflash */
863 while (processed < write_total) {
864 rc = flash_bad_block (fd, mtd_type, &blockstart);
865 if (rc < 0) /* block test failed */
868 if (blockstart + erasesize > top_of_range) {
869 fprintf (stderr, "End of range reached, aborting\n");
873 if (rc) { /* block is bad */
874 blockstart += blocklen;
878 if (mtd_type != MTD_ABSENT) {
879 erase.start = blockstart;
880 ioctl(fd, MEMUNLOCK, &erase);
881 /* These do not need an explicit erase cycle */
882 if (mtd_type != MTD_DATAFLASH)
883 if (ioctl(fd, MEMERASE, &erase) != 0) {
885 "MTD erase error on %s: %s\n",
886 DEVNAME(dev), strerror(errno));
891 if (lseek (fd, blockstart, SEEK_SET) == -1) {
893 "Seek error on %s: %s\n",
894 DEVNAME (dev), strerror (errno));
899 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
902 if (write (fd, data + processed, erasesize) != erasesize) {
903 fprintf (stderr, "Write error on %s: %s\n",
904 DEVNAME (dev), strerror (errno));
908 if (mtd_type != MTD_ABSENT)
909 ioctl(fd, MEMLOCK, &erase);
911 processed += erasesize;
913 blockstart += erasesize;
916 if (write_total > count)
923 * Set obsolete flag at offset - NOR flash only
925 static int flash_flag_obsolete (int dev, int fd, off_t offset)
928 struct erase_info_user erase;
930 erase.start = DEVOFFSET (dev);
931 erase.length = DEVESIZE (dev);
932 /* This relies on the fact, that obsolete_flag == 0 */
933 rc = lseek (fd, offset, SEEK_SET);
935 fprintf (stderr, "Cannot seek to set the flag on %s \n",
939 ioctl (fd, MEMUNLOCK, &erase);
940 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
941 ioctl (fd, MEMLOCK, &erase);
943 perror ("Could not set obsolete flag");
948 /* Encrypt or decrypt the environment before writing or reading it. */
949 static int env_aes_cbc_crypt(char *payload, const int enc)
951 uint8_t *data = (uint8_t *)payload;
952 const int len = getenvsize();
953 uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
956 /* First we expand the key. */
957 aes_expand_key(common_args.aes_key, key_exp);
959 /* Calculate the number of AES blocks to encrypt. */
960 aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
963 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
965 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
970 static int flash_write (int fd_current, int fd_target, int dev_target)
974 switch (environment.flag_scheme) {
977 case FLAG_INCREMENTAL:
978 (*environment.flags)++;
981 *environment.flags = active_flag;
984 fprintf (stderr, "Unimplemented flash scheme %u \n",
985 environment.flag_scheme);
990 fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
991 DEVOFFSET (dev_target), DEVNAME (dev_target));
994 rc = flash_write_buf(dev_target, fd_target, environment.image,
995 CUR_ENVSIZE, DEVOFFSET(dev_target),
996 DEVTYPE(dev_target));
1000 if (environment.flag_scheme == FLAG_BOOLEAN) {
1001 /* Have to set obsolete flag */
1002 off_t offset = DEVOFFSET (dev_current) +
1003 offsetof (struct env_image_redundant, flags);
1006 "Setting obsolete flag in environment at 0x%lx on %s\n",
1007 DEVOFFSET (dev_current), DEVNAME (dev_current));
1009 flash_flag_obsolete (dev_current, fd_current, offset);
1015 static int flash_read (int fd)
1017 struct mtd_info_user mtdinfo;
1021 rc = fstat(fd, &st);
1023 fprintf(stderr, "Cannot stat the file %s\n",
1024 DEVNAME(dev_current));
1028 if (S_ISCHR(st.st_mode)) {
1029 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1031 fprintf(stderr, "Cannot get MTD information for %s\n",
1032 DEVNAME(dev_current));
1035 if (mtdinfo.type != MTD_NORFLASH &&
1036 mtdinfo.type != MTD_NANDFLASH &&
1037 mtdinfo.type != MTD_DATAFLASH &&
1038 mtdinfo.type != MTD_UBIVOLUME) {
1039 fprintf (stderr, "Unsupported flash type %u on %s\n",
1040 mtdinfo.type, DEVNAME(dev_current));
1044 memset(&mtdinfo, 0, sizeof(mtdinfo));
1045 mtdinfo.type = MTD_ABSENT;
1048 DEVTYPE(dev_current) = mtdinfo.type;
1050 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1051 DEVOFFSET (dev_current), mtdinfo.type);
1052 if (rc != CUR_ENVSIZE)
1058 static int flash_io (int mode)
1060 int fd_current, fd_target, rc, dev_target;
1062 /* dev_current: fd_current, erase_current */
1063 fd_current = open (DEVNAME (dev_current), mode);
1064 if (fd_current < 0) {
1066 "Can't open %s: %s\n",
1067 DEVNAME (dev_current), strerror (errno));
1071 if (mode == O_RDWR) {
1072 if (HaveRedundEnv) {
1073 /* switch to next partition for writing */
1074 dev_target = !dev_current;
1075 /* dev_target: fd_target, erase_target */
1076 fd_target = open (DEVNAME (dev_target), mode);
1077 if (fd_target < 0) {
1079 "Can't open %s: %s\n",
1080 DEVNAME (dev_target),
1086 dev_target = dev_current;
1087 fd_target = fd_current;
1090 rc = flash_write (fd_current, fd_target, dev_target);
1092 if (HaveRedundEnv) {
1093 if (close (fd_target)) {
1095 "I/O error on %s: %s\n",
1096 DEVNAME (dev_target),
1102 rc = flash_read (fd_current);
1106 if (close (fd_current)) {
1108 "I/O error on %s: %s\n",
1109 DEVNAME (dev_current), strerror (errno));
1117 * s1 is either a simple 'name', or a 'name=value' pair.
1118 * s2 is a 'name=value' pair.
1119 * If the names match, return the value of s2, else NULL.
1122 static char *envmatch (char * s1, char * s2)
1124 if (s1 == NULL || s2 == NULL)
1127 while (*s1 == *s2++)
1130 if (*s1 == '\0' && *(s2 - 1) == '=')
1136 * Prevent confusion if running from erased flash memory
1138 int fw_env_open(void)
1141 unsigned char flag0;
1145 unsigned char flag1;
1150 struct env_image_single *single;
1151 struct env_image_redundant *redundant;
1153 if (parse_config ()) /* should fill envdevices */
1156 addr0 = calloc(1, CUR_ENVSIZE);
1157 if (addr0 == NULL) {
1159 "Not enough memory for environment (%ld bytes)\n",
1164 /* read environment from FLASH to local buffer */
1165 environment.image = addr0;
1167 if (HaveRedundEnv) {
1169 environment.crc = &redundant->crc;
1170 environment.flags = &redundant->flags;
1171 environment.data = redundant->data;
1174 environment.crc = &single->crc;
1175 environment.flags = NULL;
1176 environment.data = single->data;
1180 if (flash_io (O_RDONLY))
1183 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1185 if (common_args.aes_flag) {
1186 ret = env_aes_cbc_crypt(environment.data, 0);
1191 crc0_ok = (crc0 == *environment.crc);
1192 if (!HaveRedundEnv) {
1195 "Warning: Bad CRC, using default environment\n");
1196 memcpy(environment.data, default_environment, sizeof default_environment);
1199 flag0 = *environment.flags;
1202 addr1 = calloc(1, CUR_ENVSIZE);
1203 if (addr1 == NULL) {
1205 "Not enough memory for environment (%ld bytes)\n",
1212 * have to set environment.image for flash_read(), careful -
1213 * other pointers in environment still point inside addr0
1215 environment.image = addr1;
1216 if (flash_io (O_RDONLY))
1219 /* Check flag scheme compatibility */
1220 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1221 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1222 environment.flag_scheme = FLAG_BOOLEAN;
1223 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1224 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1225 environment.flag_scheme = FLAG_INCREMENTAL;
1226 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1227 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1228 environment.flag_scheme = FLAG_BOOLEAN;
1229 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1230 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1231 environment.flag_scheme = FLAG_INCREMENTAL;
1232 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1233 DEVTYPE(!dev_current) == MTD_ABSENT) {
1234 environment.flag_scheme = FLAG_INCREMENTAL;
1236 fprintf (stderr, "Incompatible flash types!\n");
1240 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1242 if (common_args.aes_flag) {
1243 ret = env_aes_cbc_crypt(redundant->data, 0);
1248 crc1_ok = (crc1 == redundant->crc);
1249 flag1 = redundant->flags;
1251 if (crc0_ok && !crc1_ok) {
1253 } else if (!crc0_ok && crc1_ok) {
1255 } else if (!crc0_ok && !crc1_ok) {
1257 "Warning: Bad CRC, using default environment\n");
1258 memcpy (environment.data, default_environment,
1259 sizeof default_environment);
1262 switch (environment.flag_scheme) {
1264 if (flag0 == active_flag &&
1265 flag1 == obsolete_flag) {
1267 } else if (flag0 == obsolete_flag &&
1268 flag1 == active_flag) {
1270 } else if (flag0 == flag1) {
1272 } else if (flag0 == 0xFF) {
1274 } else if (flag1 == 0xFF) {
1280 case FLAG_INCREMENTAL:
1281 if (flag0 == 255 && flag1 == 0)
1283 else if ((flag1 == 255 && flag0 == 0) ||
1286 else /* flag1 > flag0 */
1290 fprintf (stderr, "Unknown flag scheme %u \n",
1291 environment.flag_scheme);
1297 * If we are reading, we don't need the flag and the CRC any
1298 * more, if we are writing, we will re-calculate CRC and update
1299 * flags before writing out
1302 environment.image = addr1;
1303 environment.crc = &redundant->crc;
1304 environment.flags = &redundant->flags;
1305 environment.data = redundant->data;
1308 environment.image = addr0;
1309 /* Other pointers are already set */
1313 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1320 static int parse_config ()
1324 #if defined(CONFIG_FILE)
1325 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1326 if (get_config(common_args.config_file)) {
1327 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1328 common_args.config_file);
1332 DEVNAME (0) = DEVICE1_NAME;
1333 DEVOFFSET (0) = DEVICE1_OFFSET;
1334 ENVSIZE (0) = ENV1_SIZE;
1335 /* Default values are: erase-size=env-size */
1336 DEVESIZE (0) = ENVSIZE (0);
1337 /* #sectors=env-size/erase-size (rounded up) */
1338 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1339 #ifdef DEVICE1_ESIZE
1340 DEVESIZE (0) = DEVICE1_ESIZE;
1342 #ifdef DEVICE1_ENVSECTORS
1343 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1347 DEVNAME (1) = DEVICE2_NAME;
1348 DEVOFFSET (1) = DEVICE2_OFFSET;
1349 ENVSIZE (1) = ENV2_SIZE;
1350 /* Default values are: erase-size=env-size */
1351 DEVESIZE (1) = ENVSIZE (1);
1352 /* #sectors=env-size/erase-size (rounded up) */
1353 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1354 #ifdef DEVICE2_ESIZE
1355 DEVESIZE (1) = DEVICE2_ESIZE;
1357 #ifdef DEVICE2_ENVSECTORS
1358 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1363 if (stat (DEVNAME (0), &st)) {
1365 "Cannot access MTD device %s: %s\n",
1366 DEVNAME (0), strerror (errno));
1370 if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
1372 "Cannot access MTD device %s: %s\n",
1373 DEVNAME (1), strerror (errno));
1379 #if defined(CONFIG_FILE)
1380 static int get_config (char *fname)
1388 fp = fopen (fname, "r");
1392 while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1393 /* Skip incomplete conversions and comment strings */
1397 rc = sscanf (dump, "%ms %lx %lx %lx %lx",
1407 DEVNAME(i) = devname;
1410 /* Assume the erase size is the same as the env-size */
1411 DEVESIZE(i) = ENVSIZE(i);
1414 /* Assume enough env sectors to cover the environment */
1415 ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1421 HaveRedundEnv = i - 1;
1422 if (!i) { /* No valid entries found */