1 // SPDX-License-Identifier: GPL-2.0+
3 * (C) Copyright 2000-2010
4 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
7 * Guennadi Liakhovetski, DENX Software Engineering, lg@denx.de.
15 #include <env_flags.h>
19 #include <linux/stringify.h>
25 #include <sys/types.h>
26 #include <sys/ioctl.h>
28 #include <u-boot/crc.h>
34 # include <linux/mtd/mtd.h>
36 # define __user /* nothing */
37 # include <mtd/mtd-user.h>
40 #include <mtd/ubi-user.h>
42 #include "fw_env_private.h"
45 struct env_opts default_opts = {
47 .config_file = CONFIG_FILE
51 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
53 #define min(x, y) ({ \
54 typeof(x) _min1 = (x); \
55 typeof(y) _min2 = (y); \
56 (void) (&_min1 == &_min2); \
57 _min1 < _min2 ? _min1 : _min2; })
60 const char *devname; /* Device name */
61 long long devoff; /* Device offset */
62 ulong env_size; /* environment size */
63 ulong erase_size; /* device erase size */
64 ulong env_sectors; /* number of environment sectors */
65 uint8_t mtd_type; /* type of the MTD device */
66 int is_ubi; /* set if we use UBI volume */
69 static struct envdev_s envdevices[2] = {
71 .mtd_type = MTD_ABSENT,
73 .mtd_type = MTD_ABSENT,
77 static int dev_current;
79 #define DEVNAME(i) envdevices[(i)].devname
80 #define DEVOFFSET(i) envdevices[(i)].devoff
81 #define ENVSIZE(i) envdevices[(i)].env_size
82 #define DEVESIZE(i) envdevices[(i)].erase_size
83 #define ENVSECTORS(i) envdevices[(i)].env_sectors
84 #define DEVTYPE(i) envdevices[(i)].mtd_type
85 #define IS_UBI(i) envdevices[(i)].is_ubi
87 #define CUR_ENVSIZE ENVSIZE(dev_current)
89 static unsigned long usable_envsize;
90 #define ENV_SIZE usable_envsize
92 struct env_image_single {
93 uint32_t crc; /* CRC32 over data bytes */
97 struct env_image_redundant {
98 uint32_t crc; /* CRC32 over data bytes */
99 unsigned char flags; /* active or obsolete */
112 unsigned char *flags;
114 enum flag_scheme flag_scheme;
118 static struct environment environment = {
119 .flag_scheme = FLAG_NONE,
122 static int have_redund_env;
124 #define DEFAULT_ENV_INSTANCE_STATIC
125 #include <env_default.h>
127 #define UBI_DEV_START "/dev/ubi"
128 #define UBI_SYSFS "/sys/class/ubi"
129 #define UBI_VOL_NAME_PATT "ubi%d_%d"
131 static int is_ubi_devname(const char *devname)
133 return !strncmp(devname, UBI_DEV_START, sizeof(UBI_DEV_START) - 1);
136 static int ubi_check_volume_sysfs_name(const char *volume_sysfs_name,
144 strcpy(path, UBI_SYSFS "/");
145 strcat(path, volume_sysfs_name);
146 strcat(path, "/name");
148 file = fopen(path, "r");
152 ret = fscanf(file, "%ms", &name);
154 if (ret <= 0 || !name) {
156 "Failed to read from file %s, ret = %d, name = %s\n",
161 if (!strcmp(name, volname)) {
170 static int ubi_get_volnum_by_name(int devnum, const char *volname)
173 struct dirent *dirent;
178 sysfs_ubi = opendir(UBI_SYSFS);
183 fprintf(stderr, "Looking for volume name \"%s\"\n", volname);
187 dirent = readdir(sysfs_ubi);
191 ret = sscanf(dirent->d_name, UBI_VOL_NAME_PATT,
192 &tmp_devnum, &volnum);
193 if (ret == 2 && devnum == tmp_devnum) {
194 if (ubi_check_volume_sysfs_name(dirent->d_name,
203 static int ubi_get_devnum_by_devname(const char *devname)
208 ret = sscanf(devname + sizeof(UBI_DEV_START) - 1, "%d", &devnum);
215 static const char *ubi_get_volume_devname(const char *devname,
218 char *volume_devname;
223 devnum = ubi_get_devnum_by_devname(devname);
227 volnum = ubi_get_volnum_by_name(devnum, volname);
231 ret = asprintf(&volume_devname, "%s_%d", devname, volnum);
236 fprintf(stderr, "Found ubi volume \"%s:%s\" -> %s\n",
237 devname, volname, volume_devname);
240 return volume_devname;
243 static void ubi_check_dev(unsigned int dev_id)
245 char *devname = (char *)DEVNAME(dev_id);
247 const char *volname = NULL;
248 const char *volume_devname;
250 if (!is_ubi_devname(DEVNAME(dev_id)))
255 for (pname = devname; *pname != '\0'; pname++) {
264 /* Let's find real volume device name */
265 volume_devname = ubi_get_volume_devname(devname, volname);
266 if (!volume_devname) {
267 fprintf(stderr, "Didn't found ubi volume \"%s\"\n",
273 DEVNAME(dev_id) = volume_devname;
277 static int ubi_update_start(int fd, int64_t bytes)
279 if (ioctl(fd, UBI_IOCVOLUP, &bytes))
284 static int ubi_read(int fd, void *buf, size_t count)
289 ret = read(fd, buf, count);
299 * Happens in case of too short volume data size. If we
300 * return error status we will fail it will be treated
301 * as UBI device error.
303 * Leave catching this error to CRC check.
305 fprintf(stderr, "Warning: end of data on ubi volume\n");
307 } else if (errno == EBADF) {
309 * Happens in case of corrupted volume. The same as
310 * above, we cannot return error now, as we will still
311 * be able to successfully write environment later.
313 fprintf(stderr, "Warning: corrupted volume?\n");
315 } else if (errno == EINTR) {
319 fprintf(stderr, "Cannot read %u bytes from ubi volume, %s\n",
320 (unsigned int)count, strerror(errno));
327 static int ubi_write(int fd, const void *buf, size_t count)
332 ret = write(fd, buf, count);
334 if (ret < 0 && errno == EINTR)
337 fprintf(stderr, "Cannot write %u bytes to ubi volume\n",
338 (unsigned int)count);
349 static int flash_io(int mode);
350 static int parse_config(struct env_opts *opts);
352 #if defined(CONFIG_FILE)
353 static int get_config(char *);
356 static char *skip_chars(char *s)
358 for (; *s != '\0'; s++) {
359 if (isblank(*s) || *s == '=')
365 static char *skip_blanks(char *s)
367 for (; *s != '\0'; s++) {
375 * s1 is either a simple 'name', or a 'name=value' pair.
376 * s2 is a 'name=value' pair.
377 * If the names match, return the value of s2, else NULL.
379 static char *envmatch(char *s1, char *s2)
381 if (s1 == NULL || s2 == NULL)
387 if (*s1 == '\0' && *(s2 - 1) == '=')
393 * Search the environment for a variable.
394 * Return the value, if found, or NULL, if not found.
396 char *fw_getenv(char *name)
400 for (env = environment.data; *env; env = nxt + 1) {
403 for (nxt = env; *nxt; ++nxt) {
404 if (nxt >= &environment.data[ENV_SIZE]) {
405 fprintf(stderr, "## Error: "
406 "environment not terminated\n");
410 val = envmatch(name, env);
419 * Search the default environment for a variable.
420 * Return the value, if found, or NULL, if not found.
422 char *fw_getdefenv(char *name)
426 for (env = default_environment; *env; env = nxt + 1) {
429 for (nxt = env; *nxt; ++nxt) {
430 if (nxt >= &default_environment[ENV_SIZE]) {
431 fprintf(stderr, "## Error: "
432 "default environment not terminated\n");
436 val = envmatch(name, env);
445 * Print the current definition of one, or more, or all
446 * environment variables
448 int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
452 if (value_only && argc != 1) {
454 "## Error: `-n'/`--noheader' option requires exactly one argument\n");
459 opts = &default_opts;
461 if (fw_env_open(opts))
464 if (argc == 0) { /* Print all env variables */
466 for (env = environment.data; *env; env = nxt + 1) {
467 for (nxt = env; *nxt; ++nxt) {
468 if (nxt >= &environment.data[ENV_SIZE]) {
469 fprintf(stderr, "## Error: "
470 "environment not terminated\n");
481 for (i = 0; i < argc; ++i) { /* print a subset of env variables */
482 char *name = argv[i];
485 val = fw_getenv(name);
487 fprintf(stderr, "## Error: \"%s\" not defined\n", name);
497 printf("%s=%s\n", name, val);
505 int fw_env_flush(struct env_opts *opts)
508 opts = &default_opts;
510 if (!environment.dirty)
516 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
518 /* write environment back to flash */
519 if (flash_io(O_RDWR)) {
520 fprintf(stderr, "Error: can't write fw_env to flash\n");
528 * Set/Clear a single variable in the environment.
529 * This is called in sequence to update the environment
530 * in RAM without updating the copy in flash after each set
532 int fw_env_write(char *name, char *value)
537 int deleting, creating, overwriting;
540 * search if variable with this name already exists
542 for (nxt = env = environment.data; *env; env = nxt + 1) {
543 for (nxt = env; *nxt; ++nxt) {
544 if (nxt >= &environment.data[ENV_SIZE]) {
545 fprintf(stderr, "## Error: "
546 "environment not terminated\n");
551 oldval = envmatch(name, env);
556 deleting = (oldval && !(value && strlen(value)));
557 creating = (!oldval && (value && strlen(value)));
558 overwriting = (oldval && (value && strlen(value) &&
559 strcmp(oldval, value)));
561 /* check for permission */
563 if (env_flags_validate_varaccess(name,
564 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
565 printf("Can't delete \"%s\"\n", name);
569 } else if (overwriting) {
570 if (env_flags_validate_varaccess(name,
571 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
572 printf("Can't overwrite \"%s\"\n", name);
575 } else if (env_flags_validate_varaccess(name,
576 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
577 const char *defval = fw_getdefenv(name);
581 if (strcmp(oldval, defval)
583 printf("Can't overwrite \"%s\"\n", name);
588 } else if (creating) {
589 if (env_flags_validate_varaccess(name,
590 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
591 printf("Can't create \"%s\"\n", name);
599 environment.dirty = 1;
600 if (deleting || overwriting) {
601 if (*++nxt == '\0') {
606 if ((*env == '\0') && (*nxt == '\0'))
615 if (!value || !strlen(value))
619 * Append new definition at the end
621 for (env = environment.data; *env || *(env + 1); ++env)
623 if (env > environment.data)
627 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
629 len = strlen(name) + 2;
630 /* add '=' for first arg, ' ' for all others */
631 len += strlen(value) + 1;
633 if (len > (&environment.data[ENV_SIZE] - env)) {
635 "Error: environment overflow, \"%s\" deleted\n", name);
639 while ((*env = *name++) != '\0')
642 while ((*++env = *value++) != '\0')
645 /* end is marked with double '\0' */
652 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
654 * EINVAL - need at least 1 argument
655 * EROFS - certain variables ("ethaddr", "serial#") cannot be
656 * modified or deleted
659 int fw_env_set(int argc, char *argv[], struct env_opts *opts)
670 opts = &default_opts;
673 fprintf(stderr, "## Error: variable name missing\n");
678 if (fw_env_open(opts)) {
679 fprintf(stderr, "Error: environment not initialized\n");
687 if (env_flags_validate_env_set_params(name, valv, valc) < 0) {
693 for (i = 0; i < valc; ++i) {
695 size_t val_len = strlen(val);
698 value[len - 1] = ' ';
700 value = realloc(value, len + val_len + 1);
703 "Cannot malloc %zu bytes: %s\n",
704 len, strerror(errno));
709 memcpy(value + len, val, val_len);
714 fw_env_write(name, value);
718 ret = fw_env_flush(opts);
725 * Parse a file and configure the u-boot variables.
726 * The script file has a very simple format, as follows:
728 * Each line has a couple with name, value:
729 * <white spaces>variable_name<white spaces>variable_value
731 * Both variable_name and variable_value are interpreted as strings.
732 * Any character after <white spaces> and before ending \r\n is interpreted
733 * as variable's value (no comment allowed on these lines !)
735 * Comments are allowed if the first character in the line is #
737 * Returns -1 and sets errno error codes:
741 int fw_parse_script(char *fname, struct env_opts *opts)
753 opts = &default_opts;
755 if (fw_env_open(opts)) {
756 fprintf(stderr, "Error: environment not initialized\n");
760 if (strcmp(fname, "-") == 0)
763 fp = fopen(fname, "r");
765 fprintf(stderr, "I cannot open %s for reading\n",
771 while ((len = getline(&line, &linesize, fp)) != -1) {
775 * Read a whole line from the file. If the line is not
776 * terminated, reports an error and exit.
778 if (line[len - 1] != '\n') {
780 "Line %d not correctly terminated\n",
786 /* Drop ending line feed / carriage return */
788 if (len && line[len - 1] == '\r')
791 /* Skip comment or empty lines */
792 if (len == 0 || line[0] == '#')
796 * Search for variable's name remove leading whitespaces
798 name = skip_blanks(line);
802 /* The first white space is the end of variable name */
803 val = skip_chars(name);
807 if ((val - name) < len)
808 val = skip_blanks(val);
813 fprintf(stderr, "Setting %s : %s\n",
814 name, val ? val : " removed");
817 if (env_flags_validate_type(name, val) < 0) {
823 * If there is an error setting a variable,
824 * try to save the environment and returns an error
826 if (fw_env_write(name, val)) {
828 "fw_env_write returns with error : %s\n",
837 /* Close file if not stdin */
838 if (strcmp(fname, "-") != 0)
841 ret |= fw_env_flush(opts);
849 * environment_end() - compute offset of first byte right after environment
850 * @dev - index of enviroment buffer
852 * device offset of first byte right after environment
854 off_t environment_end(int dev)
856 /* environment is block aligned */
857 return DEVOFFSET(dev) + ENVSECTORS(dev) * DEVESIZE(dev);
861 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
864 * < 0 - failed to test
866 static int flash_bad_block(int fd, uint8_t mtd_type, loff_t blockstart)
868 if (mtd_type == MTD_NANDFLASH) {
869 int badblock = ioctl(fd, MEMGETBADBLOCK, &blockstart);
872 perror("Cannot read bad block mark");
878 fprintf(stderr, "Bad block at 0x%llx, skipping\n",
879 (unsigned long long)blockstart);
889 * Read data from flash at an offset into a provided buffer. On NAND it skips
890 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
891 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
893 static int flash_read_buf(int dev, int fd, void *buf, size_t count,
896 size_t blocklen; /* erase / write length - one block on NAND,
898 size_t processed = 0; /* progress counter */
899 size_t readlen = count; /* current read length */
900 off_t block_seek; /* offset inside the current block to the start
902 loff_t blockstart; /* running start of the current block -
903 MEMGETBADBLOCK needs 64 bits */
906 blockstart = (offset / DEVESIZE(dev)) * DEVESIZE(dev);
908 /* Offset inside a block */
909 block_seek = offset - blockstart;
911 if (DEVTYPE(dev) == MTD_NANDFLASH) {
913 * NAND: calculate which blocks we are reading. We have
914 * to read one block at a time to skip bad blocks.
916 blocklen = DEVESIZE(dev);
918 /* Limit to one block for the first read */
919 if (readlen > blocklen - block_seek)
920 readlen = blocklen - block_seek;
925 /* This only runs once on NOR flash */
926 while (processed < count) {
927 rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
928 if (rc < 0) /* block test failed */
931 if (blockstart + block_seek + readlen > environment_end(dev)) {
932 /* End of range is reached */
933 fprintf(stderr, "Too few good blocks within range\n");
937 if (rc) { /* block is bad */
938 blockstart += blocklen;
943 * If a block is bad, we retry in the next block at the same
944 * offset - see env/nand.c::writeenv()
946 lseek(fd, blockstart + block_seek, SEEK_SET);
948 rc = read(fd, buf + processed, readlen);
950 fprintf(stderr, "Read error on %s: %s\n",
951 DEVNAME(dev), strerror(errno));
955 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
956 rc, (unsigned long long)blockstart + block_seek,
959 processed += readlen;
960 readlen = min(blocklen, count - processed);
962 blockstart += blocklen;
969 * Write count bytes from begin of environment, but stay within
970 * ENVSECTORS(dev) sectors of
971 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
972 * erase and write the whole data at once.
974 static int flash_write_buf(int dev, int fd, void *buf, size_t count)
977 struct erase_info_user erase;
978 size_t blocklen; /* length of NAND block / NOR erase sector */
979 size_t erase_len; /* whole area that can be erased - may include
981 size_t erasesize; /* erase / write length - one block on NAND,
983 size_t processed = 0; /* progress counter */
984 size_t write_total; /* total size to actually write - excluding
986 off_t erase_offset; /* offset to the first erase block (aligned)
988 off_t block_seek; /* offset inside the erase block to the start
990 loff_t blockstart; /* running start of the current block -
991 MEMGETBADBLOCK needs 64 bits */
995 * For mtd devices only offset and size of the environment do matter
997 if (DEVTYPE(dev) == MTD_ABSENT) {
999 erase_len = blocklen;
1000 blockstart = DEVOFFSET(dev);
1002 write_total = blocklen;
1004 blocklen = DEVESIZE(dev);
1006 erase_offset = DEVOFFSET(dev);
1008 /* Maximum area we may use */
1009 erase_len = environment_end(dev) - erase_offset;
1011 blockstart = erase_offset;
1013 /* Offset inside a block */
1014 block_seek = DEVOFFSET(dev) - erase_offset;
1017 * Data size we actually write: from the start of the block
1018 * to the start of the data, then count bytes of data, and
1019 * to the end of the block
1021 write_total = ((block_seek + count + blocklen - 1) /
1022 blocklen) * blocklen;
1026 * Support data anywhere within erase sectors: read out the complete
1027 * area to be erased, replace the environment image, write the whole
1030 if (write_total > count) {
1031 data = malloc(erase_len);
1034 "Cannot malloc %zu bytes: %s\n",
1035 erase_len, strerror(errno));
1039 rc = flash_read_buf(dev, fd, data, write_total, erase_offset);
1040 if (write_total != rc)
1044 fprintf(stderr, "Preserving data ");
1045 if (block_seek != 0)
1046 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
1047 if (block_seek + count != write_total) {
1048 if (block_seek != 0)
1049 fprintf(stderr, " and ");
1050 fprintf(stderr, "0x%lx - 0x%lx",
1051 (unsigned long)block_seek + count,
1052 (unsigned long)write_total - 1);
1054 fprintf(stderr, "\n");
1056 /* Overwrite the old environment */
1057 memcpy(data + block_seek, buf, count);
1060 * We get here, iff offset is block-aligned and count is a
1061 * multiple of blocklen - see write_total calculation above
1066 if (DEVTYPE(dev) == MTD_NANDFLASH) {
1068 * NAND: calculate which blocks we are writing. We have
1069 * to write one block at a time to skip bad blocks.
1071 erasesize = blocklen;
1073 erasesize = erase_len;
1076 erase.length = erasesize;
1078 /* This only runs once on NOR flash and SPI-dataflash */
1079 while (processed < write_total) {
1080 rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
1081 if (rc < 0) /* block test failed */
1084 if (blockstart + erasesize > environment_end(dev)) {
1085 fprintf(stderr, "End of range reached, aborting\n");
1089 if (rc) { /* block is bad */
1090 blockstart += blocklen;
1094 if (DEVTYPE(dev) != MTD_ABSENT) {
1095 erase.start = blockstart;
1096 ioctl(fd, MEMUNLOCK, &erase);
1097 /* These do not need an explicit erase cycle */
1098 if (DEVTYPE(dev) != MTD_DATAFLASH)
1099 if (ioctl(fd, MEMERASE, &erase) != 0) {
1101 "MTD erase error on %s: %s\n",
1102 DEVNAME(dev), strerror(errno));
1107 if (lseek(fd, blockstart, SEEK_SET) == -1) {
1109 "Seek error on %s: %s\n",
1110 DEVNAME(dev), strerror(errno));
1114 fprintf(stderr, "Write 0x%llx bytes at 0x%llx\n",
1115 (unsigned long long)erasesize,
1116 (unsigned long long)blockstart);
1118 if (write(fd, data + processed, erasesize) != erasesize) {
1119 fprintf(stderr, "Write error on %s: %s\n",
1120 DEVNAME(dev), strerror(errno));
1124 if (DEVTYPE(dev) != MTD_ABSENT)
1125 ioctl(fd, MEMLOCK, &erase);
1127 processed += erasesize;
1129 blockstart += erasesize;
1132 if (write_total > count)
1139 * Set obsolete flag at offset - NOR flash only
1141 static int flash_flag_obsolete(int dev, int fd, off_t offset)
1144 struct erase_info_user erase;
1145 char tmp = ENV_REDUND_OBSOLETE;
1147 erase.start = DEVOFFSET(dev);
1148 erase.length = DEVESIZE(dev);
1149 /* This relies on the fact, that ENV_REDUND_OBSOLETE == 0 */
1150 rc = lseek(fd, offset, SEEK_SET);
1152 fprintf(stderr, "Cannot seek to set the flag on %s\n",
1156 ioctl(fd, MEMUNLOCK, &erase);
1157 rc = write(fd, &tmp, sizeof(tmp));
1158 ioctl(fd, MEMLOCK, &erase);
1160 perror("Could not set obsolete flag");
1165 static int flash_write(int fd_current, int fd_target, int dev_target)
1169 switch (environment.flag_scheme) {
1172 case FLAG_INCREMENTAL:
1173 (*environment.flags)++;
1176 *environment.flags = ENV_REDUND_ACTIVE;
1179 fprintf(stderr, "Unimplemented flash scheme %u\n",
1180 environment.flag_scheme);
1185 fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
1186 DEVOFFSET(dev_target), DEVNAME(dev_target));
1189 if (IS_UBI(dev_target)) {
1190 if (ubi_update_start(fd_target, CUR_ENVSIZE) < 0)
1192 return ubi_write(fd_target, environment.image, CUR_ENVSIZE);
1195 rc = flash_write_buf(dev_target, fd_target, environment.image,
1200 if (environment.flag_scheme == FLAG_BOOLEAN) {
1201 /* Have to set obsolete flag */
1202 off_t offset = DEVOFFSET(dev_current) +
1203 offsetof(struct env_image_redundant, flags);
1206 "Setting obsolete flag in environment at 0x%llx on %s\n",
1207 DEVOFFSET(dev_current), DEVNAME(dev_current));
1209 flash_flag_obsolete(dev_current, fd_current, offset);
1215 static int flash_read(int fd)
1219 if (IS_UBI(dev_current)) {
1220 DEVTYPE(dev_current) = MTD_ABSENT;
1222 return ubi_read(fd, environment.image, CUR_ENVSIZE);
1225 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1226 DEVOFFSET(dev_current));
1227 if (rc != CUR_ENVSIZE)
1233 static int flash_open_tempfile(const char **dname, const char **target_temp)
1235 char *dup_name = strdup(DEVNAME(dev_current));
1236 char *temp_name = NULL;
1242 *dname = dirname(dup_name);
1246 rc = asprintf(&temp_name, "%s/XXXXXX", *dname);
1250 rc = mkstemp(temp_name);
1252 /* fall back to in place write */
1254 "Can't create %s: %s\n", temp_name, strerror(errno));
1257 *target_temp = temp_name;
1258 /* deliberately leak dup_name as dname /might/ point into
1259 * it and we need it for our caller
1271 static int flash_io_write(int fd_current)
1273 int fd_target = -1, rc, dev_target;
1274 const char *dname, *target_temp = NULL;
1276 if (have_redund_env) {
1277 /* switch to next partition for writing */
1278 dev_target = !dev_current;
1279 /* dev_target: fd_target, erase_target */
1280 fd_target = open(DEVNAME(dev_target), O_RDWR);
1281 if (fd_target < 0) {
1283 "Can't open %s: %s\n",
1284 DEVNAME(dev_target), strerror(errno));
1291 if (fstat(fd_current, &sb) == 0 && S_ISREG(sb.st_mode)) {
1292 /* if any part of flash_open_tempfile() fails we fall
1293 * back to in-place writes
1295 fd_target = flash_open_tempfile(&dname, &target_temp);
1297 dev_target = dev_current;
1298 if (fd_target == -1)
1299 fd_target = fd_current;
1302 rc = flash_write(fd_current, fd_target, dev_target);
1304 if (fsync(fd_current) && !(errno == EINVAL || errno == EROFS)) {
1306 "fsync failed on %s: %s\n",
1307 DEVNAME(dev_current), strerror(errno));
1310 if (fd_current != fd_target) {
1311 if (fsync(fd_target) &&
1312 !(errno == EINVAL || errno == EROFS)) {
1314 "fsync failed on %s: %s\n",
1315 DEVNAME(dev_current), strerror(errno));
1318 if (close(fd_target)) {
1320 "I/O error on %s: %s\n",
1321 DEVNAME(dev_target), strerror(errno));
1325 if (rc >= 0 && target_temp) {
1328 dir_fd = open(dname, O_DIRECTORY | O_RDONLY);
1331 "Can't open %s: %s\n",
1332 dname, strerror(errno));
1334 if (rename(target_temp, DEVNAME(dev_target))) {
1336 "rename failed %s => %s: %s\n",
1337 target_temp, DEVNAME(dev_target),
1342 if (dir_fd != -1 && fsync(dir_fd))
1344 "fsync failed on %s: %s\n",
1345 dname, strerror(errno));
1347 if (dir_fd != -1 && close(dir_fd))
1349 "I/O error on %s: %s\n",
1350 dname, strerror(errno));
1357 static int flash_io(int mode)
1361 /* dev_current: fd_current, erase_current */
1362 fd_current = open(DEVNAME(dev_current), mode);
1363 if (fd_current < 0) {
1365 "Can't open %s: %s\n",
1366 DEVNAME(dev_current), strerror(errno));
1370 if (mode == O_RDWR) {
1371 rc = flash_io_write(fd_current);
1373 rc = flash_read(fd_current);
1376 if (close(fd_current)) {
1378 "I/O error on %s: %s\n",
1379 DEVNAME(dev_current), strerror(errno));
1387 * Prevent confusion if running from erased flash memory
1389 int fw_env_open(struct env_opts *opts)
1392 unsigned char flag0;
1396 unsigned char flag1;
1401 struct env_image_single *single;
1402 struct env_image_redundant *redundant;
1405 opts = &default_opts;
1407 if (parse_config(opts)) /* should fill envdevices */
1410 addr0 = calloc(1, CUR_ENVSIZE);
1411 if (addr0 == NULL) {
1413 "Not enough memory for environment (%ld bytes)\n",
1419 /* read environment from FLASH to local buffer */
1420 environment.image = addr0;
1422 if (have_redund_env) {
1424 environment.crc = &redundant->crc;
1425 environment.flags = &redundant->flags;
1426 environment.data = redundant->data;
1429 environment.crc = &single->crc;
1430 environment.flags = NULL;
1431 environment.data = single->data;
1435 if (flash_io(O_RDONLY)) {
1440 crc0 = crc32(0, (uint8_t *)environment.data, ENV_SIZE);
1442 crc0_ok = (crc0 == *environment.crc);
1443 if (!have_redund_env) {
1446 "Warning: Bad CRC, using default environment\n");
1447 memcpy(environment.data, default_environment,
1448 sizeof(default_environment));
1449 environment.dirty = 1;
1452 flag0 = *environment.flags;
1455 addr1 = calloc(1, CUR_ENVSIZE);
1456 if (addr1 == NULL) {
1458 "Not enough memory for environment (%ld bytes)\n",
1466 * have to set environment.image for flash_read(), careful -
1467 * other pointers in environment still point inside addr0
1469 environment.image = addr1;
1470 if (flash_io(O_RDONLY)) {
1475 /* Check flag scheme compatibility */
1476 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1477 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1478 environment.flag_scheme = FLAG_BOOLEAN;
1479 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1480 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1481 environment.flag_scheme = FLAG_INCREMENTAL;
1482 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1483 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1484 environment.flag_scheme = FLAG_BOOLEAN;
1485 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1486 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1487 environment.flag_scheme = FLAG_INCREMENTAL;
1488 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1489 DEVTYPE(!dev_current) == MTD_ABSENT &&
1490 IS_UBI(dev_current) == IS_UBI(!dev_current)) {
1491 environment.flag_scheme = FLAG_INCREMENTAL;
1493 fprintf(stderr, "Incompatible flash types!\n");
1498 crc1 = crc32(0, (uint8_t *)redundant->data, ENV_SIZE);
1500 crc1_ok = (crc1 == redundant->crc);
1501 flag1 = redundant->flags;
1504 * environment.data still points to ((struct
1505 * env_image_redundant *)addr0)->data. If the two
1506 * environments differ, or one has bad crc, force a
1507 * write-out by marking the environment dirty.
1509 if (memcmp(environment.data, redundant->data, ENV_SIZE) ||
1510 !crc0_ok || !crc1_ok)
1511 environment.dirty = 1;
1513 if (crc0_ok && !crc1_ok) {
1515 } else if (!crc0_ok && crc1_ok) {
1517 } else if (!crc0_ok && !crc1_ok) {
1519 "Warning: Bad CRC, using default environment\n");
1520 memcpy(environment.data, default_environment,
1521 sizeof(default_environment));
1522 environment.dirty = 1;
1525 switch (environment.flag_scheme) {
1527 if (flag0 == ENV_REDUND_ACTIVE &&
1528 flag1 == ENV_REDUND_OBSOLETE) {
1530 } else if (flag0 == ENV_REDUND_OBSOLETE &&
1531 flag1 == ENV_REDUND_ACTIVE) {
1533 } else if (flag0 == flag1) {
1535 } else if (flag0 == 0xFF) {
1537 } else if (flag1 == 0xFF) {
1543 case FLAG_INCREMENTAL:
1544 if (flag0 == 255 && flag1 == 0)
1546 else if ((flag1 == 255 && flag0 == 0) ||
1549 else /* flag1 > flag0 */
1553 fprintf(stderr, "Unknown flag scheme %u\n",
1554 environment.flag_scheme);
1560 * If we are reading, we don't need the flag and the CRC any
1561 * more, if we are writing, we will re-calculate CRC and update
1562 * flags before writing out
1565 environment.image = addr1;
1566 environment.crc = &redundant->crc;
1567 environment.flags = &redundant->flags;
1568 environment.data = redundant->data;
1571 environment.image = addr0;
1572 /* Other pointers are already set */
1576 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1592 * Simply free allocated buffer with environment
1594 int fw_env_close(struct env_opts *opts)
1596 if (environment.image)
1597 free(environment.image);
1599 environment.image = NULL;
1604 static int check_device_config(int dev)
1610 /* Fills in IS_UBI(), converts DEVNAME() with ubi volume name */
1613 fd = open(DEVNAME(dev), O_RDONLY);
1616 "Cannot open %s: %s\n", DEVNAME(dev), strerror(errno));
1620 rc = fstat(fd, &st);
1622 fprintf(stderr, "Cannot stat the file %s\n", DEVNAME(dev));
1627 rc = ioctl(fd, UBI_IOCEBISMAP, &lnum);
1629 fprintf(stderr, "Cannot get UBI information for %s\n",
1633 } else if (S_ISCHR(st.st_mode)) {
1634 struct mtd_info_user mtdinfo;
1635 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1637 fprintf(stderr, "Cannot get MTD information for %s\n",
1641 if (mtdinfo.type != MTD_NORFLASH &&
1642 mtdinfo.type != MTD_NANDFLASH &&
1643 mtdinfo.type != MTD_DATAFLASH &&
1644 mtdinfo.type != MTD_UBIVOLUME) {
1645 fprintf(stderr, "Unsupported flash type %u on %s\n",
1646 mtdinfo.type, DEVNAME(dev));
1649 DEVTYPE(dev) = mtdinfo.type;
1650 if (DEVESIZE(dev) == 0)
1651 /* Assume the erase size is the same as the env-size */
1652 DEVESIZE(dev) = ENVSIZE(dev);
1655 DEVTYPE(dev) = MTD_ABSENT;
1656 if (DEVESIZE(dev) == 0)
1657 /* Assume the erase size to be 512 bytes */
1658 DEVESIZE(dev) = 0x200;
1661 * Check for negative offsets, treat it as backwards offset
1662 * from the end of the block device
1664 if (DEVOFFSET(dev) < 0) {
1665 rc = ioctl(fd, BLKGETSIZE64, &size);
1668 "Could not get block device size on %s\n",
1673 DEVOFFSET(dev) = DEVOFFSET(dev) + size;
1676 "Calculated device offset 0x%llx on %s\n",
1677 DEVOFFSET(dev), DEVNAME(dev));
1682 if (ENVSECTORS(dev) == 0)
1683 /* Assume enough sectors to cover the environment */
1684 ENVSECTORS(dev) = DIV_ROUND_UP(ENVSIZE(dev), DEVESIZE(dev));
1686 if (DEVOFFSET(dev) % DEVESIZE(dev) != 0) {
1688 "Environment does not start on (erase) block boundary\n");
1693 if (ENVSIZE(dev) > ENVSECTORS(dev) * DEVESIZE(dev)) {
1695 "Environment does not fit into available sectors\n");
1705 static int parse_config(struct env_opts *opts)
1710 opts = &default_opts;
1712 #if defined(CONFIG_FILE)
1713 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1714 if (get_config(opts->config_file)) {
1715 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1720 DEVNAME(0) = DEVICE1_NAME;
1721 DEVOFFSET(0) = DEVICE1_OFFSET;
1722 ENVSIZE(0) = ENV1_SIZE;
1724 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1727 #ifdef DEVICE1_ESIZE
1728 DEVESIZE(0) = DEVICE1_ESIZE;
1730 #ifdef DEVICE1_ENVSECTORS
1731 ENVSECTORS(0) = DEVICE1_ENVSECTORS;
1735 DEVNAME(1) = DEVICE2_NAME;
1736 DEVOFFSET(1) = DEVICE2_OFFSET;
1737 ENVSIZE(1) = ENV2_SIZE;
1739 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1742 #ifdef DEVICE2_ESIZE
1743 DEVESIZE(1) = DEVICE2_ESIZE;
1745 #ifdef DEVICE2_ENVSECTORS
1746 ENVSECTORS(1) = DEVICE2_ENVSECTORS;
1748 have_redund_env = 1;
1751 rc = check_device_config(0);
1755 if (have_redund_env) {
1756 rc = check_device_config(1);
1760 if (ENVSIZE(0) != ENVSIZE(1)) {
1762 "Redundant environments have unequal size\n");
1767 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1768 if (have_redund_env)
1769 usable_envsize -= sizeof(char);
1774 #if defined(CONFIG_FILE)
1775 static int get_config(char *fname)
1781 size_t linesize = 0;
1784 fp = fopen(fname, "r");
1788 while (i < 2 && getline(&line, &linesize, fp) != -1) {
1789 /* Skip comment strings */
1793 rc = sscanf(line, "%ms %lli %lx %lx %lx",
1796 &ENVSIZE(i), &DEVESIZE(i), &ENVSECTORS(i));
1801 DEVNAME(i) = devname;
1803 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1812 have_redund_env = i - 1;
1813 if (!i) { /* No valid entries found */