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 *skip_chars(char *s)
138 for (; *s != '\0'; s++) {
145 static char *skip_blanks(char *s)
147 for (; *s != '\0'; s++) {
155 * Search the environment for a variable.
156 * Return the value, if found, or NULL, if not found.
158 char *fw_getenv (char *name)
162 for (env = environment.data; *env; env = nxt + 1) {
165 for (nxt = env; *nxt; ++nxt) {
166 if (nxt >= &environment.data[ENV_SIZE]) {
167 fprintf (stderr, "## Error: "
168 "environment not terminated\n");
172 val = envmatch (name, env);
181 * Search the default environment for a variable.
182 * Return the value, if found, or NULL, if not found.
184 char *fw_getdefenv(char *name)
188 for (env = default_environment; *env; env = nxt + 1) {
191 for (nxt = env; *nxt; ++nxt) {
192 if (nxt >= &default_environment[ENV_SIZE]) {
193 fprintf(stderr, "## Error: "
194 "default environment not terminated\n");
198 val = envmatch(name, env);
206 int parse_aes_key(char *key, uint8_t *bin_key)
208 char tmp[5] = { '0', 'x', 0, 0, 0 };
212 if (strnlen(key, 64) != 32) {
214 "## Error: '-a' option requires 16-byte AES key\n");
218 for (i = 0; i < 16; i++) {
222 ul = strtoul(tmp, NULL, 16);
225 "## Error: '-a' option requires valid AES key\n");
228 bin_key[i] = ul & 0xff;
235 * Print the current definition of one, or more, or all
236 * environment variables
238 int fw_printenv (int argc, char *argv[])
246 if (argc == 0) { /* Print all env variables */
247 for (env = environment.data; *env; env = nxt + 1) {
248 for (nxt = env; *nxt; ++nxt) {
249 if (nxt >= &environment.data[ENV_SIZE]) {
250 fprintf (stderr, "## Error: "
251 "environment not terminated\n");
256 printf ("%s\n", env);
261 if (printenv_args.name_suppress && argc != 1) {
263 "## Error: `-n' option requires exactly one argument\n");
267 for (i = 0; i < argc; ++i) { /* print single env variables */
268 char *name = argv[i];
271 for (env = environment.data; *env; env = nxt + 1) {
273 for (nxt = env; *nxt; ++nxt) {
274 if (nxt >= &environment.data[ENV_SIZE]) {
275 fprintf (stderr, "## Error: "
276 "environment not terminated\n");
280 val = envmatch (name, env);
282 if (!printenv_args.name_suppress) {
283 fputs (name, stdout);
291 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
299 int fw_env_close(void)
302 if (common_args.aes_flag) {
303 ret = env_aes_cbc_crypt(environment.data, 1);
306 "Error: can't encrypt env for flash\n");
314 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
316 /* write environment back to flash */
317 if (flash_io(O_RDWR)) {
319 "Error: can't write fw_env to flash\n");
328 * Set/Clear a single variable in the environment.
329 * This is called in sequence to update the environment
330 * in RAM without updating the copy in flash after each set
332 int fw_env_write(char *name, char *value)
337 int deleting, creating, overwriting;
340 * search if variable with this name already exists
342 for (nxt = env = environment.data; *env; env = nxt + 1) {
343 for (nxt = env; *nxt; ++nxt) {
344 if (nxt >= &environment.data[ENV_SIZE]) {
345 fprintf(stderr, "## Error: "
346 "environment not terminated\n");
351 if ((oldval = envmatch (name, env)) != NULL)
355 deleting = (oldval && !(value && strlen(value)));
356 creating = (!oldval && (value && strlen(value)));
357 overwriting = (oldval && (value && strlen(value)));
359 /* check for permission */
361 if (env_flags_validate_varaccess(name,
362 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
363 printf("Can't delete \"%s\"\n", name);
367 } else if (overwriting) {
368 if (env_flags_validate_varaccess(name,
369 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
370 printf("Can't overwrite \"%s\"\n", name);
373 } else if (env_flags_validate_varaccess(name,
374 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
375 const char *defval = fw_getdefenv(name);
379 if (strcmp(oldval, defval)
381 printf("Can't overwrite \"%s\"\n", name);
386 } else if (creating) {
387 if (env_flags_validate_varaccess(name,
388 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
389 printf("Can't create \"%s\"\n", name);
397 if (deleting || overwriting) {
398 if (*++nxt == '\0') {
403 if ((*env == '\0') && (*nxt == '\0'))
412 if (!value || !strlen(value))
416 * Append new definition at the end
418 for (env = environment.data; *env || *(env + 1); ++env);
419 if (env > environment.data)
423 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
425 len = strlen (name) + 2;
426 /* add '=' for first arg, ' ' for all others */
427 len += strlen(value) + 1;
429 if (len > (&environment.data[ENV_SIZE] - env)) {
431 "Error: environment overflow, \"%s\" deleted\n",
436 while ((*env = *name++) != '\0')
439 while ((*++env = *value++) != '\0')
442 /* end is marked with double '\0' */
449 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
451 * EINVAL - need at least 1 argument
452 * EROFS - certain variables ("ethaddr", "serial#") cannot be
453 * modified or deleted
456 int fw_setenv(int argc, char *argv[])
465 fprintf(stderr, "## Error: variable name missing\n");
471 fprintf(stderr, "Error: environment not initialized\n");
479 if (env_flags_validate_env_set_params(name, valv, valc) < 0)
483 for (i = 0; i < valc; ++i) {
485 size_t val_len = strlen(val);
488 value[len - 1] = ' ';
489 value = realloc(value, len + val_len + 1);
492 "Cannot malloc %zu bytes: %s\n",
493 len, strerror(errno));
497 memcpy(value + len, val, val_len);
502 fw_env_write(name, value);
506 return fw_env_close();
510 * Parse a file and configure the u-boot variables.
511 * The script file has a very simple format, as follows:
513 * Each line has a couple with name, value:
514 * <white spaces>variable_name<white spaces>variable_value
516 * Both variable_name and variable_value are interpreted as strings.
517 * Any character after <white spaces> and before ending \r\n is interpreted
518 * as variable's value (no comment allowed on these lines !)
520 * Comments are allowed if the first character in the line is #
522 * Returns -1 and sets errno error codes:
526 int fw_parse_script(char *fname)
529 char dump[1024]; /* Maximum line length in the file */
537 fprintf(stderr, "Error: environment not initialized\n");
541 if (strcmp(fname, "-") == 0)
544 fp = fopen(fname, "r");
546 fprintf(stderr, "I cannot open %s for reading\n",
552 while (fgets(dump, sizeof(dump), fp)) {
557 * Read a whole line from the file. If the line is too long
558 * or is not terminated, reports an error and exit.
560 if (dump[len - 1] != '\n') {
562 "Line %d not corrected terminated or too long\n",
568 /* Drop ending line feed / carriage return */
569 while (len > 0 && (dump[len - 1] == '\n' ||
570 dump[len - 1] == '\r')) {
571 dump[len - 1] = '\0';
575 /* Skip comment or empty lines */
576 if ((len == 0) || dump[0] == '#')
580 * Search for variable's name,
581 * remove leading whitespaces
583 name = skip_blanks(dump);
587 /* The first white space is the end of variable name */
588 val = skip_chars(name);
592 if ((val - name) < len)
593 val = skip_blanks(val);
599 fprintf(stderr, "Setting %s : %s\n",
600 name, val ? val : " removed");
603 if (env_flags_validate_type(name, val) < 0) {
609 * If there is an error setting a variable,
610 * try to save the environment and returns an error
612 if (fw_env_write(name, val)) {
614 "fw_env_write returns with error : %s\n",
622 /* Close file if not stdin */
623 if (strcmp(fname, "-") != 0)
626 ret |= fw_env_close();
633 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
636 * < 0 - failed to test
638 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
640 if (mtd_type == MTD_NANDFLASH) {
641 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
644 perror ("Cannot read bad block mark");
650 fprintf (stderr, "Bad block at 0x%llx, "
651 "skipping\n", *blockstart);
661 * Read data from flash at an offset into a provided buffer. On NAND it skips
662 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
663 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
665 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
666 off_t offset, uint8_t mtd_type)
668 size_t blocklen; /* erase / write length - one block on NAND,
670 size_t processed = 0; /* progress counter */
671 size_t readlen = count; /* current read length */
672 off_t top_of_range; /* end of the last block we may use */
673 off_t block_seek; /* offset inside the current block to the start
675 loff_t blockstart; /* running start of the current block -
676 MEMGETBADBLOCK needs 64 bits */
679 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
681 /* Offset inside a block */
682 block_seek = offset - blockstart;
684 if (mtd_type == MTD_NANDFLASH) {
686 * NAND: calculate which blocks we are reading. We have
687 * to read one block at a time to skip bad blocks.
689 blocklen = DEVESIZE (dev);
692 * To calculate the top of the range, we have to use the
693 * global DEVOFFSET (dev), which can be different from offset
695 top_of_range = ((DEVOFFSET(dev) / blocklen) +
696 ENVSECTORS (dev)) * blocklen;
698 /* Limit to one block for the first read */
699 if (readlen > blocklen - block_seek)
700 readlen = blocklen - block_seek;
703 top_of_range = offset + count;
706 /* This only runs once on NOR flash */
707 while (processed < count) {
708 rc = flash_bad_block (fd, mtd_type, &blockstart);
709 if (rc < 0) /* block test failed */
712 if (blockstart + block_seek + readlen > top_of_range) {
713 /* End of range is reached */
715 "Too few good blocks within range\n");
719 if (rc) { /* block is bad */
720 blockstart += blocklen;
725 * If a block is bad, we retry in the next block at the same
726 * offset - see common/env_nand.c::writeenv()
728 lseek (fd, blockstart + block_seek, SEEK_SET);
730 rc = read (fd, buf + processed, readlen);
732 fprintf (stderr, "Read error on %s: %s\n",
733 DEVNAME (dev), strerror (errno));
737 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
738 rc, blockstart + block_seek, DEVNAME(dev));
740 processed += readlen;
741 readlen = min (blocklen, count - processed);
743 blockstart += blocklen;
750 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
751 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
752 * erase and write the whole data at once.
754 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
755 off_t offset, uint8_t mtd_type)
758 struct erase_info_user erase;
759 size_t blocklen; /* length of NAND block / NOR erase sector */
760 size_t erase_len; /* whole area that can be erased - may include
762 size_t erasesize; /* erase / write length - one block on NAND,
764 size_t processed = 0; /* progress counter */
765 size_t write_total; /* total size to actually write - excluding
767 off_t erase_offset; /* offset to the first erase block (aligned)
769 off_t block_seek; /* offset inside the erase block to the start
771 off_t top_of_range; /* end of the last block we may use */
772 loff_t blockstart; /* running start of the current block -
773 MEMGETBADBLOCK needs 64 bits */
777 * For mtd devices only offset and size of the environment do matter
779 if (mtd_type == MTD_ABSENT) {
781 top_of_range = offset + count;
782 erase_len = blocklen;
785 write_total = blocklen;
787 blocklen = DEVESIZE(dev);
789 top_of_range = ((DEVOFFSET(dev) / blocklen) +
790 ENVSECTORS(dev)) * blocklen;
792 erase_offset = (offset / blocklen) * blocklen;
794 /* Maximum area we may use */
795 erase_len = top_of_range - erase_offset;
797 blockstart = erase_offset;
798 /* Offset inside a block */
799 block_seek = offset - erase_offset;
802 * Data size we actually write: from the start of the block
803 * to the start of the data, then count bytes of data, and
804 * to the end of the block
806 write_total = ((block_seek + count + blocklen - 1) /
807 blocklen) * blocklen;
811 * Support data anywhere within erase sectors: read out the complete
812 * area to be erased, replace the environment image, write the whole
815 if (write_total > count) {
816 data = malloc (erase_len);
819 "Cannot malloc %zu bytes: %s\n",
820 erase_len, strerror (errno));
824 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
826 if (write_total != rc)
830 fprintf(stderr, "Preserving data ");
832 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
833 if (block_seek + count != write_total) {
835 fprintf(stderr, " and ");
836 fprintf(stderr, "0x%lx - 0x%x",
837 block_seek + count, write_total - 1);
839 fprintf(stderr, "\n");
841 /* Overwrite the old environment */
842 memcpy (data + block_seek, buf, count);
845 * We get here, iff offset is block-aligned and count is a
846 * multiple of blocklen - see write_total calculation above
851 if (mtd_type == MTD_NANDFLASH) {
853 * NAND: calculate which blocks we are writing. We have
854 * to write one block at a time to skip bad blocks.
856 erasesize = blocklen;
858 erasesize = erase_len;
861 erase.length = erasesize;
863 /* This only runs once on NOR flash and SPI-dataflash */
864 while (processed < write_total) {
865 rc = flash_bad_block (fd, mtd_type, &blockstart);
866 if (rc < 0) /* block test failed */
869 if (blockstart + erasesize > top_of_range) {
870 fprintf (stderr, "End of range reached, aborting\n");
874 if (rc) { /* block is bad */
875 blockstart += blocklen;
879 if (mtd_type != MTD_ABSENT) {
880 erase.start = blockstart;
881 ioctl(fd, MEMUNLOCK, &erase);
882 /* These do not need an explicit erase cycle */
883 if (mtd_type != MTD_DATAFLASH)
884 if (ioctl(fd, MEMERASE, &erase) != 0) {
886 "MTD erase error on %s: %s\n",
887 DEVNAME(dev), strerror(errno));
892 if (lseek (fd, blockstart, SEEK_SET) == -1) {
894 "Seek error on %s: %s\n",
895 DEVNAME (dev), strerror (errno));
900 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
903 if (write (fd, data + processed, erasesize) != erasesize) {
904 fprintf (stderr, "Write error on %s: %s\n",
905 DEVNAME (dev), strerror (errno));
909 if (mtd_type != MTD_ABSENT)
910 ioctl(fd, MEMLOCK, &erase);
912 processed += erasesize;
914 blockstart += erasesize;
917 if (write_total > count)
924 * Set obsolete flag at offset - NOR flash only
926 static int flash_flag_obsolete (int dev, int fd, off_t offset)
929 struct erase_info_user erase;
931 erase.start = DEVOFFSET (dev);
932 erase.length = DEVESIZE (dev);
933 /* This relies on the fact, that obsolete_flag == 0 */
934 rc = lseek (fd, offset, SEEK_SET);
936 fprintf (stderr, "Cannot seek to set the flag on %s \n",
940 ioctl (fd, MEMUNLOCK, &erase);
941 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
942 ioctl (fd, MEMLOCK, &erase);
944 perror ("Could not set obsolete flag");
949 /* Encrypt or decrypt the environment before writing or reading it. */
950 static int env_aes_cbc_crypt(char *payload, const int enc)
952 uint8_t *data = (uint8_t *)payload;
953 const int len = getenvsize();
954 uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
957 /* First we expand the key. */
958 aes_expand_key(common_args.aes_key, key_exp);
960 /* Calculate the number of AES blocks to encrypt. */
961 aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
964 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
966 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
971 static int flash_write (int fd_current, int fd_target, int dev_target)
975 switch (environment.flag_scheme) {
978 case FLAG_INCREMENTAL:
979 (*environment.flags)++;
982 *environment.flags = active_flag;
985 fprintf (stderr, "Unimplemented flash scheme %u \n",
986 environment.flag_scheme);
991 fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
992 DEVOFFSET (dev_target), DEVNAME (dev_target));
995 rc = flash_write_buf(dev_target, fd_target, environment.image,
996 CUR_ENVSIZE, DEVOFFSET(dev_target),
997 DEVTYPE(dev_target));
1001 if (environment.flag_scheme == FLAG_BOOLEAN) {
1002 /* Have to set obsolete flag */
1003 off_t offset = DEVOFFSET (dev_current) +
1004 offsetof (struct env_image_redundant, flags);
1007 "Setting obsolete flag in environment at 0x%lx on %s\n",
1008 DEVOFFSET (dev_current), DEVNAME (dev_current));
1010 flash_flag_obsolete (dev_current, fd_current, offset);
1016 static int flash_read (int fd)
1018 struct mtd_info_user mtdinfo;
1022 rc = fstat(fd, &st);
1024 fprintf(stderr, "Cannot stat the file %s\n",
1025 DEVNAME(dev_current));
1029 if (S_ISCHR(st.st_mode)) {
1030 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1032 fprintf(stderr, "Cannot get MTD information for %s\n",
1033 DEVNAME(dev_current));
1036 if (mtdinfo.type != MTD_NORFLASH &&
1037 mtdinfo.type != MTD_NANDFLASH &&
1038 mtdinfo.type != MTD_DATAFLASH &&
1039 mtdinfo.type != MTD_UBIVOLUME) {
1040 fprintf (stderr, "Unsupported flash type %u on %s\n",
1041 mtdinfo.type, DEVNAME(dev_current));
1045 memset(&mtdinfo, 0, sizeof(mtdinfo));
1046 mtdinfo.type = MTD_ABSENT;
1049 DEVTYPE(dev_current) = mtdinfo.type;
1051 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1052 DEVOFFSET (dev_current), mtdinfo.type);
1053 if (rc != CUR_ENVSIZE)
1059 static int flash_io (int mode)
1061 int fd_current, fd_target, rc, dev_target;
1063 /* dev_current: fd_current, erase_current */
1064 fd_current = open (DEVNAME (dev_current), mode);
1065 if (fd_current < 0) {
1067 "Can't open %s: %s\n",
1068 DEVNAME (dev_current), strerror (errno));
1072 if (mode == O_RDWR) {
1073 if (HaveRedundEnv) {
1074 /* switch to next partition for writing */
1075 dev_target = !dev_current;
1076 /* dev_target: fd_target, erase_target */
1077 fd_target = open (DEVNAME (dev_target), mode);
1078 if (fd_target < 0) {
1080 "Can't open %s: %s\n",
1081 DEVNAME (dev_target),
1087 dev_target = dev_current;
1088 fd_target = fd_current;
1091 rc = flash_write (fd_current, fd_target, dev_target);
1093 if (HaveRedundEnv) {
1094 if (close (fd_target)) {
1096 "I/O error on %s: %s\n",
1097 DEVNAME (dev_target),
1103 rc = flash_read (fd_current);
1107 if (close (fd_current)) {
1109 "I/O error on %s: %s\n",
1110 DEVNAME (dev_current), strerror (errno));
1118 * s1 is either a simple 'name', or a 'name=value' pair.
1119 * s2 is a 'name=value' pair.
1120 * If the names match, return the value of s2, else NULL.
1123 static char *envmatch (char * s1, char * s2)
1125 if (s1 == NULL || s2 == NULL)
1128 while (*s1 == *s2++)
1131 if (*s1 == '\0' && *(s2 - 1) == '=')
1137 * Prevent confusion if running from erased flash memory
1139 int fw_env_open(void)
1142 unsigned char flag0;
1146 unsigned char flag1;
1151 struct env_image_single *single;
1152 struct env_image_redundant *redundant;
1154 if (parse_config ()) /* should fill envdevices */
1157 addr0 = calloc(1, CUR_ENVSIZE);
1158 if (addr0 == NULL) {
1160 "Not enough memory for environment (%ld bytes)\n",
1165 /* read environment from FLASH to local buffer */
1166 environment.image = addr0;
1168 if (HaveRedundEnv) {
1170 environment.crc = &redundant->crc;
1171 environment.flags = &redundant->flags;
1172 environment.data = redundant->data;
1175 environment.crc = &single->crc;
1176 environment.flags = NULL;
1177 environment.data = single->data;
1181 if (flash_io (O_RDONLY))
1184 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1186 if (common_args.aes_flag) {
1187 ret = env_aes_cbc_crypt(environment.data, 0);
1192 crc0_ok = (crc0 == *environment.crc);
1193 if (!HaveRedundEnv) {
1196 "Warning: Bad CRC, using default environment\n");
1197 memcpy(environment.data, default_environment, sizeof default_environment);
1200 flag0 = *environment.flags;
1203 addr1 = calloc(1, CUR_ENVSIZE);
1204 if (addr1 == NULL) {
1206 "Not enough memory for environment (%ld bytes)\n",
1213 * have to set environment.image for flash_read(), careful -
1214 * other pointers in environment still point inside addr0
1216 environment.image = addr1;
1217 if (flash_io (O_RDONLY))
1220 /* Check flag scheme compatibility */
1221 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1222 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1223 environment.flag_scheme = FLAG_BOOLEAN;
1224 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1225 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1226 environment.flag_scheme = FLAG_INCREMENTAL;
1227 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1228 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1229 environment.flag_scheme = FLAG_BOOLEAN;
1230 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1231 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1232 environment.flag_scheme = FLAG_INCREMENTAL;
1233 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1234 DEVTYPE(!dev_current) == MTD_ABSENT) {
1235 environment.flag_scheme = FLAG_INCREMENTAL;
1237 fprintf (stderr, "Incompatible flash types!\n");
1241 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1243 if (common_args.aes_flag) {
1244 ret = env_aes_cbc_crypt(redundant->data, 0);
1249 crc1_ok = (crc1 == redundant->crc);
1250 flag1 = redundant->flags;
1252 if (crc0_ok && !crc1_ok) {
1254 } else if (!crc0_ok && crc1_ok) {
1256 } else if (!crc0_ok && !crc1_ok) {
1258 "Warning: Bad CRC, using default environment\n");
1259 memcpy (environment.data, default_environment,
1260 sizeof default_environment);
1263 switch (environment.flag_scheme) {
1265 if (flag0 == active_flag &&
1266 flag1 == obsolete_flag) {
1268 } else if (flag0 == obsolete_flag &&
1269 flag1 == active_flag) {
1271 } else if (flag0 == flag1) {
1273 } else if (flag0 == 0xFF) {
1275 } else if (flag1 == 0xFF) {
1281 case FLAG_INCREMENTAL:
1282 if (flag0 == 255 && flag1 == 0)
1284 else if ((flag1 == 255 && flag0 == 0) ||
1287 else /* flag1 > flag0 */
1291 fprintf (stderr, "Unknown flag scheme %u \n",
1292 environment.flag_scheme);
1298 * If we are reading, we don't need the flag and the CRC any
1299 * more, if we are writing, we will re-calculate CRC and update
1300 * flags before writing out
1303 environment.image = addr1;
1304 environment.crc = &redundant->crc;
1305 environment.flags = &redundant->flags;
1306 environment.data = redundant->data;
1309 environment.image = addr0;
1310 /* Other pointers are already set */
1314 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1321 static int parse_config ()
1325 #if defined(CONFIG_FILE)
1326 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1327 if (get_config(common_args.config_file)) {
1328 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1329 common_args.config_file);
1333 DEVNAME (0) = DEVICE1_NAME;
1334 DEVOFFSET (0) = DEVICE1_OFFSET;
1335 ENVSIZE (0) = ENV1_SIZE;
1336 /* Default values are: erase-size=env-size */
1337 DEVESIZE (0) = ENVSIZE (0);
1338 /* #sectors=env-size/erase-size (rounded up) */
1339 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1340 #ifdef DEVICE1_ESIZE
1341 DEVESIZE (0) = DEVICE1_ESIZE;
1343 #ifdef DEVICE1_ENVSECTORS
1344 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1348 DEVNAME (1) = DEVICE2_NAME;
1349 DEVOFFSET (1) = DEVICE2_OFFSET;
1350 ENVSIZE (1) = ENV2_SIZE;
1351 /* Default values are: erase-size=env-size */
1352 DEVESIZE (1) = ENVSIZE (1);
1353 /* #sectors=env-size/erase-size (rounded up) */
1354 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1355 #ifdef DEVICE2_ESIZE
1356 DEVESIZE (1) = DEVICE2_ESIZE;
1358 #ifdef DEVICE2_ENVSECTORS
1359 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1364 if (stat (DEVNAME (0), &st)) {
1366 "Cannot access MTD device %s: %s\n",
1367 DEVNAME (0), strerror (errno));
1371 if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
1373 "Cannot access MTD device %s: %s\n",
1374 DEVNAME (1), strerror (errno));
1380 #if defined(CONFIG_FILE)
1381 static int get_config (char *fname)
1389 fp = fopen (fname, "r");
1393 while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1394 /* Skip incomplete conversions and comment strings */
1398 rc = sscanf (dump, "%ms %lx %lx %lx %lx",
1408 DEVNAME(i) = devname;
1411 /* Assume the erase size is the same as the env-size */
1412 DEVESIZE(i) = ENVSIZE(i);
1415 /* Assume enough env sectors to cover the environment */
1416 ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1422 HaveRedundEnv = i - 1;
1423 if (!i) { /* No valid entries found */