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>
23 #include <sys/types.h>
24 #include <sys/ioctl.h>
30 # include <linux/mtd/mtd.h>
32 # define __user /* nothing */
33 # include <mtd/mtd-user.h>
38 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
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 static int env_aes_cbc_crypt(char *data, const int enc);
107 static int HaveRedundEnv = 0;
109 static unsigned char active_flag = 1;
110 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
111 static unsigned char obsolete_flag = 0;
113 #define DEFAULT_ENV_INSTANCE_STATIC
114 #include <env_default.h>
116 static int flash_io (int mode);
117 static char *envmatch (char * s1, char * s2);
118 static int parse_config (void);
120 #if defined(CONFIG_FILE)
121 static int get_config (char *);
123 static inline ulong getenvsize (void)
125 ulong rc = CUR_ENVSIZE - sizeof(uint32_t);
130 if (common_args.aes_flag)
131 rc &= ~(AES_KEY_LENGTH - 1);
136 static char *fw_string_blank(char *s, int noblank)
141 for (i = 0; i < len; i++, s++) {
142 if ((noblank && !isblank(*s)) ||
143 (!noblank && isblank(*s)))
153 * Search the environment for a variable.
154 * Return the value, if found, or NULL, if not found.
156 char *fw_getenv (char *name)
160 for (env = environment.data; *env; env = nxt + 1) {
163 for (nxt = env; *nxt; ++nxt) {
164 if (nxt >= &environment.data[ENV_SIZE]) {
165 fprintf (stderr, "## Error: "
166 "environment not terminated\n");
170 val = envmatch (name, env);
179 * Search the default environment for a variable.
180 * Return the value, if found, or NULL, if not found.
182 char *fw_getdefenv(char *name)
186 for (env = default_environment; *env; env = nxt + 1) {
189 for (nxt = env; *nxt; ++nxt) {
190 if (nxt >= &default_environment[ENV_SIZE]) {
191 fprintf(stderr, "## Error: "
192 "default environment not terminated\n");
196 val = envmatch(name, env);
204 int parse_aes_key(char *key, uint8_t *bin_key)
206 char tmp[5] = { '0', 'x', 0, 0, 0 };
210 if (strnlen(key, 64) != 32) {
212 "## Error: '-a' option requires 16-byte AES key\n");
216 for (i = 0; i < 16; i++) {
220 ul = strtoul(tmp, NULL, 16);
223 "## Error: '-a' option requires valid AES key\n");
226 bin_key[i] = ul & 0xff;
233 * Print the current definition of one, or more, or all
234 * environment variables
236 int fw_printenv (int argc, char *argv[])
244 if (argc == 0) { /* Print all env variables */
245 for (env = environment.data; *env; env = nxt + 1) {
246 for (nxt = env; *nxt; ++nxt) {
247 if (nxt >= &environment.data[ENV_SIZE]) {
248 fprintf (stderr, "## Error: "
249 "environment not terminated\n");
254 printf ("%s\n", env);
259 if (printenv_args.name_suppress && argc != 1) {
261 "## Error: `-n' option requires exactly one argument\n");
265 for (i = 0; i < argc; ++i) { /* print single env variables */
266 char *name = argv[i];
269 for (env = environment.data; *env; env = nxt + 1) {
271 for (nxt = env; *nxt; ++nxt) {
272 if (nxt >= &environment.data[ENV_SIZE]) {
273 fprintf (stderr, "## Error: "
274 "environment not terminated\n");
278 val = envmatch (name, env);
280 if (!printenv_args.name_suppress) {
281 fputs (name, stdout);
289 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
297 int fw_env_close(void)
300 if (common_args.aes_flag) {
301 ret = env_aes_cbc_crypt(environment.data, 1);
304 "Error: can't encrypt env for flash\n");
312 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
314 /* write environment back to flash */
315 if (flash_io(O_RDWR)) {
317 "Error: can't write fw_env to flash\n");
326 * Set/Clear a single variable in the environment.
327 * This is called in sequence to update the environment
328 * in RAM without updating the copy in flash after each set
330 int fw_env_write(char *name, char *value)
335 int deleting, creating, overwriting;
338 * search if variable with this name already exists
340 for (nxt = env = environment.data; *env; env = nxt + 1) {
341 for (nxt = env; *nxt; ++nxt) {
342 if (nxt >= &environment.data[ENV_SIZE]) {
343 fprintf(stderr, "## Error: "
344 "environment not terminated\n");
349 if ((oldval = envmatch (name, env)) != NULL)
353 deleting = (oldval && !(value && strlen(value)));
354 creating = (!oldval && (value && strlen(value)));
355 overwriting = (oldval && (value && strlen(value)));
357 /* check for permission */
359 if (env_flags_validate_varaccess(name,
360 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
361 printf("Can't delete \"%s\"\n", name);
365 } else if (overwriting) {
366 if (env_flags_validate_varaccess(name,
367 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
368 printf("Can't overwrite \"%s\"\n", name);
371 } else if (env_flags_validate_varaccess(name,
372 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
373 const char *defval = fw_getdefenv(name);
377 if (strcmp(oldval, defval)
379 printf("Can't overwrite \"%s\"\n", name);
384 } else if (creating) {
385 if (env_flags_validate_varaccess(name,
386 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
387 printf("Can't create \"%s\"\n", name);
395 if (deleting || overwriting) {
396 if (*++nxt == '\0') {
401 if ((*env == '\0') && (*nxt == '\0'))
410 if (!value || !strlen(value))
414 * Append new definition at the end
416 for (env = environment.data; *env || *(env + 1); ++env);
417 if (env > environment.data)
421 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
423 len = strlen (name) + 2;
424 /* add '=' for first arg, ' ' for all others */
425 len += strlen(value) + 1;
427 if (len > (&environment.data[ENV_SIZE] - env)) {
429 "Error: environment overflow, \"%s\" deleted\n",
434 while ((*env = *name++) != '\0')
437 while ((*++env = *value++) != '\0')
440 /* end is marked with double '\0' */
447 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
449 * EINVAL - need at least 1 argument
450 * EROFS - certain variables ("ethaddr", "serial#") cannot be
451 * modified or deleted
454 int fw_setenv(int argc, char *argv[])
463 fprintf(stderr, "## Error: variable name missing\n");
469 fprintf(stderr, "Error: environment not initialized\n");
477 if (env_flags_validate_env_set_params(name, valv, valc) < 0)
481 for (i = 0; i < valc; ++i) {
483 size_t val_len = strlen(val);
486 value[len - 1] = ' ';
487 value = realloc(value, len + val_len + 1);
490 "Cannot malloc %zu bytes: %s\n",
491 len, strerror(errno));
495 memcpy(value + len, val, val_len);
500 fw_env_write(name, value);
504 return fw_env_close();
508 * Parse a file and configure the u-boot variables.
509 * The script file has a very simple format, as follows:
511 * Each line has a couple with name, value:
512 * <white spaces>variable_name<white spaces>variable_value
514 * Both variable_name and variable_value are interpreted as strings.
515 * Any character after <white spaces> and before ending \r\n is interpreted
516 * as variable's value (no comment allowed on these lines !)
518 * Comments are allowed if the first character in the line is #
520 * Returns -1 and sets errno error codes:
524 int fw_parse_script(char *fname)
527 char dump[1024]; /* Maximum line length in the file */
535 fprintf(stderr, "Error: environment not initialized\n");
539 if (strcmp(fname, "-") == 0)
542 fp = fopen(fname, "r");
544 fprintf(stderr, "I cannot open %s for reading\n",
550 while (fgets(dump, sizeof(dump), fp)) {
555 * Read a whole line from the file. If the line is too long
556 * or is not terminated, reports an error and exit.
558 if (dump[len - 1] != '\n') {
560 "Line %d not corrected terminated or too long\n",
566 /* Drop ending line feed / carriage return */
567 while (len > 0 && (dump[len - 1] == '\n' ||
568 dump[len - 1] == '\r')) {
569 dump[len - 1] = '\0';
573 /* Skip comment or empty lines */
574 if ((len == 0) || dump[0] == '#')
578 * Search for variable's name,
579 * remove leading whitespaces
581 name = fw_string_blank(dump, 1);
585 /* The first white space is the end of variable name */
586 val = fw_string_blank(name, 0);
590 if ((val - name) < len)
591 val = fw_string_blank(val, 1);
597 fprintf(stderr, "Setting %s : %s\n",
598 name, val ? val : " removed");
601 if (env_flags_validate_type(name, val) < 0) {
607 * If there is an error setting a variable,
608 * try to save the environment and returns an error
610 if (fw_env_write(name, val)) {
612 "fw_env_write returns with error : %s\n",
620 /* Close file if not stdin */
621 if (strcmp(fname, "-") != 0)
624 ret |= fw_env_close();
631 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
634 * < 0 - failed to test
636 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
638 if (mtd_type == MTD_NANDFLASH) {
639 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
642 perror ("Cannot read bad block mark");
648 fprintf (stderr, "Bad block at 0x%llx, "
649 "skipping\n", *blockstart);
659 * Read data from flash at an offset into a provided buffer. On NAND it skips
660 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
661 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
663 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
664 off_t offset, uint8_t mtd_type)
666 size_t blocklen; /* erase / write length - one block on NAND,
668 size_t processed = 0; /* progress counter */
669 size_t readlen = count; /* current read length */
670 off_t top_of_range; /* end of the last block we may use */
671 off_t block_seek; /* offset inside the current block to the start
673 loff_t blockstart; /* running start of the current block -
674 MEMGETBADBLOCK needs 64 bits */
677 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
679 /* Offset inside a block */
680 block_seek = offset - blockstart;
682 if (mtd_type == MTD_NANDFLASH) {
684 * NAND: calculate which blocks we are reading. We have
685 * to read one block at a time to skip bad blocks.
687 blocklen = DEVESIZE (dev);
690 * To calculate the top of the range, we have to use the
691 * global DEVOFFSET (dev), which can be different from offset
693 top_of_range = ((DEVOFFSET(dev) / blocklen) +
694 ENVSECTORS (dev)) * blocklen;
696 /* Limit to one block for the first read */
697 if (readlen > blocklen - block_seek)
698 readlen = blocklen - block_seek;
701 top_of_range = offset + count;
704 /* This only runs once on NOR flash */
705 while (processed < count) {
706 rc = flash_bad_block (fd, mtd_type, &blockstart);
707 if (rc < 0) /* block test failed */
710 if (blockstart + block_seek + readlen > top_of_range) {
711 /* End of range is reached */
713 "Too few good blocks within range\n");
717 if (rc) { /* block is bad */
718 blockstart += blocklen;
723 * If a block is bad, we retry in the next block at the same
724 * offset - see common/env_nand.c::writeenv()
726 lseek (fd, blockstart + block_seek, SEEK_SET);
728 rc = read (fd, buf + processed, readlen);
730 fprintf (stderr, "Read error on %s: %s\n",
731 DEVNAME (dev), strerror (errno));
735 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
736 rc, blockstart + block_seek, DEVNAME(dev));
738 processed += readlen;
739 readlen = min (blocklen, count - processed);
741 blockstart += blocklen;
748 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
749 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
750 * erase and write the whole data at once.
752 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
753 off_t offset, uint8_t mtd_type)
756 struct erase_info_user erase;
757 size_t blocklen; /* length of NAND block / NOR erase sector */
758 size_t erase_len; /* whole area that can be erased - may include
760 size_t erasesize; /* erase / write length - one block on NAND,
762 size_t processed = 0; /* progress counter */
763 size_t write_total; /* total size to actually write - excluding
765 off_t erase_offset; /* offset to the first erase block (aligned)
767 off_t block_seek; /* offset inside the erase block to the start
769 off_t top_of_range; /* end of the last block we may use */
770 loff_t blockstart; /* running start of the current block -
771 MEMGETBADBLOCK needs 64 bits */
775 * For mtd devices only offset and size of the environment do matter
777 if (mtd_type == MTD_ABSENT) {
779 top_of_range = offset + count;
780 erase_len = blocklen;
783 write_total = blocklen;
785 blocklen = DEVESIZE(dev);
787 top_of_range = ((DEVOFFSET(dev) / blocklen) +
788 ENVSECTORS(dev)) * blocklen;
790 erase_offset = (offset / blocklen) * blocklen;
792 /* Maximum area we may use */
793 erase_len = top_of_range - erase_offset;
795 blockstart = erase_offset;
796 /* Offset inside a block */
797 block_seek = offset - erase_offset;
800 * Data size we actually write: from the start of the block
801 * to the start of the data, then count bytes of data, and
802 * to the end of the block
804 write_total = ((block_seek + count + blocklen - 1) /
805 blocklen) * blocklen;
809 * Support data anywhere within erase sectors: read out the complete
810 * area to be erased, replace the environment image, write the whole
813 if (write_total > count) {
814 data = malloc (erase_len);
817 "Cannot malloc %zu bytes: %s\n",
818 erase_len, strerror (errno));
822 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
824 if (write_total != rc)
828 fprintf(stderr, "Preserving data ");
830 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
831 if (block_seek + count != write_total) {
833 fprintf(stderr, " and ");
834 fprintf(stderr, "0x%lx - 0x%x",
835 block_seek + count, write_total - 1);
837 fprintf(stderr, "\n");
839 /* Overwrite the old environment */
840 memcpy (data + block_seek, buf, count);
843 * We get here, iff offset is block-aligned and count is a
844 * multiple of blocklen - see write_total calculation above
849 if (mtd_type == MTD_NANDFLASH) {
851 * NAND: calculate which blocks we are writing. We have
852 * to write one block at a time to skip bad blocks.
854 erasesize = blocklen;
856 erasesize = erase_len;
859 erase.length = erasesize;
861 /* This only runs once on NOR flash and SPI-dataflash */
862 while (processed < write_total) {
863 rc = flash_bad_block (fd, mtd_type, &blockstart);
864 if (rc < 0) /* block test failed */
867 if (blockstart + erasesize > top_of_range) {
868 fprintf (stderr, "End of range reached, aborting\n");
872 if (rc) { /* block is bad */
873 blockstart += blocklen;
877 if (mtd_type != MTD_ABSENT) {
878 erase.start = blockstart;
879 ioctl(fd, MEMUNLOCK, &erase);
880 /* These do not need an explicit erase cycle */
881 if (mtd_type != MTD_DATAFLASH)
882 if (ioctl(fd, MEMERASE, &erase) != 0) {
884 "MTD erase error on %s: %s\n",
885 DEVNAME(dev), strerror(errno));
890 if (lseek (fd, blockstart, SEEK_SET) == -1) {
892 "Seek error on %s: %s\n",
893 DEVNAME (dev), strerror (errno));
898 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
901 if (write (fd, data + processed, erasesize) != erasesize) {
902 fprintf (stderr, "Write error on %s: %s\n",
903 DEVNAME (dev), strerror (errno));
907 if (mtd_type != MTD_ABSENT)
908 ioctl(fd, MEMLOCK, &erase);
910 processed += erasesize;
912 blockstart += erasesize;
915 if (write_total > count)
922 * Set obsolete flag at offset - NOR flash only
924 static int flash_flag_obsolete (int dev, int fd, off_t offset)
927 struct erase_info_user erase;
929 erase.start = DEVOFFSET (dev);
930 erase.length = DEVESIZE (dev);
931 /* This relies on the fact, that obsolete_flag == 0 */
932 rc = lseek (fd, offset, SEEK_SET);
934 fprintf (stderr, "Cannot seek to set the flag on %s \n",
938 ioctl (fd, MEMUNLOCK, &erase);
939 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
940 ioctl (fd, MEMLOCK, &erase);
942 perror ("Could not set obsolete flag");
947 /* Encrypt or decrypt the environment before writing or reading it. */
948 static int env_aes_cbc_crypt(char *payload, const int enc)
950 uint8_t *data = (uint8_t *)payload;
951 const int len = getenvsize();
952 uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
955 /* First we expand the key. */
956 aes_expand_key(common_args.aes_key, key_exp);
958 /* Calculate the number of AES blocks to encrypt. */
959 aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
962 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
964 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
969 static int flash_write (int fd_current, int fd_target, int dev_target)
973 switch (environment.flag_scheme) {
976 case FLAG_INCREMENTAL:
977 (*environment.flags)++;
980 *environment.flags = active_flag;
983 fprintf (stderr, "Unimplemented flash scheme %u \n",
984 environment.flag_scheme);
989 fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
990 DEVOFFSET (dev_target), DEVNAME (dev_target));
993 rc = flash_write_buf(dev_target, fd_target, environment.image,
994 CUR_ENVSIZE, DEVOFFSET(dev_target),
995 DEVTYPE(dev_target));
999 if (environment.flag_scheme == FLAG_BOOLEAN) {
1000 /* Have to set obsolete flag */
1001 off_t offset = DEVOFFSET (dev_current) +
1002 offsetof (struct env_image_redundant, flags);
1005 "Setting obsolete flag in environment at 0x%lx on %s\n",
1006 DEVOFFSET (dev_current), DEVNAME (dev_current));
1008 flash_flag_obsolete (dev_current, fd_current, offset);
1014 static int flash_read (int fd)
1016 struct mtd_info_user mtdinfo;
1020 rc = fstat(fd, &st);
1022 fprintf(stderr, "Cannot stat the file %s\n",
1023 DEVNAME(dev_current));
1027 if (S_ISCHR(st.st_mode)) {
1028 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1030 fprintf(stderr, "Cannot get MTD information for %s\n",
1031 DEVNAME(dev_current));
1034 if (mtdinfo.type != MTD_NORFLASH &&
1035 mtdinfo.type != MTD_NANDFLASH &&
1036 mtdinfo.type != MTD_DATAFLASH &&
1037 mtdinfo.type != MTD_UBIVOLUME) {
1038 fprintf (stderr, "Unsupported flash type %u on %s\n",
1039 mtdinfo.type, DEVNAME(dev_current));
1043 memset(&mtdinfo, 0, sizeof(mtdinfo));
1044 mtdinfo.type = MTD_ABSENT;
1047 DEVTYPE(dev_current) = mtdinfo.type;
1049 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1050 DEVOFFSET (dev_current), mtdinfo.type);
1051 if (rc != CUR_ENVSIZE)
1057 static int flash_io (int mode)
1059 int fd_current, fd_target, rc, dev_target;
1061 /* dev_current: fd_current, erase_current */
1062 fd_current = open (DEVNAME (dev_current), mode);
1063 if (fd_current < 0) {
1065 "Can't open %s: %s\n",
1066 DEVNAME (dev_current), strerror (errno));
1070 if (mode == O_RDWR) {
1071 if (HaveRedundEnv) {
1072 /* switch to next partition for writing */
1073 dev_target = !dev_current;
1074 /* dev_target: fd_target, erase_target */
1075 fd_target = open (DEVNAME (dev_target), mode);
1076 if (fd_target < 0) {
1078 "Can't open %s: %s\n",
1079 DEVNAME (dev_target),
1085 dev_target = dev_current;
1086 fd_target = fd_current;
1089 rc = flash_write (fd_current, fd_target, dev_target);
1091 if (HaveRedundEnv) {
1092 if (close (fd_target)) {
1094 "I/O error on %s: %s\n",
1095 DEVNAME (dev_target),
1101 rc = flash_read (fd_current);
1105 if (close (fd_current)) {
1107 "I/O error on %s: %s\n",
1108 DEVNAME (dev_current), strerror (errno));
1116 * s1 is either a simple 'name', or a 'name=value' pair.
1117 * s2 is a 'name=value' pair.
1118 * If the names match, return the value of s2, else NULL.
1121 static char *envmatch (char * s1, char * s2)
1123 if (s1 == NULL || s2 == NULL)
1126 while (*s1 == *s2++)
1129 if (*s1 == '\0' && *(s2 - 1) == '=')
1135 * Prevent confusion if running from erased flash memory
1137 int fw_env_open(void)
1140 unsigned char flag0;
1144 unsigned char flag1;
1149 struct env_image_single *single;
1150 struct env_image_redundant *redundant;
1152 if (parse_config ()) /* should fill envdevices */
1155 addr0 = calloc(1, CUR_ENVSIZE);
1156 if (addr0 == NULL) {
1158 "Not enough memory for environment (%ld bytes)\n",
1163 /* read environment from FLASH to local buffer */
1164 environment.image = addr0;
1166 if (HaveRedundEnv) {
1168 environment.crc = &redundant->crc;
1169 environment.flags = &redundant->flags;
1170 environment.data = redundant->data;
1173 environment.crc = &single->crc;
1174 environment.flags = NULL;
1175 environment.data = single->data;
1179 if (flash_io (O_RDONLY))
1182 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1184 if (common_args.aes_flag) {
1185 ret = env_aes_cbc_crypt(environment.data, 0);
1190 crc0_ok = (crc0 == *environment.crc);
1191 if (!HaveRedundEnv) {
1194 "Warning: Bad CRC, using default environment\n");
1195 memcpy(environment.data, default_environment, sizeof default_environment);
1198 flag0 = *environment.flags;
1201 addr1 = calloc(1, CUR_ENVSIZE);
1202 if (addr1 == NULL) {
1204 "Not enough memory for environment (%ld bytes)\n",
1211 * have to set environment.image for flash_read(), careful -
1212 * other pointers in environment still point inside addr0
1214 environment.image = addr1;
1215 if (flash_io (O_RDONLY))
1218 /* Check flag scheme compatibility */
1219 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1220 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1221 environment.flag_scheme = FLAG_BOOLEAN;
1222 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1223 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1224 environment.flag_scheme = FLAG_INCREMENTAL;
1225 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1226 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1227 environment.flag_scheme = FLAG_BOOLEAN;
1228 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1229 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1230 environment.flag_scheme = FLAG_INCREMENTAL;
1231 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1232 DEVTYPE(!dev_current) == MTD_ABSENT) {
1233 environment.flag_scheme = FLAG_INCREMENTAL;
1235 fprintf (stderr, "Incompatible flash types!\n");
1239 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1241 if (common_args.aes_flag) {
1242 ret = env_aes_cbc_crypt(redundant->data, 0);
1247 crc1_ok = (crc1 == redundant->crc);
1248 flag1 = redundant->flags;
1250 if (crc0_ok && !crc1_ok) {
1252 } else if (!crc0_ok && crc1_ok) {
1254 } else if (!crc0_ok && !crc1_ok) {
1256 "Warning: Bad CRC, using default environment\n");
1257 memcpy (environment.data, default_environment,
1258 sizeof default_environment);
1261 switch (environment.flag_scheme) {
1263 if (flag0 == active_flag &&
1264 flag1 == obsolete_flag) {
1266 } else if (flag0 == obsolete_flag &&
1267 flag1 == active_flag) {
1269 } else if (flag0 == flag1) {
1271 } else if (flag0 == 0xFF) {
1273 } else if (flag1 == 0xFF) {
1279 case FLAG_INCREMENTAL:
1280 if (flag0 == 255 && flag1 == 0)
1282 else if ((flag1 == 255 && flag0 == 0) ||
1285 else /* flag1 > flag0 */
1289 fprintf (stderr, "Unknown flag scheme %u \n",
1290 environment.flag_scheme);
1296 * If we are reading, we don't need the flag and the CRC any
1297 * more, if we are writing, we will re-calculate CRC and update
1298 * flags before writing out
1301 environment.image = addr1;
1302 environment.crc = &redundant->crc;
1303 environment.flags = &redundant->flags;
1304 environment.data = redundant->data;
1307 environment.image = addr0;
1308 /* Other pointers are already set */
1312 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1319 static int parse_config ()
1323 #if defined(CONFIG_FILE)
1324 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1325 if (get_config(common_args.config_file)) {
1326 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1327 common_args.config_file);
1331 DEVNAME (0) = DEVICE1_NAME;
1332 DEVOFFSET (0) = DEVICE1_OFFSET;
1333 ENVSIZE (0) = ENV1_SIZE;
1334 /* Default values are: erase-size=env-size */
1335 DEVESIZE (0) = ENVSIZE (0);
1336 /* #sectors=env-size/erase-size (rounded up) */
1337 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1338 #ifdef DEVICE1_ESIZE
1339 DEVESIZE (0) = DEVICE1_ESIZE;
1341 #ifdef DEVICE1_ENVSECTORS
1342 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1346 DEVNAME (1) = DEVICE2_NAME;
1347 DEVOFFSET (1) = DEVICE2_OFFSET;
1348 ENVSIZE (1) = ENV2_SIZE;
1349 /* Default values are: erase-size=env-size */
1350 DEVESIZE (1) = ENVSIZE (1);
1351 /* #sectors=env-size/erase-size (rounded up) */
1352 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1353 #ifdef DEVICE2_ESIZE
1354 DEVESIZE (1) = DEVICE2_ESIZE;
1356 #ifdef DEVICE2_ENVSECTORS
1357 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1362 if (stat (DEVNAME (0), &st)) {
1364 "Cannot access MTD device %s: %s\n",
1365 DEVNAME (0), strerror (errno));
1369 if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
1371 "Cannot access MTD device %s: %s\n",
1372 DEVNAME (1), strerror (errno));
1378 #if defined(CONFIG_FILE)
1379 static int get_config (char *fname)
1387 fp = fopen (fname, "r");
1391 while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1392 /* Skip incomplete conversions and comment strings */
1396 rc = sscanf (dump, "%ms %lx %lx %lx %lx",
1406 DEVNAME(i) = devname;
1409 /* Assume the erase size is the same as the env-size */
1410 DEVESIZE(i) = ENVSIZE(i);
1413 /* Assume enough env sectors to cover the environment */
1414 ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1420 HaveRedundEnv = i - 1;
1421 if (!i) { /* No valid entries found */