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;
117 static struct environment environment = {
118 .flag_scheme = FLAG_NONE,
121 static int have_redund_env;
123 #define DEFAULT_ENV_INSTANCE_STATIC
124 #include <env_default.h>
126 #define UBI_DEV_START "/dev/ubi"
127 #define UBI_SYSFS "/sys/class/ubi"
128 #define UBI_VOL_NAME_PATT "ubi%d_%d"
130 static int is_ubi_devname(const char *devname)
132 return !strncmp(devname, UBI_DEV_START, sizeof(UBI_DEV_START) - 1);
135 static int ubi_check_volume_sysfs_name(const char *volume_sysfs_name,
143 strcpy(path, UBI_SYSFS "/");
144 strcat(path, volume_sysfs_name);
145 strcat(path, "/name");
147 file = fopen(path, "r");
151 ret = fscanf(file, "%ms", &name);
153 if (ret <= 0 || !name) {
155 "Failed to read from file %s, ret = %d, name = %s\n",
160 if (!strcmp(name, volname)) {
169 static int ubi_get_volnum_by_name(int devnum, const char *volname)
172 struct dirent *dirent;
177 sysfs_ubi = opendir(UBI_SYSFS);
182 fprintf(stderr, "Looking for volume name \"%s\"\n", volname);
186 dirent = readdir(sysfs_ubi);
190 ret = sscanf(dirent->d_name, UBI_VOL_NAME_PATT,
191 &tmp_devnum, &volnum);
192 if (ret == 2 && devnum == tmp_devnum) {
193 if (ubi_check_volume_sysfs_name(dirent->d_name,
202 static int ubi_get_devnum_by_devname(const char *devname)
207 ret = sscanf(devname + sizeof(UBI_DEV_START) - 1, "%d", &devnum);
214 static const char *ubi_get_volume_devname(const char *devname,
217 char *volume_devname;
222 devnum = ubi_get_devnum_by_devname(devname);
226 volnum = ubi_get_volnum_by_name(devnum, volname);
230 ret = asprintf(&volume_devname, "%s_%d", devname, volnum);
235 fprintf(stderr, "Found ubi volume \"%s:%s\" -> %s\n",
236 devname, volname, volume_devname);
239 return volume_devname;
242 static void ubi_check_dev(unsigned int dev_id)
244 char *devname = (char *)DEVNAME(dev_id);
246 const char *volname = NULL;
247 const char *volume_devname;
249 if (!is_ubi_devname(DEVNAME(dev_id)))
254 for (pname = devname; *pname != '\0'; pname++) {
263 /* Let's find real volume device name */
264 volume_devname = ubi_get_volume_devname(devname, volname);
265 if (!volume_devname) {
266 fprintf(stderr, "Didn't found ubi volume \"%s\"\n",
272 DEVNAME(dev_id) = volume_devname;
276 static int ubi_update_start(int fd, int64_t bytes)
278 if (ioctl(fd, UBI_IOCVOLUP, &bytes))
283 static int ubi_read(int fd, void *buf, size_t count)
288 ret = read(fd, buf, count);
298 * Happens in case of too short volume data size. If we
299 * return error status we will fail it will be treated
300 * as UBI device error.
302 * Leave catching this error to CRC check.
304 fprintf(stderr, "Warning: end of data on ubi volume\n");
306 } else if (errno == EBADF) {
308 * Happens in case of corrupted volume. The same as
309 * above, we cannot return error now, as we will still
310 * be able to successfully write environment later.
312 fprintf(stderr, "Warning: corrupted volume?\n");
314 } else if (errno == EINTR) {
318 fprintf(stderr, "Cannot read %u bytes from ubi volume, %s\n",
319 (unsigned int)count, strerror(errno));
326 static int ubi_write(int fd, const void *buf, size_t count)
331 ret = write(fd, buf, count);
333 if (ret < 0 && errno == EINTR)
336 fprintf(stderr, "Cannot write %u bytes to ubi volume\n",
337 (unsigned int)count);
348 static int flash_io(int mode);
349 static int parse_config(struct env_opts *opts);
351 #if defined(CONFIG_FILE)
352 static int get_config(char *);
355 static char *skip_chars(char *s)
357 for (; *s != '\0'; s++) {
358 if (isblank(*s) || *s == '=')
364 static char *skip_blanks(char *s)
366 for (; *s != '\0'; s++) {
374 * s1 is either a simple 'name', or a 'name=value' pair.
375 * s2 is a 'name=value' pair.
376 * If the names match, return the value of s2, else NULL.
378 static char *envmatch(char *s1, char *s2)
380 if (s1 == NULL || s2 == NULL)
386 if (*s1 == '\0' && *(s2 - 1) == '=')
392 * Search the environment for a variable.
393 * Return the value, if found, or NULL, if not found.
395 char *fw_getenv(char *name)
399 for (env = environment.data; *env; env = nxt + 1) {
402 for (nxt = env; *nxt; ++nxt) {
403 if (nxt >= &environment.data[ENV_SIZE]) {
404 fprintf(stderr, "## Error: "
405 "environment not terminated\n");
409 val = envmatch(name, env);
418 * Search the default environment for a variable.
419 * Return the value, if found, or NULL, if not found.
421 char *fw_getdefenv(char *name)
425 for (env = default_environment; *env; env = nxt + 1) {
428 for (nxt = env; *nxt; ++nxt) {
429 if (nxt >= &default_environment[ENV_SIZE]) {
430 fprintf(stderr, "## Error: "
431 "default environment not terminated\n");
435 val = envmatch(name, env);
444 * Print the current definition of one, or more, or all
445 * environment variables
447 int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
451 if (value_only && argc != 1) {
453 "## Error: `-n'/`--noheader' option requires exactly one argument\n");
458 opts = &default_opts;
460 if (fw_env_open(opts))
463 if (argc == 0) { /* Print all env variables */
465 for (env = environment.data; *env; env = nxt + 1) {
466 for (nxt = env; *nxt; ++nxt) {
467 if (nxt >= &environment.data[ENV_SIZE]) {
468 fprintf(stderr, "## Error: "
469 "environment not terminated\n");
480 for (i = 0; i < argc; ++i) { /* print a subset of env variables */
481 char *name = argv[i];
484 val = fw_getenv(name);
486 fprintf(stderr, "## Error: \"%s\" not defined\n", name);
496 printf("%s=%s\n", name, val);
504 int fw_env_flush(struct env_opts *opts)
507 opts = &default_opts;
512 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
514 /* write environment back to flash */
515 if (flash_io(O_RDWR)) {
516 fprintf(stderr, "Error: can't write fw_env to flash\n");
524 * Set/Clear a single variable in the environment.
525 * This is called in sequence to update the environment
526 * in RAM without updating the copy in flash after each set
528 int fw_env_write(char *name, char *value)
533 int deleting, creating, overwriting;
536 * search if variable with this name already exists
538 for (nxt = env = environment.data; *env; env = nxt + 1) {
539 for (nxt = env; *nxt; ++nxt) {
540 if (nxt >= &environment.data[ENV_SIZE]) {
541 fprintf(stderr, "## Error: "
542 "environment not terminated\n");
547 oldval = envmatch(name, env);
552 deleting = (oldval && !(value && strlen(value)));
553 creating = (!oldval && (value && strlen(value)));
554 overwriting = (oldval && (value && strlen(value)));
556 /* check for permission */
558 if (env_flags_validate_varaccess(name,
559 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
560 printf("Can't delete \"%s\"\n", name);
564 } else if (overwriting) {
565 if (env_flags_validate_varaccess(name,
566 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
567 printf("Can't overwrite \"%s\"\n", name);
570 } else if (env_flags_validate_varaccess(name,
571 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
572 const char *defval = fw_getdefenv(name);
576 if (strcmp(oldval, defval)
578 printf("Can't overwrite \"%s\"\n", name);
583 } else if (creating) {
584 if (env_flags_validate_varaccess(name,
585 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
586 printf("Can't create \"%s\"\n", name);
594 if (deleting || overwriting) {
595 if (*++nxt == '\0') {
600 if ((*env == '\0') && (*nxt == '\0'))
609 if (!value || !strlen(value))
613 * Append new definition at the end
615 for (env = environment.data; *env || *(env + 1); ++env)
617 if (env > environment.data)
621 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
623 len = strlen(name) + 2;
624 /* add '=' for first arg, ' ' for all others */
625 len += strlen(value) + 1;
627 if (len > (&environment.data[ENV_SIZE] - env)) {
629 "Error: environment overflow, \"%s\" deleted\n", name);
633 while ((*env = *name++) != '\0')
636 while ((*++env = *value++) != '\0')
639 /* end is marked with double '\0' */
646 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
648 * EINVAL - need at least 1 argument
649 * EROFS - certain variables ("ethaddr", "serial#") cannot be
650 * modified or deleted
653 int fw_env_set(int argc, char *argv[], struct env_opts *opts)
664 opts = &default_opts;
667 fprintf(stderr, "## Error: variable name missing\n");
672 if (fw_env_open(opts)) {
673 fprintf(stderr, "Error: environment not initialized\n");
681 if (env_flags_validate_env_set_params(name, valv, valc) < 0) {
687 for (i = 0; i < valc; ++i) {
689 size_t val_len = strlen(val);
692 value[len - 1] = ' ';
694 value = realloc(value, len + val_len + 1);
697 "Cannot malloc %zu bytes: %s\n",
698 len, strerror(errno));
703 memcpy(value + len, val, val_len);
708 fw_env_write(name, value);
712 ret = fw_env_flush(opts);
719 * Parse a file and configure the u-boot variables.
720 * The script file has a very simple format, as follows:
722 * Each line has a couple with name, value:
723 * <white spaces>variable_name<white spaces>variable_value
725 * Both variable_name and variable_value are interpreted as strings.
726 * Any character after <white spaces> and before ending \r\n is interpreted
727 * as variable's value (no comment allowed on these lines !)
729 * Comments are allowed if the first character in the line is #
731 * Returns -1 and sets errno error codes:
735 int fw_parse_script(char *fname, struct env_opts *opts)
747 opts = &default_opts;
749 if (fw_env_open(opts)) {
750 fprintf(stderr, "Error: environment not initialized\n");
754 if (strcmp(fname, "-") == 0)
757 fp = fopen(fname, "r");
759 fprintf(stderr, "I cannot open %s for reading\n",
765 while ((len = getline(&line, &linesize, fp)) != -1) {
769 * Read a whole line from the file. If the line is not
770 * terminated, reports an error and exit.
772 if (line[len - 1] != '\n') {
774 "Line %d not correctly terminated\n",
780 /* Drop ending line feed / carriage return */
782 if (len && line[len - 1] == '\r')
785 /* Skip comment or empty lines */
786 if (len == 0 || line[0] == '#')
790 * Search for variable's name remove leading whitespaces
792 name = skip_blanks(line);
796 /* The first white space is the end of variable name */
797 val = skip_chars(name);
801 if ((val - name) < len)
802 val = skip_blanks(val);
807 fprintf(stderr, "Setting %s : %s\n",
808 name, val ? val : " removed");
811 if (env_flags_validate_type(name, val) < 0) {
817 * If there is an error setting a variable,
818 * try to save the environment and returns an error
820 if (fw_env_write(name, val)) {
822 "fw_env_write returns with error : %s\n",
831 /* Close file if not stdin */
832 if (strcmp(fname, "-") != 0)
835 ret |= fw_env_flush(opts);
843 * environment_end() - compute offset of first byte right after environment
844 * @dev - index of enviroment buffer
846 * device offset of first byte right after environment
848 off_t environment_end(int dev)
850 /* environment is block aligned */
851 return DEVOFFSET(dev) + ENVSECTORS(dev) * DEVESIZE(dev);
855 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
858 * < 0 - failed to test
860 static int flash_bad_block(int fd, uint8_t mtd_type, loff_t blockstart)
862 if (mtd_type == MTD_NANDFLASH) {
863 int badblock = ioctl(fd, MEMGETBADBLOCK, &blockstart);
866 perror("Cannot read bad block mark");
872 fprintf(stderr, "Bad block at 0x%llx, skipping\n",
873 (unsigned long long)blockstart);
883 * Read data from flash at an offset into a provided buffer. On NAND it skips
884 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
885 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
887 static int flash_read_buf(int dev, int fd, void *buf, size_t count,
890 size_t blocklen; /* erase / write length - one block on NAND,
892 size_t processed = 0; /* progress counter */
893 size_t readlen = count; /* current read length */
894 off_t block_seek; /* offset inside the current block to the start
896 loff_t blockstart; /* running start of the current block -
897 MEMGETBADBLOCK needs 64 bits */
900 blockstart = (offset / DEVESIZE(dev)) * DEVESIZE(dev);
902 /* Offset inside a block */
903 block_seek = offset - blockstart;
905 if (DEVTYPE(dev) == MTD_NANDFLASH) {
907 * NAND: calculate which blocks we are reading. We have
908 * to read one block at a time to skip bad blocks.
910 blocklen = DEVESIZE(dev);
912 /* Limit to one block for the first read */
913 if (readlen > blocklen - block_seek)
914 readlen = blocklen - block_seek;
919 /* This only runs once on NOR flash */
920 while (processed < count) {
921 rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
922 if (rc < 0) /* block test failed */
925 if (blockstart + block_seek + readlen > environment_end(dev)) {
926 /* End of range is reached */
927 fprintf(stderr, "Too few good blocks within range\n");
931 if (rc) { /* block is bad */
932 blockstart += blocklen;
937 * If a block is bad, we retry in the next block at the same
938 * offset - see env/nand.c::writeenv()
940 lseek(fd, blockstart + block_seek, SEEK_SET);
942 rc = read(fd, buf + processed, readlen);
944 fprintf(stderr, "Read error on %s: %s\n",
945 DEVNAME(dev), strerror(errno));
949 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
950 rc, (unsigned long long)blockstart + block_seek,
953 processed += readlen;
954 readlen = min(blocklen, count - processed);
956 blockstart += blocklen;
963 * Write count bytes from begin of environment, but stay within
964 * ENVSECTORS(dev) sectors of
965 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
966 * erase and write the whole data at once.
968 static int flash_write_buf(int dev, int fd, void *buf, size_t count)
971 struct erase_info_user erase;
972 size_t blocklen; /* length of NAND block / NOR erase sector */
973 size_t erase_len; /* whole area that can be erased - may include
975 size_t erasesize; /* erase / write length - one block on NAND,
977 size_t processed = 0; /* progress counter */
978 size_t write_total; /* total size to actually write - excluding
980 off_t erase_offset; /* offset to the first erase block (aligned)
982 off_t block_seek; /* offset inside the erase block to the start
984 loff_t blockstart; /* running start of the current block -
985 MEMGETBADBLOCK needs 64 bits */
989 * For mtd devices only offset and size of the environment do matter
991 if (DEVTYPE(dev) == MTD_ABSENT) {
993 erase_len = blocklen;
994 blockstart = DEVOFFSET(dev);
996 write_total = blocklen;
998 blocklen = DEVESIZE(dev);
1000 erase_offset = DEVOFFSET(dev);
1002 /* Maximum area we may use */
1003 erase_len = environment_end(dev) - erase_offset;
1005 blockstart = erase_offset;
1007 /* Offset inside a block */
1008 block_seek = DEVOFFSET(dev) - erase_offset;
1011 * Data size we actually write: from the start of the block
1012 * to the start of the data, then count bytes of data, and
1013 * to the end of the block
1015 write_total = ((block_seek + count + blocklen - 1) /
1016 blocklen) * blocklen;
1020 * Support data anywhere within erase sectors: read out the complete
1021 * area to be erased, replace the environment image, write the whole
1024 if (write_total > count) {
1025 data = malloc(erase_len);
1028 "Cannot malloc %zu bytes: %s\n",
1029 erase_len, strerror(errno));
1033 rc = flash_read_buf(dev, fd, data, write_total, erase_offset);
1034 if (write_total != rc)
1038 fprintf(stderr, "Preserving data ");
1039 if (block_seek != 0)
1040 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
1041 if (block_seek + count != write_total) {
1042 if (block_seek != 0)
1043 fprintf(stderr, " and ");
1044 fprintf(stderr, "0x%lx - 0x%lx",
1045 (unsigned long)block_seek + count,
1046 (unsigned long)write_total - 1);
1048 fprintf(stderr, "\n");
1050 /* Overwrite the old environment */
1051 memcpy(data + block_seek, buf, count);
1054 * We get here, iff offset is block-aligned and count is a
1055 * multiple of blocklen - see write_total calculation above
1060 if (DEVTYPE(dev) == MTD_NANDFLASH) {
1062 * NAND: calculate which blocks we are writing. We have
1063 * to write one block at a time to skip bad blocks.
1065 erasesize = blocklen;
1067 erasesize = erase_len;
1070 erase.length = erasesize;
1072 /* This only runs once on NOR flash and SPI-dataflash */
1073 while (processed < write_total) {
1074 rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
1075 if (rc < 0) /* block test failed */
1078 if (blockstart + erasesize > environment_end(dev)) {
1079 fprintf(stderr, "End of range reached, aborting\n");
1083 if (rc) { /* block is bad */
1084 blockstart += blocklen;
1088 if (DEVTYPE(dev) != MTD_ABSENT) {
1089 erase.start = blockstart;
1090 ioctl(fd, MEMUNLOCK, &erase);
1091 /* These do not need an explicit erase cycle */
1092 if (DEVTYPE(dev) != MTD_DATAFLASH)
1093 if (ioctl(fd, MEMERASE, &erase) != 0) {
1095 "MTD erase error on %s: %s\n",
1096 DEVNAME(dev), strerror(errno));
1101 if (lseek(fd, blockstart, SEEK_SET) == -1) {
1103 "Seek error on %s: %s\n",
1104 DEVNAME(dev), strerror(errno));
1108 fprintf(stderr, "Write 0x%llx bytes at 0x%llx\n",
1109 (unsigned long long)erasesize,
1110 (unsigned long long)blockstart);
1112 if (write(fd, data + processed, erasesize) != erasesize) {
1113 fprintf(stderr, "Write error on %s: %s\n",
1114 DEVNAME(dev), strerror(errno));
1118 if (DEVTYPE(dev) != MTD_ABSENT)
1119 ioctl(fd, MEMLOCK, &erase);
1121 processed += erasesize;
1123 blockstart += erasesize;
1126 if (write_total > count)
1133 * Set obsolete flag at offset - NOR flash only
1135 static int flash_flag_obsolete(int dev, int fd, off_t offset)
1138 struct erase_info_user erase;
1139 char tmp = ENV_REDUND_OBSOLETE;
1141 erase.start = DEVOFFSET(dev);
1142 erase.length = DEVESIZE(dev);
1143 /* This relies on the fact, that ENV_REDUND_OBSOLETE == 0 */
1144 rc = lseek(fd, offset, SEEK_SET);
1146 fprintf(stderr, "Cannot seek to set the flag on %s\n",
1150 ioctl(fd, MEMUNLOCK, &erase);
1151 rc = write(fd, &tmp, sizeof(tmp));
1152 ioctl(fd, MEMLOCK, &erase);
1154 perror("Could not set obsolete flag");
1159 static int flash_write(int fd_current, int fd_target, int dev_target)
1163 switch (environment.flag_scheme) {
1166 case FLAG_INCREMENTAL:
1167 (*environment.flags)++;
1170 *environment.flags = ENV_REDUND_ACTIVE;
1173 fprintf(stderr, "Unimplemented flash scheme %u\n",
1174 environment.flag_scheme);
1179 fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
1180 DEVOFFSET(dev_target), DEVNAME(dev_target));
1183 if (IS_UBI(dev_target)) {
1184 if (ubi_update_start(fd_target, CUR_ENVSIZE) < 0)
1186 return ubi_write(fd_target, environment.image, CUR_ENVSIZE);
1189 rc = flash_write_buf(dev_target, fd_target, environment.image,
1194 if (environment.flag_scheme == FLAG_BOOLEAN) {
1195 /* Have to set obsolete flag */
1196 off_t offset = DEVOFFSET(dev_current) +
1197 offsetof(struct env_image_redundant, flags);
1200 "Setting obsolete flag in environment at 0x%llx on %s\n",
1201 DEVOFFSET(dev_current), DEVNAME(dev_current));
1203 flash_flag_obsolete(dev_current, fd_current, offset);
1209 static int flash_read(int fd)
1213 if (IS_UBI(dev_current)) {
1214 DEVTYPE(dev_current) = MTD_ABSENT;
1216 return ubi_read(fd, environment.image, CUR_ENVSIZE);
1219 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1220 DEVOFFSET(dev_current));
1221 if (rc != CUR_ENVSIZE)
1227 static int flash_open_tempfile(const char **dname, const char **target_temp)
1229 char *dup_name = strdup(DEVNAME(dev_current));
1230 char *temp_name = NULL;
1236 *dname = dirname(dup_name);
1240 rc = asprintf(&temp_name, "%s/XXXXXX", *dname);
1244 rc = mkstemp(temp_name);
1246 /* fall back to in place write */
1248 "Can't create %s: %s\n", temp_name, strerror(errno));
1251 *target_temp = temp_name;
1252 /* deliberately leak dup_name as dname /might/ point into
1253 * it and we need it for our caller
1265 static int flash_io_write(int fd_current)
1267 int fd_target = -1, rc, dev_target;
1268 const char *dname, *target_temp = NULL;
1270 if (have_redund_env) {
1271 /* switch to next partition for writing */
1272 dev_target = !dev_current;
1273 /* dev_target: fd_target, erase_target */
1274 fd_target = open(DEVNAME(dev_target), O_RDWR);
1275 if (fd_target < 0) {
1277 "Can't open %s: %s\n",
1278 DEVNAME(dev_target), strerror(errno));
1285 if (fstat(fd_current, &sb) == 0 && S_ISREG(sb.st_mode)) {
1286 /* if any part of flash_open_tempfile() fails we fall
1287 * back to in-place writes
1289 fd_target = flash_open_tempfile(&dname, &target_temp);
1291 dev_target = dev_current;
1292 if (fd_target == -1)
1293 fd_target = fd_current;
1296 rc = flash_write(fd_current, fd_target, dev_target);
1298 if (fsync(fd_current) && !(errno == EINVAL || errno == EROFS)) {
1300 "fsync failed on %s: %s\n",
1301 DEVNAME(dev_current), strerror(errno));
1304 if (fd_current != fd_target) {
1305 if (fsync(fd_target) &&
1306 !(errno == EINVAL || errno == EROFS)) {
1308 "fsync failed on %s: %s\n",
1309 DEVNAME(dev_current), strerror(errno));
1312 if (close(fd_target)) {
1314 "I/O error on %s: %s\n",
1315 DEVNAME(dev_target), strerror(errno));
1319 if (rc >= 0 && target_temp) {
1322 dir_fd = open(dname, O_DIRECTORY | O_RDONLY);
1325 "Can't open %s: %s\n",
1326 dname, strerror(errno));
1328 if (rename(target_temp, DEVNAME(dev_target))) {
1330 "rename failed %s => %s: %s\n",
1331 target_temp, DEVNAME(dev_target),
1336 if (dir_fd != -1 && fsync(dir_fd))
1338 "fsync failed on %s: %s\n",
1339 dname, strerror(errno));
1341 if (dir_fd != -1 && close(dir_fd))
1343 "I/O error on %s: %s\n",
1344 dname, strerror(errno));
1351 static int flash_io(int mode)
1355 /* dev_current: fd_current, erase_current */
1356 fd_current = open(DEVNAME(dev_current), mode);
1357 if (fd_current < 0) {
1359 "Can't open %s: %s\n",
1360 DEVNAME(dev_current), strerror(errno));
1364 if (mode == O_RDWR) {
1365 rc = flash_io_write(fd_current);
1367 rc = flash_read(fd_current);
1370 if (close(fd_current)) {
1372 "I/O error on %s: %s\n",
1373 DEVNAME(dev_current), strerror(errno));
1381 * Prevent confusion if running from erased flash memory
1383 int fw_env_open(struct env_opts *opts)
1386 unsigned char flag0;
1390 unsigned char flag1;
1395 struct env_image_single *single;
1396 struct env_image_redundant *redundant;
1399 opts = &default_opts;
1401 if (parse_config(opts)) /* should fill envdevices */
1404 addr0 = calloc(1, CUR_ENVSIZE);
1405 if (addr0 == NULL) {
1407 "Not enough memory for environment (%ld bytes)\n",
1413 /* read environment from FLASH to local buffer */
1414 environment.image = addr0;
1416 if (have_redund_env) {
1418 environment.crc = &redundant->crc;
1419 environment.flags = &redundant->flags;
1420 environment.data = redundant->data;
1423 environment.crc = &single->crc;
1424 environment.flags = NULL;
1425 environment.data = single->data;
1429 if (flash_io(O_RDONLY)) {
1434 crc0 = crc32(0, (uint8_t *)environment.data, ENV_SIZE);
1436 crc0_ok = (crc0 == *environment.crc);
1437 if (!have_redund_env) {
1440 "Warning: Bad CRC, using default environment\n");
1441 memcpy(environment.data, default_environment,
1442 sizeof(default_environment));
1445 flag0 = *environment.flags;
1448 addr1 = calloc(1, CUR_ENVSIZE);
1449 if (addr1 == NULL) {
1451 "Not enough memory for environment (%ld bytes)\n",
1459 * have to set environment.image for flash_read(), careful -
1460 * other pointers in environment still point inside addr0
1462 environment.image = addr1;
1463 if (flash_io(O_RDONLY)) {
1468 /* Check flag scheme compatibility */
1469 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1470 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1471 environment.flag_scheme = FLAG_BOOLEAN;
1472 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1473 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1474 environment.flag_scheme = FLAG_INCREMENTAL;
1475 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1476 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1477 environment.flag_scheme = FLAG_BOOLEAN;
1478 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1479 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1480 environment.flag_scheme = FLAG_INCREMENTAL;
1481 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1482 DEVTYPE(!dev_current) == MTD_ABSENT &&
1483 IS_UBI(dev_current) == IS_UBI(!dev_current)) {
1484 environment.flag_scheme = FLAG_INCREMENTAL;
1486 fprintf(stderr, "Incompatible flash types!\n");
1491 crc1 = crc32(0, (uint8_t *)redundant->data, ENV_SIZE);
1493 crc1_ok = (crc1 == redundant->crc);
1494 flag1 = redundant->flags;
1496 if (crc0_ok && !crc1_ok) {
1498 } else if (!crc0_ok && crc1_ok) {
1500 } else if (!crc0_ok && !crc1_ok) {
1502 "Warning: Bad CRC, using default environment\n");
1503 memcpy(environment.data, default_environment,
1504 sizeof(default_environment));
1507 switch (environment.flag_scheme) {
1509 if (flag0 == ENV_REDUND_ACTIVE &&
1510 flag1 == ENV_REDUND_OBSOLETE) {
1512 } else if (flag0 == ENV_REDUND_OBSOLETE &&
1513 flag1 == ENV_REDUND_ACTIVE) {
1515 } else if (flag0 == flag1) {
1517 } else if (flag0 == 0xFF) {
1519 } else if (flag1 == 0xFF) {
1525 case FLAG_INCREMENTAL:
1526 if (flag0 == 255 && flag1 == 0)
1528 else if ((flag1 == 255 && flag0 == 0) ||
1531 else /* flag1 > flag0 */
1535 fprintf(stderr, "Unknown flag scheme %u\n",
1536 environment.flag_scheme);
1542 * If we are reading, we don't need the flag and the CRC any
1543 * more, if we are writing, we will re-calculate CRC and update
1544 * flags before writing out
1547 environment.image = addr1;
1548 environment.crc = &redundant->crc;
1549 environment.flags = &redundant->flags;
1550 environment.data = redundant->data;
1553 environment.image = addr0;
1554 /* Other pointers are already set */
1558 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1574 * Simply free allocated buffer with environment
1576 int fw_env_close(struct env_opts *opts)
1578 if (environment.image)
1579 free(environment.image);
1581 environment.image = NULL;
1586 static int check_device_config(int dev)
1592 /* Fills in IS_UBI(), converts DEVNAME() with ubi volume name */
1595 fd = open(DEVNAME(dev), O_RDONLY);
1598 "Cannot open %s: %s\n", DEVNAME(dev), strerror(errno));
1602 rc = fstat(fd, &st);
1604 fprintf(stderr, "Cannot stat the file %s\n", DEVNAME(dev));
1609 rc = ioctl(fd, UBI_IOCEBISMAP, &lnum);
1611 fprintf(stderr, "Cannot get UBI information for %s\n",
1615 } else if (S_ISCHR(st.st_mode)) {
1616 struct mtd_info_user mtdinfo;
1617 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1619 fprintf(stderr, "Cannot get MTD information for %s\n",
1623 if (mtdinfo.type != MTD_NORFLASH &&
1624 mtdinfo.type != MTD_NANDFLASH &&
1625 mtdinfo.type != MTD_DATAFLASH &&
1626 mtdinfo.type != MTD_UBIVOLUME) {
1627 fprintf(stderr, "Unsupported flash type %u on %s\n",
1628 mtdinfo.type, DEVNAME(dev));
1631 DEVTYPE(dev) = mtdinfo.type;
1632 if (DEVESIZE(dev) == 0)
1633 /* Assume the erase size is the same as the env-size */
1634 DEVESIZE(dev) = ENVSIZE(dev);
1637 DEVTYPE(dev) = MTD_ABSENT;
1638 if (DEVESIZE(dev) == 0)
1639 /* Assume the erase size to be 512 bytes */
1640 DEVESIZE(dev) = 0x200;
1643 * Check for negative offsets, treat it as backwards offset
1644 * from the end of the block device
1646 if (DEVOFFSET(dev) < 0) {
1647 rc = ioctl(fd, BLKGETSIZE64, &size);
1650 "Could not get block device size on %s\n",
1655 DEVOFFSET(dev) = DEVOFFSET(dev) + size;
1658 "Calculated device offset 0x%llx on %s\n",
1659 DEVOFFSET(dev), DEVNAME(dev));
1664 if (ENVSECTORS(dev) == 0)
1665 /* Assume enough sectors to cover the environment */
1666 ENVSECTORS(dev) = DIV_ROUND_UP(ENVSIZE(dev), DEVESIZE(dev));
1668 if (DEVOFFSET(dev) % DEVESIZE(dev) != 0) {
1670 "Environment does not start on (erase) block boundary\n");
1675 if (ENVSIZE(dev) > ENVSECTORS(dev) * DEVESIZE(dev)) {
1677 "Environment does not fit into available sectors\n");
1687 static int parse_config(struct env_opts *opts)
1692 opts = &default_opts;
1694 #if defined(CONFIG_FILE)
1695 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1696 if (get_config(opts->config_file)) {
1697 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1702 DEVNAME(0) = DEVICE1_NAME;
1703 DEVOFFSET(0) = DEVICE1_OFFSET;
1704 ENVSIZE(0) = ENV1_SIZE;
1706 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1709 #ifdef DEVICE1_ESIZE
1710 DEVESIZE(0) = DEVICE1_ESIZE;
1712 #ifdef DEVICE1_ENVSECTORS
1713 ENVSECTORS(0) = DEVICE1_ENVSECTORS;
1717 DEVNAME(1) = DEVICE2_NAME;
1718 DEVOFFSET(1) = DEVICE2_OFFSET;
1719 ENVSIZE(1) = ENV2_SIZE;
1721 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1724 #ifdef DEVICE2_ESIZE
1725 DEVESIZE(1) = DEVICE2_ESIZE;
1727 #ifdef DEVICE2_ENVSECTORS
1728 ENVSECTORS(1) = DEVICE2_ENVSECTORS;
1730 have_redund_env = 1;
1733 rc = check_device_config(0);
1737 if (have_redund_env) {
1738 rc = check_device_config(1);
1742 if (ENVSIZE(0) != ENVSIZE(1)) {
1744 "Redundant environments have unequal size\n");
1749 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1750 if (have_redund_env)
1751 usable_envsize -= sizeof(char);
1756 #if defined(CONFIG_FILE)
1757 static int get_config(char *fname)
1763 size_t linesize = 0;
1766 fp = fopen(fname, "r");
1770 while (i < 2 && getline(&line, &linesize, fp) != -1) {
1771 /* Skip comment strings */
1775 rc = sscanf(line, "%ms %lli %lx %lx %lx",
1778 &ENVSIZE(i), &DEVESIZE(i), &ENVSECTORS(i));
1783 DEVNAME(i) = devname;
1785 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1794 have_redund_env = i - 1;
1795 if (!i) { /* No valid entries found */