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>
37 #include "fw_env_private.h"
40 struct env_opts default_opts = {
42 .config_file = CONFIG_FILE
46 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
48 #define min(x, y) ({ \
49 typeof(x) _min1 = (x); \
50 typeof(y) _min2 = (y); \
51 (void) (&_min1 == &_min2); \
52 _min1 < _min2 ? _min1 : _min2; })
55 const char *devname; /* Device name */
56 long long devoff; /* Device offset */
57 ulong env_size; /* environment size */
58 ulong erase_size; /* device erase size */
59 ulong env_sectors; /* number of environment sectors */
60 uint8_t mtd_type; /* type of the MTD device */
63 static struct envdev_s envdevices[2] =
66 .mtd_type = MTD_ABSENT,
68 .mtd_type = MTD_ABSENT,
71 static int dev_current;
73 #define DEVNAME(i) envdevices[(i)].devname
74 #define DEVOFFSET(i) envdevices[(i)].devoff
75 #define ENVSIZE(i) envdevices[(i)].env_size
76 #define DEVESIZE(i) envdevices[(i)].erase_size
77 #define ENVSECTORS(i) envdevices[(i)].env_sectors
78 #define DEVTYPE(i) envdevices[(i)].mtd_type
80 #define CUR_ENVSIZE ENVSIZE(dev_current)
82 static unsigned long usable_envsize;
83 #define ENV_SIZE usable_envsize
85 struct env_image_single {
86 uint32_t crc; /* CRC32 over data bytes */
90 struct env_image_redundant {
91 uint32_t crc; /* CRC32 over data bytes */
92 unsigned char flags; /* active or obsolete */
105 unsigned char *flags;
107 enum flag_scheme flag_scheme;
110 static struct environment environment = {
111 .flag_scheme = FLAG_NONE,
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 int parse_config(struct env_opts *opts);
126 #if defined(CONFIG_FILE)
127 static int get_config (char *);
130 static char *skip_chars(char *s)
132 for (; *s != '\0'; s++) {
139 static char *skip_blanks(char *s)
141 for (; *s != '\0'; s++) {
149 * s1 is either a simple 'name', or a 'name=value' pair.
150 * s2 is a 'name=value' pair.
151 * If the names match, return the value of s2, else NULL.
153 static char *envmatch(char *s1, char *s2)
155 if (s1 == NULL || s2 == NULL)
161 if (*s1 == '\0' && *(s2 - 1) == '=')
167 * Search the environment for a variable.
168 * Return the value, if found, or NULL, if not found.
170 char *fw_getenv (char *name)
174 for (env = environment.data; *env; env = nxt + 1) {
177 for (nxt = env; *nxt; ++nxt) {
178 if (nxt >= &environment.data[ENV_SIZE]) {
179 fprintf (stderr, "## Error: "
180 "environment not terminated\n");
184 val = envmatch (name, env);
193 * Search the default environment for a variable.
194 * Return the value, if found, or NULL, if not found.
196 char *fw_getdefenv(char *name)
200 for (env = default_environment; *env; env = nxt + 1) {
203 for (nxt = env; *nxt; ++nxt) {
204 if (nxt >= &default_environment[ENV_SIZE]) {
205 fprintf(stderr, "## Error: "
206 "default environment not terminated\n");
210 val = envmatch(name, env);
219 * Print the current definition of one, or more, or all
220 * environment variables
222 int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
226 if (value_only && argc != 1) {
228 "## Error: `-n' option requires exactly one argument\n");
233 opts = &default_opts;
235 if (fw_env_open(opts))
238 if (argc == 0) { /* Print all env variables */
240 for (env = environment.data; *env; env = nxt + 1) {
241 for (nxt = env; *nxt; ++nxt) {
242 if (nxt >= &environment.data[ENV_SIZE]) {
243 fprintf (stderr, "## Error: "
244 "environment not terminated\n");
249 printf ("%s\n", env);
255 for (i = 0; i < argc; ++i) { /* print a subset of env variables */
256 char *name = argv[i];
259 val = fw_getenv(name);
261 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
271 printf("%s=%s\n", name, val);
279 int fw_env_flush(struct env_opts *opts)
284 opts = &default_opts;
289 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
291 /* write environment back to flash */
292 if (flash_io(O_RDWR)) {
294 "Error: can't write fw_env to flash\n");
303 * Set/Clear a single variable in the environment.
304 * This is called in sequence to update the environment
305 * in RAM without updating the copy in flash after each set
307 int fw_env_write(char *name, char *value)
312 int deleting, creating, overwriting;
315 * search if variable with this name already exists
317 for (nxt = env = environment.data; *env; env = nxt + 1) {
318 for (nxt = env; *nxt; ++nxt) {
319 if (nxt >= &environment.data[ENV_SIZE]) {
320 fprintf(stderr, "## Error: "
321 "environment not terminated\n");
326 if ((oldval = envmatch (name, env)) != NULL)
330 deleting = (oldval && !(value && strlen(value)));
331 creating = (!oldval && (value && strlen(value)));
332 overwriting = (oldval && (value && strlen(value)));
334 /* check for permission */
336 if (env_flags_validate_varaccess(name,
337 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
338 printf("Can't delete \"%s\"\n", name);
342 } else if (overwriting) {
343 if (env_flags_validate_varaccess(name,
344 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
345 printf("Can't overwrite \"%s\"\n", name);
348 } else if (env_flags_validate_varaccess(name,
349 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
350 const char *defval = fw_getdefenv(name);
354 if (strcmp(oldval, defval)
356 printf("Can't overwrite \"%s\"\n", name);
361 } else if (creating) {
362 if (env_flags_validate_varaccess(name,
363 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
364 printf("Can't create \"%s\"\n", name);
372 if (deleting || overwriting) {
373 if (*++nxt == '\0') {
378 if ((*env == '\0') && (*nxt == '\0'))
387 if (!value || !strlen(value))
391 * Append new definition at the end
393 for (env = environment.data; *env || *(env + 1); ++env);
394 if (env > environment.data)
398 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
400 len = strlen (name) + 2;
401 /* add '=' for first arg, ' ' for all others */
402 len += strlen(value) + 1;
404 if (len > (&environment.data[ENV_SIZE] - env)) {
406 "Error: environment overflow, \"%s\" deleted\n",
411 while ((*env = *name++) != '\0')
414 while ((*++env = *value++) != '\0')
417 /* end is marked with double '\0' */
424 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
426 * EINVAL - need at least 1 argument
427 * EROFS - certain variables ("ethaddr", "serial#") cannot be
428 * modified or deleted
431 int fw_env_set(int argc, char *argv[], struct env_opts *opts)
442 opts = &default_opts;
445 fprintf(stderr, "## Error: variable name missing\n");
450 if (fw_env_open(opts)) {
451 fprintf(stderr, "Error: environment not initialized\n");
459 if (env_flags_validate_env_set_params(name, valv, valc) < 0) {
465 for (i = 0; i < valc; ++i) {
467 size_t val_len = strlen(val);
470 value[len - 1] = ' ';
472 value = realloc(value, len + val_len + 1);
475 "Cannot malloc %zu bytes: %s\n",
476 len, strerror(errno));
481 memcpy(value + len, val, val_len);
486 fw_env_write(name, value);
490 ret = fw_env_flush(opts);
497 * Parse a file and configure the u-boot variables.
498 * The script file has a very simple format, as follows:
500 * Each line has a couple with name, value:
501 * <white spaces>variable_name<white spaces>variable_value
503 * Both variable_name and variable_value are interpreted as strings.
504 * Any character after <white spaces> and before ending \r\n is interpreted
505 * as variable's value (no comment allowed on these lines !)
507 * Comments are allowed if the first character in the line is #
509 * Returns -1 and sets errno error codes:
513 int fw_parse_script(char *fname, struct env_opts *opts)
516 char dump[1024]; /* Maximum line length in the file */
524 opts = &default_opts;
526 if (fw_env_open(opts)) {
527 fprintf(stderr, "Error: environment not initialized\n");
531 if (strcmp(fname, "-") == 0)
534 fp = fopen(fname, "r");
536 fprintf(stderr, "I cannot open %s for reading\n",
542 while (fgets(dump, sizeof(dump), fp)) {
547 * Read a whole line from the file. If the line is too long
548 * or is not terminated, reports an error and exit.
550 if (dump[len - 1] != '\n') {
552 "Line %d not corrected terminated or too long\n",
558 /* Drop ending line feed / carriage return */
560 if (len && dump[len - 1] == '\r')
563 /* Skip comment or empty lines */
564 if (len == 0 || dump[0] == '#')
568 * Search for variable's name,
569 * remove leading whitespaces
571 name = skip_blanks(dump);
575 /* The first white space is the end of variable name */
576 val = skip_chars(name);
580 if ((val - name) < len)
581 val = skip_blanks(val);
587 fprintf(stderr, "Setting %s : %s\n",
588 name, val ? val : " removed");
591 if (env_flags_validate_type(name, val) < 0) {
597 * If there is an error setting a variable,
598 * try to save the environment and returns an error
600 if (fw_env_write(name, val)) {
602 "fw_env_write returns with error : %s\n",
610 /* Close file if not stdin */
611 if (strcmp(fname, "-") != 0)
614 ret |= fw_env_flush(opts);
622 * environment_end() - compute offset of first byte right after environemnt
623 * @dev - index of enviroment buffer
625 * device offset of first byte right after environemnt
627 off_t environment_end(int dev)
629 /* environment is block aligned */
630 return DEVOFFSET(dev) + ENVSECTORS(dev) * DEVESIZE(dev);
634 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
637 * < 0 - failed to test
639 static int flash_bad_block(int fd, uint8_t mtd_type, loff_t blockstart)
641 if (mtd_type == MTD_NANDFLASH) {
642 int badblock = ioctl(fd, MEMGETBADBLOCK, &blockstart);
645 perror ("Cannot read bad block mark");
651 fprintf (stderr, "Bad block at 0x%llx, skipping\n",
652 (unsigned long long)blockstart);
662 * Read data from flash at an offset into a provided buffer. On NAND it skips
663 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
664 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
666 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
669 size_t blocklen; /* erase / write length - one block on NAND,
671 size_t processed = 0; /* progress counter */
672 size_t readlen = count; /* current read length */
673 off_t block_seek; /* offset inside the current block to the start
675 loff_t blockstart; /* running start of the current block -
676 MEMGETBADBLOCK needs 64 bits */
679 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
681 /* Offset inside a block */
682 block_seek = offset - blockstart;
684 if (DEVTYPE(dev) == MTD_NANDFLASH) {
686 * NAND: calculate which blocks we are reading. We have
687 * to read one block at a time to skip bad blocks.
689 blocklen = DEVESIZE (dev);
691 /* Limit to one block for the first read */
692 if (readlen > blocklen - block_seek)
693 readlen = blocklen - block_seek;
698 /* This only runs once on NOR flash */
699 while (processed < count) {
700 rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
701 if (rc < 0) /* block test failed */
704 if (blockstart + block_seek + readlen > environment_end(dev)) {
705 /* End of range is reached */
707 "Too few good blocks within range\n");
711 if (rc) { /* block is bad */
712 blockstart += blocklen;
717 * If a block is bad, we retry in the next block at the same
718 * offset - see env/nand.c::writeenv()
720 lseek (fd, blockstart + block_seek, SEEK_SET);
722 rc = read (fd, buf + processed, readlen);
724 fprintf (stderr, "Read error on %s: %s\n",
725 DEVNAME (dev), strerror (errno));
729 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
730 rc, (unsigned long long) blockstart + block_seek,
733 processed += readlen;
734 readlen = min (blocklen, count - processed);
736 blockstart += blocklen;
743 * Write count bytes from begin of environment, but stay within
744 * ENVSECTORS(dev) sectors of
745 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
746 * erase and write the whole data at once.
748 static int flash_write_buf(int dev, int fd, void *buf, size_t count)
751 struct erase_info_user erase;
752 size_t blocklen; /* length of NAND block / NOR erase sector */
753 size_t erase_len; /* whole area that can be erased - may include
755 size_t erasesize; /* erase / write length - one block on NAND,
757 size_t processed = 0; /* progress counter */
758 size_t write_total; /* total size to actually write - excluding
760 off_t erase_offset; /* offset to the first erase block (aligned)
762 off_t block_seek; /* offset inside the erase block to the start
764 loff_t blockstart; /* running start of the current block -
765 MEMGETBADBLOCK needs 64 bits */
769 * For mtd devices only offset and size of the environment do matter
771 if (DEVTYPE(dev) == MTD_ABSENT) {
773 erase_len = blocklen;
774 blockstart = DEVOFFSET(dev);
776 write_total = blocklen;
778 blocklen = DEVESIZE(dev);
780 erase_offset = DEVOFFSET(dev);
782 /* Maximum area we may use */
783 erase_len = environment_end(dev) - erase_offset;
785 blockstart = erase_offset;
787 /* Offset inside a block */
788 block_seek = DEVOFFSET(dev) - erase_offset;
791 * Data size we actually write: from the start of the block
792 * to the start of the data, then count bytes of data, and
793 * to the end of the block
795 write_total = ((block_seek + count + blocklen - 1) /
796 blocklen) * blocklen;
800 * Support data anywhere within erase sectors: read out the complete
801 * area to be erased, replace the environment image, write the whole
804 if (write_total > count) {
805 data = malloc (erase_len);
808 "Cannot malloc %zu bytes: %s\n",
809 erase_len, strerror (errno));
813 rc = flash_read_buf(dev, fd, data, write_total, erase_offset);
814 if (write_total != rc)
818 fprintf(stderr, "Preserving data ");
820 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
821 if (block_seek + count != write_total) {
823 fprintf(stderr, " and ");
824 fprintf(stderr, "0x%lx - 0x%lx",
825 (unsigned long) block_seek + count,
826 (unsigned long) write_total - 1);
828 fprintf(stderr, "\n");
830 /* Overwrite the old environment */
831 memcpy (data + block_seek, buf, count);
834 * We get here, iff offset is block-aligned and count is a
835 * multiple of blocklen - see write_total calculation above
840 if (DEVTYPE(dev) == MTD_NANDFLASH) {
842 * NAND: calculate which blocks we are writing. We have
843 * to write one block at a time to skip bad blocks.
845 erasesize = blocklen;
847 erasesize = erase_len;
850 erase.length = erasesize;
852 /* This only runs once on NOR flash and SPI-dataflash */
853 while (processed < write_total) {
854 rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
855 if (rc < 0) /* block test failed */
858 if (blockstart + erasesize > environment_end(dev)) {
859 fprintf (stderr, "End of range reached, aborting\n");
863 if (rc) { /* block is bad */
864 blockstart += blocklen;
868 if (DEVTYPE(dev) != MTD_ABSENT) {
869 erase.start = blockstart;
870 ioctl(fd, MEMUNLOCK, &erase);
871 /* These do not need an explicit erase cycle */
872 if (DEVTYPE(dev) != MTD_DATAFLASH)
873 if (ioctl(fd, MEMERASE, &erase) != 0) {
875 "MTD erase error on %s: %s\n",
876 DEVNAME(dev), strerror(errno));
881 if (lseek (fd, blockstart, SEEK_SET) == -1) {
883 "Seek error on %s: %s\n",
884 DEVNAME (dev), strerror (errno));
889 fprintf(stderr, "Write 0x%llx bytes at 0x%llx\n",
890 (unsigned long long) erasesize,
891 (unsigned long long) blockstart);
893 if (write (fd, data + processed, erasesize) != erasesize) {
894 fprintf (stderr, "Write error on %s: %s\n",
895 DEVNAME (dev), strerror (errno));
899 if (DEVTYPE(dev) != MTD_ABSENT)
900 ioctl(fd, MEMLOCK, &erase);
902 processed += erasesize;
904 blockstart += erasesize;
907 if (write_total > count)
914 * Set obsolete flag at offset - NOR flash only
916 static int flash_flag_obsolete (int dev, int fd, off_t offset)
919 struct erase_info_user erase;
921 erase.start = DEVOFFSET (dev);
922 erase.length = DEVESIZE (dev);
923 /* This relies on the fact, that obsolete_flag == 0 */
924 rc = lseek (fd, offset, SEEK_SET);
926 fprintf (stderr, "Cannot seek to set the flag on %s \n",
930 ioctl (fd, MEMUNLOCK, &erase);
931 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
932 ioctl (fd, MEMLOCK, &erase);
934 perror ("Could not set obsolete flag");
939 static int flash_write (int fd_current, int fd_target, int dev_target)
943 switch (environment.flag_scheme) {
946 case FLAG_INCREMENTAL:
947 (*environment.flags)++;
950 *environment.flags = active_flag;
953 fprintf (stderr, "Unimplemented flash scheme %u \n",
954 environment.flag_scheme);
959 fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
960 DEVOFFSET (dev_target), DEVNAME (dev_target));
963 rc = flash_write_buf(dev_target, fd_target, environment.image,
968 if (environment.flag_scheme == FLAG_BOOLEAN) {
969 /* Have to set obsolete flag */
970 off_t offset = DEVOFFSET (dev_current) +
971 offsetof (struct env_image_redundant, flags);
974 "Setting obsolete flag in environment at 0x%llx on %s\n",
975 DEVOFFSET (dev_current), DEVNAME (dev_current));
977 flash_flag_obsolete (dev_current, fd_current, offset);
983 static int flash_read (int fd)
987 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
988 DEVOFFSET(dev_current));
989 if (rc != CUR_ENVSIZE)
995 static int flash_io (int mode)
997 int fd_current, fd_target, rc, dev_target;
999 /* dev_current: fd_current, erase_current */
1000 fd_current = open (DEVNAME (dev_current), mode);
1001 if (fd_current < 0) {
1003 "Can't open %s: %s\n",
1004 DEVNAME (dev_current), strerror (errno));
1008 if (mode == O_RDWR) {
1009 if (HaveRedundEnv) {
1010 /* switch to next partition for writing */
1011 dev_target = !dev_current;
1012 /* dev_target: fd_target, erase_target */
1013 fd_target = open (DEVNAME (dev_target), mode);
1014 if (fd_target < 0) {
1016 "Can't open %s: %s\n",
1017 DEVNAME (dev_target),
1023 dev_target = dev_current;
1024 fd_target = fd_current;
1027 rc = flash_write (fd_current, fd_target, dev_target);
1029 if (fsync(fd_current) &&
1030 !(errno == EINVAL || errno == EROFS)) {
1032 "fsync failed on %s: %s\n",
1033 DEVNAME (dev_current), strerror (errno));
1036 if (HaveRedundEnv) {
1037 if (fsync(fd_target) &&
1038 !(errno == EINVAL || errno == EROFS)) {
1040 "fsync failed on %s: %s\n",
1041 DEVNAME (dev_current), strerror (errno));
1044 if (close (fd_target)) {
1046 "I/O error on %s: %s\n",
1047 DEVNAME (dev_target),
1053 rc = flash_read (fd_current);
1057 if (close (fd_current)) {
1059 "I/O error on %s: %s\n",
1060 DEVNAME (dev_current), strerror (errno));
1068 * Prevent confusion if running from erased flash memory
1070 int fw_env_open(struct env_opts *opts)
1073 unsigned char flag0;
1077 unsigned char flag1;
1082 struct env_image_single *single;
1083 struct env_image_redundant *redundant;
1086 opts = &default_opts;
1088 if (parse_config(opts)) /* should fill envdevices */
1091 addr0 = calloc(1, CUR_ENVSIZE);
1092 if (addr0 == NULL) {
1094 "Not enough memory for environment (%ld bytes)\n",
1100 /* read environment from FLASH to local buffer */
1101 environment.image = addr0;
1103 if (HaveRedundEnv) {
1105 environment.crc = &redundant->crc;
1106 environment.flags = &redundant->flags;
1107 environment.data = redundant->data;
1110 environment.crc = &single->crc;
1111 environment.flags = NULL;
1112 environment.data = single->data;
1116 if (flash_io(O_RDONLY)) {
1121 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1123 crc0_ok = (crc0 == *environment.crc);
1124 if (!HaveRedundEnv) {
1127 "Warning: Bad CRC, using default environment\n");
1128 memcpy(environment.data, default_environment, sizeof default_environment);
1131 flag0 = *environment.flags;
1134 addr1 = calloc(1, CUR_ENVSIZE);
1135 if (addr1 == NULL) {
1137 "Not enough memory for environment (%ld bytes)\n",
1145 * have to set environment.image for flash_read(), careful -
1146 * other pointers in environment still point inside addr0
1148 environment.image = addr1;
1149 if (flash_io(O_RDONLY)) {
1154 /* Check flag scheme compatibility */
1155 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1156 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1157 environment.flag_scheme = FLAG_BOOLEAN;
1158 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1159 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1160 environment.flag_scheme = FLAG_INCREMENTAL;
1161 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1162 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1163 environment.flag_scheme = FLAG_BOOLEAN;
1164 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1165 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1166 environment.flag_scheme = FLAG_INCREMENTAL;
1167 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1168 DEVTYPE(!dev_current) == MTD_ABSENT) {
1169 environment.flag_scheme = FLAG_INCREMENTAL;
1171 fprintf (stderr, "Incompatible flash types!\n");
1176 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1178 crc1_ok = (crc1 == redundant->crc);
1179 flag1 = redundant->flags;
1181 if (crc0_ok && !crc1_ok) {
1183 } else if (!crc0_ok && crc1_ok) {
1185 } else if (!crc0_ok && !crc1_ok) {
1187 "Warning: Bad CRC, using default environment\n");
1188 memcpy (environment.data, default_environment,
1189 sizeof default_environment);
1192 switch (environment.flag_scheme) {
1194 if (flag0 == active_flag &&
1195 flag1 == obsolete_flag) {
1197 } else if (flag0 == obsolete_flag &&
1198 flag1 == active_flag) {
1200 } else if (flag0 == flag1) {
1202 } else if (flag0 == 0xFF) {
1204 } else if (flag1 == 0xFF) {
1210 case FLAG_INCREMENTAL:
1211 if (flag0 == 255 && flag1 == 0)
1213 else if ((flag1 == 255 && flag0 == 0) ||
1216 else /* flag1 > flag0 */
1220 fprintf (stderr, "Unknown flag scheme %u \n",
1221 environment.flag_scheme);
1227 * If we are reading, we don't need the flag and the CRC any
1228 * more, if we are writing, we will re-calculate CRC and update
1229 * flags before writing out
1232 environment.image = addr1;
1233 environment.crc = &redundant->crc;
1234 environment.flags = &redundant->flags;
1235 environment.data = redundant->data;
1238 environment.image = addr0;
1239 /* Other pointers are already set */
1243 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1259 * Simply free allocated buffer with environment
1261 int fw_env_close(struct env_opts *opts)
1263 if (environment.image)
1264 free(environment.image);
1266 environment.image = NULL;
1271 static int check_device_config(int dev)
1276 fd = open(DEVNAME(dev), O_RDONLY);
1279 "Cannot open %s: %s\n",
1280 DEVNAME(dev), strerror(errno));
1284 rc = fstat(fd, &st);
1286 fprintf(stderr, "Cannot stat the file %s\n",
1291 if (S_ISCHR(st.st_mode)) {
1292 struct mtd_info_user mtdinfo;
1293 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1295 fprintf(stderr, "Cannot get MTD information for %s\n",
1299 if (mtdinfo.type != MTD_NORFLASH &&
1300 mtdinfo.type != MTD_NANDFLASH &&
1301 mtdinfo.type != MTD_DATAFLASH &&
1302 mtdinfo.type != MTD_UBIVOLUME) {
1303 fprintf(stderr, "Unsupported flash type %u on %s\n",
1304 mtdinfo.type, DEVNAME(dev));
1307 DEVTYPE(dev) = mtdinfo.type;
1308 if (DEVESIZE(dev) == 0)
1309 /* Assume the erase size is the same as the env-size */
1310 DEVESIZE(dev) = ENVSIZE(dev);
1313 DEVTYPE(dev) = MTD_ABSENT;
1314 if (DEVESIZE(dev) == 0)
1315 /* Assume the erase size to be 512 bytes */
1316 DEVESIZE(dev) = 0x200;
1319 * Check for negative offsets, treat it as backwards offset
1320 * from the end of the block device
1322 if (DEVOFFSET(dev) < 0) {
1323 rc = ioctl(fd, BLKGETSIZE64, &size);
1325 fprintf(stderr, "Could not get block device size on %s\n",
1330 DEVOFFSET(dev) = DEVOFFSET(dev) + size;
1332 fprintf(stderr, "Calculated device offset 0x%llx on %s\n",
1333 DEVOFFSET(dev), DEVNAME(dev));
1338 if (ENVSECTORS(dev) == 0)
1339 /* Assume enough sectors to cover the environment */
1340 ENVSECTORS(dev) = DIV_ROUND_UP(ENVSIZE(dev), DEVESIZE(dev));
1342 if (DEVOFFSET(dev) % DEVESIZE(dev) != 0) {
1343 fprintf(stderr, "Environment does not start on (erase) block boundary\n");
1348 if (ENVSIZE(dev) > ENVSECTORS(dev) * DEVESIZE(dev)) {
1349 fprintf(stderr, "Environment does not fit into available sectors\n");
1359 static int parse_config(struct env_opts *opts)
1364 opts = &default_opts;
1366 #if defined(CONFIG_FILE)
1367 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1368 if (get_config(opts->config_file)) {
1369 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1374 DEVNAME (0) = DEVICE1_NAME;
1375 DEVOFFSET (0) = DEVICE1_OFFSET;
1376 ENVSIZE (0) = ENV1_SIZE;
1378 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1381 #ifdef DEVICE1_ESIZE
1382 DEVESIZE (0) = DEVICE1_ESIZE;
1384 #ifdef DEVICE1_ENVSECTORS
1385 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1389 DEVNAME (1) = DEVICE2_NAME;
1390 DEVOFFSET (1) = DEVICE2_OFFSET;
1391 ENVSIZE (1) = ENV2_SIZE;
1393 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1396 #ifdef DEVICE2_ESIZE
1397 DEVESIZE (1) = DEVICE2_ESIZE;
1399 #ifdef DEVICE2_ENVSECTORS
1400 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1405 rc = check_device_config(0);
1409 if (HaveRedundEnv) {
1410 rc = check_device_config(1);
1414 if (ENVSIZE(0) != ENVSIZE(1)) {
1416 "Redundant environments have unequal size");
1421 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1423 usable_envsize -= sizeof(char);
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;
1458 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1466 HaveRedundEnv = i - 1;
1467 if (!i) { /* No valid entries found */