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.
14 #include <env_flags.h>
18 #include <linux/stringify.h>
24 #include <sys/types.h>
25 #include <sys/ioctl.h>
32 # include <linux/mtd/mtd.h>
34 # define __user /* nothing */
35 # include <mtd/mtd-user.h>
38 #include <mtd/ubi-user.h>
40 #include "fw_env_private.h"
43 struct env_opts default_opts
= {
45 .config_file
= CONFIG_FILE
49 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
51 #define min(x, y) ({ \
52 typeof(x) _min1 = (x); \
53 typeof(y) _min2 = (y); \
54 (void) (&_min1 == &_min2); \
55 _min1 < _min2 ? _min1 : _min2; })
58 const char *devname
; /* Device name */
59 long long devoff
; /* Device offset */
60 ulong env_size
; /* environment size */
61 ulong erase_size
; /* device erase size */
62 ulong env_sectors
; /* number of environment sectors */
63 uint8_t mtd_type
; /* type of the MTD device */
64 int is_ubi
; /* set if we use UBI volume */
67 static struct envdev_s envdevices
[2] = {
69 .mtd_type
= MTD_ABSENT
,
71 .mtd_type
= MTD_ABSENT
,
75 static int dev_current
;
77 #define DEVNAME(i) envdevices[(i)].devname
78 #define DEVOFFSET(i) envdevices[(i)].devoff
79 #define ENVSIZE(i) envdevices[(i)].env_size
80 #define DEVESIZE(i) envdevices[(i)].erase_size
81 #define ENVSECTORS(i) envdevices[(i)].env_sectors
82 #define DEVTYPE(i) envdevices[(i)].mtd_type
83 #define IS_UBI(i) envdevices[(i)].is_ubi
85 #define CUR_ENVSIZE ENVSIZE(dev_current)
87 static unsigned long usable_envsize
;
88 #define ENV_SIZE usable_envsize
90 struct env_image_single
{
91 uint32_t crc
; /* CRC32 over data bytes */
95 struct env_image_redundant
{
96 uint32_t crc
; /* CRC32 over data bytes */
97 unsigned char flags
; /* active or obsolete */
110 unsigned char *flags
;
112 enum flag_scheme flag_scheme
;
115 static struct environment environment
= {
116 .flag_scheme
= FLAG_NONE
,
119 static int have_redund_env
;
121 static unsigned char active_flag
= 1;
122 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
123 static unsigned char obsolete_flag
= 0;
125 #define DEFAULT_ENV_INSTANCE_STATIC
126 #include <env_default.h>
128 #define UBI_DEV_START "/dev/ubi"
129 #define UBI_SYSFS "/sys/class/ubi"
130 #define UBI_VOL_NAME_PATT "ubi%d_%d"
132 static int is_ubi_devname(const char *devname
)
134 return !strncmp(devname
, UBI_DEV_START
, sizeof(UBI_DEV_START
) - 1);
137 static int ubi_check_volume_sysfs_name(const char *volume_sysfs_name
,
145 strcpy(path
, UBI_SYSFS
"/");
146 strcat(path
, volume_sysfs_name
);
147 strcat(path
, "/name");
149 file
= fopen(path
, "r");
153 ret
= fscanf(file
, "%ms", &name
);
155 if (ret
<= 0 || !name
) {
157 "Failed to read from file %s, ret = %d, name = %s\n",
162 if (!strcmp(name
, volname
)) {
171 static int ubi_get_volnum_by_name(int devnum
, const char *volname
)
174 struct dirent
*dirent
;
179 sysfs_ubi
= opendir(UBI_SYSFS
);
184 fprintf(stderr
, "Looking for volume name \"%s\"\n", volname
);
188 dirent
= readdir(sysfs_ubi
);
192 ret
= sscanf(dirent
->d_name
, UBI_VOL_NAME_PATT
,
193 &tmp_devnum
, &volnum
);
194 if (ret
== 2 && devnum
== tmp_devnum
) {
195 if (ubi_check_volume_sysfs_name(dirent
->d_name
,
204 static int ubi_get_devnum_by_devname(const char *devname
)
209 ret
= sscanf(devname
+ sizeof(UBI_DEV_START
) - 1, "%d", &devnum
);
216 static const char *ubi_get_volume_devname(const char *devname
,
219 char *volume_devname
;
224 devnum
= ubi_get_devnum_by_devname(devname
);
228 volnum
= ubi_get_volnum_by_name(devnum
, volname
);
232 ret
= asprintf(&volume_devname
, "%s_%d", devname
, volnum
);
237 fprintf(stderr
, "Found ubi volume \"%s:%s\" -> %s\n",
238 devname
, volname
, volume_devname
);
241 return volume_devname
;
244 static void ubi_check_dev(unsigned int dev_id
)
246 char *devname
= (char *)DEVNAME(dev_id
);
248 const char *volname
= NULL
;
249 const char *volume_devname
;
251 if (!is_ubi_devname(DEVNAME(dev_id
)))
256 for (pname
= devname
; *pname
!= '\0'; pname
++) {
265 /* Let's find real volume device name */
266 volume_devname
= ubi_get_volume_devname(devname
, volname
);
267 if (!volume_devname
) {
268 fprintf(stderr
, "Didn't found ubi volume \"%s\"\n",
274 DEVNAME(dev_id
) = volume_devname
;
278 static int ubi_update_start(int fd
, int64_t bytes
)
280 if (ioctl(fd
, UBI_IOCVOLUP
, &bytes
))
285 static int ubi_read(int fd
, void *buf
, size_t count
)
290 ret
= read(fd
, buf
, count
);
300 * Happens in case of too short volume data size. If we
301 * return error status we will fail it will be treated
302 * as UBI device error.
304 * Leave catching this error to CRC check.
306 fprintf(stderr
, "Warning: end of data on ubi volume\n");
308 } else if (errno
== EBADF
) {
310 * Happens in case of corrupted volume. The same as
311 * above, we cannot return error now, as we will still
312 * be able to successfully write environment later.
314 fprintf(stderr
, "Warning: corrupted volume?\n");
316 } else if (errno
== EINTR
) {
320 fprintf(stderr
, "Cannot read %u bytes from ubi volume, %s\n",
321 (unsigned int)count
, strerror(errno
));
328 static int ubi_write(int fd
, const void *buf
, size_t count
)
333 ret
= write(fd
, buf
, count
);
335 if (ret
< 0 && errno
== EINTR
)
338 fprintf(stderr
, "Cannot write %u bytes to ubi volume\n",
339 (unsigned int)count
);
350 static int flash_io(int mode
);
351 static int parse_config(struct env_opts
*opts
);
353 #if defined(CONFIG_FILE)
354 static int get_config(char *);
357 static char *skip_chars(char *s
)
359 for (; *s
!= '\0'; s
++) {
360 if (isblank(*s
) || *s
== '=')
366 static char *skip_blanks(char *s
)
368 for (; *s
!= '\0'; s
++) {
376 * s1 is either a simple 'name', or a 'name=value' pair.
377 * s2 is a 'name=value' pair.
378 * If the names match, return the value of s2, else NULL.
380 static char *envmatch(char *s1
, char *s2
)
382 if (s1
== NULL
|| s2
== NULL
)
388 if (*s1
== '\0' && *(s2
- 1) == '=')
394 * Search the environment for a variable.
395 * Return the value, if found, or NULL, if not found.
397 char *fw_getenv(char *name
)
401 for (env
= environment
.data
; *env
; env
= nxt
+ 1) {
404 for (nxt
= env
; *nxt
; ++nxt
) {
405 if (nxt
>= &environment
.data
[ENV_SIZE
]) {
406 fprintf(stderr
, "## Error: "
407 "environment not terminated\n");
411 val
= envmatch(name
, env
);
420 * Search the default environment for a variable.
421 * Return the value, if found, or NULL, if not found.
423 char *fw_getdefenv(char *name
)
427 for (env
= default_environment
; *env
; env
= nxt
+ 1) {
430 for (nxt
= env
; *nxt
; ++nxt
) {
431 if (nxt
>= &default_environment
[ENV_SIZE
]) {
432 fprintf(stderr
, "## Error: "
433 "default environment not terminated\n");
437 val
= envmatch(name
, env
);
446 * Print the current definition of one, or more, or all
447 * environment variables
449 int fw_printenv(int argc
, char *argv
[], int value_only
, struct env_opts
*opts
)
453 if (value_only
&& argc
!= 1) {
455 "## Error: `-n'/`--noheader' option requires exactly one argument\n");
460 opts
= &default_opts
;
462 if (fw_env_open(opts
))
465 if (argc
== 0) { /* Print all env variables */
467 for (env
= environment
.data
; *env
; env
= nxt
+ 1) {
468 for (nxt
= env
; *nxt
; ++nxt
) {
469 if (nxt
>= &environment
.data
[ENV_SIZE
]) {
470 fprintf(stderr
, "## Error: "
471 "environment not terminated\n");
482 for (i
= 0; i
< argc
; ++i
) { /* print a subset of env variables */
483 char *name
= argv
[i
];
486 val
= fw_getenv(name
);
488 fprintf(stderr
, "## Error: \"%s\" not defined\n", name
);
498 printf("%s=%s\n", name
, val
);
506 int fw_env_flush(struct env_opts
*opts
)
509 opts
= &default_opts
;
514 *environment
.crc
= crc32(0, (uint8_t *) environment
.data
, ENV_SIZE
);
516 /* write environment back to flash */
517 if (flash_io(O_RDWR
)) {
518 fprintf(stderr
, "Error: can't write fw_env to flash\n");
526 * Set/Clear a single variable in the environment.
527 * This is called in sequence to update the environment
528 * in RAM without updating the copy in flash after each set
530 int fw_env_write(char *name
, char *value
)
535 int deleting
, creating
, overwriting
;
538 * search if variable with this name already exists
540 for (nxt
= env
= environment
.data
; *env
; env
= nxt
+ 1) {
541 for (nxt
= env
; *nxt
; ++nxt
) {
542 if (nxt
>= &environment
.data
[ENV_SIZE
]) {
543 fprintf(stderr
, "## Error: "
544 "environment not terminated\n");
549 oldval
= envmatch(name
, env
);
554 deleting
= (oldval
&& !(value
&& strlen(value
)));
555 creating
= (!oldval
&& (value
&& strlen(value
)));
556 overwriting
= (oldval
&& (value
&& strlen(value
)));
558 /* check for permission */
560 if (env_flags_validate_varaccess(name
,
561 ENV_FLAGS_VARACCESS_PREVENT_DELETE
)) {
562 printf("Can't delete \"%s\"\n", name
);
566 } else if (overwriting
) {
567 if (env_flags_validate_varaccess(name
,
568 ENV_FLAGS_VARACCESS_PREVENT_OVERWR
)) {
569 printf("Can't overwrite \"%s\"\n", name
);
572 } else if (env_flags_validate_varaccess(name
,
573 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR
)) {
574 const char *defval
= fw_getdefenv(name
);
578 if (strcmp(oldval
, defval
)
580 printf("Can't overwrite \"%s\"\n", name
);
585 } else if (creating
) {
586 if (env_flags_validate_varaccess(name
,
587 ENV_FLAGS_VARACCESS_PREVENT_CREATE
)) {
588 printf("Can't create \"%s\"\n", name
);
596 if (deleting
|| overwriting
) {
597 if (*++nxt
== '\0') {
602 if ((*env
== '\0') && (*nxt
== '\0'))
611 if (!value
|| !strlen(value
))
615 * Append new definition at the end
617 for (env
= environment
.data
; *env
|| *(env
+ 1); ++env
)
619 if (env
> environment
.data
)
623 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
625 len
= strlen(name
) + 2;
626 /* add '=' for first arg, ' ' for all others */
627 len
+= strlen(value
) + 1;
629 if (len
> (&environment
.data
[ENV_SIZE
] - env
)) {
631 "Error: environment overflow, \"%s\" deleted\n", name
);
635 while ((*env
= *name
++) != '\0')
638 while ((*++env
= *value
++) != '\0')
641 /* end is marked with double '\0' */
648 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
650 * EINVAL - need at least 1 argument
651 * EROFS - certain variables ("ethaddr", "serial#") cannot be
652 * modified or deleted
655 int fw_env_set(int argc
, char *argv
[], struct env_opts
*opts
)
666 opts
= &default_opts
;
669 fprintf(stderr
, "## Error: variable name missing\n");
674 if (fw_env_open(opts
)) {
675 fprintf(stderr
, "Error: environment not initialized\n");
683 if (env_flags_validate_env_set_params(name
, valv
, valc
) < 0) {
689 for (i
= 0; i
< valc
; ++i
) {
691 size_t val_len
= strlen(val
);
694 value
[len
- 1] = ' ';
696 value
= realloc(value
, len
+ val_len
+ 1);
699 "Cannot malloc %zu bytes: %s\n",
700 len
, strerror(errno
));
705 memcpy(value
+ len
, val
, val_len
);
710 fw_env_write(name
, value
);
714 ret
= fw_env_flush(opts
);
721 * Parse a file and configure the u-boot variables.
722 * The script file has a very simple format, as follows:
724 * Each line has a couple with name, value:
725 * <white spaces>variable_name<white spaces>variable_value
727 * Both variable_name and variable_value are interpreted as strings.
728 * Any character after <white spaces> and before ending \r\n is interpreted
729 * as variable's value (no comment allowed on these lines !)
731 * Comments are allowed if the first character in the line is #
733 * Returns -1 and sets errno error codes:
737 int fw_parse_script(char *fname
, struct env_opts
*opts
)
749 opts
= &default_opts
;
751 if (fw_env_open(opts
)) {
752 fprintf(stderr
, "Error: environment not initialized\n");
756 if (strcmp(fname
, "-") == 0)
759 fp
= fopen(fname
, "r");
761 fprintf(stderr
, "I cannot open %s for reading\n",
767 while ((len
= getline(&line
, &linesize
, fp
)) != -1) {
771 * Read a whole line from the file. If the line is not
772 * terminated, reports an error and exit.
774 if (line
[len
- 1] != '\n') {
776 "Line %d not correctly terminated\n",
782 /* Drop ending line feed / carriage return */
784 if (len
&& line
[len
- 1] == '\r')
787 /* Skip comment or empty lines */
788 if (len
== 0 || line
[0] == '#')
792 * Search for variable's name remove leading whitespaces
794 name
= skip_blanks(line
);
798 /* The first white space is the end of variable name */
799 val
= skip_chars(name
);
803 if ((val
- name
) < len
)
804 val
= skip_blanks(val
);
809 fprintf(stderr
, "Setting %s : %s\n",
810 name
, val
? val
: " removed");
813 if (env_flags_validate_type(name
, val
) < 0) {
819 * If there is an error setting a variable,
820 * try to save the environment and returns an error
822 if (fw_env_write(name
, val
)) {
824 "fw_env_write returns with error : %s\n",
833 /* Close file if not stdin */
834 if (strcmp(fname
, "-") != 0)
837 ret
|= fw_env_flush(opts
);
845 * environment_end() - compute offset of first byte right after environment
846 * @dev - index of enviroment buffer
848 * device offset of first byte right after environment
850 off_t
environment_end(int dev
)
852 /* environment is block aligned */
853 return DEVOFFSET(dev
) + ENVSECTORS(dev
) * DEVESIZE(dev
);
857 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
860 * < 0 - failed to test
862 static int flash_bad_block(int fd
, uint8_t mtd_type
, loff_t blockstart
)
864 if (mtd_type
== MTD_NANDFLASH
) {
865 int badblock
= ioctl(fd
, MEMGETBADBLOCK
, &blockstart
);
868 perror("Cannot read bad block mark");
874 fprintf(stderr
, "Bad block at 0x%llx, skipping\n",
875 (unsigned long long)blockstart
);
885 * Read data from flash at an offset into a provided buffer. On NAND it skips
886 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
887 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
889 static int flash_read_buf(int dev
, int fd
, void *buf
, size_t count
,
892 size_t blocklen
; /* erase / write length - one block on NAND,
894 size_t processed
= 0; /* progress counter */
895 size_t readlen
= count
; /* current read length */
896 off_t block_seek
; /* offset inside the current block to the start
898 loff_t blockstart
; /* running start of the current block -
899 MEMGETBADBLOCK needs 64 bits */
902 blockstart
= (offset
/ DEVESIZE(dev
)) * DEVESIZE(dev
);
904 /* Offset inside a block */
905 block_seek
= offset
- blockstart
;
907 if (DEVTYPE(dev
) == MTD_NANDFLASH
) {
909 * NAND: calculate which blocks we are reading. We have
910 * to read one block at a time to skip bad blocks.
912 blocklen
= DEVESIZE(dev
);
914 /* Limit to one block for the first read */
915 if (readlen
> blocklen
- block_seek
)
916 readlen
= blocklen
- block_seek
;
921 /* This only runs once on NOR flash */
922 while (processed
< count
) {
923 rc
= flash_bad_block(fd
, DEVTYPE(dev
), blockstart
);
924 if (rc
< 0) /* block test failed */
927 if (blockstart
+ block_seek
+ readlen
> environment_end(dev
)) {
928 /* End of range is reached */
929 fprintf(stderr
, "Too few good blocks within range\n");
933 if (rc
) { /* block is bad */
934 blockstart
+= blocklen
;
939 * If a block is bad, we retry in the next block at the same
940 * offset - see env/nand.c::writeenv()
942 lseek(fd
, blockstart
+ block_seek
, SEEK_SET
);
944 rc
= read(fd
, buf
+ processed
, readlen
);
946 fprintf(stderr
, "Read error on %s: %s\n",
947 DEVNAME(dev
), strerror(errno
));
951 fprintf(stderr
, "Read 0x%x bytes at 0x%llx on %s\n",
952 rc
, (unsigned long long)blockstart
+ block_seek
,
955 processed
+= readlen
;
956 readlen
= min(blocklen
, count
- processed
);
958 blockstart
+= blocklen
;
965 * Write count bytes from begin of environment, but stay within
966 * ENVSECTORS(dev) sectors of
967 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
968 * erase and write the whole data at once.
970 static int flash_write_buf(int dev
, int fd
, void *buf
, size_t count
)
973 struct erase_info_user erase
;
974 size_t blocklen
; /* length of NAND block / NOR erase sector */
975 size_t erase_len
; /* whole area that can be erased - may include
977 size_t erasesize
; /* erase / write length - one block on NAND,
979 size_t processed
= 0; /* progress counter */
980 size_t write_total
; /* total size to actually write - excluding
982 off_t erase_offset
; /* offset to the first erase block (aligned)
984 off_t block_seek
; /* offset inside the erase block to the start
986 loff_t blockstart
; /* running start of the current block -
987 MEMGETBADBLOCK needs 64 bits */
991 * For mtd devices only offset and size of the environment do matter
993 if (DEVTYPE(dev
) == MTD_ABSENT
) {
995 erase_len
= blocklen
;
996 blockstart
= DEVOFFSET(dev
);
998 write_total
= blocklen
;
1000 blocklen
= DEVESIZE(dev
);
1002 erase_offset
= DEVOFFSET(dev
);
1004 /* Maximum area we may use */
1005 erase_len
= environment_end(dev
) - erase_offset
;
1007 blockstart
= erase_offset
;
1009 /* Offset inside a block */
1010 block_seek
= DEVOFFSET(dev
) - erase_offset
;
1013 * Data size we actually write: from the start of the block
1014 * to the start of the data, then count bytes of data, and
1015 * to the end of the block
1017 write_total
= ((block_seek
+ count
+ blocklen
- 1) /
1018 blocklen
) * blocklen
;
1022 * Support data anywhere within erase sectors: read out the complete
1023 * area to be erased, replace the environment image, write the whole
1026 if (write_total
> count
) {
1027 data
= malloc(erase_len
);
1030 "Cannot malloc %zu bytes: %s\n",
1031 erase_len
, strerror(errno
));
1035 rc
= flash_read_buf(dev
, fd
, data
, write_total
, erase_offset
);
1036 if (write_total
!= rc
)
1040 fprintf(stderr
, "Preserving data ");
1041 if (block_seek
!= 0)
1042 fprintf(stderr
, "0x%x - 0x%lx", 0, block_seek
- 1);
1043 if (block_seek
+ count
!= write_total
) {
1044 if (block_seek
!= 0)
1045 fprintf(stderr
, " and ");
1046 fprintf(stderr
, "0x%lx - 0x%lx",
1047 (unsigned long)block_seek
+ count
,
1048 (unsigned long)write_total
- 1);
1050 fprintf(stderr
, "\n");
1052 /* Overwrite the old environment */
1053 memcpy(data
+ block_seek
, buf
, count
);
1056 * We get here, iff offset is block-aligned and count is a
1057 * multiple of blocklen - see write_total calculation above
1062 if (DEVTYPE(dev
) == MTD_NANDFLASH
) {
1064 * NAND: calculate which blocks we are writing. We have
1065 * to write one block at a time to skip bad blocks.
1067 erasesize
= blocklen
;
1069 erasesize
= erase_len
;
1072 erase
.length
= erasesize
;
1074 /* This only runs once on NOR flash and SPI-dataflash */
1075 while (processed
< write_total
) {
1076 rc
= flash_bad_block(fd
, DEVTYPE(dev
), blockstart
);
1077 if (rc
< 0) /* block test failed */
1080 if (blockstart
+ erasesize
> environment_end(dev
)) {
1081 fprintf(stderr
, "End of range reached, aborting\n");
1085 if (rc
) { /* block is bad */
1086 blockstart
+= blocklen
;
1090 if (DEVTYPE(dev
) != MTD_ABSENT
) {
1091 erase
.start
= blockstart
;
1092 ioctl(fd
, MEMUNLOCK
, &erase
);
1093 /* These do not need an explicit erase cycle */
1094 if (DEVTYPE(dev
) != MTD_DATAFLASH
)
1095 if (ioctl(fd
, MEMERASE
, &erase
) != 0) {
1097 "MTD erase error on %s: %s\n",
1098 DEVNAME(dev
), strerror(errno
));
1103 if (lseek(fd
, blockstart
, SEEK_SET
) == -1) {
1105 "Seek error on %s: %s\n",
1106 DEVNAME(dev
), strerror(errno
));
1110 fprintf(stderr
, "Write 0x%llx bytes at 0x%llx\n",
1111 (unsigned long long)erasesize
,
1112 (unsigned long long)blockstart
);
1114 if (write(fd
, data
+ processed
, erasesize
) != erasesize
) {
1115 fprintf(stderr
, "Write error on %s: %s\n",
1116 DEVNAME(dev
), strerror(errno
));
1120 if (DEVTYPE(dev
) != MTD_ABSENT
)
1121 ioctl(fd
, MEMLOCK
, &erase
);
1123 processed
+= erasesize
;
1125 blockstart
+= erasesize
;
1128 if (write_total
> count
)
1135 * Set obsolete flag at offset - NOR flash only
1137 static int flash_flag_obsolete(int dev
, int fd
, off_t offset
)
1140 struct erase_info_user erase
;
1142 erase
.start
= DEVOFFSET(dev
);
1143 erase
.length
= DEVESIZE(dev
);
1144 /* This relies on the fact, that obsolete_flag == 0 */
1145 rc
= lseek(fd
, offset
, SEEK_SET
);
1147 fprintf(stderr
, "Cannot seek to set the flag on %s\n",
1151 ioctl(fd
, MEMUNLOCK
, &erase
);
1152 rc
= write(fd
, &obsolete_flag
, sizeof(obsolete_flag
));
1153 ioctl(fd
, MEMLOCK
, &erase
);
1155 perror("Could not set obsolete flag");
1160 static int flash_write(int fd_current
, int fd_target
, int dev_target
)
1164 switch (environment
.flag_scheme
) {
1167 case FLAG_INCREMENTAL
:
1168 (*environment
.flags
)++;
1171 *environment
.flags
= active_flag
;
1174 fprintf(stderr
, "Unimplemented flash scheme %u\n",
1175 environment
.flag_scheme
);
1180 fprintf(stderr
, "Writing new environment at 0x%llx on %s\n",
1181 DEVOFFSET(dev_target
), DEVNAME(dev_target
));
1184 if (IS_UBI(dev_target
)) {
1185 if (ubi_update_start(fd_target
, CUR_ENVSIZE
) < 0)
1187 return ubi_write(fd_target
, environment
.image
, CUR_ENVSIZE
);
1190 rc
= flash_write_buf(dev_target
, fd_target
, environment
.image
,
1195 if (environment
.flag_scheme
== FLAG_BOOLEAN
) {
1196 /* Have to set obsolete flag */
1197 off_t offset
= DEVOFFSET(dev_current
) +
1198 offsetof(struct env_image_redundant
, flags
);
1201 "Setting obsolete flag in environment at 0x%llx on %s\n",
1202 DEVOFFSET(dev_current
), DEVNAME(dev_current
));
1204 flash_flag_obsolete(dev_current
, fd_current
, offset
);
1210 static int flash_read(int fd
)
1214 if (IS_UBI(dev_current
)) {
1215 DEVTYPE(dev_current
) = MTD_ABSENT
;
1217 return ubi_read(fd
, environment
.image
, CUR_ENVSIZE
);
1220 rc
= flash_read_buf(dev_current
, fd
, environment
.image
, CUR_ENVSIZE
,
1221 DEVOFFSET(dev_current
));
1222 if (rc
!= CUR_ENVSIZE
)
1228 static int flash_open_tempfile(const char **dname
, const char **target_temp
)
1230 char *dup_name
= strdup(DEVNAME(dev_current
));
1231 char *temp_name
= NULL
;
1237 *dname
= dirname(dup_name
);
1241 rc
= asprintf(&temp_name
, "%s/XXXXXX", *dname
);
1245 rc
= mkstemp(temp_name
);
1247 /* fall back to in place write */
1249 "Can't create %s: %s\n", temp_name
, strerror(errno
));
1252 *target_temp
= temp_name
;
1253 /* deliberately leak dup_name as dname /might/ point into
1254 * it and we need it for our caller
1266 static int flash_io_write(int fd_current
)
1268 int fd_target
= -1, rc
, dev_target
;
1269 const char *dname
, *target_temp
= NULL
;
1271 if (have_redund_env
) {
1272 /* switch to next partition for writing */
1273 dev_target
= !dev_current
;
1274 /* dev_target: fd_target, erase_target */
1275 fd_target
= open(DEVNAME(dev_target
), O_RDWR
);
1276 if (fd_target
< 0) {
1278 "Can't open %s: %s\n",
1279 DEVNAME(dev_target
), strerror(errno
));
1286 if (fstat(fd_current
, &sb
) == 0 && S_ISREG(sb
.st_mode
)) {
1287 /* if any part of flash_open_tempfile() fails we fall
1288 * back to in-place writes
1290 fd_target
= flash_open_tempfile(&dname
, &target_temp
);
1292 dev_target
= dev_current
;
1293 if (fd_target
== -1)
1294 fd_target
= fd_current
;
1297 rc
= flash_write(fd_current
, fd_target
, dev_target
);
1299 if (fsync(fd_current
) && !(errno
== EINVAL
|| errno
== EROFS
)) {
1301 "fsync failed on %s: %s\n",
1302 DEVNAME(dev_current
), strerror(errno
));
1305 if (fd_current
!= fd_target
) {
1306 if (fsync(fd_target
) &&
1307 !(errno
== EINVAL
|| errno
== EROFS
)) {
1309 "fsync failed on %s: %s\n",
1310 DEVNAME(dev_current
), strerror(errno
));
1313 if (close(fd_target
)) {
1315 "I/O error on %s: %s\n",
1316 DEVNAME(dev_target
), strerror(errno
));
1323 dir_fd
= open(dname
, O_DIRECTORY
| O_RDONLY
);
1326 "Can't open %s: %s\n",
1327 dname
, strerror(errno
));
1329 if (rename(target_temp
, DEVNAME(dev_target
))) {
1331 "rename failed %s => %s: %s\n",
1332 target_temp
, DEVNAME(dev_target
),
1337 if (dir_fd
!= -1 && fsync(dir_fd
))
1339 "fsync failed on %s: %s\n",
1340 dname
, strerror(errno
));
1342 if (dir_fd
!= -1 && close(dir_fd
))
1344 "I/O error on %s: %s\n",
1345 dname
, strerror(errno
));
1352 static int flash_io(int mode
)
1356 /* dev_current: fd_current, erase_current */
1357 fd_current
= open(DEVNAME(dev_current
), mode
);
1358 if (fd_current
< 0) {
1360 "Can't open %s: %s\n",
1361 DEVNAME(dev_current
), strerror(errno
));
1365 if (mode
== O_RDWR
) {
1366 rc
= flash_io_write(fd_current
);
1368 rc
= flash_read(fd_current
);
1371 if (close(fd_current
)) {
1373 "I/O error on %s: %s\n",
1374 DEVNAME(dev_current
), strerror(errno
));
1382 * Prevent confusion if running from erased flash memory
1384 int fw_env_open(struct env_opts
*opts
)
1387 unsigned char flag0
;
1391 unsigned char flag1
;
1396 struct env_image_single
*single
;
1397 struct env_image_redundant
*redundant
;
1400 opts
= &default_opts
;
1402 if (parse_config(opts
)) /* should fill envdevices */
1405 addr0
= calloc(1, CUR_ENVSIZE
);
1406 if (addr0
== NULL
) {
1408 "Not enough memory for environment (%ld bytes)\n",
1414 /* read environment from FLASH to local buffer */
1415 environment
.image
= addr0
;
1417 if (have_redund_env
) {
1419 environment
.crc
= &redundant
->crc
;
1420 environment
.flags
= &redundant
->flags
;
1421 environment
.data
= redundant
->data
;
1424 environment
.crc
= &single
->crc
;
1425 environment
.flags
= NULL
;
1426 environment
.data
= single
->data
;
1430 if (flash_io(O_RDONLY
)) {
1435 crc0
= crc32(0, (uint8_t *)environment
.data
, ENV_SIZE
);
1437 crc0_ok
= (crc0
== *environment
.crc
);
1438 if (!have_redund_env
) {
1441 "Warning: Bad CRC, using default environment\n");
1442 memcpy(environment
.data
, default_environment
,
1443 sizeof(default_environment
));
1446 flag0
= *environment
.flags
;
1449 addr1
= calloc(1, CUR_ENVSIZE
);
1450 if (addr1
== NULL
) {
1452 "Not enough memory for environment (%ld bytes)\n",
1460 * have to set environment.image for flash_read(), careful -
1461 * other pointers in environment still point inside addr0
1463 environment
.image
= addr1
;
1464 if (flash_io(O_RDONLY
)) {
1469 /* Check flag scheme compatibility */
1470 if (DEVTYPE(dev_current
) == MTD_NORFLASH
&&
1471 DEVTYPE(!dev_current
) == MTD_NORFLASH
) {
1472 environment
.flag_scheme
= FLAG_BOOLEAN
;
1473 } else if (DEVTYPE(dev_current
) == MTD_NANDFLASH
&&
1474 DEVTYPE(!dev_current
) == MTD_NANDFLASH
) {
1475 environment
.flag_scheme
= FLAG_INCREMENTAL
;
1476 } else if (DEVTYPE(dev_current
) == MTD_DATAFLASH
&&
1477 DEVTYPE(!dev_current
) == MTD_DATAFLASH
) {
1478 environment
.flag_scheme
= FLAG_BOOLEAN
;
1479 } else if (DEVTYPE(dev_current
) == MTD_UBIVOLUME
&&
1480 DEVTYPE(!dev_current
) == MTD_UBIVOLUME
) {
1481 environment
.flag_scheme
= FLAG_INCREMENTAL
;
1482 } else if (DEVTYPE(dev_current
) == MTD_ABSENT
&&
1483 DEVTYPE(!dev_current
) == MTD_ABSENT
&&
1484 IS_UBI(dev_current
) == IS_UBI(!dev_current
)) {
1485 environment
.flag_scheme
= FLAG_INCREMENTAL
;
1487 fprintf(stderr
, "Incompatible flash types!\n");
1492 crc1
= crc32(0, (uint8_t *)redundant
->data
, ENV_SIZE
);
1494 crc1_ok
= (crc1
== redundant
->crc
);
1495 flag1
= redundant
->flags
;
1497 if (crc0_ok
&& !crc1_ok
) {
1499 } else if (!crc0_ok
&& crc1_ok
) {
1501 } else if (!crc0_ok
&& !crc1_ok
) {
1503 "Warning: Bad CRC, using default environment\n");
1504 memcpy(environment
.data
, default_environment
,
1505 sizeof(default_environment
));
1508 switch (environment
.flag_scheme
) {
1510 if (flag0
== active_flag
&&
1511 flag1
== obsolete_flag
) {
1513 } else if (flag0
== obsolete_flag
&&
1514 flag1
== active_flag
) {
1516 } else if (flag0
== flag1
) {
1518 } else if (flag0
== 0xFF) {
1520 } else if (flag1
== 0xFF) {
1526 case FLAG_INCREMENTAL
:
1527 if (flag0
== 255 && flag1
== 0)
1529 else if ((flag1
== 255 && flag0
== 0) ||
1532 else /* flag1 > flag0 */
1536 fprintf(stderr
, "Unknown flag scheme %u\n",
1537 environment
.flag_scheme
);
1543 * If we are reading, we don't need the flag and the CRC any
1544 * more, if we are writing, we will re-calculate CRC and update
1545 * flags before writing out
1548 environment
.image
= addr1
;
1549 environment
.crc
= &redundant
->crc
;
1550 environment
.flags
= &redundant
->flags
;
1551 environment
.data
= redundant
->data
;
1554 environment
.image
= addr0
;
1555 /* Other pointers are already set */
1559 fprintf(stderr
, "Selected env in %s\n", DEVNAME(dev_current
));
1575 * Simply free allocated buffer with environment
1577 int fw_env_close(struct env_opts
*opts
)
1579 if (environment
.image
)
1580 free(environment
.image
);
1582 environment
.image
= NULL
;
1587 static int check_device_config(int dev
)
1593 /* Fills in IS_UBI(), converts DEVNAME() with ubi volume name */
1596 fd
= open(DEVNAME(dev
), O_RDONLY
);
1599 "Cannot open %s: %s\n", DEVNAME(dev
), strerror(errno
));
1603 rc
= fstat(fd
, &st
);
1605 fprintf(stderr
, "Cannot stat the file %s\n", DEVNAME(dev
));
1610 rc
= ioctl(fd
, UBI_IOCEBISMAP
, &lnum
);
1612 fprintf(stderr
, "Cannot get UBI information for %s\n",
1616 } else if (S_ISCHR(st
.st_mode
)) {
1617 struct mtd_info_user mtdinfo
;
1618 rc
= ioctl(fd
, MEMGETINFO
, &mtdinfo
);
1620 fprintf(stderr
, "Cannot get MTD information for %s\n",
1624 if (mtdinfo
.type
!= MTD_NORFLASH
&&
1625 mtdinfo
.type
!= MTD_NANDFLASH
&&
1626 mtdinfo
.type
!= MTD_DATAFLASH
&&
1627 mtdinfo
.type
!= MTD_UBIVOLUME
) {
1628 fprintf(stderr
, "Unsupported flash type %u on %s\n",
1629 mtdinfo
.type
, DEVNAME(dev
));
1632 DEVTYPE(dev
) = mtdinfo
.type
;
1633 if (DEVESIZE(dev
) == 0)
1634 /* Assume the erase size is the same as the env-size */
1635 DEVESIZE(dev
) = ENVSIZE(dev
);
1638 DEVTYPE(dev
) = MTD_ABSENT
;
1639 if (DEVESIZE(dev
) == 0)
1640 /* Assume the erase size to be 512 bytes */
1641 DEVESIZE(dev
) = 0x200;
1644 * Check for negative offsets, treat it as backwards offset
1645 * from the end of the block device
1647 if (DEVOFFSET(dev
) < 0) {
1648 rc
= ioctl(fd
, BLKGETSIZE64
, &size
);
1651 "Could not get block device size on %s\n",
1656 DEVOFFSET(dev
) = DEVOFFSET(dev
) + size
;
1659 "Calculated device offset 0x%llx on %s\n",
1660 DEVOFFSET(dev
), DEVNAME(dev
));
1665 if (ENVSECTORS(dev
) == 0)
1666 /* Assume enough sectors to cover the environment */
1667 ENVSECTORS(dev
) = DIV_ROUND_UP(ENVSIZE(dev
), DEVESIZE(dev
));
1669 if (DEVOFFSET(dev
) % DEVESIZE(dev
) != 0) {
1671 "Environment does not start on (erase) block boundary\n");
1676 if (ENVSIZE(dev
) > ENVSECTORS(dev
) * DEVESIZE(dev
)) {
1678 "Environment does not fit into available sectors\n");
1688 static int parse_config(struct env_opts
*opts
)
1693 opts
= &default_opts
;
1695 #if defined(CONFIG_FILE)
1696 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1697 if (get_config(opts
->config_file
)) {
1698 fprintf(stderr
, "Cannot parse config file '%s': %m\n",
1703 DEVNAME(0) = DEVICE1_NAME
;
1704 DEVOFFSET(0) = DEVICE1_OFFSET
;
1705 ENVSIZE(0) = ENV1_SIZE
;
1707 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1710 #ifdef DEVICE1_ESIZE
1711 DEVESIZE(0) = DEVICE1_ESIZE
;
1713 #ifdef DEVICE1_ENVSECTORS
1714 ENVSECTORS(0) = DEVICE1_ENVSECTORS
;
1718 DEVNAME(1) = DEVICE2_NAME
;
1719 DEVOFFSET(1) = DEVICE2_OFFSET
;
1720 ENVSIZE(1) = ENV2_SIZE
;
1722 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1725 #ifdef DEVICE2_ESIZE
1726 DEVESIZE(1) = DEVICE2_ESIZE
;
1728 #ifdef DEVICE2_ENVSECTORS
1729 ENVSECTORS(1) = DEVICE2_ENVSECTORS
;
1731 have_redund_env
= 1;
1734 rc
= check_device_config(0);
1738 if (have_redund_env
) {
1739 rc
= check_device_config(1);
1743 if (ENVSIZE(0) != ENVSIZE(1)) {
1745 "Redundant environments have unequal size");
1750 usable_envsize
= CUR_ENVSIZE
- sizeof(uint32_t);
1751 if (have_redund_env
)
1752 usable_envsize
-= sizeof(char);
1757 #if defined(CONFIG_FILE)
1758 static int get_config(char *fname
)
1764 size_t linesize
= 0;
1767 fp
= fopen(fname
, "r");
1771 while (i
< 2 && getline(&line
, &linesize
, fp
) != -1) {
1772 /* Skip comment strings */
1776 rc
= sscanf(line
, "%ms %lli %lx %lx %lx",
1779 &ENVSIZE(i
), &DEVESIZE(i
), &ENVSECTORS(i
));
1784 DEVNAME(i
) = devname
;
1786 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1795 have_redund_env
= i
- 1;
1796 if (!i
) { /* No valid entries found */