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 #define DEFAULT_ENV_INSTANCE_STATIC
123 #include <env_default.h>
125 #define UBI_DEV_START "/dev/ubi"
126 #define UBI_SYSFS "/sys/class/ubi"
127 #define UBI_VOL_NAME_PATT "ubi%d_%d"
129 static int is_ubi_devname(const char *devname)
131 return !strncmp(devname, UBI_DEV_START, sizeof(UBI_DEV_START) - 1);
134 static int ubi_check_volume_sysfs_name(const char *volume_sysfs_name,
142 strcpy(path, UBI_SYSFS "/");
143 strcat(path, volume_sysfs_name);
144 strcat(path, "/name");
146 file = fopen(path, "r");
150 ret = fscanf(file, "%ms", &name);
152 if (ret <= 0 || !name) {
154 "Failed to read from file %s, ret = %d, name = %s\n",
159 if (!strcmp(name, volname)) {
168 static int ubi_get_volnum_by_name(int devnum, const char *volname)
171 struct dirent *dirent;
176 sysfs_ubi = opendir(UBI_SYSFS);
181 fprintf(stderr, "Looking for volume name \"%s\"\n", volname);
185 dirent = readdir(sysfs_ubi);
189 ret = sscanf(dirent->d_name, UBI_VOL_NAME_PATT,
190 &tmp_devnum, &volnum);
191 if (ret == 2 && devnum == tmp_devnum) {
192 if (ubi_check_volume_sysfs_name(dirent->d_name,
201 static int ubi_get_devnum_by_devname(const char *devname)
206 ret = sscanf(devname + sizeof(UBI_DEV_START) - 1, "%d", &devnum);
213 static const char *ubi_get_volume_devname(const char *devname,
216 char *volume_devname;
221 devnum = ubi_get_devnum_by_devname(devname);
225 volnum = ubi_get_volnum_by_name(devnum, volname);
229 ret = asprintf(&volume_devname, "%s_%d", devname, volnum);
234 fprintf(stderr, "Found ubi volume \"%s:%s\" -> %s\n",
235 devname, volname, volume_devname);
238 return volume_devname;
241 static void ubi_check_dev(unsigned int dev_id)
243 char *devname = (char *)DEVNAME(dev_id);
245 const char *volname = NULL;
246 const char *volume_devname;
248 if (!is_ubi_devname(DEVNAME(dev_id)))
253 for (pname = devname; *pname != '\0'; pname++) {
262 /* Let's find real volume device name */
263 volume_devname = ubi_get_volume_devname(devname, volname);
264 if (!volume_devname) {
265 fprintf(stderr, "Didn't found ubi volume \"%s\"\n",
271 DEVNAME(dev_id) = volume_devname;
275 static int ubi_update_start(int fd, int64_t bytes)
277 if (ioctl(fd, UBI_IOCVOLUP, &bytes))
282 static int ubi_read(int fd, void *buf, size_t count)
287 ret = read(fd, buf, count);
297 * Happens in case of too short volume data size. If we
298 * return error status we will fail it will be treated
299 * as UBI device error.
301 * Leave catching this error to CRC check.
303 fprintf(stderr, "Warning: end of data on ubi volume\n");
305 } else if (errno == EBADF) {
307 * Happens in case of corrupted volume. The same as
308 * above, we cannot return error now, as we will still
309 * be able to successfully write environment later.
311 fprintf(stderr, "Warning: corrupted volume?\n");
313 } else if (errno == EINTR) {
317 fprintf(stderr, "Cannot read %u bytes from ubi volume, %s\n",
318 (unsigned int)count, strerror(errno));
325 static int ubi_write(int fd, const void *buf, size_t count)
330 ret = write(fd, buf, count);
332 if (ret < 0 && errno == EINTR)
335 fprintf(stderr, "Cannot write %u bytes to ubi volume\n",
336 (unsigned int)count);
347 static int flash_io(int mode);
348 static int parse_config(struct env_opts *opts);
350 #if defined(CONFIG_FILE)
351 static int get_config(char *);
354 static char *skip_chars(char *s)
356 for (; *s != '\0'; s++) {
357 if (isblank(*s) || *s == '=')
363 static char *skip_blanks(char *s)
365 for (; *s != '\0'; s++) {
373 * s1 is either a simple 'name', or a 'name=value' pair.
374 * s2 is a 'name=value' pair.
375 * If the names match, return the value of s2, else NULL.
377 static char *envmatch(char *s1, char *s2)
379 if (s1 == NULL || s2 == NULL)
385 if (*s1 == '\0' && *(s2 - 1) == '=')
391 * Search the environment for a variable.
392 * Return the value, if found, or NULL, if not found.
394 char *fw_getenv(char *name)
398 for (env = environment.data; *env; env = nxt + 1) {
401 for (nxt = env; *nxt; ++nxt) {
402 if (nxt >= &environment.data[ENV_SIZE]) {
403 fprintf(stderr, "## Error: "
404 "environment not terminated\n");
408 val = envmatch(name, env);
417 * Search the default environment for a variable.
418 * Return the value, if found, or NULL, if not found.
420 char *fw_getdefenv(char *name)
424 for (env = default_environment; *env; env = nxt + 1) {
427 for (nxt = env; *nxt; ++nxt) {
428 if (nxt >= &default_environment[ENV_SIZE]) {
429 fprintf(stderr, "## Error: "
430 "default environment not terminated\n");
434 val = envmatch(name, env);
443 * Print the current definition of one, or more, or all
444 * environment variables
446 int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
450 if (value_only && argc != 1) {
452 "## Error: `-n'/`--noheader' option requires exactly one argument\n");
457 opts = &default_opts;
459 if (fw_env_open(opts))
462 if (argc == 0) { /* Print all env variables */
464 for (env = environment.data; *env; env = nxt + 1) {
465 for (nxt = env; *nxt; ++nxt) {
466 if (nxt >= &environment.data[ENV_SIZE]) {
467 fprintf(stderr, "## Error: "
468 "environment not terminated\n");
479 for (i = 0; i < argc; ++i) { /* print a subset of env variables */
480 char *name = argv[i];
483 val = fw_getenv(name);
485 fprintf(stderr, "## Error: \"%s\" not defined\n", name);
495 printf("%s=%s\n", name, val);
503 int fw_env_flush(struct env_opts *opts)
506 opts = &default_opts;
511 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
513 /* write environment back to flash */
514 if (flash_io(O_RDWR)) {
515 fprintf(stderr, "Error: can't write fw_env to flash\n");
523 * Set/Clear a single variable in the environment.
524 * This is called in sequence to update the environment
525 * in RAM without updating the copy in flash after each set
527 int fw_env_write(char *name, char *value)
532 int deleting, creating, overwriting;
535 * search if variable with this name already exists
537 for (nxt = env = environment.data; *env; env = nxt + 1) {
538 for (nxt = env; *nxt; ++nxt) {
539 if (nxt >= &environment.data[ENV_SIZE]) {
540 fprintf(stderr, "## Error: "
541 "environment not terminated\n");
546 oldval = envmatch(name, env);
551 deleting = (oldval && !(value && strlen(value)));
552 creating = (!oldval && (value && strlen(value)));
553 overwriting = (oldval && (value && strlen(value)));
555 /* check for permission */
557 if (env_flags_validate_varaccess(name,
558 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
559 printf("Can't delete \"%s\"\n", name);
563 } else if (overwriting) {
564 if (env_flags_validate_varaccess(name,
565 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
566 printf("Can't overwrite \"%s\"\n", name);
569 } else if (env_flags_validate_varaccess(name,
570 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
571 const char *defval = fw_getdefenv(name);
575 if (strcmp(oldval, defval)
577 printf("Can't overwrite \"%s\"\n", name);
582 } else if (creating) {
583 if (env_flags_validate_varaccess(name,
584 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
585 printf("Can't create \"%s\"\n", name);
593 if (deleting || overwriting) {
594 if (*++nxt == '\0') {
599 if ((*env == '\0') && (*nxt == '\0'))
608 if (!value || !strlen(value))
612 * Append new definition at the end
614 for (env = environment.data; *env || *(env + 1); ++env)
616 if (env > environment.data)
620 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
622 len = strlen(name) + 2;
623 /* add '=' for first arg, ' ' for all others */
624 len += strlen(value) + 1;
626 if (len > (&environment.data[ENV_SIZE] - env)) {
628 "Error: environment overflow, \"%s\" deleted\n", name);
632 while ((*env = *name++) != '\0')
635 while ((*++env = *value++) != '\0')
638 /* end is marked with double '\0' */
645 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
647 * EINVAL - need at least 1 argument
648 * EROFS - certain variables ("ethaddr", "serial#") cannot be
649 * modified or deleted
652 int fw_env_set(int argc, char *argv[], struct env_opts *opts)
663 opts = &default_opts;
666 fprintf(stderr, "## Error: variable name missing\n");
671 if (fw_env_open(opts)) {
672 fprintf(stderr, "Error: environment not initialized\n");
680 if (env_flags_validate_env_set_params(name, valv, valc) < 0) {
686 for (i = 0; i < valc; ++i) {
688 size_t val_len = strlen(val);
691 value[len - 1] = ' ';
693 value = realloc(value, len + val_len + 1);
696 "Cannot malloc %zu bytes: %s\n",
697 len, strerror(errno));
702 memcpy(value + len, val, val_len);
707 fw_env_write(name, value);
711 ret = fw_env_flush(opts);
718 * Parse a file and configure the u-boot variables.
719 * The script file has a very simple format, as follows:
721 * Each line has a couple with name, value:
722 * <white spaces>variable_name<white spaces>variable_value
724 * Both variable_name and variable_value are interpreted as strings.
725 * Any character after <white spaces> and before ending \r\n is interpreted
726 * as variable's value (no comment allowed on these lines !)
728 * Comments are allowed if the first character in the line is #
730 * Returns -1 and sets errno error codes:
734 int fw_parse_script(char *fname, struct env_opts *opts)
746 opts = &default_opts;
748 if (fw_env_open(opts)) {
749 fprintf(stderr, "Error: environment not initialized\n");
753 if (strcmp(fname, "-") == 0)
756 fp = fopen(fname, "r");
758 fprintf(stderr, "I cannot open %s for reading\n",
764 while ((len = getline(&line, &linesize, fp)) != -1) {
768 * Read a whole line from the file. If the line is not
769 * terminated, reports an error and exit.
771 if (line[len - 1] != '\n') {
773 "Line %d not correctly terminated\n",
779 /* Drop ending line feed / carriage return */
781 if (len && line[len - 1] == '\r')
784 /* Skip comment or empty lines */
785 if (len == 0 || line[0] == '#')
789 * Search for variable's name remove leading whitespaces
791 name = skip_blanks(line);
795 /* The first white space is the end of variable name */
796 val = skip_chars(name);
800 if ((val - name) < len)
801 val = skip_blanks(val);
806 fprintf(stderr, "Setting %s : %s\n",
807 name, val ? val : " removed");
810 if (env_flags_validate_type(name, val) < 0) {
816 * If there is an error setting a variable,
817 * try to save the environment and returns an error
819 if (fw_env_write(name, val)) {
821 "fw_env_write returns with error : %s\n",
830 /* Close file if not stdin */
831 if (strcmp(fname, "-") != 0)
834 ret |= fw_env_flush(opts);
842 * environment_end() - compute offset of first byte right after environment
843 * @dev - index of enviroment buffer
845 * device offset of first byte right after environment
847 off_t environment_end(int dev)
849 /* environment is block aligned */
850 return DEVOFFSET(dev) + ENVSECTORS(dev) * DEVESIZE(dev);
854 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
857 * < 0 - failed to test
859 static int flash_bad_block(int fd, uint8_t mtd_type, loff_t blockstart)
861 if (mtd_type == MTD_NANDFLASH) {
862 int badblock = ioctl(fd, MEMGETBADBLOCK, &blockstart);
865 perror("Cannot read bad block mark");
871 fprintf(stderr, "Bad block at 0x%llx, skipping\n",
872 (unsigned long long)blockstart);
882 * Read data from flash at an offset into a provided buffer. On NAND it skips
883 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
884 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
886 static int flash_read_buf(int dev, int fd, void *buf, size_t count,
889 size_t blocklen; /* erase / write length - one block on NAND,
891 size_t processed = 0; /* progress counter */
892 size_t readlen = count; /* current read length */
893 off_t block_seek; /* offset inside the current block to the start
895 loff_t blockstart; /* running start of the current block -
896 MEMGETBADBLOCK needs 64 bits */
899 blockstart = (offset / DEVESIZE(dev)) * DEVESIZE(dev);
901 /* Offset inside a block */
902 block_seek = offset - blockstart;
904 if (DEVTYPE(dev) == MTD_NANDFLASH) {
906 * NAND: calculate which blocks we are reading. We have
907 * to read one block at a time to skip bad blocks.
909 blocklen = DEVESIZE(dev);
911 /* Limit to one block for the first read */
912 if (readlen > blocklen - block_seek)
913 readlen = blocklen - block_seek;
918 /* This only runs once on NOR flash */
919 while (processed < count) {
920 rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
921 if (rc < 0) /* block test failed */
924 if (blockstart + block_seek + readlen > environment_end(dev)) {
925 /* End of range is reached */
926 fprintf(stderr, "Too few good blocks within range\n");
930 if (rc) { /* block is bad */
931 blockstart += blocklen;
936 * If a block is bad, we retry in the next block at the same
937 * offset - see env/nand.c::writeenv()
939 lseek(fd, blockstart + block_seek, SEEK_SET);
941 rc = read(fd, buf + processed, readlen);
943 fprintf(stderr, "Read error on %s: %s\n",
944 DEVNAME(dev), strerror(errno));
948 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
949 rc, (unsigned long long)blockstart + block_seek,
952 processed += readlen;
953 readlen = min(blocklen, count - processed);
955 blockstart += blocklen;
962 * Write count bytes from begin of environment, but stay within
963 * ENVSECTORS(dev) sectors of
964 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
965 * erase and write the whole data at once.
967 static int flash_write_buf(int dev, int fd, void *buf, size_t count)
970 struct erase_info_user erase;
971 size_t blocklen; /* length of NAND block / NOR erase sector */
972 size_t erase_len; /* whole area that can be erased - may include
974 size_t erasesize; /* erase / write length - one block on NAND,
976 size_t processed = 0; /* progress counter */
977 size_t write_total; /* total size to actually write - excluding
979 off_t erase_offset; /* offset to the first erase block (aligned)
981 off_t block_seek; /* offset inside the erase block to the start
983 loff_t blockstart; /* running start of the current block -
984 MEMGETBADBLOCK needs 64 bits */
988 * For mtd devices only offset and size of the environment do matter
990 if (DEVTYPE(dev) == MTD_ABSENT) {
992 erase_len = blocklen;
993 blockstart = DEVOFFSET(dev);
995 write_total = blocklen;
997 blocklen = DEVESIZE(dev);
999 erase_offset = DEVOFFSET(dev);
1001 /* Maximum area we may use */
1002 erase_len = environment_end(dev) - erase_offset;
1004 blockstart = erase_offset;
1006 /* Offset inside a block */
1007 block_seek = DEVOFFSET(dev) - erase_offset;
1010 * Data size we actually write: from the start of the block
1011 * to the start of the data, then count bytes of data, and
1012 * to the end of the block
1014 write_total = ((block_seek + count + blocklen - 1) /
1015 blocklen) * blocklen;
1019 * Support data anywhere within erase sectors: read out the complete
1020 * area to be erased, replace the environment image, write the whole
1023 if (write_total > count) {
1024 data = malloc(erase_len);
1027 "Cannot malloc %zu bytes: %s\n",
1028 erase_len, strerror(errno));
1032 rc = flash_read_buf(dev, fd, data, write_total, erase_offset);
1033 if (write_total != rc)
1037 fprintf(stderr, "Preserving data ");
1038 if (block_seek != 0)
1039 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
1040 if (block_seek + count != write_total) {
1041 if (block_seek != 0)
1042 fprintf(stderr, " and ");
1043 fprintf(stderr, "0x%lx - 0x%lx",
1044 (unsigned long)block_seek + count,
1045 (unsigned long)write_total - 1);
1047 fprintf(stderr, "\n");
1049 /* Overwrite the old environment */
1050 memcpy(data + block_seek, buf, count);
1053 * We get here, iff offset is block-aligned and count is a
1054 * multiple of blocklen - see write_total calculation above
1059 if (DEVTYPE(dev) == MTD_NANDFLASH) {
1061 * NAND: calculate which blocks we are writing. We have
1062 * to write one block at a time to skip bad blocks.
1064 erasesize = blocklen;
1066 erasesize = erase_len;
1069 erase.length = erasesize;
1071 /* This only runs once on NOR flash and SPI-dataflash */
1072 while (processed < write_total) {
1073 rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
1074 if (rc < 0) /* block test failed */
1077 if (blockstart + erasesize > environment_end(dev)) {
1078 fprintf(stderr, "End of range reached, aborting\n");
1082 if (rc) { /* block is bad */
1083 blockstart += blocklen;
1087 if (DEVTYPE(dev) != MTD_ABSENT) {
1088 erase.start = blockstart;
1089 ioctl(fd, MEMUNLOCK, &erase);
1090 /* These do not need an explicit erase cycle */
1091 if (DEVTYPE(dev) != MTD_DATAFLASH)
1092 if (ioctl(fd, MEMERASE, &erase) != 0) {
1094 "MTD erase error on %s: %s\n",
1095 DEVNAME(dev), strerror(errno));
1100 if (lseek(fd, blockstart, SEEK_SET) == -1) {
1102 "Seek error on %s: %s\n",
1103 DEVNAME(dev), strerror(errno));
1107 fprintf(stderr, "Write 0x%llx bytes at 0x%llx\n",
1108 (unsigned long long)erasesize,
1109 (unsigned long long)blockstart);
1111 if (write(fd, data + processed, erasesize) != erasesize) {
1112 fprintf(stderr, "Write error on %s: %s\n",
1113 DEVNAME(dev), strerror(errno));
1117 if (DEVTYPE(dev) != MTD_ABSENT)
1118 ioctl(fd, MEMLOCK, &erase);
1120 processed += erasesize;
1122 blockstart += erasesize;
1125 if (write_total > count)
1132 * Set obsolete flag at offset - NOR flash only
1134 static int flash_flag_obsolete(int dev, int fd, off_t offset)
1137 struct erase_info_user erase;
1138 char tmp = ENV_REDUND_OBSOLETE;
1140 erase.start = DEVOFFSET(dev);
1141 erase.length = DEVESIZE(dev);
1142 /* This relies on the fact, that ENV_REDUND_OBSOLETE == 0 */
1143 rc = lseek(fd, offset, SEEK_SET);
1145 fprintf(stderr, "Cannot seek to set the flag on %s\n",
1149 ioctl(fd, MEMUNLOCK, &erase);
1150 rc = write(fd, &tmp, sizeof(tmp));
1151 ioctl(fd, MEMLOCK, &erase);
1153 perror("Could not set obsolete flag");
1158 static int flash_write(int fd_current, int fd_target, int dev_target)
1162 switch (environment.flag_scheme) {
1165 case FLAG_INCREMENTAL:
1166 (*environment.flags)++;
1169 *environment.flags = ENV_REDUND_ACTIVE;
1172 fprintf(stderr, "Unimplemented flash scheme %u\n",
1173 environment.flag_scheme);
1178 fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
1179 DEVOFFSET(dev_target), DEVNAME(dev_target));
1182 if (IS_UBI(dev_target)) {
1183 if (ubi_update_start(fd_target, CUR_ENVSIZE) < 0)
1185 return ubi_write(fd_target, environment.image, CUR_ENVSIZE);
1188 rc = flash_write_buf(dev_target, fd_target, environment.image,
1193 if (environment.flag_scheme == FLAG_BOOLEAN) {
1194 /* Have to set obsolete flag */
1195 off_t offset = DEVOFFSET(dev_current) +
1196 offsetof(struct env_image_redundant, flags);
1199 "Setting obsolete flag in environment at 0x%llx on %s\n",
1200 DEVOFFSET(dev_current), DEVNAME(dev_current));
1202 flash_flag_obsolete(dev_current, fd_current, offset);
1208 static int flash_read(int fd)
1212 if (IS_UBI(dev_current)) {
1213 DEVTYPE(dev_current) = MTD_ABSENT;
1215 return ubi_read(fd, environment.image, CUR_ENVSIZE);
1218 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1219 DEVOFFSET(dev_current));
1220 if (rc != CUR_ENVSIZE)
1226 static int flash_open_tempfile(const char **dname, const char **target_temp)
1228 char *dup_name = strdup(DEVNAME(dev_current));
1229 char *temp_name = NULL;
1235 *dname = dirname(dup_name);
1239 rc = asprintf(&temp_name, "%s/XXXXXX", *dname);
1243 rc = mkstemp(temp_name);
1245 /* fall back to in place write */
1247 "Can't create %s: %s\n", temp_name, strerror(errno));
1250 *target_temp = temp_name;
1251 /* deliberately leak dup_name as dname /might/ point into
1252 * it and we need it for our caller
1264 static int flash_io_write(int fd_current)
1266 int fd_target = -1, rc, dev_target;
1267 const char *dname, *target_temp = NULL;
1269 if (have_redund_env) {
1270 /* switch to next partition for writing */
1271 dev_target = !dev_current;
1272 /* dev_target: fd_target, erase_target */
1273 fd_target = open(DEVNAME(dev_target), O_RDWR);
1274 if (fd_target < 0) {
1276 "Can't open %s: %s\n",
1277 DEVNAME(dev_target), strerror(errno));
1284 if (fstat(fd_current, &sb) == 0 && S_ISREG(sb.st_mode)) {
1285 /* if any part of flash_open_tempfile() fails we fall
1286 * back to in-place writes
1288 fd_target = flash_open_tempfile(&dname, &target_temp);
1290 dev_target = dev_current;
1291 if (fd_target == -1)
1292 fd_target = fd_current;
1295 rc = flash_write(fd_current, fd_target, dev_target);
1297 if (fsync(fd_current) && !(errno == EINVAL || errno == EROFS)) {
1299 "fsync failed on %s: %s\n",
1300 DEVNAME(dev_current), strerror(errno));
1303 if (fd_current != fd_target) {
1304 if (fsync(fd_target) &&
1305 !(errno == EINVAL || errno == EROFS)) {
1307 "fsync failed on %s: %s\n",
1308 DEVNAME(dev_current), strerror(errno));
1311 if (close(fd_target)) {
1313 "I/O error on %s: %s\n",
1314 DEVNAME(dev_target), strerror(errno));
1318 if (rc >= 0 && target_temp) {
1321 dir_fd = open(dname, O_DIRECTORY | O_RDONLY);
1324 "Can't open %s: %s\n",
1325 dname, strerror(errno));
1327 if (rename(target_temp, DEVNAME(dev_target))) {
1329 "rename failed %s => %s: %s\n",
1330 target_temp, DEVNAME(dev_target),
1335 if (dir_fd != -1 && fsync(dir_fd))
1337 "fsync failed on %s: %s\n",
1338 dname, strerror(errno));
1340 if (dir_fd != -1 && close(dir_fd))
1342 "I/O error on %s: %s\n",
1343 dname, strerror(errno));
1350 static int flash_io(int mode)
1354 /* dev_current: fd_current, erase_current */
1355 fd_current = open(DEVNAME(dev_current), mode);
1356 if (fd_current < 0) {
1358 "Can't open %s: %s\n",
1359 DEVNAME(dev_current), strerror(errno));
1363 if (mode == O_RDWR) {
1364 rc = flash_io_write(fd_current);
1366 rc = flash_read(fd_current);
1369 if (close(fd_current)) {
1371 "I/O error on %s: %s\n",
1372 DEVNAME(dev_current), strerror(errno));
1380 * Prevent confusion if running from erased flash memory
1382 int fw_env_open(struct env_opts *opts)
1385 unsigned char flag0;
1389 unsigned char flag1;
1394 struct env_image_single *single;
1395 struct env_image_redundant *redundant;
1398 opts = &default_opts;
1400 if (parse_config(opts)) /* should fill envdevices */
1403 addr0 = calloc(1, CUR_ENVSIZE);
1404 if (addr0 == NULL) {
1406 "Not enough memory for environment (%ld bytes)\n",
1412 /* read environment from FLASH to local buffer */
1413 environment.image = addr0;
1415 if (have_redund_env) {
1417 environment.crc = &redundant->crc;
1418 environment.flags = &redundant->flags;
1419 environment.data = redundant->data;
1422 environment.crc = &single->crc;
1423 environment.flags = NULL;
1424 environment.data = single->data;
1428 if (flash_io(O_RDONLY)) {
1433 crc0 = crc32(0, (uint8_t *)environment.data, ENV_SIZE);
1435 crc0_ok = (crc0 == *environment.crc);
1436 if (!have_redund_env) {
1439 "Warning: Bad CRC, using default environment\n");
1440 memcpy(environment.data, default_environment,
1441 sizeof(default_environment));
1444 flag0 = *environment.flags;
1447 addr1 = calloc(1, CUR_ENVSIZE);
1448 if (addr1 == NULL) {
1450 "Not enough memory for environment (%ld bytes)\n",
1458 * have to set environment.image for flash_read(), careful -
1459 * other pointers in environment still point inside addr0
1461 environment.image = addr1;
1462 if (flash_io(O_RDONLY)) {
1467 /* Check flag scheme compatibility */
1468 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1469 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1470 environment.flag_scheme = FLAG_BOOLEAN;
1471 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1472 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1473 environment.flag_scheme = FLAG_INCREMENTAL;
1474 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1475 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1476 environment.flag_scheme = FLAG_BOOLEAN;
1477 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1478 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1479 environment.flag_scheme = FLAG_INCREMENTAL;
1480 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1481 DEVTYPE(!dev_current) == MTD_ABSENT &&
1482 IS_UBI(dev_current) == IS_UBI(!dev_current)) {
1483 environment.flag_scheme = FLAG_INCREMENTAL;
1485 fprintf(stderr, "Incompatible flash types!\n");
1490 crc1 = crc32(0, (uint8_t *)redundant->data, ENV_SIZE);
1492 crc1_ok = (crc1 == redundant->crc);
1493 flag1 = redundant->flags;
1495 if (crc0_ok && !crc1_ok) {
1497 } else if (!crc0_ok && crc1_ok) {
1499 } else if (!crc0_ok && !crc1_ok) {
1501 "Warning: Bad CRC, using default environment\n");
1502 memcpy(environment.data, default_environment,
1503 sizeof(default_environment));
1506 switch (environment.flag_scheme) {
1508 if (flag0 == ENV_REDUND_ACTIVE &&
1509 flag1 == ENV_REDUND_OBSOLETE) {
1511 } else if (flag0 == ENV_REDUND_OBSOLETE &&
1512 flag1 == ENV_REDUND_ACTIVE) {
1514 } else if (flag0 == flag1) {
1516 } else if (flag0 == 0xFF) {
1518 } else if (flag1 == 0xFF) {
1524 case FLAG_INCREMENTAL:
1525 if (flag0 == 255 && flag1 == 0)
1527 else if ((flag1 == 255 && flag0 == 0) ||
1530 else /* flag1 > flag0 */
1534 fprintf(stderr, "Unknown flag scheme %u\n",
1535 environment.flag_scheme);
1541 * If we are reading, we don't need the flag and the CRC any
1542 * more, if we are writing, we will re-calculate CRC and update
1543 * flags before writing out
1546 environment.image = addr1;
1547 environment.crc = &redundant->crc;
1548 environment.flags = &redundant->flags;
1549 environment.data = redundant->data;
1552 environment.image = addr0;
1553 /* Other pointers are already set */
1557 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1573 * Simply free allocated buffer with environment
1575 int fw_env_close(struct env_opts *opts)
1577 if (environment.image)
1578 free(environment.image);
1580 environment.image = NULL;
1585 static int check_device_config(int dev)
1591 /* Fills in IS_UBI(), converts DEVNAME() with ubi volume name */
1594 fd = open(DEVNAME(dev), O_RDONLY);
1597 "Cannot open %s: %s\n", DEVNAME(dev), strerror(errno));
1601 rc = fstat(fd, &st);
1603 fprintf(stderr, "Cannot stat the file %s\n", DEVNAME(dev));
1608 rc = ioctl(fd, UBI_IOCEBISMAP, &lnum);
1610 fprintf(stderr, "Cannot get UBI information for %s\n",
1614 } else if (S_ISCHR(st.st_mode)) {
1615 struct mtd_info_user mtdinfo;
1616 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1618 fprintf(stderr, "Cannot get MTD information for %s\n",
1622 if (mtdinfo.type != MTD_NORFLASH &&
1623 mtdinfo.type != MTD_NANDFLASH &&
1624 mtdinfo.type != MTD_DATAFLASH &&
1625 mtdinfo.type != MTD_UBIVOLUME) {
1626 fprintf(stderr, "Unsupported flash type %u on %s\n",
1627 mtdinfo.type, DEVNAME(dev));
1630 DEVTYPE(dev) = mtdinfo.type;
1631 if (DEVESIZE(dev) == 0)
1632 /* Assume the erase size is the same as the env-size */
1633 DEVESIZE(dev) = ENVSIZE(dev);
1636 DEVTYPE(dev) = MTD_ABSENT;
1637 if (DEVESIZE(dev) == 0)
1638 /* Assume the erase size to be 512 bytes */
1639 DEVESIZE(dev) = 0x200;
1642 * Check for negative offsets, treat it as backwards offset
1643 * from the end of the block device
1645 if (DEVOFFSET(dev) < 0) {
1646 rc = ioctl(fd, BLKGETSIZE64, &size);
1649 "Could not get block device size on %s\n",
1654 DEVOFFSET(dev) = DEVOFFSET(dev) + size;
1657 "Calculated device offset 0x%llx on %s\n",
1658 DEVOFFSET(dev), DEVNAME(dev));
1663 if (ENVSECTORS(dev) == 0)
1664 /* Assume enough sectors to cover the environment */
1665 ENVSECTORS(dev) = DIV_ROUND_UP(ENVSIZE(dev), DEVESIZE(dev));
1667 if (DEVOFFSET(dev) % DEVESIZE(dev) != 0) {
1669 "Environment does not start on (erase) block boundary\n");
1674 if (ENVSIZE(dev) > ENVSECTORS(dev) * DEVESIZE(dev)) {
1676 "Environment does not fit into available sectors\n");
1686 static int parse_config(struct env_opts *opts)
1691 opts = &default_opts;
1693 #if defined(CONFIG_FILE)
1694 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1695 if (get_config(opts->config_file)) {
1696 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1701 DEVNAME(0) = DEVICE1_NAME;
1702 DEVOFFSET(0) = DEVICE1_OFFSET;
1703 ENVSIZE(0) = ENV1_SIZE;
1705 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1708 #ifdef DEVICE1_ESIZE
1709 DEVESIZE(0) = DEVICE1_ESIZE;
1711 #ifdef DEVICE1_ENVSECTORS
1712 ENVSECTORS(0) = DEVICE1_ENVSECTORS;
1716 DEVNAME(1) = DEVICE2_NAME;
1717 DEVOFFSET(1) = DEVICE2_OFFSET;
1718 ENVSIZE(1) = ENV2_SIZE;
1720 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1723 #ifdef DEVICE2_ESIZE
1724 DEVESIZE(1) = DEVICE2_ESIZE;
1726 #ifdef DEVICE2_ENVSECTORS
1727 ENVSECTORS(1) = DEVICE2_ENVSECTORS;
1729 have_redund_env = 1;
1732 rc = check_device_config(0);
1736 if (have_redund_env) {
1737 rc = check_device_config(1);
1741 if (ENVSIZE(0) != ENVSIZE(1)) {
1743 "Redundant environments have unequal size\n");
1748 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1749 if (have_redund_env)
1750 usable_envsize -= sizeof(char);
1755 #if defined(CONFIG_FILE)
1756 static int get_config(char *fname)
1762 size_t linesize = 0;
1765 fp = fopen(fname, "r");
1769 while (i < 2 && getline(&line, &linesize, fp) != -1) {
1770 /* Skip comment strings */
1774 rc = sscanf(line, "%ms %lli %lx %lx %lx",
1777 &ENVSIZE(i), &DEVESIZE(i), &ENVSECTORS(i));
1782 DEVNAME(i) = devname;
1784 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1793 have_redund_env = i - 1;
1794 if (!i) { /* No valid entries found */