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>
19 #include <linux/stringify.h>
25 #include <sys/types.h>
26 #include <sys/ioctl.h>
33 # include <linux/mtd/mtd.h>
35 # define __user /* nothing */
36 # include <mtd/mtd-user.h>
39 #include <mtd/ubi-user.h>
41 #include "fw_env_private.h"
44 struct env_opts default_opts = {
46 .config_file = CONFIG_FILE
50 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
52 #define min(x, y) ({ \
53 typeof(x) _min1 = (x); \
54 typeof(y) _min2 = (y); \
55 (void) (&_min1 == &_min2); \
56 _min1 < _min2 ? _min1 : _min2; })
59 const char *devname; /* Device name */
60 long long devoff; /* Device offset */
61 ulong env_size; /* environment size */
62 ulong erase_size; /* device erase size */
63 ulong env_sectors; /* number of environment sectors */
64 uint8_t mtd_type; /* type of the MTD device */
65 int is_ubi; /* set if we use UBI volume */
68 static struct envdev_s envdevices[2] = {
70 .mtd_type = MTD_ABSENT,
72 .mtd_type = MTD_ABSENT,
76 static int dev_current;
78 #define DEVNAME(i) envdevices[(i)].devname
79 #define DEVOFFSET(i) envdevices[(i)].devoff
80 #define ENVSIZE(i) envdevices[(i)].env_size
81 #define DEVESIZE(i) envdevices[(i)].erase_size
82 #define ENVSECTORS(i) envdevices[(i)].env_sectors
83 #define DEVTYPE(i) envdevices[(i)].mtd_type
84 #define IS_UBI(i) envdevices[(i)].is_ubi
86 #define CUR_ENVSIZE ENVSIZE(dev_current)
88 static unsigned long usable_envsize;
89 #define ENV_SIZE usable_envsize
91 struct env_image_single {
92 uint32_t crc; /* CRC32 over data bytes */
96 struct env_image_redundant {
97 uint32_t crc; /* CRC32 over data bytes */
98 unsigned char flags; /* active or obsolete */
111 unsigned char *flags;
113 enum flag_scheme flag_scheme;
116 static struct environment environment = {
117 .flag_scheme = FLAG_NONE,
120 static int have_redund_env;
122 static unsigned char active_flag = 1;
123 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
124 static unsigned char obsolete_flag = 0;
126 #define DEFAULT_ENV_INSTANCE_STATIC
127 #include <env_default.h>
129 #define UBI_DEV_START "/dev/ubi"
130 #define UBI_SYSFS "/sys/class/ubi"
131 #define UBI_VOL_NAME_PATT "ubi%d_%d"
133 static int is_ubi_devname(const char *devname)
135 return !strncmp(devname, UBI_DEV_START, sizeof(UBI_DEV_START) - 1);
138 static int ubi_check_volume_sysfs_name(const char *volume_sysfs_name,
146 strcpy(path, UBI_SYSFS "/");
147 strcat(path, volume_sysfs_name);
148 strcat(path, "/name");
150 file = fopen(path, "r");
154 ret = fscanf(file, "%ms", &name);
156 if (ret <= 0 || !name) {
158 "Failed to read from file %s, ret = %d, name = %s\n",
163 if (!strcmp(name, volname)) {
172 static int ubi_get_volnum_by_name(int devnum, const char *volname)
175 struct dirent *dirent;
180 sysfs_ubi = opendir(UBI_SYSFS);
185 fprintf(stderr, "Looking for volume name \"%s\"\n", volname);
189 dirent = readdir(sysfs_ubi);
193 ret = sscanf(dirent->d_name, UBI_VOL_NAME_PATT,
194 &tmp_devnum, &volnum);
195 if (ret == 2 && devnum == tmp_devnum) {
196 if (ubi_check_volume_sysfs_name(dirent->d_name,
205 static int ubi_get_devnum_by_devname(const char *devname)
210 ret = sscanf(devname + sizeof(UBI_DEV_START) - 1, "%d", &devnum);
217 static const char *ubi_get_volume_devname(const char *devname,
220 char *volume_devname;
225 devnum = ubi_get_devnum_by_devname(devname);
229 volnum = ubi_get_volnum_by_name(devnum, volname);
233 ret = asprintf(&volume_devname, "%s_%d", devname, volnum);
238 fprintf(stderr, "Found ubi volume \"%s:%s\" -> %s\n",
239 devname, volname, volume_devname);
242 return volume_devname;
245 static void ubi_check_dev(unsigned int dev_id)
247 char *devname = (char *)DEVNAME(dev_id);
249 const char *volname = NULL;
250 const char *volume_devname;
252 if (!is_ubi_devname(DEVNAME(dev_id)))
257 for (pname = devname; *pname != '\0'; pname++) {
266 /* Let's find real volume device name */
267 volume_devname = ubi_get_volume_devname(devname, volname);
268 if (!volume_devname) {
269 fprintf(stderr, "Didn't found ubi volume \"%s\"\n",
275 DEVNAME(dev_id) = volume_devname;
279 static int ubi_update_start(int fd, int64_t bytes)
281 if (ioctl(fd, UBI_IOCVOLUP, &bytes))
286 static int ubi_read(int fd, void *buf, size_t count)
291 ret = read(fd, buf, count);
301 * Happens in case of too short volume data size. If we
302 * return error status we will fail it will be treated
303 * as UBI device error.
305 * Leave catching this error to CRC check.
307 fprintf(stderr, "Warning: end of data on ubi volume\n");
309 } else if (errno == EBADF) {
311 * Happens in case of corrupted volume. The same as
312 * above, we cannot return error now, as we will still
313 * be able to successfully write environment later.
315 fprintf(stderr, "Warning: corrupted volume?\n");
317 } else if (errno == EINTR) {
321 fprintf(stderr, "Cannot read %u bytes from ubi volume, %s\n",
322 (unsigned int)count, strerror(errno));
329 static int ubi_write(int fd, const void *buf, size_t count)
334 ret = write(fd, buf, count);
336 if (ret < 0 && errno == EINTR)
339 fprintf(stderr, "Cannot write %u bytes to ubi volume\n",
340 (unsigned int)count);
351 static int flash_io(int mode);
352 static int parse_config(struct env_opts *opts);
354 #if defined(CONFIG_FILE)
355 static int get_config(char *);
358 static char *skip_chars(char *s)
360 for (; *s != '\0'; s++) {
361 if (isblank(*s) || *s == '=')
367 static char *skip_blanks(char *s)
369 for (; *s != '\0'; s++) {
377 * s1 is either a simple 'name', or a 'name=value' pair.
378 * s2 is a 'name=value' pair.
379 * If the names match, return the value of s2, else NULL.
381 static char *envmatch(char *s1, char *s2)
383 if (s1 == NULL || s2 == NULL)
389 if (*s1 == '\0' && *(s2 - 1) == '=')
395 * Search the environment for a variable.
396 * Return the value, if found, or NULL, if not found.
398 char *fw_getenv(char *name)
402 for (env = environment.data; *env; env = nxt + 1) {
405 for (nxt = env; *nxt; ++nxt) {
406 if (nxt >= &environment.data[ENV_SIZE]) {
407 fprintf(stderr, "## Error: "
408 "environment not terminated\n");
412 val = envmatch(name, env);
421 * Search the default environment for a variable.
422 * Return the value, if found, or NULL, if not found.
424 char *fw_getdefenv(char *name)
428 for (env = default_environment; *env; env = nxt + 1) {
431 for (nxt = env; *nxt; ++nxt) {
432 if (nxt >= &default_environment[ENV_SIZE]) {
433 fprintf(stderr, "## Error: "
434 "default environment not terminated\n");
438 val = envmatch(name, env);
447 * Print the current definition of one, or more, or all
448 * environment variables
450 int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
454 if (value_only && argc != 1) {
456 "## Error: `-n'/`--noheader' option requires exactly one argument\n");
461 opts = &default_opts;
463 if (fw_env_open(opts))
466 if (argc == 0) { /* Print all env variables */
468 for (env = environment.data; *env; env = nxt + 1) {
469 for (nxt = env; *nxt; ++nxt) {
470 if (nxt >= &environment.data[ENV_SIZE]) {
471 fprintf(stderr, "## Error: "
472 "environment not terminated\n");
483 for (i = 0; i < argc; ++i) { /* print a subset of env variables */
484 char *name = argv[i];
487 val = fw_getenv(name);
489 fprintf(stderr, "## Error: \"%s\" not defined\n", name);
499 printf("%s=%s\n", name, val);
507 int fw_env_flush(struct env_opts *opts)
510 opts = &default_opts;
515 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
517 /* write environment back to flash */
518 if (flash_io(O_RDWR)) {
519 fprintf(stderr, "Error: can't write fw_env to flash\n");
527 * Set/Clear a single variable in the environment.
528 * This is called in sequence to update the environment
529 * in RAM without updating the copy in flash after each set
531 int fw_env_write(char *name, char *value)
536 int deleting, creating, overwriting;
539 * search if variable with this name already exists
541 for (nxt = env = environment.data; *env; env = nxt + 1) {
542 for (nxt = env; *nxt; ++nxt) {
543 if (nxt >= &environment.data[ENV_SIZE]) {
544 fprintf(stderr, "## Error: "
545 "environment not terminated\n");
550 oldval = envmatch(name, env);
555 deleting = (oldval && !(value && strlen(value)));
556 creating = (!oldval && (value && strlen(value)));
557 overwriting = (oldval && (value && strlen(value)));
559 /* check for permission */
561 if (env_flags_validate_varaccess(name,
562 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
563 printf("Can't delete \"%s\"\n", name);
567 } else if (overwriting) {
568 if (env_flags_validate_varaccess(name,
569 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
570 printf("Can't overwrite \"%s\"\n", name);
573 } else if (env_flags_validate_varaccess(name,
574 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
575 const char *defval = fw_getdefenv(name);
579 if (strcmp(oldval, defval)
581 printf("Can't overwrite \"%s\"\n", name);
586 } else if (creating) {
587 if (env_flags_validate_varaccess(name,
588 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
589 printf("Can't create \"%s\"\n", name);
597 if (deleting || overwriting) {
598 if (*++nxt == '\0') {
603 if ((*env == '\0') && (*nxt == '\0'))
612 if (!value || !strlen(value))
616 * Append new definition at the end
618 for (env = environment.data; *env || *(env + 1); ++env)
620 if (env > environment.data)
624 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
626 len = strlen(name) + 2;
627 /* add '=' for first arg, ' ' for all others */
628 len += strlen(value) + 1;
630 if (len > (&environment.data[ENV_SIZE] - env)) {
632 "Error: environment overflow, \"%s\" deleted\n", name);
636 while ((*env = *name++) != '\0')
639 while ((*++env = *value++) != '\0')
642 /* end is marked with double '\0' */
649 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
651 * EINVAL - need at least 1 argument
652 * EROFS - certain variables ("ethaddr", "serial#") cannot be
653 * modified or deleted
656 int fw_env_set(int argc, char *argv[], struct env_opts *opts)
667 opts = &default_opts;
670 fprintf(stderr, "## Error: variable name missing\n");
675 if (fw_env_open(opts)) {
676 fprintf(stderr, "Error: environment not initialized\n");
684 if (env_flags_validate_env_set_params(name, valv, valc) < 0) {
690 for (i = 0; i < valc; ++i) {
692 size_t val_len = strlen(val);
695 value[len - 1] = ' ';
697 value = realloc(value, len + val_len + 1);
700 "Cannot malloc %zu bytes: %s\n",
701 len, strerror(errno));
706 memcpy(value + len, val, val_len);
711 fw_env_write(name, value);
715 ret = fw_env_flush(opts);
722 * Parse a file and configure the u-boot variables.
723 * The script file has a very simple format, as follows:
725 * Each line has a couple with name, value:
726 * <white spaces>variable_name<white spaces>variable_value
728 * Both variable_name and variable_value are interpreted as strings.
729 * Any character after <white spaces> and before ending \r\n is interpreted
730 * as variable's value (no comment allowed on these lines !)
732 * Comments are allowed if the first character in the line is #
734 * Returns -1 and sets errno error codes:
738 int fw_parse_script(char *fname, struct env_opts *opts)
741 char dump[1024]; /* Maximum line length in the file */
749 opts = &default_opts;
751 if (fw_env_open(opts)) {
752 fprintf(stderr, "Error: environment not initialized\n");
756 if (strcmp(fname, "-") == 0)
759 fp = fopen(fname, "r");
761 fprintf(stderr, "I cannot open %s for reading\n",
767 while (fgets(dump, sizeof(dump), fp)) {
772 * Read a whole line from the file. If the line is too long
773 * or is not terminated, reports an error and exit.
775 if (dump[len - 1] != '\n') {
777 "Line %d not corrected terminated or too long\n",
783 /* Drop ending line feed / carriage return */
785 if (len && dump[len - 1] == '\r')
788 /* Skip comment or empty lines */
789 if (len == 0 || dump[0] == '#')
793 * Search for variable's name,
794 * remove leading whitespaces
796 name = skip_blanks(dump);
800 /* The first white space is the end of variable name */
801 val = skip_chars(name);
805 if ((val - name) < len)
806 val = skip_blanks(val);
811 fprintf(stderr, "Setting %s : %s\n",
812 name, val ? val : " removed");
815 if (env_flags_validate_type(name, val) < 0) {
821 * If there is an error setting a variable,
822 * try to save the environment and returns an error
824 if (fw_env_write(name, val)) {
826 "fw_env_write returns with error : %s\n",
834 /* Close file if not stdin */
835 if (strcmp(fname, "-") != 0)
838 ret |= fw_env_flush(opts);
846 * environment_end() - compute offset of first byte right after environemnt
847 * @dev - index of enviroment buffer
849 * device offset of first byte right after environemnt
851 off_t environment_end(int dev)
853 /* environment is block aligned */
854 return DEVOFFSET(dev) + ENVSECTORS(dev) * DEVESIZE(dev);
858 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
861 * < 0 - failed to test
863 static int flash_bad_block(int fd, uint8_t mtd_type, loff_t blockstart)
865 if (mtd_type == MTD_NANDFLASH) {
866 int badblock = ioctl(fd, MEMGETBADBLOCK, &blockstart);
869 perror("Cannot read bad block mark");
875 fprintf(stderr, "Bad block at 0x%llx, skipping\n",
876 (unsigned long long)blockstart);
886 * Read data from flash at an offset into a provided buffer. On NAND it skips
887 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
888 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
890 static int flash_read_buf(int dev, int fd, void *buf, size_t count,
893 size_t blocklen; /* erase / write length - one block on NAND,
895 size_t processed = 0; /* progress counter */
896 size_t readlen = count; /* current read length */
897 off_t block_seek; /* offset inside the current block to the start
899 loff_t blockstart; /* running start of the current block -
900 MEMGETBADBLOCK needs 64 bits */
903 blockstart = (offset / DEVESIZE(dev)) * DEVESIZE(dev);
905 /* Offset inside a block */
906 block_seek = offset - blockstart;
908 if (DEVTYPE(dev) == MTD_NANDFLASH) {
910 * NAND: calculate which blocks we are reading. We have
911 * to read one block at a time to skip bad blocks.
913 blocklen = DEVESIZE(dev);
915 /* Limit to one block for the first read */
916 if (readlen > blocklen - block_seek)
917 readlen = blocklen - block_seek;
922 /* This only runs once on NOR flash */
923 while (processed < count) {
924 rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
925 if (rc < 0) /* block test failed */
928 if (blockstart + block_seek + readlen > environment_end(dev)) {
929 /* End of range is reached */
930 fprintf(stderr, "Too few good blocks within range\n");
934 if (rc) { /* block is bad */
935 blockstart += blocklen;
940 * If a block is bad, we retry in the next block at the same
941 * offset - see env/nand.c::writeenv()
943 lseek(fd, blockstart + block_seek, SEEK_SET);
945 rc = read(fd, buf + processed, readlen);
947 fprintf(stderr, "Read error on %s: %s\n",
948 DEVNAME(dev), strerror(errno));
952 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
953 rc, (unsigned long long)blockstart + block_seek,
956 processed += readlen;
957 readlen = min(blocklen, count - processed);
959 blockstart += blocklen;
966 * Write count bytes from begin of environment, but stay within
967 * ENVSECTORS(dev) sectors of
968 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
969 * erase and write the whole data at once.
971 static int flash_write_buf(int dev, int fd, void *buf, size_t count)
974 struct erase_info_user erase;
975 size_t blocklen; /* length of NAND block / NOR erase sector */
976 size_t erase_len; /* whole area that can be erased - may include
978 size_t erasesize; /* erase / write length - one block on NAND,
980 size_t processed = 0; /* progress counter */
981 size_t write_total; /* total size to actually write - excluding
983 off_t erase_offset; /* offset to the first erase block (aligned)
985 off_t block_seek; /* offset inside the erase block to the start
987 loff_t blockstart; /* running start of the current block -
988 MEMGETBADBLOCK needs 64 bits */
992 * For mtd devices only offset and size of the environment do matter
994 if (DEVTYPE(dev) == MTD_ABSENT) {
996 erase_len = blocklen;
997 blockstart = DEVOFFSET(dev);
999 write_total = blocklen;
1001 blocklen = DEVESIZE(dev);
1003 erase_offset = DEVOFFSET(dev);
1005 /* Maximum area we may use */
1006 erase_len = environment_end(dev) - erase_offset;
1008 blockstart = erase_offset;
1010 /* Offset inside a block */
1011 block_seek = DEVOFFSET(dev) - erase_offset;
1014 * Data size we actually write: from the start of the block
1015 * to the start of the data, then count bytes of data, and
1016 * to the end of the block
1018 write_total = ((block_seek + count + blocklen - 1) /
1019 blocklen) * blocklen;
1023 * Support data anywhere within erase sectors: read out the complete
1024 * area to be erased, replace the environment image, write the whole
1027 if (write_total > count) {
1028 data = malloc(erase_len);
1031 "Cannot malloc %zu bytes: %s\n",
1032 erase_len, strerror(errno));
1036 rc = flash_read_buf(dev, fd, data, write_total, erase_offset);
1037 if (write_total != rc)
1041 fprintf(stderr, "Preserving data ");
1042 if (block_seek != 0)
1043 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
1044 if (block_seek + count != write_total) {
1045 if (block_seek != 0)
1046 fprintf(stderr, " and ");
1047 fprintf(stderr, "0x%lx - 0x%lx",
1048 (unsigned long)block_seek + count,
1049 (unsigned long)write_total - 1);
1051 fprintf(stderr, "\n");
1053 /* Overwrite the old environment */
1054 memcpy(data + block_seek, buf, count);
1057 * We get here, iff offset is block-aligned and count is a
1058 * multiple of blocklen - see write_total calculation above
1063 if (DEVTYPE(dev) == MTD_NANDFLASH) {
1065 * NAND: calculate which blocks we are writing. We have
1066 * to write one block at a time to skip bad blocks.
1068 erasesize = blocklen;
1070 erasesize = erase_len;
1073 erase.length = erasesize;
1075 /* This only runs once on NOR flash and SPI-dataflash */
1076 while (processed < write_total) {
1077 rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
1078 if (rc < 0) /* block test failed */
1081 if (blockstart + erasesize > environment_end(dev)) {
1082 fprintf(stderr, "End of range reached, aborting\n");
1086 if (rc) { /* block is bad */
1087 blockstart += blocklen;
1091 if (DEVTYPE(dev) != MTD_ABSENT) {
1092 erase.start = blockstart;
1093 ioctl(fd, MEMUNLOCK, &erase);
1094 /* These do not need an explicit erase cycle */
1095 if (DEVTYPE(dev) != MTD_DATAFLASH)
1096 if (ioctl(fd, MEMERASE, &erase) != 0) {
1098 "MTD erase error on %s: %s\n",
1099 DEVNAME(dev), strerror(errno));
1104 if (lseek(fd, blockstart, SEEK_SET) == -1) {
1106 "Seek error on %s: %s\n",
1107 DEVNAME(dev), strerror(errno));
1111 fprintf(stderr, "Write 0x%llx bytes at 0x%llx\n",
1112 (unsigned long long)erasesize,
1113 (unsigned long long)blockstart);
1115 if (write(fd, data + processed, erasesize) != erasesize) {
1116 fprintf(stderr, "Write error on %s: %s\n",
1117 DEVNAME(dev), strerror(errno));
1121 if (DEVTYPE(dev) != MTD_ABSENT)
1122 ioctl(fd, MEMLOCK, &erase);
1124 processed += erasesize;
1126 blockstart += erasesize;
1129 if (write_total > count)
1136 * Set obsolete flag at offset - NOR flash only
1138 static int flash_flag_obsolete(int dev, int fd, off_t offset)
1141 struct erase_info_user erase;
1143 erase.start = DEVOFFSET(dev);
1144 erase.length = DEVESIZE(dev);
1145 /* This relies on the fact, that obsolete_flag == 0 */
1146 rc = lseek(fd, offset, SEEK_SET);
1148 fprintf(stderr, "Cannot seek to set the flag on %s\n",
1152 ioctl(fd, MEMUNLOCK, &erase);
1153 rc = write(fd, &obsolete_flag, sizeof(obsolete_flag));
1154 ioctl(fd, MEMLOCK, &erase);
1156 perror("Could not set obsolete flag");
1161 static int flash_write(int fd_current, int fd_target, int dev_target)
1165 switch (environment.flag_scheme) {
1168 case FLAG_INCREMENTAL:
1169 (*environment.flags)++;
1172 *environment.flags = active_flag;
1175 fprintf(stderr, "Unimplemented flash scheme %u\n",
1176 environment.flag_scheme);
1181 fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
1182 DEVOFFSET(dev_target), DEVNAME(dev_target));
1185 if (IS_UBI(dev_target)) {
1186 if (ubi_update_start(fd_target, CUR_ENVSIZE) < 0)
1188 return ubi_write(fd_target, environment.image, CUR_ENVSIZE);
1191 rc = flash_write_buf(dev_target, fd_target, environment.image,
1196 if (environment.flag_scheme == FLAG_BOOLEAN) {
1197 /* Have to set obsolete flag */
1198 off_t offset = DEVOFFSET(dev_current) +
1199 offsetof(struct env_image_redundant, flags);
1202 "Setting obsolete flag in environment at 0x%llx on %s\n",
1203 DEVOFFSET(dev_current), DEVNAME(dev_current));
1205 flash_flag_obsolete(dev_current, fd_current, offset);
1211 static int flash_read(int fd)
1215 if (IS_UBI(dev_current)) {
1216 DEVTYPE(dev_current) = MTD_ABSENT;
1218 return ubi_read(fd, environment.image, CUR_ENVSIZE);
1221 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1222 DEVOFFSET(dev_current));
1223 if (rc != CUR_ENVSIZE)
1229 static int flash_open_tempfile(const char **dname, const char **target_temp)
1231 char *dup_name = strdup(DEVNAME(dev_current));
1232 char *temp_name = NULL;
1238 *dname = dirname(dup_name);
1242 rc = asprintf(&temp_name, "%s/XXXXXX", *dname);
1246 rc = mkstemp(temp_name);
1248 /* fall back to in place write */
1250 "Can't create %s: %s\n", temp_name, strerror(errno));
1253 *target_temp = temp_name;
1254 /* deliberately leak dup_name as dname /might/ point into
1255 * it and we need it for our caller
1267 static int flash_io_write(int fd_current)
1269 int fd_target = -1, rc, dev_target;
1270 const char *dname, *target_temp = NULL;
1272 if (have_redund_env) {
1273 /* switch to next partition for writing */
1274 dev_target = !dev_current;
1275 /* dev_target: fd_target, erase_target */
1276 fd_target = open(DEVNAME(dev_target), O_RDWR);
1277 if (fd_target < 0) {
1279 "Can't open %s: %s\n",
1280 DEVNAME(dev_target), strerror(errno));
1287 if (fstat(fd_current, &sb) == 0 && S_ISREG(sb.st_mode)) {
1288 /* if any part of flash_open_tempfile() fails we fall
1289 * back to in-place writes
1291 fd_target = flash_open_tempfile(&dname, &target_temp);
1293 dev_target = dev_current;
1294 if (fd_target == -1)
1295 fd_target = fd_current;
1298 rc = flash_write(fd_current, fd_target, dev_target);
1300 if (fsync(fd_current) && !(errno == EINVAL || errno == EROFS)) {
1302 "fsync failed on %s: %s\n",
1303 DEVNAME(dev_current), strerror(errno));
1306 if (fd_current != fd_target) {
1307 if (fsync(fd_target) &&
1308 !(errno == EINVAL || errno == EROFS)) {
1310 "fsync failed on %s: %s\n",
1311 DEVNAME(dev_current), strerror(errno));
1314 if (close(fd_target)) {
1316 "I/O error on %s: %s\n",
1317 DEVNAME(dev_target), strerror(errno));
1324 dir_fd = open(dname, O_DIRECTORY | O_RDONLY);
1327 "Can't open %s: %s\n",
1328 dname, strerror(errno));
1330 if (rename(target_temp, DEVNAME(dev_target))) {
1332 "rename failed %s => %s: %s\n",
1333 target_temp, DEVNAME(dev_target),
1338 if (dir_fd != -1 && fsync(dir_fd))
1340 "fsync failed on %s: %s\n",
1341 dname, strerror(errno));
1343 if (dir_fd != -1 && close(dir_fd))
1345 "I/O error on %s: %s\n",
1346 dname, strerror(errno));
1353 static int flash_io(int mode)
1357 /* dev_current: fd_current, erase_current */
1358 fd_current = open(DEVNAME(dev_current), mode);
1359 if (fd_current < 0) {
1361 "Can't open %s: %s\n",
1362 DEVNAME(dev_current), strerror(errno));
1366 if (mode == O_RDWR) {
1367 rc = flash_io_write(fd_current);
1369 rc = flash_read(fd_current);
1372 if (close(fd_current)) {
1374 "I/O error on %s: %s\n",
1375 DEVNAME(dev_current), strerror(errno));
1383 * Prevent confusion if running from erased flash memory
1385 int fw_env_open(struct env_opts *opts)
1388 unsigned char flag0;
1392 unsigned char flag1;
1397 struct env_image_single *single;
1398 struct env_image_redundant *redundant;
1401 opts = &default_opts;
1403 if (parse_config(opts)) /* should fill envdevices */
1406 addr0 = calloc(1, CUR_ENVSIZE);
1407 if (addr0 == NULL) {
1409 "Not enough memory for environment (%ld bytes)\n",
1415 /* read environment from FLASH to local buffer */
1416 environment.image = addr0;
1418 if (have_redund_env) {
1420 environment.crc = &redundant->crc;
1421 environment.flags = &redundant->flags;
1422 environment.data = redundant->data;
1425 environment.crc = &single->crc;
1426 environment.flags = NULL;
1427 environment.data = single->data;
1431 if (flash_io(O_RDONLY)) {
1436 crc0 = crc32(0, (uint8_t *)environment.data, ENV_SIZE);
1438 crc0_ok = (crc0 == *environment.crc);
1439 if (!have_redund_env) {
1442 "Warning: Bad CRC, using default environment\n");
1443 memcpy(environment.data, default_environment,
1444 sizeof(default_environment));
1447 flag0 = *environment.flags;
1450 addr1 = calloc(1, CUR_ENVSIZE);
1451 if (addr1 == NULL) {
1453 "Not enough memory for environment (%ld bytes)\n",
1461 * have to set environment.image for flash_read(), careful -
1462 * other pointers in environment still point inside addr0
1464 environment.image = addr1;
1465 if (flash_io(O_RDONLY)) {
1470 /* Check flag scheme compatibility */
1471 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1472 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1473 environment.flag_scheme = FLAG_BOOLEAN;
1474 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1475 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1476 environment.flag_scheme = FLAG_INCREMENTAL;
1477 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1478 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1479 environment.flag_scheme = FLAG_BOOLEAN;
1480 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1481 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1482 environment.flag_scheme = FLAG_INCREMENTAL;
1483 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1484 DEVTYPE(!dev_current) == MTD_ABSENT &&
1485 IS_UBI(dev_current) == IS_UBI(!dev_current)) {
1486 environment.flag_scheme = FLAG_INCREMENTAL;
1488 fprintf(stderr, "Incompatible flash types!\n");
1493 crc1 = crc32(0, (uint8_t *)redundant->data, ENV_SIZE);
1495 crc1_ok = (crc1 == redundant->crc);
1496 flag1 = redundant->flags;
1498 if (crc0_ok && !crc1_ok) {
1500 } else if (!crc0_ok && crc1_ok) {
1502 } else if (!crc0_ok && !crc1_ok) {
1504 "Warning: Bad CRC, using default environment\n");
1505 memcpy(environment.data, default_environment,
1506 sizeof(default_environment));
1509 switch (environment.flag_scheme) {
1511 if (flag0 == active_flag &&
1512 flag1 == obsolete_flag) {
1514 } else if (flag0 == obsolete_flag &&
1515 flag1 == active_flag) {
1517 } else if (flag0 == flag1) {
1519 } else if (flag0 == 0xFF) {
1521 } else if (flag1 == 0xFF) {
1527 case FLAG_INCREMENTAL:
1528 if (flag0 == 255 && flag1 == 0)
1530 else if ((flag1 == 255 && flag0 == 0) ||
1533 else /* flag1 > flag0 */
1537 fprintf(stderr, "Unknown flag scheme %u\n",
1538 environment.flag_scheme);
1544 * If we are reading, we don't need the flag and the CRC any
1545 * more, if we are writing, we will re-calculate CRC and update
1546 * flags before writing out
1549 environment.image = addr1;
1550 environment.crc = &redundant->crc;
1551 environment.flags = &redundant->flags;
1552 environment.data = redundant->data;
1555 environment.image = addr0;
1556 /* Other pointers are already set */
1560 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1576 * Simply free allocated buffer with environment
1578 int fw_env_close(struct env_opts *opts)
1580 if (environment.image)
1581 free(environment.image);
1583 environment.image = NULL;
1588 static int check_device_config(int dev)
1594 /* Fills in IS_UBI(), converts DEVNAME() with ubi volume name */
1597 fd = open(DEVNAME(dev), O_RDONLY);
1600 "Cannot open %s: %s\n", DEVNAME(dev), strerror(errno));
1604 rc = fstat(fd, &st);
1606 fprintf(stderr, "Cannot stat the file %s\n", DEVNAME(dev));
1611 rc = ioctl(fd, UBI_IOCEBISMAP, &lnum);
1613 fprintf(stderr, "Cannot get UBI information for %s\n",
1617 } else if (S_ISCHR(st.st_mode)) {
1618 struct mtd_info_user mtdinfo;
1619 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1621 fprintf(stderr, "Cannot get MTD information for %s\n",
1625 if (mtdinfo.type != MTD_NORFLASH &&
1626 mtdinfo.type != MTD_NANDFLASH &&
1627 mtdinfo.type != MTD_DATAFLASH &&
1628 mtdinfo.type != MTD_UBIVOLUME) {
1629 fprintf(stderr, "Unsupported flash type %u on %s\n",
1630 mtdinfo.type, DEVNAME(dev));
1633 DEVTYPE(dev) = mtdinfo.type;
1634 if (DEVESIZE(dev) == 0)
1635 /* Assume the erase size is the same as the env-size */
1636 DEVESIZE(dev) = ENVSIZE(dev);
1639 DEVTYPE(dev) = MTD_ABSENT;
1640 if (DEVESIZE(dev) == 0)
1641 /* Assume the erase size to be 512 bytes */
1642 DEVESIZE(dev) = 0x200;
1645 * Check for negative offsets, treat it as backwards offset
1646 * from the end of the block device
1648 if (DEVOFFSET(dev) < 0) {
1649 rc = ioctl(fd, BLKGETSIZE64, &size);
1652 "Could not get block device size on %s\n",
1657 DEVOFFSET(dev) = DEVOFFSET(dev) + size;
1660 "Calculated device offset 0x%llx on %s\n",
1661 DEVOFFSET(dev), DEVNAME(dev));
1666 if (ENVSECTORS(dev) == 0)
1667 /* Assume enough sectors to cover the environment */
1668 ENVSECTORS(dev) = DIV_ROUND_UP(ENVSIZE(dev), DEVESIZE(dev));
1670 if (DEVOFFSET(dev) % DEVESIZE(dev) != 0) {
1672 "Environment does not start on (erase) block boundary\n");
1677 if (ENVSIZE(dev) > ENVSECTORS(dev) * DEVESIZE(dev)) {
1679 "Environment does not fit into available sectors\n");
1689 static int parse_config(struct env_opts *opts)
1694 opts = &default_opts;
1696 #if defined(CONFIG_FILE)
1697 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1698 if (get_config(opts->config_file)) {
1699 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1704 DEVNAME(0) = DEVICE1_NAME;
1705 DEVOFFSET(0) = DEVICE1_OFFSET;
1706 ENVSIZE(0) = ENV1_SIZE;
1708 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1711 #ifdef DEVICE1_ESIZE
1712 DEVESIZE(0) = DEVICE1_ESIZE;
1714 #ifdef DEVICE1_ENVSECTORS
1715 ENVSECTORS(0) = DEVICE1_ENVSECTORS;
1719 DEVNAME(1) = DEVICE2_NAME;
1720 DEVOFFSET(1) = DEVICE2_OFFSET;
1721 ENVSIZE(1) = ENV2_SIZE;
1723 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1726 #ifdef DEVICE2_ESIZE
1727 DEVESIZE(1) = DEVICE2_ESIZE;
1729 #ifdef DEVICE2_ENVSECTORS
1730 ENVSECTORS(1) = DEVICE2_ENVSECTORS;
1732 have_redund_env = 1;
1735 rc = check_device_config(0);
1739 if (have_redund_env) {
1740 rc = check_device_config(1);
1744 if (ENVSIZE(0) != ENVSIZE(1)) {
1746 "Redundant environments have unequal size");
1751 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1752 if (have_redund_env)
1753 usable_envsize -= sizeof(char);
1758 #if defined(CONFIG_FILE)
1759 static int get_config(char *fname)
1767 fp = fopen(fname, "r");
1771 while (i < 2 && fgets(dump, sizeof(dump), fp)) {
1772 /* Skip incomplete conversions and comment strings */
1776 rc = sscanf(dump, "%ms %lli %lx %lx %lx",
1779 &ENVSIZE(i), &DEVESIZE(i), &ENVSECTORS(i));
1784 DEVNAME(i) = devname;
1786 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1794 have_redund_env = i - 1;
1795 if (!i) { /* No valid entries found */