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)
255 if (value_only && argc != 1) {
257 "## Error: `-n' option requires exactly one argument\n");
262 opts = &default_opts;
264 if (fw_env_open(opts))
267 if (argc == 0) { /* Print all env variables */
269 for (env = environment.data; *env; env = nxt + 1) {
270 for (nxt = env; *nxt; ++nxt) {
271 if (nxt >= &environment.data[ENV_SIZE]) {
272 fprintf (stderr, "## Error: "
273 "environment not terminated\n");
278 printf ("%s\n", env);
283 for (i = 0; i < argc; ++i) { /* print a subset of env variables */
284 char *name = argv[i];
287 val = fw_getenv(name);
289 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
299 printf("%s=%s\n", name, val);
305 int fw_env_close(struct env_opts *opts)
310 opts = &default_opts;
312 if (opts->aes_flag) {
313 ret = env_aes_cbc_crypt(environment.data, 1,
317 "Error: can't encrypt env for flash\n");
325 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
327 /* write environment back to flash */
328 if (flash_io(O_RDWR)) {
330 "Error: can't write fw_env to flash\n");
339 * Set/Clear a single variable in the environment.
340 * This is called in sequence to update the environment
341 * in RAM without updating the copy in flash after each set
343 int fw_env_write(char *name, char *value)
348 int deleting, creating, overwriting;
351 * search if variable with this name already exists
353 for (nxt = env = environment.data; *env; env = nxt + 1) {
354 for (nxt = env; *nxt; ++nxt) {
355 if (nxt >= &environment.data[ENV_SIZE]) {
356 fprintf(stderr, "## Error: "
357 "environment not terminated\n");
362 if ((oldval = envmatch (name, env)) != NULL)
366 deleting = (oldval && !(value && strlen(value)));
367 creating = (!oldval && (value && strlen(value)));
368 overwriting = (oldval && (value && strlen(value)));
370 /* check for permission */
372 if (env_flags_validate_varaccess(name,
373 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
374 printf("Can't delete \"%s\"\n", name);
378 } else if (overwriting) {
379 if (env_flags_validate_varaccess(name,
380 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
381 printf("Can't overwrite \"%s\"\n", name);
384 } else if (env_flags_validate_varaccess(name,
385 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
386 const char *defval = fw_getdefenv(name);
390 if (strcmp(oldval, defval)
392 printf("Can't overwrite \"%s\"\n", name);
397 } else if (creating) {
398 if (env_flags_validate_varaccess(name,
399 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
400 printf("Can't create \"%s\"\n", name);
408 if (deleting || overwriting) {
409 if (*++nxt == '\0') {
414 if ((*env == '\0') && (*nxt == '\0'))
423 if (!value || !strlen(value))
427 * Append new definition at the end
429 for (env = environment.data; *env || *(env + 1); ++env);
430 if (env > environment.data)
434 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
436 len = strlen (name) + 2;
437 /* add '=' for first arg, ' ' for all others */
438 len += strlen(value) + 1;
440 if (len > (&environment.data[ENV_SIZE] - env)) {
442 "Error: environment overflow, \"%s\" deleted\n",
447 while ((*env = *name++) != '\0')
450 while ((*++env = *value++) != '\0')
453 /* end is marked with double '\0' */
460 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
462 * EINVAL - need at least 1 argument
463 * EROFS - certain variables ("ethaddr", "serial#") cannot be
464 * modified or deleted
467 int fw_setenv(int argc, char *argv[], struct env_opts *opts)
476 opts = &default_opts;
479 fprintf(stderr, "## Error: variable name missing\n");
484 if (fw_env_open(opts)) {
485 fprintf(stderr, "Error: environment not initialized\n");
493 if (env_flags_validate_env_set_params(name, valv, valc) < 0)
497 for (i = 0; i < valc; ++i) {
499 size_t val_len = strlen(val);
502 value[len - 1] = ' ';
503 value = realloc(value, len + val_len + 1);
506 "Cannot malloc %zu bytes: %s\n",
507 len, strerror(errno));
511 memcpy(value + len, val, val_len);
516 fw_env_write(name, value);
520 return fw_env_close(opts);
524 * Parse a file and configure the u-boot variables.
525 * The script file has a very simple format, as follows:
527 * Each line has a couple with name, value:
528 * <white spaces>variable_name<white spaces>variable_value
530 * Both variable_name and variable_value are interpreted as strings.
531 * Any character after <white spaces> and before ending \r\n is interpreted
532 * as variable's value (no comment allowed on these lines !)
534 * Comments are allowed if the first character in the line is #
536 * Returns -1 and sets errno error codes:
540 int fw_parse_script(char *fname, struct env_opts *opts)
543 char dump[1024]; /* Maximum line length in the file */
551 opts = &default_opts;
553 if (fw_env_open(opts)) {
554 fprintf(stderr, "Error: environment not initialized\n");
558 if (strcmp(fname, "-") == 0)
561 fp = fopen(fname, "r");
563 fprintf(stderr, "I cannot open %s for reading\n",
569 while (fgets(dump, sizeof(dump), fp)) {
574 * Read a whole line from the file. If the line is too long
575 * or is not terminated, reports an error and exit.
577 if (dump[len - 1] != '\n') {
579 "Line %d not corrected terminated or too long\n",
585 /* Drop ending line feed / carriage return */
587 if (len && dump[len - 1] == '\r')
590 /* Skip comment or empty lines */
591 if (len == 0 || dump[0] == '#')
595 * Search for variable's name,
596 * remove leading whitespaces
598 name = skip_blanks(dump);
602 /* The first white space is the end of variable name */
603 val = skip_chars(name);
607 if ((val - name) < len)
608 val = skip_blanks(val);
614 fprintf(stderr, "Setting %s : %s\n",
615 name, val ? val : " removed");
618 if (env_flags_validate_type(name, val) < 0) {
624 * If there is an error setting a variable,
625 * try to save the environment and returns an error
627 if (fw_env_write(name, val)) {
629 "fw_env_write returns with error : %s\n",
637 /* Close file if not stdin */
638 if (strcmp(fname, "-") != 0)
641 ret |= fw_env_close(opts);
647 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
650 * < 0 - failed to test
652 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
654 if (mtd_type == MTD_NANDFLASH) {
655 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
658 perror ("Cannot read bad block mark");
664 fprintf (stderr, "Bad block at 0x%llx, "
665 "skipping\n", *blockstart);
675 * Read data from flash at an offset into a provided buffer. On NAND it skips
676 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
677 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
679 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
680 off_t offset, uint8_t mtd_type)
682 size_t blocklen; /* erase / write length - one block on NAND,
684 size_t processed = 0; /* progress counter */
685 size_t readlen = count; /* current read length */
686 off_t top_of_range; /* end of the last block we may use */
687 off_t block_seek; /* offset inside the current block to the start
689 loff_t blockstart; /* running start of the current block -
690 MEMGETBADBLOCK needs 64 bits */
693 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
695 /* Offset inside a block */
696 block_seek = offset - blockstart;
698 if (mtd_type == MTD_NANDFLASH) {
700 * NAND: calculate which blocks we are reading. We have
701 * to read one block at a time to skip bad blocks.
703 blocklen = DEVESIZE (dev);
706 * To calculate the top of the range, we have to use the
707 * global DEVOFFSET (dev), which can be different from offset
709 top_of_range = ((DEVOFFSET(dev) / blocklen) +
710 ENVSECTORS (dev)) * blocklen;
712 /* Limit to one block for the first read */
713 if (readlen > blocklen - block_seek)
714 readlen = blocklen - block_seek;
717 top_of_range = offset + count;
720 /* This only runs once on NOR flash */
721 while (processed < count) {
722 rc = flash_bad_block (fd, mtd_type, &blockstart);
723 if (rc < 0) /* block test failed */
726 if (blockstart + block_seek + readlen > top_of_range) {
727 /* End of range is reached */
729 "Too few good blocks within range\n");
733 if (rc) { /* block is bad */
734 blockstart += blocklen;
739 * If a block is bad, we retry in the next block at the same
740 * offset - see common/env_nand.c::writeenv()
742 lseek (fd, blockstart + block_seek, SEEK_SET);
744 rc = read (fd, buf + processed, readlen);
746 fprintf (stderr, "Read error on %s: %s\n",
747 DEVNAME (dev), strerror (errno));
751 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
752 rc, blockstart + block_seek, DEVNAME(dev));
754 processed += readlen;
755 readlen = min (blocklen, count - processed);
757 blockstart += blocklen;
764 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
765 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
766 * erase and write the whole data at once.
768 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
769 off_t offset, uint8_t mtd_type)
772 struct erase_info_user erase;
773 size_t blocklen; /* length of NAND block / NOR erase sector */
774 size_t erase_len; /* whole area that can be erased - may include
776 size_t erasesize; /* erase / write length - one block on NAND,
778 size_t processed = 0; /* progress counter */
779 size_t write_total; /* total size to actually write - excluding
781 off_t erase_offset; /* offset to the first erase block (aligned)
783 off_t block_seek; /* offset inside the erase block to the start
785 off_t top_of_range; /* end of the last block we may use */
786 loff_t blockstart; /* running start of the current block -
787 MEMGETBADBLOCK needs 64 bits */
791 * For mtd devices only offset and size of the environment do matter
793 if (mtd_type == MTD_ABSENT) {
795 top_of_range = offset + count;
796 erase_len = blocklen;
799 write_total = blocklen;
801 blocklen = DEVESIZE(dev);
803 top_of_range = ((DEVOFFSET(dev) / blocklen) +
804 ENVSECTORS(dev)) * blocklen;
806 erase_offset = (offset / blocklen) * blocklen;
808 /* Maximum area we may use */
809 erase_len = top_of_range - erase_offset;
811 blockstart = erase_offset;
812 /* Offset inside a block */
813 block_seek = offset - erase_offset;
816 * Data size we actually write: from the start of the block
817 * to the start of the data, then count bytes of data, and
818 * to the end of the block
820 write_total = ((block_seek + count + blocklen - 1) /
821 blocklen) * blocklen;
825 * Support data anywhere within erase sectors: read out the complete
826 * area to be erased, replace the environment image, write the whole
829 if (write_total > count) {
830 data = malloc (erase_len);
833 "Cannot malloc %zu bytes: %s\n",
834 erase_len, strerror (errno));
838 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
840 if (write_total != rc)
844 fprintf(stderr, "Preserving data ");
846 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
847 if (block_seek + count != write_total) {
849 fprintf(stderr, " and ");
850 fprintf(stderr, "0x%lx - 0x%x",
851 block_seek + count, write_total - 1);
853 fprintf(stderr, "\n");
855 /* Overwrite the old environment */
856 memcpy (data + block_seek, buf, count);
859 * We get here, iff offset is block-aligned and count is a
860 * multiple of blocklen - see write_total calculation above
865 if (mtd_type == MTD_NANDFLASH) {
867 * NAND: calculate which blocks we are writing. We have
868 * to write one block at a time to skip bad blocks.
870 erasesize = blocklen;
872 erasesize = erase_len;
875 erase.length = erasesize;
877 /* This only runs once on NOR flash and SPI-dataflash */
878 while (processed < write_total) {
879 rc = flash_bad_block (fd, mtd_type, &blockstart);
880 if (rc < 0) /* block test failed */
883 if (blockstart + erasesize > top_of_range) {
884 fprintf (stderr, "End of range reached, aborting\n");
888 if (rc) { /* block is bad */
889 blockstart += blocklen;
893 if (mtd_type != MTD_ABSENT) {
894 erase.start = blockstart;
895 ioctl(fd, MEMUNLOCK, &erase);
896 /* These do not need an explicit erase cycle */
897 if (mtd_type != MTD_DATAFLASH)
898 if (ioctl(fd, MEMERASE, &erase) != 0) {
900 "MTD erase error on %s: %s\n",
901 DEVNAME(dev), strerror(errno));
906 if (lseek (fd, blockstart, SEEK_SET) == -1) {
908 "Seek error on %s: %s\n",
909 DEVNAME (dev), strerror (errno));
914 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
917 if (write (fd, data + processed, erasesize) != erasesize) {
918 fprintf (stderr, "Write error on %s: %s\n",
919 DEVNAME (dev), strerror (errno));
923 if (mtd_type != MTD_ABSENT)
924 ioctl(fd, MEMLOCK, &erase);
926 processed += erasesize;
928 blockstart += erasesize;
931 if (write_total > count)
938 * Set obsolete flag at offset - NOR flash only
940 static int flash_flag_obsolete (int dev, int fd, off_t offset)
943 struct erase_info_user erase;
945 erase.start = DEVOFFSET (dev);
946 erase.length = DEVESIZE (dev);
947 /* This relies on the fact, that obsolete_flag == 0 */
948 rc = lseek (fd, offset, SEEK_SET);
950 fprintf (stderr, "Cannot seek to set the flag on %s \n",
954 ioctl (fd, MEMUNLOCK, &erase);
955 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
956 ioctl (fd, MEMLOCK, &erase);
958 perror ("Could not set obsolete flag");
963 /* Encrypt or decrypt the environment before writing or reading it. */
964 static int env_aes_cbc_crypt(char *payload, const int enc, uint8_t *key)
966 uint8_t *data = (uint8_t *)payload;
967 const int len = usable_envsize;
968 uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
971 /* First we expand the key. */
972 aes_expand_key(key, key_exp);
974 /* Calculate the number of AES blocks to encrypt. */
975 aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
978 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
980 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
985 static int flash_write (int fd_current, int fd_target, int dev_target)
989 switch (environment.flag_scheme) {
992 case FLAG_INCREMENTAL:
993 (*environment.flags)++;
996 *environment.flags = active_flag;
999 fprintf (stderr, "Unimplemented flash scheme %u \n",
1000 environment.flag_scheme);
1005 fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
1006 DEVOFFSET (dev_target), DEVNAME (dev_target));
1009 rc = flash_write_buf(dev_target, fd_target, environment.image,
1010 CUR_ENVSIZE, DEVOFFSET(dev_target),
1011 DEVTYPE(dev_target));
1015 if (environment.flag_scheme == FLAG_BOOLEAN) {
1016 /* Have to set obsolete flag */
1017 off_t offset = DEVOFFSET (dev_current) +
1018 offsetof (struct env_image_redundant, flags);
1021 "Setting obsolete flag in environment at 0x%llx on %s\n",
1022 DEVOFFSET (dev_current), DEVNAME (dev_current));
1024 flash_flag_obsolete (dev_current, fd_current, offset);
1030 static int flash_read (int fd)
1034 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1035 DEVOFFSET(dev_current), DEVTYPE(dev_current));
1036 if (rc != CUR_ENVSIZE)
1042 static int flash_io (int mode)
1044 int fd_current, fd_target, rc, dev_target;
1046 /* dev_current: fd_current, erase_current */
1047 fd_current = open (DEVNAME (dev_current), mode);
1048 if (fd_current < 0) {
1050 "Can't open %s: %s\n",
1051 DEVNAME (dev_current), strerror (errno));
1055 if (mode == O_RDWR) {
1056 if (HaveRedundEnv) {
1057 /* switch to next partition for writing */
1058 dev_target = !dev_current;
1059 /* dev_target: fd_target, erase_target */
1060 fd_target = open (DEVNAME (dev_target), mode);
1061 if (fd_target < 0) {
1063 "Can't open %s: %s\n",
1064 DEVNAME (dev_target),
1070 dev_target = dev_current;
1071 fd_target = fd_current;
1074 rc = flash_write (fd_current, fd_target, dev_target);
1076 if (HaveRedundEnv) {
1077 if (close (fd_target)) {
1079 "I/O error on %s: %s\n",
1080 DEVNAME (dev_target),
1086 rc = flash_read (fd_current);
1090 if (close (fd_current)) {
1092 "I/O error on %s: %s\n",
1093 DEVNAME (dev_current), strerror (errno));
1101 * Prevent confusion if running from erased flash memory
1103 int fw_env_open(struct env_opts *opts)
1106 unsigned char flag0;
1110 unsigned char flag1;
1115 struct env_image_single *single;
1116 struct env_image_redundant *redundant;
1119 opts = &default_opts;
1121 if (parse_config(opts)) /* should fill envdevices */
1124 addr0 = calloc(1, CUR_ENVSIZE);
1125 if (addr0 == NULL) {
1127 "Not enough memory for environment (%ld bytes)\n",
1132 /* read environment from FLASH to local buffer */
1133 environment.image = addr0;
1135 if (HaveRedundEnv) {
1137 environment.crc = &redundant->crc;
1138 environment.flags = &redundant->flags;
1139 environment.data = redundant->data;
1142 environment.crc = &single->crc;
1143 environment.flags = NULL;
1144 environment.data = single->data;
1148 if (flash_io (O_RDONLY))
1151 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1153 if (opts->aes_flag) {
1154 ret = env_aes_cbc_crypt(environment.data, 0,
1160 crc0_ok = (crc0 == *environment.crc);
1161 if (!HaveRedundEnv) {
1164 "Warning: Bad CRC, using default environment\n");
1165 memcpy(environment.data, default_environment, sizeof default_environment);
1168 flag0 = *environment.flags;
1171 addr1 = calloc(1, CUR_ENVSIZE);
1172 if (addr1 == NULL) {
1174 "Not enough memory for environment (%ld bytes)\n",
1181 * have to set environment.image for flash_read(), careful -
1182 * other pointers in environment still point inside addr0
1184 environment.image = addr1;
1185 if (flash_io (O_RDONLY))
1188 /* Check flag scheme compatibility */
1189 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1190 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1191 environment.flag_scheme = FLAG_BOOLEAN;
1192 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1193 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1194 environment.flag_scheme = FLAG_INCREMENTAL;
1195 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1196 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1197 environment.flag_scheme = FLAG_BOOLEAN;
1198 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1199 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1200 environment.flag_scheme = FLAG_INCREMENTAL;
1201 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1202 DEVTYPE(!dev_current) == MTD_ABSENT) {
1203 environment.flag_scheme = FLAG_INCREMENTAL;
1205 fprintf (stderr, "Incompatible flash types!\n");
1209 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1211 if (opts->aes_flag) {
1212 ret = env_aes_cbc_crypt(redundant->data, 0,
1218 crc1_ok = (crc1 == redundant->crc);
1219 flag1 = redundant->flags;
1221 if (crc0_ok && !crc1_ok) {
1223 } else if (!crc0_ok && crc1_ok) {
1225 } else if (!crc0_ok && !crc1_ok) {
1227 "Warning: Bad CRC, using default environment\n");
1228 memcpy (environment.data, default_environment,
1229 sizeof default_environment);
1232 switch (environment.flag_scheme) {
1234 if (flag0 == active_flag &&
1235 flag1 == obsolete_flag) {
1237 } else if (flag0 == obsolete_flag &&
1238 flag1 == active_flag) {
1240 } else if (flag0 == flag1) {
1242 } else if (flag0 == 0xFF) {
1244 } else if (flag1 == 0xFF) {
1250 case FLAG_INCREMENTAL:
1251 if (flag0 == 255 && flag1 == 0)
1253 else if ((flag1 == 255 && flag0 == 0) ||
1256 else /* flag1 > flag0 */
1260 fprintf (stderr, "Unknown flag scheme %u \n",
1261 environment.flag_scheme);
1267 * If we are reading, we don't need the flag and the CRC any
1268 * more, if we are writing, we will re-calculate CRC and update
1269 * flags before writing out
1272 environment.image = addr1;
1273 environment.crc = &redundant->crc;
1274 environment.flags = &redundant->flags;
1275 environment.data = redundant->data;
1278 environment.image = addr0;
1279 /* Other pointers are already set */
1283 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1289 static int check_device_config(int dev)
1294 fd = open(DEVNAME(dev), O_RDONLY);
1297 "Cannot open %s: %s\n",
1298 DEVNAME(dev), strerror(errno));
1302 rc = fstat(fd, &st);
1304 fprintf(stderr, "Cannot stat the file %s\n",
1309 if (S_ISCHR(st.st_mode)) {
1310 struct mtd_info_user mtdinfo;
1311 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1313 fprintf(stderr, "Cannot get MTD information for %s\n",
1317 if (mtdinfo.type != MTD_NORFLASH &&
1318 mtdinfo.type != MTD_NANDFLASH &&
1319 mtdinfo.type != MTD_DATAFLASH &&
1320 mtdinfo.type != MTD_UBIVOLUME) {
1321 fprintf(stderr, "Unsupported flash type %u on %s\n",
1322 mtdinfo.type, DEVNAME(dev));
1325 DEVTYPE(dev) = mtdinfo.type;
1328 DEVTYPE(dev) = MTD_ABSENT;
1331 * Check for negative offsets, treat it as backwards offset
1332 * from the end of the block device
1334 if (DEVOFFSET(dev) < 0) {
1335 rc = ioctl(fd, BLKGETSIZE64, &size);
1337 fprintf(stderr, "Could not get block device size on %s\n",
1342 DEVOFFSET(dev) = DEVOFFSET(dev) + size;
1344 fprintf(stderr, "Calculated device offset 0x%llx on %s\n",
1345 DEVOFFSET(dev), DEVNAME(dev));
1355 static int parse_config(struct env_opts *opts)
1360 opts = &default_opts;
1362 #if defined(CONFIG_FILE)
1363 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1364 if (get_config(opts->config_file)) {
1365 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1370 DEVNAME (0) = DEVICE1_NAME;
1371 DEVOFFSET (0) = DEVICE1_OFFSET;
1372 ENVSIZE (0) = ENV1_SIZE;
1373 /* Default values are: erase-size=env-size */
1374 DEVESIZE (0) = ENVSIZE (0);
1375 /* #sectors=env-size/erase-size (rounded up) */
1376 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1377 #ifdef DEVICE1_ESIZE
1378 DEVESIZE (0) = DEVICE1_ESIZE;
1380 #ifdef DEVICE1_ENVSECTORS
1381 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1385 DEVNAME (1) = DEVICE2_NAME;
1386 DEVOFFSET (1) = DEVICE2_OFFSET;
1387 ENVSIZE (1) = ENV2_SIZE;
1388 /* Default values are: erase-size=env-size */
1389 DEVESIZE (1) = ENVSIZE (1);
1390 /* #sectors=env-size/erase-size (rounded up) */
1391 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1392 #ifdef DEVICE2_ESIZE
1393 DEVESIZE (1) = DEVICE2_ESIZE;
1395 #ifdef DEVICE2_ENVSECTORS
1396 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1401 rc = check_device_config(0);
1405 if (HaveRedundEnv) {
1406 rc = check_device_config(1);
1410 if (ENVSIZE(0) != ENVSIZE(1)) {
1411 ENVSIZE(0) = ENVSIZE(1) = min(ENVSIZE(0), ENVSIZE(1));
1413 "Redundant environments have inequal size, set to 0x%08lx\n",
1418 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1420 usable_envsize -= sizeof(char);
1423 usable_envsize &= ~(AES_KEY_LENGTH - 1);
1428 #if defined(CONFIG_FILE)
1429 static int get_config (char *fname)
1437 fp = fopen (fname, "r");
1441 while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1442 /* Skip incomplete conversions and comment strings */
1446 rc = sscanf(dump, "%ms %lli %lx %lx %lx",
1456 DEVNAME(i) = devname;
1459 /* Assume the erase size is the same as the env-size */
1460 DEVESIZE(i) = ENVSIZE(i);
1463 /* Assume enough env sectors to cover the environment */
1464 ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1470 HaveRedundEnv = i - 1;
1471 if (!i) { /* No valid entries found */