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 struct env_opts default_opts = {
40 .config_file = CONFIG_FILE
44 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
46 #define min(x, y) ({ \
47 typeof(x) _min1 = (x); \
48 typeof(y) _min2 = (y); \
49 (void) (&_min1 == &_min2); \
50 _min1 < _min2 ? _min1 : _min2; })
53 const char *devname; /* Device name */
54 ulong devoff; /* Device offset */
55 ulong env_size; /* environment size */
56 ulong erase_size; /* device erase size */
57 ulong env_sectors; /* number of environment sectors */
58 uint8_t mtd_type; /* type of the MTD device */
61 static struct envdev_s envdevices[2] =
64 .mtd_type = MTD_ABSENT,
66 .mtd_type = MTD_ABSENT,
69 static int dev_current;
71 #define DEVNAME(i) envdevices[(i)].devname
72 #define DEVOFFSET(i) envdevices[(i)].devoff
73 #define ENVSIZE(i) envdevices[(i)].env_size
74 #define DEVESIZE(i) envdevices[(i)].erase_size
75 #define ENVSECTORS(i) envdevices[(i)].env_sectors
76 #define DEVTYPE(i) envdevices[(i)].mtd_type
78 #define CUR_ENVSIZE ENVSIZE(dev_current)
80 static unsigned long usable_envsize;
81 #define ENV_SIZE usable_envsize
83 struct env_image_single {
84 uint32_t crc; /* CRC32 over data bytes */
88 struct env_image_redundant {
89 uint32_t crc; /* CRC32 over data bytes */
90 unsigned char flags; /* active or obsolete */
103 unsigned char *flags;
105 enum flag_scheme flag_scheme;
108 static struct environment environment = {
109 .flag_scheme = FLAG_NONE,
112 static int env_aes_cbc_crypt(char *data, const int enc, uint8_t *key);
114 static int HaveRedundEnv = 0;
116 static unsigned char active_flag = 1;
117 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
118 static unsigned char obsolete_flag = 0;
120 #define DEFAULT_ENV_INSTANCE_STATIC
121 #include <env_default.h>
123 static int flash_io (int mode);
124 static char *envmatch (char * s1, char * s2);
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 * Search the environment for a variable.
151 * Return the value, if found, or NULL, if not found.
153 char *fw_getenv (char *name)
157 for (env = environment.data; *env; env = nxt + 1) {
160 for (nxt = env; *nxt; ++nxt) {
161 if (nxt >= &environment.data[ENV_SIZE]) {
162 fprintf (stderr, "## Error: "
163 "environment not terminated\n");
167 val = envmatch (name, env);
176 * Search the default environment for a variable.
177 * Return the value, if found, or NULL, if not found.
179 char *fw_getdefenv(char *name)
183 for (env = default_environment; *env; env = nxt + 1) {
186 for (nxt = env; *nxt; ++nxt) {
187 if (nxt >= &default_environment[ENV_SIZE]) {
188 fprintf(stderr, "## Error: "
189 "default environment not terminated\n");
193 val = envmatch(name, env);
201 int parse_aes_key(char *key, uint8_t *bin_key)
203 char tmp[5] = { '0', 'x', 0, 0, 0 };
207 if (strnlen(key, 64) != 32) {
209 "## Error: '-a' option requires 16-byte AES key\n");
213 for (i = 0; i < 16; i++) {
217 ul = strtoul(tmp, NULL, 16);
220 "## Error: '-a' option requires valid AES key\n");
223 bin_key[i] = ul & 0xff;
230 * Print the current definition of one, or more, or all
231 * environment variables
233 int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
239 opts = &default_opts;
241 if (fw_env_open(opts))
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 (value_only && 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);
281 fputs (name, stdout);
289 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
297 int fw_env_close(struct env_opts *opts)
302 opts = &default_opts;
304 if (opts->aes_flag) {
305 ret = env_aes_cbc_crypt(environment.data, 1,
309 "Error: can't encrypt env for flash\n");
317 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
319 /* write environment back to flash */
320 if (flash_io(O_RDWR)) {
322 "Error: can't write fw_env to flash\n");
331 * Set/Clear a single variable in the environment.
332 * This is called in sequence to update the environment
333 * in RAM without updating the copy in flash after each set
335 int fw_env_write(char *name, char *value)
340 int deleting, creating, overwriting;
343 * search if variable with this name already exists
345 for (nxt = env = environment.data; *env; env = nxt + 1) {
346 for (nxt = env; *nxt; ++nxt) {
347 if (nxt >= &environment.data[ENV_SIZE]) {
348 fprintf(stderr, "## Error: "
349 "environment not terminated\n");
354 if ((oldval = envmatch (name, env)) != NULL)
358 deleting = (oldval && !(value && strlen(value)));
359 creating = (!oldval && (value && strlen(value)));
360 overwriting = (oldval && (value && strlen(value)));
362 /* check for permission */
364 if (env_flags_validate_varaccess(name,
365 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
366 printf("Can't delete \"%s\"\n", name);
370 } else if (overwriting) {
371 if (env_flags_validate_varaccess(name,
372 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
373 printf("Can't overwrite \"%s\"\n", name);
376 } else if (env_flags_validate_varaccess(name,
377 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
378 const char *defval = fw_getdefenv(name);
382 if (strcmp(oldval, defval)
384 printf("Can't overwrite \"%s\"\n", name);
389 } else if (creating) {
390 if (env_flags_validate_varaccess(name,
391 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
392 printf("Can't create \"%s\"\n", name);
400 if (deleting || overwriting) {
401 if (*++nxt == '\0') {
406 if ((*env == '\0') && (*nxt == '\0'))
415 if (!value || !strlen(value))
419 * Append new definition at the end
421 for (env = environment.data; *env || *(env + 1); ++env);
422 if (env > environment.data)
426 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
428 len = strlen (name) + 2;
429 /* add '=' for first arg, ' ' for all others */
430 len += strlen(value) + 1;
432 if (len > (&environment.data[ENV_SIZE] - env)) {
434 "Error: environment overflow, \"%s\" deleted\n",
439 while ((*env = *name++) != '\0')
442 while ((*++env = *value++) != '\0')
445 /* end is marked with double '\0' */
452 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
454 * EINVAL - need at least 1 argument
455 * EROFS - certain variables ("ethaddr", "serial#") cannot be
456 * modified or deleted
459 int fw_setenv(int argc, char *argv[], struct env_opts *opts)
468 opts = &default_opts;
471 fprintf(stderr, "## Error: variable name missing\n");
476 if (fw_env_open(opts)) {
477 fprintf(stderr, "Error: environment not initialized\n");
485 if (env_flags_validate_env_set_params(name, valv, valc) < 0)
489 for (i = 0; i < valc; ++i) {
491 size_t val_len = strlen(val);
494 value[len - 1] = ' ';
495 value = realloc(value, len + val_len + 1);
498 "Cannot malloc %zu bytes: %s\n",
499 len, strerror(errno));
503 memcpy(value + len, val, val_len);
508 fw_env_write(name, value);
512 return fw_env_close(opts);
516 * Parse a file and configure the u-boot variables.
517 * The script file has a very simple format, as follows:
519 * Each line has a couple with name, value:
520 * <white spaces>variable_name<white spaces>variable_value
522 * Both variable_name and variable_value are interpreted as strings.
523 * Any character after <white spaces> and before ending \r\n is interpreted
524 * as variable's value (no comment allowed on these lines !)
526 * Comments are allowed if the first character in the line is #
528 * Returns -1 and sets errno error codes:
532 int fw_parse_script(char *fname, struct env_opts *opts)
535 char dump[1024]; /* Maximum line length in the file */
543 opts = &default_opts;
545 if (fw_env_open(opts)) {
546 fprintf(stderr, "Error: environment not initialized\n");
550 if (strcmp(fname, "-") == 0)
553 fp = fopen(fname, "r");
555 fprintf(stderr, "I cannot open %s for reading\n",
561 while (fgets(dump, sizeof(dump), fp)) {
566 * Read a whole line from the file. If the line is too long
567 * or is not terminated, reports an error and exit.
569 if (dump[len - 1] != '\n') {
571 "Line %d not corrected terminated or too long\n",
577 /* Drop ending line feed / carriage return */
579 if (len && dump[len - 1] == '\r')
582 /* Skip comment or empty lines */
583 if (len == 0 || dump[0] == '#')
587 * Search for variable's name,
588 * remove leading whitespaces
590 name = skip_blanks(dump);
594 /* The first white space is the end of variable name */
595 val = skip_chars(name);
599 if ((val - name) < len)
600 val = skip_blanks(val);
606 fprintf(stderr, "Setting %s : %s\n",
607 name, val ? val : " removed");
610 if (env_flags_validate_type(name, val) < 0) {
616 * If there is an error setting a variable,
617 * try to save the environment and returns an error
619 if (fw_env_write(name, val)) {
621 "fw_env_write returns with error : %s\n",
629 /* Close file if not stdin */
630 if (strcmp(fname, "-") != 0)
633 ret |= fw_env_close(opts);
639 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
642 * < 0 - failed to test
644 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
646 if (mtd_type == MTD_NANDFLASH) {
647 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
650 perror ("Cannot read bad block mark");
656 fprintf (stderr, "Bad block at 0x%llx, "
657 "skipping\n", *blockstart);
667 * Read data from flash at an offset into a provided buffer. On NAND it skips
668 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
669 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
671 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
672 off_t offset, uint8_t mtd_type)
674 size_t blocklen; /* erase / write length - one block on NAND,
676 size_t processed = 0; /* progress counter */
677 size_t readlen = count; /* current read length */
678 off_t top_of_range; /* end of the last block we may use */
679 off_t block_seek; /* offset inside the current block to the start
681 loff_t blockstart; /* running start of the current block -
682 MEMGETBADBLOCK needs 64 bits */
685 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
687 /* Offset inside a block */
688 block_seek = offset - blockstart;
690 if (mtd_type == MTD_NANDFLASH) {
692 * NAND: calculate which blocks we are reading. We have
693 * to read one block at a time to skip bad blocks.
695 blocklen = DEVESIZE (dev);
698 * To calculate the top of the range, we have to use the
699 * global DEVOFFSET (dev), which can be different from offset
701 top_of_range = ((DEVOFFSET(dev) / blocklen) +
702 ENVSECTORS (dev)) * blocklen;
704 /* Limit to one block for the first read */
705 if (readlen > blocklen - block_seek)
706 readlen = blocklen - block_seek;
709 top_of_range = offset + count;
712 /* This only runs once on NOR flash */
713 while (processed < count) {
714 rc = flash_bad_block (fd, mtd_type, &blockstart);
715 if (rc < 0) /* block test failed */
718 if (blockstart + block_seek + readlen > top_of_range) {
719 /* End of range is reached */
721 "Too few good blocks within range\n");
725 if (rc) { /* block is bad */
726 blockstart += blocklen;
731 * If a block is bad, we retry in the next block at the same
732 * offset - see common/env_nand.c::writeenv()
734 lseek (fd, blockstart + block_seek, SEEK_SET);
736 rc = read (fd, buf + processed, readlen);
738 fprintf (stderr, "Read error on %s: %s\n",
739 DEVNAME (dev), strerror (errno));
743 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
744 rc, blockstart + block_seek, DEVNAME(dev));
746 processed += readlen;
747 readlen = min (blocklen, count - processed);
749 blockstart += blocklen;
756 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
757 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
758 * erase and write the whole data at once.
760 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
761 off_t offset, uint8_t mtd_type)
764 struct erase_info_user erase;
765 size_t blocklen; /* length of NAND block / NOR erase sector */
766 size_t erase_len; /* whole area that can be erased - may include
768 size_t erasesize; /* erase / write length - one block on NAND,
770 size_t processed = 0; /* progress counter */
771 size_t write_total; /* total size to actually write - excluding
773 off_t erase_offset; /* offset to the first erase block (aligned)
775 off_t block_seek; /* offset inside the erase block to the start
777 off_t top_of_range; /* end of the last block we may use */
778 loff_t blockstart; /* running start of the current block -
779 MEMGETBADBLOCK needs 64 bits */
783 * For mtd devices only offset and size of the environment do matter
785 if (mtd_type == MTD_ABSENT) {
787 top_of_range = offset + count;
788 erase_len = blocklen;
791 write_total = blocklen;
793 blocklen = DEVESIZE(dev);
795 top_of_range = ((DEVOFFSET(dev) / blocklen) +
796 ENVSECTORS(dev)) * blocklen;
798 erase_offset = (offset / blocklen) * blocklen;
800 /* Maximum area we may use */
801 erase_len = top_of_range - erase_offset;
803 blockstart = erase_offset;
804 /* Offset inside a block */
805 block_seek = offset - erase_offset;
808 * Data size we actually write: from the start of the block
809 * to the start of the data, then count bytes of data, and
810 * to the end of the block
812 write_total = ((block_seek + count + blocklen - 1) /
813 blocklen) * blocklen;
817 * Support data anywhere within erase sectors: read out the complete
818 * area to be erased, replace the environment image, write the whole
821 if (write_total > count) {
822 data = malloc (erase_len);
825 "Cannot malloc %zu bytes: %s\n",
826 erase_len, strerror (errno));
830 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
832 if (write_total != rc)
836 fprintf(stderr, "Preserving data ");
838 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
839 if (block_seek + count != write_total) {
841 fprintf(stderr, " and ");
842 fprintf(stderr, "0x%lx - 0x%x",
843 block_seek + count, write_total - 1);
845 fprintf(stderr, "\n");
847 /* Overwrite the old environment */
848 memcpy (data + block_seek, buf, count);
851 * We get here, iff offset is block-aligned and count is a
852 * multiple of blocklen - see write_total calculation above
857 if (mtd_type == MTD_NANDFLASH) {
859 * NAND: calculate which blocks we are writing. We have
860 * to write one block at a time to skip bad blocks.
862 erasesize = blocklen;
864 erasesize = erase_len;
867 erase.length = erasesize;
869 /* This only runs once on NOR flash and SPI-dataflash */
870 while (processed < write_total) {
871 rc = flash_bad_block (fd, mtd_type, &blockstart);
872 if (rc < 0) /* block test failed */
875 if (blockstart + erasesize > top_of_range) {
876 fprintf (stderr, "End of range reached, aborting\n");
880 if (rc) { /* block is bad */
881 blockstart += blocklen;
885 if (mtd_type != MTD_ABSENT) {
886 erase.start = blockstart;
887 ioctl(fd, MEMUNLOCK, &erase);
888 /* These do not need an explicit erase cycle */
889 if (mtd_type != MTD_DATAFLASH)
890 if (ioctl(fd, MEMERASE, &erase) != 0) {
892 "MTD erase error on %s: %s\n",
893 DEVNAME(dev), strerror(errno));
898 if (lseek (fd, blockstart, SEEK_SET) == -1) {
900 "Seek error on %s: %s\n",
901 DEVNAME (dev), strerror (errno));
906 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
909 if (write (fd, data + processed, erasesize) != erasesize) {
910 fprintf (stderr, "Write error on %s: %s\n",
911 DEVNAME (dev), strerror (errno));
915 if (mtd_type != MTD_ABSENT)
916 ioctl(fd, MEMLOCK, &erase);
918 processed += erasesize;
920 blockstart += erasesize;
923 if (write_total > count)
930 * Set obsolete flag at offset - NOR flash only
932 static int flash_flag_obsolete (int dev, int fd, off_t offset)
935 struct erase_info_user erase;
937 erase.start = DEVOFFSET (dev);
938 erase.length = DEVESIZE (dev);
939 /* This relies on the fact, that obsolete_flag == 0 */
940 rc = lseek (fd, offset, SEEK_SET);
942 fprintf (stderr, "Cannot seek to set the flag on %s \n",
946 ioctl (fd, MEMUNLOCK, &erase);
947 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
948 ioctl (fd, MEMLOCK, &erase);
950 perror ("Could not set obsolete flag");
955 /* Encrypt or decrypt the environment before writing or reading it. */
956 static int env_aes_cbc_crypt(char *payload, const int enc, uint8_t *key)
958 uint8_t *data = (uint8_t *)payload;
959 const int len = usable_envsize;
960 uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
963 /* First we expand the key. */
964 aes_expand_key(key, key_exp);
966 /* Calculate the number of AES blocks to encrypt. */
967 aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
970 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
972 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
977 static int flash_write (int fd_current, int fd_target, int dev_target)
981 switch (environment.flag_scheme) {
984 case FLAG_INCREMENTAL:
985 (*environment.flags)++;
988 *environment.flags = active_flag;
991 fprintf (stderr, "Unimplemented flash scheme %u \n",
992 environment.flag_scheme);
997 fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
998 DEVOFFSET (dev_target), DEVNAME (dev_target));
1001 rc = flash_write_buf(dev_target, fd_target, environment.image,
1002 CUR_ENVSIZE, DEVOFFSET(dev_target),
1003 DEVTYPE(dev_target));
1007 if (environment.flag_scheme == FLAG_BOOLEAN) {
1008 /* Have to set obsolete flag */
1009 off_t offset = DEVOFFSET (dev_current) +
1010 offsetof (struct env_image_redundant, flags);
1013 "Setting obsolete flag in environment at 0x%lx on %s\n",
1014 DEVOFFSET (dev_current), DEVNAME (dev_current));
1016 flash_flag_obsolete (dev_current, fd_current, offset);
1022 static int flash_read (int fd)
1026 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1027 DEVOFFSET(dev_current), DEVTYPE(dev_current));
1028 if (rc != CUR_ENVSIZE)
1034 static int flash_io (int mode)
1036 int fd_current, fd_target, rc, dev_target;
1038 /* dev_current: fd_current, erase_current */
1039 fd_current = open (DEVNAME (dev_current), mode);
1040 if (fd_current < 0) {
1042 "Can't open %s: %s\n",
1043 DEVNAME (dev_current), strerror (errno));
1047 if (mode == O_RDWR) {
1048 if (HaveRedundEnv) {
1049 /* switch to next partition for writing */
1050 dev_target = !dev_current;
1051 /* dev_target: fd_target, erase_target */
1052 fd_target = open (DEVNAME (dev_target), mode);
1053 if (fd_target < 0) {
1055 "Can't open %s: %s\n",
1056 DEVNAME (dev_target),
1062 dev_target = dev_current;
1063 fd_target = fd_current;
1066 rc = flash_write (fd_current, fd_target, dev_target);
1068 if (HaveRedundEnv) {
1069 if (close (fd_target)) {
1071 "I/O error on %s: %s\n",
1072 DEVNAME (dev_target),
1078 rc = flash_read (fd_current);
1082 if (close (fd_current)) {
1084 "I/O error on %s: %s\n",
1085 DEVNAME (dev_current), strerror (errno));
1093 * s1 is either a simple 'name', or a 'name=value' pair.
1094 * s2 is a 'name=value' pair.
1095 * If the names match, return the value of s2, else NULL.
1098 static char *envmatch (char * s1, char * s2)
1100 if (s1 == NULL || s2 == NULL)
1103 while (*s1 == *s2++)
1106 if (*s1 == '\0' && *(s2 - 1) == '=')
1112 * Prevent confusion if running from erased flash memory
1114 int fw_env_open(struct env_opts *opts)
1117 unsigned char flag0;
1121 unsigned char flag1;
1126 struct env_image_single *single;
1127 struct env_image_redundant *redundant;
1130 opts = &default_opts;
1132 if (parse_config(opts)) /* should fill envdevices */
1135 addr0 = calloc(1, CUR_ENVSIZE);
1136 if (addr0 == NULL) {
1138 "Not enough memory for environment (%ld bytes)\n",
1143 /* read environment from FLASH to local buffer */
1144 environment.image = addr0;
1146 if (HaveRedundEnv) {
1148 environment.crc = &redundant->crc;
1149 environment.flags = &redundant->flags;
1150 environment.data = redundant->data;
1153 environment.crc = &single->crc;
1154 environment.flags = NULL;
1155 environment.data = single->data;
1159 if (flash_io (O_RDONLY))
1162 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1164 if (opts->aes_flag) {
1165 ret = env_aes_cbc_crypt(environment.data, 0,
1171 crc0_ok = (crc0 == *environment.crc);
1172 if (!HaveRedundEnv) {
1175 "Warning: Bad CRC, using default environment\n");
1176 memcpy(environment.data, default_environment, sizeof default_environment);
1179 flag0 = *environment.flags;
1182 addr1 = calloc(1, CUR_ENVSIZE);
1183 if (addr1 == NULL) {
1185 "Not enough memory for environment (%ld bytes)\n",
1192 * have to set environment.image for flash_read(), careful -
1193 * other pointers in environment still point inside addr0
1195 environment.image = addr1;
1196 if (flash_io (O_RDONLY))
1199 /* Check flag scheme compatibility */
1200 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1201 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1202 environment.flag_scheme = FLAG_BOOLEAN;
1203 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1204 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1205 environment.flag_scheme = FLAG_INCREMENTAL;
1206 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1207 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1208 environment.flag_scheme = FLAG_BOOLEAN;
1209 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1210 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1211 environment.flag_scheme = FLAG_INCREMENTAL;
1212 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1213 DEVTYPE(!dev_current) == MTD_ABSENT) {
1214 environment.flag_scheme = FLAG_INCREMENTAL;
1216 fprintf (stderr, "Incompatible flash types!\n");
1220 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1222 if (opts->aes_flag) {
1223 ret = env_aes_cbc_crypt(redundant->data, 0,
1229 crc1_ok = (crc1 == redundant->crc);
1230 flag1 = redundant->flags;
1232 if (crc0_ok && !crc1_ok) {
1234 } else if (!crc0_ok && crc1_ok) {
1236 } else if (!crc0_ok && !crc1_ok) {
1238 "Warning: Bad CRC, using default environment\n");
1239 memcpy (environment.data, default_environment,
1240 sizeof default_environment);
1243 switch (environment.flag_scheme) {
1245 if (flag0 == active_flag &&
1246 flag1 == obsolete_flag) {
1248 } else if (flag0 == obsolete_flag &&
1249 flag1 == active_flag) {
1251 } else if (flag0 == flag1) {
1253 } else if (flag0 == 0xFF) {
1255 } else if (flag1 == 0xFF) {
1261 case FLAG_INCREMENTAL:
1262 if (flag0 == 255 && flag1 == 0)
1264 else if ((flag1 == 255 && flag0 == 0) ||
1267 else /* flag1 > flag0 */
1271 fprintf (stderr, "Unknown flag scheme %u \n",
1272 environment.flag_scheme);
1278 * If we are reading, we don't need the flag and the CRC any
1279 * more, if we are writing, we will re-calculate CRC and update
1280 * flags before writing out
1283 environment.image = addr1;
1284 environment.crc = &redundant->crc;
1285 environment.flags = &redundant->flags;
1286 environment.data = redundant->data;
1289 environment.image = addr0;
1290 /* Other pointers are already set */
1294 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1300 static int check_device_config(int dev)
1305 fd = open(DEVNAME(dev), O_RDONLY);
1308 "Cannot open %s: %s\n",
1309 DEVNAME(dev), strerror(errno));
1313 rc = fstat(fd, &st);
1315 fprintf(stderr, "Cannot stat the file %s\n",
1320 if (S_ISCHR(st.st_mode)) {
1321 struct mtd_info_user mtdinfo;
1322 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1324 fprintf(stderr, "Cannot get MTD information for %s\n",
1328 if (mtdinfo.type != MTD_NORFLASH &&
1329 mtdinfo.type != MTD_NANDFLASH &&
1330 mtdinfo.type != MTD_DATAFLASH &&
1331 mtdinfo.type != MTD_UBIVOLUME) {
1332 fprintf(stderr, "Unsupported flash type %u on %s\n",
1333 mtdinfo.type, DEVNAME(dev));
1336 DEVTYPE(dev) = mtdinfo.type;
1338 DEVTYPE(dev) = MTD_ABSENT;
1346 static int parse_config(struct env_opts *opts)
1351 opts = &default_opts;
1353 #if defined(CONFIG_FILE)
1354 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1355 if (get_config(opts->config_file)) {
1356 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1361 DEVNAME (0) = DEVICE1_NAME;
1362 DEVOFFSET (0) = DEVICE1_OFFSET;
1363 ENVSIZE (0) = ENV1_SIZE;
1364 /* Default values are: erase-size=env-size */
1365 DEVESIZE (0) = ENVSIZE (0);
1366 /* #sectors=env-size/erase-size (rounded up) */
1367 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1368 #ifdef DEVICE1_ESIZE
1369 DEVESIZE (0) = DEVICE1_ESIZE;
1371 #ifdef DEVICE1_ENVSECTORS
1372 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1376 DEVNAME (1) = DEVICE2_NAME;
1377 DEVOFFSET (1) = DEVICE2_OFFSET;
1378 ENVSIZE (1) = ENV2_SIZE;
1379 /* Default values are: erase-size=env-size */
1380 DEVESIZE (1) = ENVSIZE (1);
1381 /* #sectors=env-size/erase-size (rounded up) */
1382 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1383 #ifdef DEVICE2_ESIZE
1384 DEVESIZE (1) = DEVICE2_ESIZE;
1386 #ifdef DEVICE2_ENVSECTORS
1387 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1392 rc = check_device_config(0);
1396 if (HaveRedundEnv) {
1397 rc = check_device_config(1);
1401 if (ENVSIZE(0) != ENVSIZE(1)) {
1402 ENVSIZE(0) = ENVSIZE(1) = min(ENVSIZE(0), ENVSIZE(1));
1404 "Redundant environments have inequal size, set to 0x%08lx\n",
1409 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1411 usable_envsize -= sizeof(char);
1414 usable_envsize &= ~(AES_KEY_LENGTH - 1);
1419 #if defined(CONFIG_FILE)
1420 static int get_config (char *fname)
1428 fp = fopen (fname, "r");
1432 while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1433 /* Skip incomplete conversions and comment strings */
1437 rc = sscanf (dump, "%ms %lx %lx %lx %lx",
1447 DEVNAME(i) = devname;
1450 /* Assume the erase size is the same as the env-size */
1451 DEVESIZE(i) = ENVSIZE(i);
1454 /* Assume enough env sectors to cover the environment */
1455 ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1461 HaveRedundEnv = i - 1;
1462 if (!i) { /* No valid entries found */