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 char *envmatch (char * s1, char * s2);
126 static int parse_config(struct env_opts *opts);
128 #if defined(CONFIG_FILE)
129 static int get_config (char *);
132 static char *skip_chars(char *s)
134 for (; *s != '\0'; s++) {
141 static char *skip_blanks(char *s)
143 for (; *s != '\0'; s++) {
151 * Search the environment for a variable.
152 * Return the value, if found, or NULL, if not found.
154 char *fw_getenv (char *name)
158 for (env = environment.data; *env; env = nxt + 1) {
161 for (nxt = env; *nxt; ++nxt) {
162 if (nxt >= &environment.data[ENV_SIZE]) {
163 fprintf (stderr, "## Error: "
164 "environment not terminated\n");
168 val = envmatch (name, env);
177 * Search the default environment for a variable.
178 * Return the value, if found, or NULL, if not found.
180 char *fw_getdefenv(char *name)
184 for (env = default_environment; *env; env = nxt + 1) {
187 for (nxt = env; *nxt; ++nxt) {
188 if (nxt >= &default_environment[ENV_SIZE]) {
189 fprintf(stderr, "## Error: "
190 "default environment not terminated\n");
194 val = envmatch(name, env);
202 int parse_aes_key(char *key, uint8_t *bin_key)
204 char tmp[5] = { '0', 'x', 0, 0, 0 };
208 if (strnlen(key, 64) != 32) {
210 "## Error: '-a' option requires 16-byte AES key\n");
214 for (i = 0; i < 16; i++) {
218 ul = strtoul(tmp, NULL, 16);
221 "## Error: '-a' option requires valid AES key\n");
224 bin_key[i] = ul & 0xff;
231 * Print the current definition of one, or more, or all
232 * environment variables
234 int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
240 opts = &default_opts;
242 if (fw_env_open(opts))
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 (value_only && 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);
282 fputs (name, stdout);
290 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
298 int fw_env_close(struct env_opts *opts)
303 opts = &default_opts;
305 if (opts->aes_flag) {
306 ret = env_aes_cbc_crypt(environment.data, 1,
310 "Error: can't encrypt env for flash\n");
318 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
320 /* write environment back to flash */
321 if (flash_io(O_RDWR)) {
323 "Error: can't write fw_env to flash\n");
332 * Set/Clear a single variable in the environment.
333 * This is called in sequence to update the environment
334 * in RAM without updating the copy in flash after each set
336 int fw_env_write(char *name, char *value)
341 int deleting, creating, overwriting;
344 * search if variable with this name already exists
346 for (nxt = env = environment.data; *env; env = nxt + 1) {
347 for (nxt = env; *nxt; ++nxt) {
348 if (nxt >= &environment.data[ENV_SIZE]) {
349 fprintf(stderr, "## Error: "
350 "environment not terminated\n");
355 if ((oldval = envmatch (name, env)) != NULL)
359 deleting = (oldval && !(value && strlen(value)));
360 creating = (!oldval && (value && strlen(value)));
361 overwriting = (oldval && (value && strlen(value)));
363 /* check for permission */
365 if (env_flags_validate_varaccess(name,
366 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
367 printf("Can't delete \"%s\"\n", name);
371 } else if (overwriting) {
372 if (env_flags_validate_varaccess(name,
373 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
374 printf("Can't overwrite \"%s\"\n", name);
377 } else if (env_flags_validate_varaccess(name,
378 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
379 const char *defval = fw_getdefenv(name);
383 if (strcmp(oldval, defval)
385 printf("Can't overwrite \"%s\"\n", name);
390 } else if (creating) {
391 if (env_flags_validate_varaccess(name,
392 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
393 printf("Can't create \"%s\"\n", name);
401 if (deleting || overwriting) {
402 if (*++nxt == '\0') {
407 if ((*env == '\0') && (*nxt == '\0'))
416 if (!value || !strlen(value))
420 * Append new definition at the end
422 for (env = environment.data; *env || *(env + 1); ++env);
423 if (env > environment.data)
427 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
429 len = strlen (name) + 2;
430 /* add '=' for first arg, ' ' for all others */
431 len += strlen(value) + 1;
433 if (len > (&environment.data[ENV_SIZE] - env)) {
435 "Error: environment overflow, \"%s\" deleted\n",
440 while ((*env = *name++) != '\0')
443 while ((*++env = *value++) != '\0')
446 /* end is marked with double '\0' */
453 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
455 * EINVAL - need at least 1 argument
456 * EROFS - certain variables ("ethaddr", "serial#") cannot be
457 * modified or deleted
460 int fw_setenv(int argc, char *argv[], struct env_opts *opts)
469 opts = &default_opts;
472 fprintf(stderr, "## Error: variable name missing\n");
477 if (fw_env_open(opts)) {
478 fprintf(stderr, "Error: environment not initialized\n");
486 if (env_flags_validate_env_set_params(name, valv, valc) < 0)
490 for (i = 0; i < valc; ++i) {
492 size_t val_len = strlen(val);
495 value[len - 1] = ' ';
496 value = realloc(value, len + val_len + 1);
499 "Cannot malloc %zu bytes: %s\n",
500 len, strerror(errno));
504 memcpy(value + len, val, val_len);
509 fw_env_write(name, value);
513 return fw_env_close(opts);
517 * Parse a file and configure the u-boot variables.
518 * The script file has a very simple format, as follows:
520 * Each line has a couple with name, value:
521 * <white spaces>variable_name<white spaces>variable_value
523 * Both variable_name and variable_value are interpreted as strings.
524 * Any character after <white spaces> and before ending \r\n is interpreted
525 * as variable's value (no comment allowed on these lines !)
527 * Comments are allowed if the first character in the line is #
529 * Returns -1 and sets errno error codes:
533 int fw_parse_script(char *fname, struct env_opts *opts)
536 char dump[1024]; /* Maximum line length in the file */
544 opts = &default_opts;
546 if (fw_env_open(opts)) {
547 fprintf(stderr, "Error: environment not initialized\n");
551 if (strcmp(fname, "-") == 0)
554 fp = fopen(fname, "r");
556 fprintf(stderr, "I cannot open %s for reading\n",
562 while (fgets(dump, sizeof(dump), fp)) {
567 * Read a whole line from the file. If the line is too long
568 * or is not terminated, reports an error and exit.
570 if (dump[len - 1] != '\n') {
572 "Line %d not corrected terminated or too long\n",
578 /* Drop ending line feed / carriage return */
580 if (len && dump[len - 1] == '\r')
583 /* Skip comment or empty lines */
584 if (len == 0 || dump[0] == '#')
588 * Search for variable's name,
589 * remove leading whitespaces
591 name = skip_blanks(dump);
595 /* The first white space is the end of variable name */
596 val = skip_chars(name);
600 if ((val - name) < len)
601 val = skip_blanks(val);
607 fprintf(stderr, "Setting %s : %s\n",
608 name, val ? val : " removed");
611 if (env_flags_validate_type(name, val) < 0) {
617 * If there is an error setting a variable,
618 * try to save the environment and returns an error
620 if (fw_env_write(name, val)) {
622 "fw_env_write returns with error : %s\n",
630 /* Close file if not stdin */
631 if (strcmp(fname, "-") != 0)
634 ret |= fw_env_close(opts);
640 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
643 * < 0 - failed to test
645 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
647 if (mtd_type == MTD_NANDFLASH) {
648 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
651 perror ("Cannot read bad block mark");
657 fprintf (stderr, "Bad block at 0x%llx, "
658 "skipping\n", *blockstart);
668 * Read data from flash at an offset into a provided buffer. On NAND it skips
669 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
670 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
672 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
673 off_t offset, uint8_t mtd_type)
675 size_t blocklen; /* erase / write length - one block on NAND,
677 size_t processed = 0; /* progress counter */
678 size_t readlen = count; /* current read length */
679 off_t top_of_range; /* end of the last block we may use */
680 off_t block_seek; /* offset inside the current block to the start
682 loff_t blockstart; /* running start of the current block -
683 MEMGETBADBLOCK needs 64 bits */
686 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
688 /* Offset inside a block */
689 block_seek = offset - blockstart;
691 if (mtd_type == MTD_NANDFLASH) {
693 * NAND: calculate which blocks we are reading. We have
694 * to read one block at a time to skip bad blocks.
696 blocklen = DEVESIZE (dev);
699 * To calculate the top of the range, we have to use the
700 * global DEVOFFSET (dev), which can be different from offset
702 top_of_range = ((DEVOFFSET(dev) / blocklen) +
703 ENVSECTORS (dev)) * blocklen;
705 /* Limit to one block for the first read */
706 if (readlen > blocklen - block_seek)
707 readlen = blocklen - block_seek;
710 top_of_range = offset + count;
713 /* This only runs once on NOR flash */
714 while (processed < count) {
715 rc = flash_bad_block (fd, mtd_type, &blockstart);
716 if (rc < 0) /* block test failed */
719 if (blockstart + block_seek + readlen > top_of_range) {
720 /* End of range is reached */
722 "Too few good blocks within range\n");
726 if (rc) { /* block is bad */
727 blockstart += blocklen;
732 * If a block is bad, we retry in the next block at the same
733 * offset - see common/env_nand.c::writeenv()
735 lseek (fd, blockstart + block_seek, SEEK_SET);
737 rc = read (fd, buf + processed, readlen);
739 fprintf (stderr, "Read error on %s: %s\n",
740 DEVNAME (dev), strerror (errno));
744 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
745 rc, blockstart + block_seek, DEVNAME(dev));
747 processed += readlen;
748 readlen = min (blocklen, count - processed);
750 blockstart += blocklen;
757 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
758 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
759 * erase and write the whole data at once.
761 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
762 off_t offset, uint8_t mtd_type)
765 struct erase_info_user erase;
766 size_t blocklen; /* length of NAND block / NOR erase sector */
767 size_t erase_len; /* whole area that can be erased - may include
769 size_t erasesize; /* erase / write length - one block on NAND,
771 size_t processed = 0; /* progress counter */
772 size_t write_total; /* total size to actually write - excluding
774 off_t erase_offset; /* offset to the first erase block (aligned)
776 off_t block_seek; /* offset inside the erase block to the start
778 off_t top_of_range; /* end of the last block we may use */
779 loff_t blockstart; /* running start of the current block -
780 MEMGETBADBLOCK needs 64 bits */
784 * For mtd devices only offset and size of the environment do matter
786 if (mtd_type == MTD_ABSENT) {
788 top_of_range = offset + count;
789 erase_len = blocklen;
792 write_total = blocklen;
794 blocklen = DEVESIZE(dev);
796 top_of_range = ((DEVOFFSET(dev) / blocklen) +
797 ENVSECTORS(dev)) * blocklen;
799 erase_offset = (offset / blocklen) * blocklen;
801 /* Maximum area we may use */
802 erase_len = top_of_range - erase_offset;
804 blockstart = erase_offset;
805 /* Offset inside a block */
806 block_seek = offset - erase_offset;
809 * Data size we actually write: from the start of the block
810 * to the start of the data, then count bytes of data, and
811 * to the end of the block
813 write_total = ((block_seek + count + blocklen - 1) /
814 blocklen) * blocklen;
818 * Support data anywhere within erase sectors: read out the complete
819 * area to be erased, replace the environment image, write the whole
822 if (write_total > count) {
823 data = malloc (erase_len);
826 "Cannot malloc %zu bytes: %s\n",
827 erase_len, strerror (errno));
831 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
833 if (write_total != rc)
837 fprintf(stderr, "Preserving data ");
839 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
840 if (block_seek + count != write_total) {
842 fprintf(stderr, " and ");
843 fprintf(stderr, "0x%lx - 0x%x",
844 block_seek + count, write_total - 1);
846 fprintf(stderr, "\n");
848 /* Overwrite the old environment */
849 memcpy (data + block_seek, buf, count);
852 * We get here, iff offset is block-aligned and count is a
853 * multiple of blocklen - see write_total calculation above
858 if (mtd_type == MTD_NANDFLASH) {
860 * NAND: calculate which blocks we are writing. We have
861 * to write one block at a time to skip bad blocks.
863 erasesize = blocklen;
865 erasesize = erase_len;
868 erase.length = erasesize;
870 /* This only runs once on NOR flash and SPI-dataflash */
871 while (processed < write_total) {
872 rc = flash_bad_block (fd, mtd_type, &blockstart);
873 if (rc < 0) /* block test failed */
876 if (blockstart + erasesize > top_of_range) {
877 fprintf (stderr, "End of range reached, aborting\n");
881 if (rc) { /* block is bad */
882 blockstart += blocklen;
886 if (mtd_type != MTD_ABSENT) {
887 erase.start = blockstart;
888 ioctl(fd, MEMUNLOCK, &erase);
889 /* These do not need an explicit erase cycle */
890 if (mtd_type != MTD_DATAFLASH)
891 if (ioctl(fd, MEMERASE, &erase) != 0) {
893 "MTD erase error on %s: %s\n",
894 DEVNAME(dev), strerror(errno));
899 if (lseek (fd, blockstart, SEEK_SET) == -1) {
901 "Seek error on %s: %s\n",
902 DEVNAME (dev), strerror (errno));
907 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
910 if (write (fd, data + processed, erasesize) != erasesize) {
911 fprintf (stderr, "Write error on %s: %s\n",
912 DEVNAME (dev), strerror (errno));
916 if (mtd_type != MTD_ABSENT)
917 ioctl(fd, MEMLOCK, &erase);
919 processed += erasesize;
921 blockstart += erasesize;
924 if (write_total > count)
931 * Set obsolete flag at offset - NOR flash only
933 static int flash_flag_obsolete (int dev, int fd, off_t offset)
936 struct erase_info_user erase;
938 erase.start = DEVOFFSET (dev);
939 erase.length = DEVESIZE (dev);
940 /* This relies on the fact, that obsolete_flag == 0 */
941 rc = lseek (fd, offset, SEEK_SET);
943 fprintf (stderr, "Cannot seek to set the flag on %s \n",
947 ioctl (fd, MEMUNLOCK, &erase);
948 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
949 ioctl (fd, MEMLOCK, &erase);
951 perror ("Could not set obsolete flag");
956 /* Encrypt or decrypt the environment before writing or reading it. */
957 static int env_aes_cbc_crypt(char *payload, const int enc, uint8_t *key)
959 uint8_t *data = (uint8_t *)payload;
960 const int len = usable_envsize;
961 uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
964 /* First we expand the key. */
965 aes_expand_key(key, key_exp);
967 /* Calculate the number of AES blocks to encrypt. */
968 aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
971 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
973 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
978 static int flash_write (int fd_current, int fd_target, int dev_target)
982 switch (environment.flag_scheme) {
985 case FLAG_INCREMENTAL:
986 (*environment.flags)++;
989 *environment.flags = active_flag;
992 fprintf (stderr, "Unimplemented flash scheme %u \n",
993 environment.flag_scheme);
998 fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
999 DEVOFFSET (dev_target), DEVNAME (dev_target));
1002 rc = flash_write_buf(dev_target, fd_target, environment.image,
1003 CUR_ENVSIZE, DEVOFFSET(dev_target),
1004 DEVTYPE(dev_target));
1008 if (environment.flag_scheme == FLAG_BOOLEAN) {
1009 /* Have to set obsolete flag */
1010 off_t offset = DEVOFFSET (dev_current) +
1011 offsetof (struct env_image_redundant, flags);
1014 "Setting obsolete flag in environment at 0x%llx on %s\n",
1015 DEVOFFSET (dev_current), DEVNAME (dev_current));
1017 flash_flag_obsolete (dev_current, fd_current, offset);
1023 static int flash_read (int fd)
1027 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1028 DEVOFFSET(dev_current), DEVTYPE(dev_current));
1029 if (rc != CUR_ENVSIZE)
1035 static int flash_io (int mode)
1037 int fd_current, fd_target, rc, dev_target;
1039 /* dev_current: fd_current, erase_current */
1040 fd_current = open (DEVNAME (dev_current), mode);
1041 if (fd_current < 0) {
1043 "Can't open %s: %s\n",
1044 DEVNAME (dev_current), strerror (errno));
1048 if (mode == O_RDWR) {
1049 if (HaveRedundEnv) {
1050 /* switch to next partition for writing */
1051 dev_target = !dev_current;
1052 /* dev_target: fd_target, erase_target */
1053 fd_target = open (DEVNAME (dev_target), mode);
1054 if (fd_target < 0) {
1056 "Can't open %s: %s\n",
1057 DEVNAME (dev_target),
1063 dev_target = dev_current;
1064 fd_target = fd_current;
1067 rc = flash_write (fd_current, fd_target, dev_target);
1069 if (HaveRedundEnv) {
1070 if (close (fd_target)) {
1072 "I/O error on %s: %s\n",
1073 DEVNAME (dev_target),
1079 rc = flash_read (fd_current);
1083 if (close (fd_current)) {
1085 "I/O error on %s: %s\n",
1086 DEVNAME (dev_current), strerror (errno));
1094 * s1 is either a simple 'name', or a 'name=value' pair.
1095 * s2 is a 'name=value' pair.
1096 * If the names match, return the value of s2, else NULL.
1099 static char *envmatch (char * s1, char * s2)
1101 if (s1 == NULL || s2 == NULL)
1104 while (*s1 == *s2++)
1107 if (*s1 == '\0' && *(s2 - 1) == '=')
1113 * Prevent confusion if running from erased flash memory
1115 int fw_env_open(struct env_opts *opts)
1118 unsigned char flag0;
1122 unsigned char flag1;
1127 struct env_image_single *single;
1128 struct env_image_redundant *redundant;
1131 opts = &default_opts;
1133 if (parse_config(opts)) /* should fill envdevices */
1136 addr0 = calloc(1, CUR_ENVSIZE);
1137 if (addr0 == NULL) {
1139 "Not enough memory for environment (%ld bytes)\n",
1144 /* read environment from FLASH to local buffer */
1145 environment.image = addr0;
1147 if (HaveRedundEnv) {
1149 environment.crc = &redundant->crc;
1150 environment.flags = &redundant->flags;
1151 environment.data = redundant->data;
1154 environment.crc = &single->crc;
1155 environment.flags = NULL;
1156 environment.data = single->data;
1160 if (flash_io (O_RDONLY))
1163 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1165 if (opts->aes_flag) {
1166 ret = env_aes_cbc_crypt(environment.data, 0,
1172 crc0_ok = (crc0 == *environment.crc);
1173 if (!HaveRedundEnv) {
1176 "Warning: Bad CRC, using default environment\n");
1177 memcpy(environment.data, default_environment, sizeof default_environment);
1180 flag0 = *environment.flags;
1183 addr1 = calloc(1, CUR_ENVSIZE);
1184 if (addr1 == NULL) {
1186 "Not enough memory for environment (%ld bytes)\n",
1193 * have to set environment.image for flash_read(), careful -
1194 * other pointers in environment still point inside addr0
1196 environment.image = addr1;
1197 if (flash_io (O_RDONLY))
1200 /* Check flag scheme compatibility */
1201 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1202 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1203 environment.flag_scheme = FLAG_BOOLEAN;
1204 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1205 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1206 environment.flag_scheme = FLAG_INCREMENTAL;
1207 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1208 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1209 environment.flag_scheme = FLAG_BOOLEAN;
1210 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1211 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1212 environment.flag_scheme = FLAG_INCREMENTAL;
1213 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1214 DEVTYPE(!dev_current) == MTD_ABSENT) {
1215 environment.flag_scheme = FLAG_INCREMENTAL;
1217 fprintf (stderr, "Incompatible flash types!\n");
1221 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1223 if (opts->aes_flag) {
1224 ret = env_aes_cbc_crypt(redundant->data, 0,
1230 crc1_ok = (crc1 == redundant->crc);
1231 flag1 = redundant->flags;
1233 if (crc0_ok && !crc1_ok) {
1235 } else if (!crc0_ok && crc1_ok) {
1237 } else if (!crc0_ok && !crc1_ok) {
1239 "Warning: Bad CRC, using default environment\n");
1240 memcpy (environment.data, default_environment,
1241 sizeof default_environment);
1244 switch (environment.flag_scheme) {
1246 if (flag0 == active_flag &&
1247 flag1 == obsolete_flag) {
1249 } else if (flag0 == obsolete_flag &&
1250 flag1 == active_flag) {
1252 } else if (flag0 == flag1) {
1254 } else if (flag0 == 0xFF) {
1256 } else if (flag1 == 0xFF) {
1262 case FLAG_INCREMENTAL:
1263 if (flag0 == 255 && flag1 == 0)
1265 else if ((flag1 == 255 && flag0 == 0) ||
1268 else /* flag1 > flag0 */
1272 fprintf (stderr, "Unknown flag scheme %u \n",
1273 environment.flag_scheme);
1279 * If we are reading, we don't need the flag and the CRC any
1280 * more, if we are writing, we will re-calculate CRC and update
1281 * flags before writing out
1284 environment.image = addr1;
1285 environment.crc = &redundant->crc;
1286 environment.flags = &redundant->flags;
1287 environment.data = redundant->data;
1290 environment.image = addr0;
1291 /* Other pointers are already set */
1295 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1301 static int check_device_config(int dev)
1306 fd = open(DEVNAME(dev), O_RDONLY);
1309 "Cannot open %s: %s\n",
1310 DEVNAME(dev), strerror(errno));
1314 rc = fstat(fd, &st);
1316 fprintf(stderr, "Cannot stat the file %s\n",
1321 if (S_ISCHR(st.st_mode)) {
1322 struct mtd_info_user mtdinfo;
1323 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1325 fprintf(stderr, "Cannot get MTD information for %s\n",
1329 if (mtdinfo.type != MTD_NORFLASH &&
1330 mtdinfo.type != MTD_NANDFLASH &&
1331 mtdinfo.type != MTD_DATAFLASH &&
1332 mtdinfo.type != MTD_UBIVOLUME) {
1333 fprintf(stderr, "Unsupported flash type %u on %s\n",
1334 mtdinfo.type, DEVNAME(dev));
1337 DEVTYPE(dev) = mtdinfo.type;
1340 DEVTYPE(dev) = MTD_ABSENT;
1343 * Check for negative offsets, treat it as backwards offset
1344 * from the end of the block device
1346 if (DEVOFFSET(dev) < 0) {
1347 rc = ioctl(fd, BLKGETSIZE64, &size);
1349 fprintf(stderr, "Could not get block device size on %s\n",
1354 DEVOFFSET(dev) = DEVOFFSET(dev) + size;
1356 fprintf(stderr, "Calculated device offset 0x%llx on %s\n",
1357 DEVOFFSET(dev), DEVNAME(dev));
1367 static int parse_config(struct env_opts *opts)
1372 opts = &default_opts;
1374 #if defined(CONFIG_FILE)
1375 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1376 if (get_config(opts->config_file)) {
1377 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1382 DEVNAME (0) = DEVICE1_NAME;
1383 DEVOFFSET (0) = DEVICE1_OFFSET;
1384 ENVSIZE (0) = ENV1_SIZE;
1385 /* Default values are: erase-size=env-size */
1386 DEVESIZE (0) = ENVSIZE (0);
1387 /* #sectors=env-size/erase-size (rounded up) */
1388 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1389 #ifdef DEVICE1_ESIZE
1390 DEVESIZE (0) = DEVICE1_ESIZE;
1392 #ifdef DEVICE1_ENVSECTORS
1393 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1397 DEVNAME (1) = DEVICE2_NAME;
1398 DEVOFFSET (1) = DEVICE2_OFFSET;
1399 ENVSIZE (1) = ENV2_SIZE;
1400 /* Default values are: erase-size=env-size */
1401 DEVESIZE (1) = ENVSIZE (1);
1402 /* #sectors=env-size/erase-size (rounded up) */
1403 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1404 #ifdef DEVICE2_ESIZE
1405 DEVESIZE (1) = DEVICE2_ESIZE;
1407 #ifdef DEVICE2_ENVSECTORS
1408 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1413 rc = check_device_config(0);
1417 if (HaveRedundEnv) {
1418 rc = check_device_config(1);
1422 if (ENVSIZE(0) != ENVSIZE(1)) {
1423 ENVSIZE(0) = ENVSIZE(1) = min(ENVSIZE(0), ENVSIZE(1));
1425 "Redundant environments have inequal size, set to 0x%08lx\n",
1430 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1432 usable_envsize -= sizeof(char);
1435 usable_envsize &= ~(AES_KEY_LENGTH - 1);
1440 #if defined(CONFIG_FILE)
1441 static int get_config (char *fname)
1449 fp = fopen (fname, "r");
1453 while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1454 /* Skip incomplete conversions and comment strings */
1458 rc = sscanf(dump, "%ms %lli %lx %lx %lx",
1468 DEVNAME(i) = devname;
1471 /* Assume the erase size is the same as the env-size */
1472 DEVESIZE(i) = ENVSIZE(i);
1475 /* Assume enough env sectors to cover the environment */
1476 ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1482 HaveRedundEnv = i - 1;
1483 if (!i) { /* No valid entries found */