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>
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 ENV_REDUND_ACTIVE = 1;
124 * ENV_REDUND_OBSOLETE must be 0 to efficiently set it on NOR flash without
127 static unsigned char ENV_REDUND_OBSOLETE;
129 #define DEFAULT_ENV_INSTANCE_STATIC
130 #include <env_default.h>
132 #define UBI_DEV_START "/dev/ubi"
133 #define UBI_SYSFS "/sys/class/ubi"
134 #define UBI_VOL_NAME_PATT "ubi%d_%d"
136 static int is_ubi_devname(const char *devname)
138 return !strncmp(devname, UBI_DEV_START, sizeof(UBI_DEV_START) - 1);
141 static int ubi_check_volume_sysfs_name(const char *volume_sysfs_name,
149 strcpy(path, UBI_SYSFS "/");
150 strcat(path, volume_sysfs_name);
151 strcat(path, "/name");
153 file = fopen(path, "r");
157 ret = fscanf(file, "%ms", &name);
159 if (ret <= 0 || !name) {
161 "Failed to read from file %s, ret = %d, name = %s\n",
166 if (!strcmp(name, volname)) {
175 static int ubi_get_volnum_by_name(int devnum, const char *volname)
178 struct dirent *dirent;
183 sysfs_ubi = opendir(UBI_SYSFS);
188 fprintf(stderr, "Looking for volume name \"%s\"\n", volname);
192 dirent = readdir(sysfs_ubi);
196 ret = sscanf(dirent->d_name, UBI_VOL_NAME_PATT,
197 &tmp_devnum, &volnum);
198 if (ret == 2 && devnum == tmp_devnum) {
199 if (ubi_check_volume_sysfs_name(dirent->d_name,
208 static int ubi_get_devnum_by_devname(const char *devname)
213 ret = sscanf(devname + sizeof(UBI_DEV_START) - 1, "%d", &devnum);
220 static const char *ubi_get_volume_devname(const char *devname,
223 char *volume_devname;
228 devnum = ubi_get_devnum_by_devname(devname);
232 volnum = ubi_get_volnum_by_name(devnum, volname);
236 ret = asprintf(&volume_devname, "%s_%d", devname, volnum);
241 fprintf(stderr, "Found ubi volume \"%s:%s\" -> %s\n",
242 devname, volname, volume_devname);
245 return volume_devname;
248 static void ubi_check_dev(unsigned int dev_id)
250 char *devname = (char *)DEVNAME(dev_id);
252 const char *volname = NULL;
253 const char *volume_devname;
255 if (!is_ubi_devname(DEVNAME(dev_id)))
260 for (pname = devname; *pname != '\0'; pname++) {
269 /* Let's find real volume device name */
270 volume_devname = ubi_get_volume_devname(devname, volname);
271 if (!volume_devname) {
272 fprintf(stderr, "Didn't found ubi volume \"%s\"\n",
278 DEVNAME(dev_id) = volume_devname;
282 static int ubi_update_start(int fd, int64_t bytes)
284 if (ioctl(fd, UBI_IOCVOLUP, &bytes))
289 static int ubi_read(int fd, void *buf, size_t count)
294 ret = read(fd, buf, count);
304 * Happens in case of too short volume data size. If we
305 * return error status we will fail it will be treated
306 * as UBI device error.
308 * Leave catching this error to CRC check.
310 fprintf(stderr, "Warning: end of data on ubi volume\n");
312 } else if (errno == EBADF) {
314 * Happens in case of corrupted volume. The same as
315 * above, we cannot return error now, as we will still
316 * be able to successfully write environment later.
318 fprintf(stderr, "Warning: corrupted volume?\n");
320 } else if (errno == EINTR) {
324 fprintf(stderr, "Cannot read %u bytes from ubi volume, %s\n",
325 (unsigned int)count, strerror(errno));
332 static int ubi_write(int fd, const void *buf, size_t count)
337 ret = write(fd, buf, count);
339 if (ret < 0 && errno == EINTR)
342 fprintf(stderr, "Cannot write %u bytes to ubi volume\n",
343 (unsigned int)count);
354 static int flash_io(int mode);
355 static int parse_config(struct env_opts *opts);
357 #if defined(CONFIG_FILE)
358 static int get_config(char *);
361 static char *skip_chars(char *s)
363 for (; *s != '\0'; s++) {
364 if (isblank(*s) || *s == '=')
370 static char *skip_blanks(char *s)
372 for (; *s != '\0'; s++) {
380 * s1 is either a simple 'name', or a 'name=value' pair.
381 * s2 is a 'name=value' pair.
382 * If the names match, return the value of s2, else NULL.
384 static char *envmatch(char *s1, char *s2)
386 if (s1 == NULL || s2 == NULL)
392 if (*s1 == '\0' && *(s2 - 1) == '=')
398 * Search the environment for a variable.
399 * Return the value, if found, or NULL, if not found.
401 char *fw_getenv(char *name)
405 for (env = environment.data; *env; env = nxt + 1) {
408 for (nxt = env; *nxt; ++nxt) {
409 if (nxt >= &environment.data[ENV_SIZE]) {
410 fprintf(stderr, "## Error: "
411 "environment not terminated\n");
415 val = envmatch(name, env);
424 * Search the default environment for a variable.
425 * Return the value, if found, or NULL, if not found.
427 char *fw_getdefenv(char *name)
431 for (env = default_environment; *env; env = nxt + 1) {
434 for (nxt = env; *nxt; ++nxt) {
435 if (nxt >= &default_environment[ENV_SIZE]) {
436 fprintf(stderr, "## Error: "
437 "default environment not terminated\n");
441 val = envmatch(name, env);
450 * Print the current definition of one, or more, or all
451 * environment variables
453 int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
457 if (value_only && argc != 1) {
459 "## Error: `-n'/`--noheader' option requires exactly one argument\n");
464 opts = &default_opts;
466 if (fw_env_open(opts))
469 if (argc == 0) { /* Print all env variables */
471 for (env = environment.data; *env; env = nxt + 1) {
472 for (nxt = env; *nxt; ++nxt) {
473 if (nxt >= &environment.data[ENV_SIZE]) {
474 fprintf(stderr, "## Error: "
475 "environment not terminated\n");
486 for (i = 0; i < argc; ++i) { /* print a subset of env variables */
487 char *name = argv[i];
490 val = fw_getenv(name);
492 fprintf(stderr, "## Error: \"%s\" not defined\n", name);
502 printf("%s=%s\n", name, val);
510 int fw_env_flush(struct env_opts *opts)
513 opts = &default_opts;
518 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
520 /* write environment back to flash */
521 if (flash_io(O_RDWR)) {
522 fprintf(stderr, "Error: can't write fw_env to flash\n");
530 * Set/Clear a single variable in the environment.
531 * This is called in sequence to update the environment
532 * in RAM without updating the copy in flash after each set
534 int fw_env_write(char *name, char *value)
539 int deleting, creating, overwriting;
542 * search if variable with this name already exists
544 for (nxt = env = environment.data; *env; env = nxt + 1) {
545 for (nxt = env; *nxt; ++nxt) {
546 if (nxt >= &environment.data[ENV_SIZE]) {
547 fprintf(stderr, "## Error: "
548 "environment not terminated\n");
553 oldval = envmatch(name, env);
558 deleting = (oldval && !(value && strlen(value)));
559 creating = (!oldval && (value && strlen(value)));
560 overwriting = (oldval && (value && strlen(value)));
562 /* check for permission */
564 if (env_flags_validate_varaccess(name,
565 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
566 printf("Can't delete \"%s\"\n", name);
570 } else if (overwriting) {
571 if (env_flags_validate_varaccess(name,
572 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
573 printf("Can't overwrite \"%s\"\n", name);
576 } else if (env_flags_validate_varaccess(name,
577 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
578 const char *defval = fw_getdefenv(name);
582 if (strcmp(oldval, defval)
584 printf("Can't overwrite \"%s\"\n", name);
589 } else if (creating) {
590 if (env_flags_validate_varaccess(name,
591 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
592 printf("Can't create \"%s\"\n", name);
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;
1146 erase.start = DEVOFFSET(dev);
1147 erase.length = DEVESIZE(dev);
1148 /* This relies on the fact, that ENV_REDUND_OBSOLETE == 0 */
1149 rc = lseek(fd, offset, SEEK_SET);
1151 fprintf(stderr, "Cannot seek to set the flag on %s\n",
1155 ioctl(fd, MEMUNLOCK, &erase);
1156 rc = write(fd, &ENV_REDUND_OBSOLETE, sizeof(ENV_REDUND_OBSOLETE));
1157 ioctl(fd, MEMLOCK, &erase);
1159 perror("Could not set obsolete flag");
1164 static int flash_write(int fd_current, int fd_target, int dev_target)
1168 switch (environment.flag_scheme) {
1171 case FLAG_INCREMENTAL:
1172 (*environment.flags)++;
1175 *environment.flags = ENV_REDUND_ACTIVE;
1178 fprintf(stderr, "Unimplemented flash scheme %u\n",
1179 environment.flag_scheme);
1184 fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
1185 DEVOFFSET(dev_target), DEVNAME(dev_target));
1188 if (IS_UBI(dev_target)) {
1189 if (ubi_update_start(fd_target, CUR_ENVSIZE) < 0)
1191 return ubi_write(fd_target, environment.image, CUR_ENVSIZE);
1194 rc = flash_write_buf(dev_target, fd_target, environment.image,
1199 if (environment.flag_scheme == FLAG_BOOLEAN) {
1200 /* Have to set obsolete flag */
1201 off_t offset = DEVOFFSET(dev_current) +
1202 offsetof(struct env_image_redundant, flags);
1205 "Setting obsolete flag in environment at 0x%llx on %s\n",
1206 DEVOFFSET(dev_current), DEVNAME(dev_current));
1208 flash_flag_obsolete(dev_current, fd_current, offset);
1214 static int flash_read(int fd)
1218 if (IS_UBI(dev_current)) {
1219 DEVTYPE(dev_current) = MTD_ABSENT;
1221 return ubi_read(fd, environment.image, CUR_ENVSIZE);
1224 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1225 DEVOFFSET(dev_current));
1226 if (rc != CUR_ENVSIZE)
1232 static int flash_open_tempfile(const char **dname, const char **target_temp)
1234 char *dup_name = strdup(DEVNAME(dev_current));
1235 char *temp_name = NULL;
1241 *dname = dirname(dup_name);
1245 rc = asprintf(&temp_name, "%s/XXXXXX", *dname);
1249 rc = mkstemp(temp_name);
1251 /* fall back to in place write */
1253 "Can't create %s: %s\n", temp_name, strerror(errno));
1256 *target_temp = temp_name;
1257 /* deliberately leak dup_name as dname /might/ point into
1258 * it and we need it for our caller
1270 static int flash_io_write(int fd_current)
1272 int fd_target = -1, rc, dev_target;
1273 const char *dname, *target_temp = NULL;
1275 if (have_redund_env) {
1276 /* switch to next partition for writing */
1277 dev_target = !dev_current;
1278 /* dev_target: fd_target, erase_target */
1279 fd_target = open(DEVNAME(dev_target), O_RDWR);
1280 if (fd_target < 0) {
1282 "Can't open %s: %s\n",
1283 DEVNAME(dev_target), strerror(errno));
1290 if (fstat(fd_current, &sb) == 0 && S_ISREG(sb.st_mode)) {
1291 /* if any part of flash_open_tempfile() fails we fall
1292 * back to in-place writes
1294 fd_target = flash_open_tempfile(&dname, &target_temp);
1296 dev_target = dev_current;
1297 if (fd_target == -1)
1298 fd_target = fd_current;
1301 rc = flash_write(fd_current, fd_target, dev_target);
1303 if (fsync(fd_current) && !(errno == EINVAL || errno == EROFS)) {
1305 "fsync failed on %s: %s\n",
1306 DEVNAME(dev_current), strerror(errno));
1309 if (fd_current != fd_target) {
1310 if (fsync(fd_target) &&
1311 !(errno == EINVAL || errno == EROFS)) {
1313 "fsync failed on %s: %s\n",
1314 DEVNAME(dev_current), strerror(errno));
1317 if (close(fd_target)) {
1319 "I/O error on %s: %s\n",
1320 DEVNAME(dev_target), strerror(errno));
1324 if (rc >= 0 && target_temp) {
1327 dir_fd = open(dname, O_DIRECTORY | O_RDONLY);
1330 "Can't open %s: %s\n",
1331 dname, strerror(errno));
1333 if (rename(target_temp, DEVNAME(dev_target))) {
1335 "rename failed %s => %s: %s\n",
1336 target_temp, DEVNAME(dev_target),
1341 if (dir_fd != -1 && fsync(dir_fd))
1343 "fsync failed on %s: %s\n",
1344 dname, strerror(errno));
1346 if (dir_fd != -1 && close(dir_fd))
1348 "I/O error on %s: %s\n",
1349 dname, strerror(errno));
1356 static int flash_io(int mode)
1360 /* dev_current: fd_current, erase_current */
1361 fd_current = open(DEVNAME(dev_current), mode);
1362 if (fd_current < 0) {
1364 "Can't open %s: %s\n",
1365 DEVNAME(dev_current), strerror(errno));
1369 if (mode == O_RDWR) {
1370 rc = flash_io_write(fd_current);
1372 rc = flash_read(fd_current);
1375 if (close(fd_current)) {
1377 "I/O error on %s: %s\n",
1378 DEVNAME(dev_current), strerror(errno));
1386 * Prevent confusion if running from erased flash memory
1388 int fw_env_open(struct env_opts *opts)
1391 unsigned char flag0;
1395 unsigned char flag1;
1400 struct env_image_single *single;
1401 struct env_image_redundant *redundant;
1404 opts = &default_opts;
1406 if (parse_config(opts)) /* should fill envdevices */
1409 addr0 = calloc(1, CUR_ENVSIZE);
1410 if (addr0 == NULL) {
1412 "Not enough memory for environment (%ld bytes)\n",
1418 /* read environment from FLASH to local buffer */
1419 environment.image = addr0;
1421 if (have_redund_env) {
1423 environment.crc = &redundant->crc;
1424 environment.flags = &redundant->flags;
1425 environment.data = redundant->data;
1428 environment.crc = &single->crc;
1429 environment.flags = NULL;
1430 environment.data = single->data;
1434 if (flash_io(O_RDONLY)) {
1439 crc0 = crc32(0, (uint8_t *)environment.data, ENV_SIZE);
1441 crc0_ok = (crc0 == *environment.crc);
1442 if (!have_redund_env) {
1445 "Warning: Bad CRC, using default environment\n");
1446 memcpy(environment.data, default_environment,
1447 sizeof(default_environment));
1450 flag0 = *environment.flags;
1453 addr1 = calloc(1, CUR_ENVSIZE);
1454 if (addr1 == NULL) {
1456 "Not enough memory for environment (%ld bytes)\n",
1464 * have to set environment.image for flash_read(), careful -
1465 * other pointers in environment still point inside addr0
1467 environment.image = addr1;
1468 if (flash_io(O_RDONLY)) {
1473 /* Check flag scheme compatibility */
1474 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1475 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1476 environment.flag_scheme = FLAG_BOOLEAN;
1477 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1478 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1479 environment.flag_scheme = FLAG_INCREMENTAL;
1480 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1481 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1482 environment.flag_scheme = FLAG_BOOLEAN;
1483 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1484 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1485 environment.flag_scheme = FLAG_INCREMENTAL;
1486 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1487 DEVTYPE(!dev_current) == MTD_ABSENT &&
1488 IS_UBI(dev_current) == IS_UBI(!dev_current)) {
1489 environment.flag_scheme = FLAG_INCREMENTAL;
1491 fprintf(stderr, "Incompatible flash types!\n");
1496 crc1 = crc32(0, (uint8_t *)redundant->data, ENV_SIZE);
1498 crc1_ok = (crc1 == redundant->crc);
1499 flag1 = redundant->flags;
1501 if (crc0_ok && !crc1_ok) {
1503 } else if (!crc0_ok && crc1_ok) {
1505 } else if (!crc0_ok && !crc1_ok) {
1507 "Warning: Bad CRC, using default environment\n");
1508 memcpy(environment.data, default_environment,
1509 sizeof(default_environment));
1512 switch (environment.flag_scheme) {
1514 if (flag0 == ENV_REDUND_ACTIVE &&
1515 flag1 == ENV_REDUND_OBSOLETE) {
1517 } else if (flag0 == ENV_REDUND_OBSOLETE &&
1518 flag1 == ENV_REDUND_ACTIVE) {
1520 } else if (flag0 == flag1) {
1522 } else if (flag0 == 0xFF) {
1524 } else if (flag1 == 0xFF) {
1530 case FLAG_INCREMENTAL:
1531 if (flag0 == 255 && flag1 == 0)
1533 else if ((flag1 == 255 && flag0 == 0) ||
1536 else /* flag1 > flag0 */
1540 fprintf(stderr, "Unknown flag scheme %u\n",
1541 environment.flag_scheme);
1547 * If we are reading, we don't need the flag and the CRC any
1548 * more, if we are writing, we will re-calculate CRC and update
1549 * flags before writing out
1552 environment.image = addr1;
1553 environment.crc = &redundant->crc;
1554 environment.flags = &redundant->flags;
1555 environment.data = redundant->data;
1558 environment.image = addr0;
1559 /* Other pointers are already set */
1563 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1579 * Simply free allocated buffer with environment
1581 int fw_env_close(struct env_opts *opts)
1583 if (environment.image)
1584 free(environment.image);
1586 environment.image = NULL;
1591 static int check_device_config(int dev)
1597 /* Fills in IS_UBI(), converts DEVNAME() with ubi volume name */
1600 fd = open(DEVNAME(dev), O_RDONLY);
1603 "Cannot open %s: %s\n", DEVNAME(dev), strerror(errno));
1607 rc = fstat(fd, &st);
1609 fprintf(stderr, "Cannot stat the file %s\n", DEVNAME(dev));
1614 rc = ioctl(fd, UBI_IOCEBISMAP, &lnum);
1616 fprintf(stderr, "Cannot get UBI information for %s\n",
1620 } else if (S_ISCHR(st.st_mode)) {
1621 struct mtd_info_user mtdinfo;
1622 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1624 fprintf(stderr, "Cannot get MTD information for %s\n",
1628 if (mtdinfo.type != MTD_NORFLASH &&
1629 mtdinfo.type != MTD_NANDFLASH &&
1630 mtdinfo.type != MTD_DATAFLASH &&
1631 mtdinfo.type != MTD_UBIVOLUME) {
1632 fprintf(stderr, "Unsupported flash type %u on %s\n",
1633 mtdinfo.type, DEVNAME(dev));
1636 DEVTYPE(dev) = mtdinfo.type;
1637 if (DEVESIZE(dev) == 0)
1638 /* Assume the erase size is the same as the env-size */
1639 DEVESIZE(dev) = ENVSIZE(dev);
1642 DEVTYPE(dev) = MTD_ABSENT;
1643 if (DEVESIZE(dev) == 0)
1644 /* Assume the erase size to be 512 bytes */
1645 DEVESIZE(dev) = 0x200;
1648 * Check for negative offsets, treat it as backwards offset
1649 * from the end of the block device
1651 if (DEVOFFSET(dev) < 0) {
1652 rc = ioctl(fd, BLKGETSIZE64, &size);
1655 "Could not get block device size on %s\n",
1660 DEVOFFSET(dev) = DEVOFFSET(dev) + size;
1663 "Calculated device offset 0x%llx on %s\n",
1664 DEVOFFSET(dev), DEVNAME(dev));
1669 if (ENVSECTORS(dev) == 0)
1670 /* Assume enough sectors to cover the environment */
1671 ENVSECTORS(dev) = DIV_ROUND_UP(ENVSIZE(dev), DEVESIZE(dev));
1673 if (DEVOFFSET(dev) % DEVESIZE(dev) != 0) {
1675 "Environment does not start on (erase) block boundary\n");
1680 if (ENVSIZE(dev) > ENVSECTORS(dev) * DEVESIZE(dev)) {
1682 "Environment does not fit into available sectors\n");
1692 static int parse_config(struct env_opts *opts)
1697 opts = &default_opts;
1699 #if defined(CONFIG_FILE)
1700 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1701 if (get_config(opts->config_file)) {
1702 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1707 DEVNAME(0) = DEVICE1_NAME;
1708 DEVOFFSET(0) = DEVICE1_OFFSET;
1709 ENVSIZE(0) = ENV1_SIZE;
1711 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1714 #ifdef DEVICE1_ESIZE
1715 DEVESIZE(0) = DEVICE1_ESIZE;
1717 #ifdef DEVICE1_ENVSECTORS
1718 ENVSECTORS(0) = DEVICE1_ENVSECTORS;
1722 DEVNAME(1) = DEVICE2_NAME;
1723 DEVOFFSET(1) = DEVICE2_OFFSET;
1724 ENVSIZE(1) = ENV2_SIZE;
1726 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1729 #ifdef DEVICE2_ESIZE
1730 DEVESIZE(1) = DEVICE2_ESIZE;
1732 #ifdef DEVICE2_ENVSECTORS
1733 ENVSECTORS(1) = DEVICE2_ENVSECTORS;
1735 have_redund_env = 1;
1738 rc = check_device_config(0);
1742 if (have_redund_env) {
1743 rc = check_device_config(1);
1747 if (ENVSIZE(0) != ENVSIZE(1)) {
1749 "Redundant environments have unequal size\n");
1754 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1755 if (have_redund_env)
1756 usable_envsize -= sizeof(char);
1761 #if defined(CONFIG_FILE)
1762 static int get_config(char *fname)
1768 size_t linesize = 0;
1771 fp = fopen(fname, "r");
1775 while (i < 2 && getline(&line, &linesize, fp) != -1) {
1776 /* Skip comment strings */
1780 rc = sscanf(line, "%ms %lli %lx %lx %lx",
1783 &ENVSIZE(i), &DEVESIZE(i), &ENVSECTORS(i));
1788 DEVNAME(i) = devname;
1790 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1799 have_redund_env = i - 1;
1800 if (!i) { /* No valid entries found */