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>
18 #include <linux/stringify.h>
24 #include <sys/types.h>
25 #include <sys/ioctl.h>
31 # include <linux/mtd/mtd.h>
33 # define __user /* nothing */
34 # include <mtd/mtd-user.h>
39 struct env_opts default_opts = {
41 .config_file = CONFIG_FILE
45 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
47 #define min(x, y) ({ \
48 typeof(x) _min1 = (x); \
49 typeof(y) _min2 = (y); \
50 (void) (&_min1 == &_min2); \
51 _min1 < _min2 ? _min1 : _min2; })
54 const char *devname; /* Device name */
55 long long devoff; /* Device offset */
56 ulong env_size; /* environment size */
57 ulong erase_size; /* device erase size */
58 ulong env_sectors; /* number of environment sectors */
59 uint8_t mtd_type; /* type of the MTD device */
62 static struct envdev_s envdevices[2] =
65 .mtd_type = MTD_ABSENT,
67 .mtd_type = MTD_ABSENT,
70 static int dev_current;
72 #define DEVNAME(i) envdevices[(i)].devname
73 #define DEVOFFSET(i) envdevices[(i)].devoff
74 #define ENVSIZE(i) envdevices[(i)].env_size
75 #define DEVESIZE(i) envdevices[(i)].erase_size
76 #define ENVSECTORS(i) envdevices[(i)].env_sectors
77 #define DEVTYPE(i) envdevices[(i)].mtd_type
79 #define CUR_ENVSIZE ENVSIZE(dev_current)
81 static unsigned long usable_envsize;
82 #define ENV_SIZE usable_envsize
84 struct env_image_single {
85 uint32_t crc; /* CRC32 over data bytes */
89 struct env_image_redundant {
90 uint32_t crc; /* CRC32 over data bytes */
91 unsigned char flags; /* active or obsolete */
104 unsigned char *flags;
106 enum flag_scheme flag_scheme;
109 static struct environment environment = {
110 .flag_scheme = FLAG_NONE,
113 static int env_aes_cbc_crypt(char *data, const int enc, uint8_t *key);
115 static int HaveRedundEnv = 0;
117 static unsigned char active_flag = 1;
118 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
119 static unsigned char obsolete_flag = 0;
121 #define DEFAULT_ENV_INSTANCE_STATIC
122 #include <env_default.h>
124 static int flash_io (int mode);
125 static int parse_config(struct env_opts *opts);
127 #if defined(CONFIG_FILE)
128 static int get_config (char *);
131 static char *skip_chars(char *s)
133 for (; *s != '\0'; s++) {
140 static char *skip_blanks(char *s)
142 for (; *s != '\0'; s++) {
150 * s1 is either a simple 'name', or a 'name=value' pair.
151 * s2 is a 'name=value' pair.
152 * If the names match, return the value of s2, else NULL.
154 static char *envmatch(char *s1, char *s2)
156 if (s1 == NULL || s2 == NULL)
162 if (*s1 == '\0' && *(s2 - 1) == '=')
168 * Search the environment for a variable.
169 * Return the value, if found, or NULL, if not found.
171 char *fw_getenv (char *name)
175 for (env = environment.data; *env; env = nxt + 1) {
178 for (nxt = env; *nxt; ++nxt) {
179 if (nxt >= &environment.data[ENV_SIZE]) {
180 fprintf (stderr, "## Error: "
181 "environment not terminated\n");
185 val = envmatch (name, env);
194 * Search the default environment for a variable.
195 * Return the value, if found, or NULL, if not found.
197 char *fw_getdefenv(char *name)
201 for (env = default_environment; *env; env = nxt + 1) {
204 for (nxt = env; *nxt; ++nxt) {
205 if (nxt >= &default_environment[ENV_SIZE]) {
206 fprintf(stderr, "## Error: "
207 "default environment not terminated\n");
211 val = envmatch(name, env);
219 int parse_aes_key(char *key, uint8_t *bin_key)
221 char tmp[5] = { '0', 'x', 0, 0, 0 };
225 if (strnlen(key, 64) != 32) {
227 "## Error: '-a' option requires 16-byte AES key\n");
231 for (i = 0; i < 16; i++) {
235 ul = strtoul(tmp, NULL, 16);
238 "## Error: '-a' option requires valid AES key\n");
241 bin_key[i] = ul & 0xff;
248 * Print the current definition of one, or more, or all
249 * environment variables
251 int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
257 opts = &default_opts;
259 if (fw_env_open(opts))
262 if (argc == 0) { /* Print all env variables */
263 for (env = environment.data; *env; env = nxt + 1) {
264 for (nxt = env; *nxt; ++nxt) {
265 if (nxt >= &environment.data[ENV_SIZE]) {
266 fprintf (stderr, "## Error: "
267 "environment not terminated\n");
272 printf ("%s\n", env);
277 if (value_only && argc != 1) {
279 "## Error: `-n' option requires exactly one argument\n");
283 for (i = 0; i < argc; ++i) { /* print single env variables */
284 char *name = argv[i];
287 for (env = environment.data; *env; env = nxt + 1) {
289 for (nxt = env; *nxt; ++nxt) {
290 if (nxt >= &environment.data[ENV_SIZE]) {
291 fprintf (stderr, "## Error: "
292 "environment not terminated\n");
296 val = envmatch (name, env);
299 fputs (name, stdout);
307 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
315 int fw_env_close(struct env_opts *opts)
320 opts = &default_opts;
322 if (opts->aes_flag) {
323 ret = env_aes_cbc_crypt(environment.data, 1,
327 "Error: can't encrypt env for flash\n");
335 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
337 /* write environment back to flash */
338 if (flash_io(O_RDWR)) {
340 "Error: can't write fw_env to flash\n");
349 * Set/Clear a single variable in the environment.
350 * This is called in sequence to update the environment
351 * in RAM without updating the copy in flash after each set
353 int fw_env_write(char *name, char *value)
358 int deleting, creating, overwriting;
361 * search if variable with this name already exists
363 for (nxt = env = environment.data; *env; env = nxt + 1) {
364 for (nxt = env; *nxt; ++nxt) {
365 if (nxt >= &environment.data[ENV_SIZE]) {
366 fprintf(stderr, "## Error: "
367 "environment not terminated\n");
372 if ((oldval = envmatch (name, env)) != NULL)
376 deleting = (oldval && !(value && strlen(value)));
377 creating = (!oldval && (value && strlen(value)));
378 overwriting = (oldval && (value && strlen(value)));
380 /* check for permission */
382 if (env_flags_validate_varaccess(name,
383 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
384 printf("Can't delete \"%s\"\n", name);
388 } else if (overwriting) {
389 if (env_flags_validate_varaccess(name,
390 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
391 printf("Can't overwrite \"%s\"\n", name);
394 } else if (env_flags_validate_varaccess(name,
395 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
396 const char *defval = fw_getdefenv(name);
400 if (strcmp(oldval, defval)
402 printf("Can't overwrite \"%s\"\n", name);
407 } else if (creating) {
408 if (env_flags_validate_varaccess(name,
409 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
410 printf("Can't create \"%s\"\n", name);
418 if (deleting || overwriting) {
419 if (*++nxt == '\0') {
424 if ((*env == '\0') && (*nxt == '\0'))
433 if (!value || !strlen(value))
437 * Append new definition at the end
439 for (env = environment.data; *env || *(env + 1); ++env);
440 if (env > environment.data)
444 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
446 len = strlen (name) + 2;
447 /* add '=' for first arg, ' ' for all others */
448 len += strlen(value) + 1;
450 if (len > (&environment.data[ENV_SIZE] - env)) {
452 "Error: environment overflow, \"%s\" deleted\n",
457 while ((*env = *name++) != '\0')
460 while ((*++env = *value++) != '\0')
463 /* end is marked with double '\0' */
470 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
472 * EINVAL - need at least 1 argument
473 * EROFS - certain variables ("ethaddr", "serial#") cannot be
474 * modified or deleted
477 int fw_setenv(int argc, char *argv[], struct env_opts *opts)
486 opts = &default_opts;
489 fprintf(stderr, "## Error: variable name missing\n");
494 if (fw_env_open(opts)) {
495 fprintf(stderr, "Error: environment not initialized\n");
503 if (env_flags_validate_env_set_params(name, valv, valc) < 0)
507 for (i = 0; i < valc; ++i) {
509 size_t val_len = strlen(val);
512 value[len - 1] = ' ';
513 value = realloc(value, len + val_len + 1);
516 "Cannot malloc %zu bytes: %s\n",
517 len, strerror(errno));
521 memcpy(value + len, val, val_len);
526 fw_env_write(name, value);
530 return fw_env_close(opts);
534 * Parse a file and configure the u-boot variables.
535 * The script file has a very simple format, as follows:
537 * Each line has a couple with name, value:
538 * <white spaces>variable_name<white spaces>variable_value
540 * Both variable_name and variable_value are interpreted as strings.
541 * Any character after <white spaces> and before ending \r\n is interpreted
542 * as variable's value (no comment allowed on these lines !)
544 * Comments are allowed if the first character in the line is #
546 * Returns -1 and sets errno error codes:
550 int fw_parse_script(char *fname, struct env_opts *opts)
553 char dump[1024]; /* Maximum line length in the file */
561 opts = &default_opts;
563 if (fw_env_open(opts)) {
564 fprintf(stderr, "Error: environment not initialized\n");
568 if (strcmp(fname, "-") == 0)
571 fp = fopen(fname, "r");
573 fprintf(stderr, "I cannot open %s for reading\n",
579 while (fgets(dump, sizeof(dump), fp)) {
584 * Read a whole line from the file. If the line is too long
585 * or is not terminated, reports an error and exit.
587 if (dump[len - 1] != '\n') {
589 "Line %d not corrected terminated or too long\n",
595 /* Drop ending line feed / carriage return */
597 if (len && dump[len - 1] == '\r')
600 /* Skip comment or empty lines */
601 if (len == 0 || dump[0] == '#')
605 * Search for variable's name,
606 * remove leading whitespaces
608 name = skip_blanks(dump);
612 /* The first white space is the end of variable name */
613 val = skip_chars(name);
617 if ((val - name) < len)
618 val = skip_blanks(val);
624 fprintf(stderr, "Setting %s : %s\n",
625 name, val ? val : " removed");
628 if (env_flags_validate_type(name, val) < 0) {
634 * If there is an error setting a variable,
635 * try to save the environment and returns an error
637 if (fw_env_write(name, val)) {
639 "fw_env_write returns with error : %s\n",
647 /* Close file if not stdin */
648 if (strcmp(fname, "-") != 0)
651 ret |= fw_env_close(opts);
657 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
660 * < 0 - failed to test
662 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
664 if (mtd_type == MTD_NANDFLASH) {
665 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
668 perror ("Cannot read bad block mark");
674 fprintf (stderr, "Bad block at 0x%llx, "
675 "skipping\n", *blockstart);
685 * Read data from flash at an offset into a provided buffer. On NAND it skips
686 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
687 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
689 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
690 off_t offset, uint8_t mtd_type)
692 size_t blocklen; /* erase / write length - one block on NAND,
694 size_t processed = 0; /* progress counter */
695 size_t readlen = count; /* current read length */
696 off_t top_of_range; /* end of the last block we may use */
697 off_t block_seek; /* offset inside the current block to the start
699 loff_t blockstart; /* running start of the current block -
700 MEMGETBADBLOCK needs 64 bits */
703 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
705 /* Offset inside a block */
706 block_seek = offset - blockstart;
708 if (mtd_type == MTD_NANDFLASH) {
710 * NAND: calculate which blocks we are reading. We have
711 * to read one block at a time to skip bad blocks.
713 blocklen = DEVESIZE (dev);
716 * To calculate the top of the range, we have to use the
717 * global DEVOFFSET (dev), which can be different from offset
719 top_of_range = ((DEVOFFSET(dev) / blocklen) +
720 ENVSECTORS (dev)) * blocklen;
722 /* Limit to one block for the first read */
723 if (readlen > blocklen - block_seek)
724 readlen = blocklen - block_seek;
727 top_of_range = offset + count;
730 /* This only runs once on NOR flash */
731 while (processed < count) {
732 rc = flash_bad_block (fd, mtd_type, &blockstart);
733 if (rc < 0) /* block test failed */
736 if (blockstart + block_seek + readlen > top_of_range) {
737 /* End of range is reached */
739 "Too few good blocks within range\n");
743 if (rc) { /* block is bad */
744 blockstart += blocklen;
749 * If a block is bad, we retry in the next block at the same
750 * offset - see common/env_nand.c::writeenv()
752 lseek (fd, blockstart + block_seek, SEEK_SET);
754 rc = read (fd, buf + processed, readlen);
756 fprintf (stderr, "Read error on %s: %s\n",
757 DEVNAME (dev), strerror (errno));
761 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
762 rc, blockstart + block_seek, DEVNAME(dev));
764 processed += readlen;
765 readlen = min (blocklen, count - processed);
767 blockstart += blocklen;
774 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
775 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
776 * erase and write the whole data at once.
778 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
779 off_t offset, uint8_t mtd_type)
782 struct erase_info_user erase;
783 size_t blocklen; /* length of NAND block / NOR erase sector */
784 size_t erase_len; /* whole area that can be erased - may include
786 size_t erasesize; /* erase / write length - one block on NAND,
788 size_t processed = 0; /* progress counter */
789 size_t write_total; /* total size to actually write - excluding
791 off_t erase_offset; /* offset to the first erase block (aligned)
793 off_t block_seek; /* offset inside the erase block to the start
795 off_t top_of_range; /* end of the last block we may use */
796 loff_t blockstart; /* running start of the current block -
797 MEMGETBADBLOCK needs 64 bits */
801 * For mtd devices only offset and size of the environment do matter
803 if (mtd_type == MTD_ABSENT) {
805 top_of_range = offset + count;
806 erase_len = blocklen;
809 write_total = blocklen;
811 blocklen = DEVESIZE(dev);
813 top_of_range = ((DEVOFFSET(dev) / blocklen) +
814 ENVSECTORS(dev)) * blocklen;
816 erase_offset = (offset / blocklen) * blocklen;
818 /* Maximum area we may use */
819 erase_len = top_of_range - erase_offset;
821 blockstart = erase_offset;
822 /* Offset inside a block */
823 block_seek = offset - erase_offset;
826 * Data size we actually write: from the start of the block
827 * to the start of the data, then count bytes of data, and
828 * to the end of the block
830 write_total = ((block_seek + count + blocklen - 1) /
831 blocklen) * blocklen;
835 * Support data anywhere within erase sectors: read out the complete
836 * area to be erased, replace the environment image, write the whole
839 if (write_total > count) {
840 data = malloc (erase_len);
843 "Cannot malloc %zu bytes: %s\n",
844 erase_len, strerror (errno));
848 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
850 if (write_total != rc)
854 fprintf(stderr, "Preserving data ");
856 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
857 if (block_seek + count != write_total) {
859 fprintf(stderr, " and ");
860 fprintf(stderr, "0x%lx - 0x%x",
861 block_seek + count, write_total - 1);
863 fprintf(stderr, "\n");
865 /* Overwrite the old environment */
866 memcpy (data + block_seek, buf, count);
869 * We get here, iff offset is block-aligned and count is a
870 * multiple of blocklen - see write_total calculation above
875 if (mtd_type == MTD_NANDFLASH) {
877 * NAND: calculate which blocks we are writing. We have
878 * to write one block at a time to skip bad blocks.
880 erasesize = blocklen;
882 erasesize = erase_len;
885 erase.length = erasesize;
887 /* This only runs once on NOR flash and SPI-dataflash */
888 while (processed < write_total) {
889 rc = flash_bad_block (fd, mtd_type, &blockstart);
890 if (rc < 0) /* block test failed */
893 if (blockstart + erasesize > top_of_range) {
894 fprintf (stderr, "End of range reached, aborting\n");
898 if (rc) { /* block is bad */
899 blockstart += blocklen;
903 if (mtd_type != MTD_ABSENT) {
904 erase.start = blockstart;
905 ioctl(fd, MEMUNLOCK, &erase);
906 /* These do not need an explicit erase cycle */
907 if (mtd_type != MTD_DATAFLASH)
908 if (ioctl(fd, MEMERASE, &erase) != 0) {
910 "MTD erase error on %s: %s\n",
911 DEVNAME(dev), strerror(errno));
916 if (lseek (fd, blockstart, SEEK_SET) == -1) {
918 "Seek error on %s: %s\n",
919 DEVNAME (dev), strerror (errno));
924 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
927 if (write (fd, data + processed, erasesize) != erasesize) {
928 fprintf (stderr, "Write error on %s: %s\n",
929 DEVNAME (dev), strerror (errno));
933 if (mtd_type != MTD_ABSENT)
934 ioctl(fd, MEMLOCK, &erase);
936 processed += erasesize;
938 blockstart += erasesize;
941 if (write_total > count)
948 * Set obsolete flag at offset - NOR flash only
950 static int flash_flag_obsolete (int dev, int fd, off_t offset)
953 struct erase_info_user erase;
955 erase.start = DEVOFFSET (dev);
956 erase.length = DEVESIZE (dev);
957 /* This relies on the fact, that obsolete_flag == 0 */
958 rc = lseek (fd, offset, SEEK_SET);
960 fprintf (stderr, "Cannot seek to set the flag on %s \n",
964 ioctl (fd, MEMUNLOCK, &erase);
965 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
966 ioctl (fd, MEMLOCK, &erase);
968 perror ("Could not set obsolete flag");
973 /* Encrypt or decrypt the environment before writing or reading it. */
974 static int env_aes_cbc_crypt(char *payload, const int enc, uint8_t *key)
976 uint8_t *data = (uint8_t *)payload;
977 const int len = usable_envsize;
978 uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
981 /* First we expand the key. */
982 aes_expand_key(key, key_exp);
984 /* Calculate the number of AES blocks to encrypt. */
985 aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
988 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
990 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
995 static int flash_write (int fd_current, int fd_target, int dev_target)
999 switch (environment.flag_scheme) {
1002 case FLAG_INCREMENTAL:
1003 (*environment.flags)++;
1006 *environment.flags = active_flag;
1009 fprintf (stderr, "Unimplemented flash scheme %u \n",
1010 environment.flag_scheme);
1015 fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
1016 DEVOFFSET (dev_target), DEVNAME (dev_target));
1019 rc = flash_write_buf(dev_target, fd_target, environment.image,
1020 CUR_ENVSIZE, DEVOFFSET(dev_target),
1021 DEVTYPE(dev_target));
1025 if (environment.flag_scheme == FLAG_BOOLEAN) {
1026 /* Have to set obsolete flag */
1027 off_t offset = DEVOFFSET (dev_current) +
1028 offsetof (struct env_image_redundant, flags);
1031 "Setting obsolete flag in environment at 0x%llx on %s\n",
1032 DEVOFFSET (dev_current), DEVNAME (dev_current));
1034 flash_flag_obsolete (dev_current, fd_current, offset);
1040 static int flash_read (int fd)
1044 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1045 DEVOFFSET(dev_current), DEVTYPE(dev_current));
1046 if (rc != CUR_ENVSIZE)
1052 static int flash_io (int mode)
1054 int fd_current, fd_target, rc, dev_target;
1056 /* dev_current: fd_current, erase_current */
1057 fd_current = open (DEVNAME (dev_current), mode);
1058 if (fd_current < 0) {
1060 "Can't open %s: %s\n",
1061 DEVNAME (dev_current), strerror (errno));
1065 if (mode == O_RDWR) {
1066 if (HaveRedundEnv) {
1067 /* switch to next partition for writing */
1068 dev_target = !dev_current;
1069 /* dev_target: fd_target, erase_target */
1070 fd_target = open (DEVNAME (dev_target), mode);
1071 if (fd_target < 0) {
1073 "Can't open %s: %s\n",
1074 DEVNAME (dev_target),
1080 dev_target = dev_current;
1081 fd_target = fd_current;
1084 rc = flash_write (fd_current, fd_target, dev_target);
1086 if (HaveRedundEnv) {
1087 if (close (fd_target)) {
1089 "I/O error on %s: %s\n",
1090 DEVNAME (dev_target),
1096 rc = flash_read (fd_current);
1100 if (close (fd_current)) {
1102 "I/O error on %s: %s\n",
1103 DEVNAME (dev_current), strerror (errno));
1111 * Prevent confusion if running from erased flash memory
1113 int fw_env_open(struct env_opts *opts)
1116 unsigned char flag0;
1120 unsigned char flag1;
1125 struct env_image_single *single;
1126 struct env_image_redundant *redundant;
1129 opts = &default_opts;
1131 if (parse_config(opts)) /* should fill envdevices */
1134 addr0 = calloc(1, CUR_ENVSIZE);
1135 if (addr0 == NULL) {
1137 "Not enough memory for environment (%ld bytes)\n",
1142 /* read environment from FLASH to local buffer */
1143 environment.image = addr0;
1145 if (HaveRedundEnv) {
1147 environment.crc = &redundant->crc;
1148 environment.flags = &redundant->flags;
1149 environment.data = redundant->data;
1152 environment.crc = &single->crc;
1153 environment.flags = NULL;
1154 environment.data = single->data;
1158 if (flash_io (O_RDONLY))
1161 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1163 if (opts->aes_flag) {
1164 ret = env_aes_cbc_crypt(environment.data, 0,
1170 crc0_ok = (crc0 == *environment.crc);
1171 if (!HaveRedundEnv) {
1174 "Warning: Bad CRC, using default environment\n");
1175 memcpy(environment.data, default_environment, sizeof default_environment);
1178 flag0 = *environment.flags;
1181 addr1 = calloc(1, CUR_ENVSIZE);
1182 if (addr1 == NULL) {
1184 "Not enough memory for environment (%ld bytes)\n",
1191 * have to set environment.image for flash_read(), careful -
1192 * other pointers in environment still point inside addr0
1194 environment.image = addr1;
1195 if (flash_io (O_RDONLY))
1198 /* Check flag scheme compatibility */
1199 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1200 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1201 environment.flag_scheme = FLAG_BOOLEAN;
1202 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1203 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1204 environment.flag_scheme = FLAG_INCREMENTAL;
1205 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1206 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1207 environment.flag_scheme = FLAG_BOOLEAN;
1208 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1209 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1210 environment.flag_scheme = FLAG_INCREMENTAL;
1211 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1212 DEVTYPE(!dev_current) == MTD_ABSENT) {
1213 environment.flag_scheme = FLAG_INCREMENTAL;
1215 fprintf (stderr, "Incompatible flash types!\n");
1219 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1221 if (opts->aes_flag) {
1222 ret = env_aes_cbc_crypt(redundant->data, 0,
1228 crc1_ok = (crc1 == redundant->crc);
1229 flag1 = redundant->flags;
1231 if (crc0_ok && !crc1_ok) {
1233 } else if (!crc0_ok && crc1_ok) {
1235 } else if (!crc0_ok && !crc1_ok) {
1237 "Warning: Bad CRC, using default environment\n");
1238 memcpy (environment.data, default_environment,
1239 sizeof default_environment);
1242 switch (environment.flag_scheme) {
1244 if (flag0 == active_flag &&
1245 flag1 == obsolete_flag) {
1247 } else if (flag0 == obsolete_flag &&
1248 flag1 == active_flag) {
1250 } else if (flag0 == flag1) {
1252 } else if (flag0 == 0xFF) {
1254 } else if (flag1 == 0xFF) {
1260 case FLAG_INCREMENTAL:
1261 if (flag0 == 255 && flag1 == 0)
1263 else if ((flag1 == 255 && flag0 == 0) ||
1266 else /* flag1 > flag0 */
1270 fprintf (stderr, "Unknown flag scheme %u \n",
1271 environment.flag_scheme);
1277 * If we are reading, we don't need the flag and the CRC any
1278 * more, if we are writing, we will re-calculate CRC and update
1279 * flags before writing out
1282 environment.image = addr1;
1283 environment.crc = &redundant->crc;
1284 environment.flags = &redundant->flags;
1285 environment.data = redundant->data;
1288 environment.image = addr0;
1289 /* Other pointers are already set */
1293 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1299 static int check_device_config(int dev)
1304 fd = open(DEVNAME(dev), O_RDONLY);
1307 "Cannot open %s: %s\n",
1308 DEVNAME(dev), strerror(errno));
1312 rc = fstat(fd, &st);
1314 fprintf(stderr, "Cannot stat the file %s\n",
1319 if (S_ISCHR(st.st_mode)) {
1320 struct mtd_info_user mtdinfo;
1321 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1323 fprintf(stderr, "Cannot get MTD information for %s\n",
1327 if (mtdinfo.type != MTD_NORFLASH &&
1328 mtdinfo.type != MTD_NANDFLASH &&
1329 mtdinfo.type != MTD_DATAFLASH &&
1330 mtdinfo.type != MTD_UBIVOLUME) {
1331 fprintf(stderr, "Unsupported flash type %u on %s\n",
1332 mtdinfo.type, DEVNAME(dev));
1335 DEVTYPE(dev) = mtdinfo.type;
1338 DEVTYPE(dev) = MTD_ABSENT;
1341 * Check for negative offsets, treat it as backwards offset
1342 * from the end of the block device
1344 if (DEVOFFSET(dev) < 0) {
1345 rc = ioctl(fd, BLKGETSIZE64, &size);
1347 fprintf(stderr, "Could not get block device size on %s\n",
1352 DEVOFFSET(dev) = DEVOFFSET(dev) + size;
1354 fprintf(stderr, "Calculated device offset 0x%llx on %s\n",
1355 DEVOFFSET(dev), DEVNAME(dev));
1365 static int parse_config(struct env_opts *opts)
1370 opts = &default_opts;
1372 #if defined(CONFIG_FILE)
1373 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1374 if (get_config(opts->config_file)) {
1375 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1380 DEVNAME (0) = DEVICE1_NAME;
1381 DEVOFFSET (0) = DEVICE1_OFFSET;
1382 ENVSIZE (0) = ENV1_SIZE;
1383 /* Default values are: erase-size=env-size */
1384 DEVESIZE (0) = ENVSIZE (0);
1385 /* #sectors=env-size/erase-size (rounded up) */
1386 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1387 #ifdef DEVICE1_ESIZE
1388 DEVESIZE (0) = DEVICE1_ESIZE;
1390 #ifdef DEVICE1_ENVSECTORS
1391 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1395 DEVNAME (1) = DEVICE2_NAME;
1396 DEVOFFSET (1) = DEVICE2_OFFSET;
1397 ENVSIZE (1) = ENV2_SIZE;
1398 /* Default values are: erase-size=env-size */
1399 DEVESIZE (1) = ENVSIZE (1);
1400 /* #sectors=env-size/erase-size (rounded up) */
1401 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1402 #ifdef DEVICE2_ESIZE
1403 DEVESIZE (1) = DEVICE2_ESIZE;
1405 #ifdef DEVICE2_ENVSECTORS
1406 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1411 rc = check_device_config(0);
1415 if (HaveRedundEnv) {
1416 rc = check_device_config(1);
1420 if (ENVSIZE(0) != ENVSIZE(1)) {
1421 ENVSIZE(0) = ENVSIZE(1) = min(ENVSIZE(0), ENVSIZE(1));
1423 "Redundant environments have inequal size, set to 0x%08lx\n",
1428 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1430 usable_envsize -= sizeof(char);
1433 usable_envsize &= ~(AES_KEY_LENGTH - 1);
1438 #if defined(CONFIG_FILE)
1439 static int get_config (char *fname)
1447 fp = fopen (fname, "r");
1451 while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1452 /* Skip incomplete conversions and comment strings */
1456 rc = sscanf(dump, "%ms %lli %lx %lx %lx",
1466 DEVNAME(i) = devname;
1469 /* Assume the erase size is the same as the env-size */
1470 DEVESIZE(i) = ENVSIZE(i);
1473 /* Assume enough env sectors to cover the environment */
1474 ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1480 HaveRedundEnv = i - 1;
1481 if (!i) { /* No valid entries found */