2 * (C) Copyright 2000-2010
3 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
6 * Guennadi Liakhovetski, DENX Software Engineering, lg@denx.de.
8 * SPDX-License-Identifier: GPL-2.0+
15 #include <env_flags.h>
17 #include <linux/stringify.h>
23 #include <sys/types.h>
24 #include <sys/ioctl.h>
30 # include <linux/mtd/mtd.h>
32 # define __user /* nothing */
33 # include <mtd/mtd-user.h>
38 struct common_args common_args
;
39 struct printenv_args printenv_args
;
40 struct setenv_args setenv_args
;
42 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
44 #define min(x, y) ({ \
45 typeof(x) _min1 = (x); \
46 typeof(y) _min2 = (y); \
47 (void) (&_min1 == &_min2); \
48 _min1 < _min2 ? _min1 : _min2; })
51 const char *devname
; /* Device name */
52 ulong devoff
; /* Device offset */
53 ulong env_size
; /* environment size */
54 ulong erase_size
; /* device erase size */
55 ulong env_sectors
; /* number of environment sectors */
56 uint8_t mtd_type
; /* type of the MTD device */
59 static struct envdev_s envdevices
[2] =
62 .mtd_type
= MTD_ABSENT
,
64 .mtd_type
= MTD_ABSENT
,
67 static int dev_current
;
69 #define DEVNAME(i) envdevices[(i)].devname
70 #define DEVOFFSET(i) envdevices[(i)].devoff
71 #define ENVSIZE(i) envdevices[(i)].env_size
72 #define DEVESIZE(i) envdevices[(i)].erase_size
73 #define ENVSECTORS(i) envdevices[(i)].env_sectors
74 #define DEVTYPE(i) envdevices[(i)].mtd_type
76 #define CUR_ENVSIZE ENVSIZE(dev_current)
78 #define ENV_SIZE getenvsize()
80 struct env_image_single
{
81 uint32_t crc
; /* CRC32 over data bytes */
85 struct env_image_redundant
{
86 uint32_t crc
; /* CRC32 over data bytes */
87 unsigned char flags
; /* active or obsolete */
100 unsigned char *flags
;
102 enum flag_scheme flag_scheme
;
105 static struct environment environment
= {
106 .flag_scheme
= FLAG_NONE
,
109 static int env_aes_cbc_crypt(char *data
, const int enc
, uint8_t *key
);
111 static int HaveRedundEnv
= 0;
113 static unsigned char active_flag
= 1;
114 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
115 static unsigned char obsolete_flag
= 0;
117 #define DEFAULT_ENV_INSTANCE_STATIC
118 #include <env_default.h>
120 static int flash_io (int mode
);
121 static char *envmatch (char * s1
, char * s2
);
122 static int parse_config (void);
124 #if defined(CONFIG_FILE)
125 static int get_config (char *);
127 static inline ulong
getenvsize (void)
129 ulong rc
= CUR_ENVSIZE
- sizeof(uint32_t);
134 if (common_args
.aes_flag
)
135 rc
&= ~(AES_KEY_LENGTH
- 1);
140 static char *skip_chars(char *s
)
142 for (; *s
!= '\0'; s
++) {
149 static char *skip_blanks(char *s
)
151 for (; *s
!= '\0'; s
++) {
159 * Search the environment for a variable.
160 * Return the value, if found, or NULL, if not found.
162 char *fw_getenv (char *name
)
166 for (env
= environment
.data
; *env
; env
= nxt
+ 1) {
169 for (nxt
= env
; *nxt
; ++nxt
) {
170 if (nxt
>= &environment
.data
[ENV_SIZE
]) {
171 fprintf (stderr
, "## Error: "
172 "environment not terminated\n");
176 val
= envmatch (name
, env
);
185 * Search the default environment for a variable.
186 * Return the value, if found, or NULL, if not found.
188 char *fw_getdefenv(char *name
)
192 for (env
= default_environment
; *env
; env
= nxt
+ 1) {
195 for (nxt
= env
; *nxt
; ++nxt
) {
196 if (nxt
>= &default_environment
[ENV_SIZE
]) {
197 fprintf(stderr
, "## Error: "
198 "default environment not terminated\n");
202 val
= envmatch(name
, env
);
210 int parse_aes_key(char *key
, uint8_t *bin_key
)
212 char tmp
[5] = { '0', 'x', 0, 0, 0 };
216 if (strnlen(key
, 64) != 32) {
218 "## Error: '-a' option requires 16-byte AES key\n");
222 for (i
= 0; i
< 16; i
++) {
226 ul
= strtoul(tmp
, NULL
, 16);
229 "## Error: '-a' option requires valid AES key\n");
232 bin_key
[i
] = ul
& 0xff;
239 * Print the current definition of one, or more, or all
240 * environment variables
242 int fw_printenv (int argc
, char *argv
[])
250 if (argc
== 0) { /* Print all env variables */
251 for (env
= environment
.data
; *env
; env
= nxt
+ 1) {
252 for (nxt
= env
; *nxt
; ++nxt
) {
253 if (nxt
>= &environment
.data
[ENV_SIZE
]) {
254 fprintf (stderr
, "## Error: "
255 "environment not terminated\n");
260 printf ("%s\n", env
);
265 if (printenv_args
.name_suppress
&& argc
!= 1) {
267 "## Error: `-n' option requires exactly one argument\n");
271 for (i
= 0; i
< argc
; ++i
) { /* print single env variables */
272 char *name
= argv
[i
];
275 for (env
= environment
.data
; *env
; env
= nxt
+ 1) {
277 for (nxt
= env
; *nxt
; ++nxt
) {
278 if (nxt
>= &environment
.data
[ENV_SIZE
]) {
279 fprintf (stderr
, "## Error: "
280 "environment not terminated\n");
284 val
= envmatch (name
, env
);
286 if (!printenv_args
.name_suppress
) {
287 fputs (name
, stdout
);
295 fprintf (stderr
, "## Error: \"%s\" not defined\n", name
);
303 int fw_env_close(void)
306 if (common_args
.aes_flag
) {
307 ret
= env_aes_cbc_crypt(environment
.data
, 1,
308 common_args
.aes_key
);
311 "Error: can't encrypt env for flash\n");
319 *environment
.crc
= crc32(0, (uint8_t *) environment
.data
, ENV_SIZE
);
321 /* write environment back to flash */
322 if (flash_io(O_RDWR
)) {
324 "Error: can't write fw_env to flash\n");
333 * Set/Clear a single variable in the environment.
334 * This is called in sequence to update the environment
335 * in RAM without updating the copy in flash after each set
337 int fw_env_write(char *name
, char *value
)
342 int deleting
, creating
, overwriting
;
345 * search if variable with this name already exists
347 for (nxt
= env
= environment
.data
; *env
; env
= nxt
+ 1) {
348 for (nxt
= env
; *nxt
; ++nxt
) {
349 if (nxt
>= &environment
.data
[ENV_SIZE
]) {
350 fprintf(stderr
, "## Error: "
351 "environment not terminated\n");
356 if ((oldval
= envmatch (name
, env
)) != NULL
)
360 deleting
= (oldval
&& !(value
&& strlen(value
)));
361 creating
= (!oldval
&& (value
&& strlen(value
)));
362 overwriting
= (oldval
&& (value
&& strlen(value
)));
364 /* check for permission */
366 if (env_flags_validate_varaccess(name
,
367 ENV_FLAGS_VARACCESS_PREVENT_DELETE
)) {
368 printf("Can't delete \"%s\"\n", name
);
372 } else if (overwriting
) {
373 if (env_flags_validate_varaccess(name
,
374 ENV_FLAGS_VARACCESS_PREVENT_OVERWR
)) {
375 printf("Can't overwrite \"%s\"\n", name
);
378 } else if (env_flags_validate_varaccess(name
,
379 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR
)) {
380 const char *defval
= fw_getdefenv(name
);
384 if (strcmp(oldval
, defval
)
386 printf("Can't overwrite \"%s\"\n", name
);
391 } else if (creating
) {
392 if (env_flags_validate_varaccess(name
,
393 ENV_FLAGS_VARACCESS_PREVENT_CREATE
)) {
394 printf("Can't create \"%s\"\n", name
);
402 if (deleting
|| overwriting
) {
403 if (*++nxt
== '\0') {
408 if ((*env
== '\0') && (*nxt
== '\0'))
417 if (!value
|| !strlen(value
))
421 * Append new definition at the end
423 for (env
= environment
.data
; *env
|| *(env
+ 1); ++env
);
424 if (env
> environment
.data
)
428 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
430 len
= strlen (name
) + 2;
431 /* add '=' for first arg, ' ' for all others */
432 len
+= strlen(value
) + 1;
434 if (len
> (&environment
.data
[ENV_SIZE
] - env
)) {
436 "Error: environment overflow, \"%s\" deleted\n",
441 while ((*env
= *name
++) != '\0')
444 while ((*++env
= *value
++) != '\0')
447 /* end is marked with double '\0' */
454 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
456 * EINVAL - need at least 1 argument
457 * EROFS - certain variables ("ethaddr", "serial#") cannot be
458 * modified or deleted
461 int fw_setenv(int argc
, char *argv
[])
470 fprintf(stderr
, "## Error: variable name missing\n");
476 fprintf(stderr
, "Error: environment not initialized\n");
484 if (env_flags_validate_env_set_params(name
, valv
, valc
) < 0)
488 for (i
= 0; i
< valc
; ++i
) {
490 size_t val_len
= strlen(val
);
493 value
[len
- 1] = ' ';
494 value
= realloc(value
, len
+ val_len
+ 1);
497 "Cannot malloc %zu bytes: %s\n",
498 len
, strerror(errno
));
502 memcpy(value
+ len
, val
, val_len
);
507 fw_env_write(name
, value
);
511 return fw_env_close();
515 * Parse a file and configure the u-boot variables.
516 * The script file has a very simple format, as follows:
518 * Each line has a couple with name, value:
519 * <white spaces>variable_name<white spaces>variable_value
521 * Both variable_name and variable_value are interpreted as strings.
522 * Any character after <white spaces> and before ending \r\n is interpreted
523 * as variable's value (no comment allowed on these lines !)
525 * Comments are allowed if the first character in the line is #
527 * Returns -1 and sets errno error codes:
531 int fw_parse_script(char *fname
)
534 char dump
[1024]; /* Maximum line length in the file */
542 fprintf(stderr
, "Error: environment not initialized\n");
546 if (strcmp(fname
, "-") == 0)
549 fp
= fopen(fname
, "r");
551 fprintf(stderr
, "I cannot open %s for reading\n",
557 while (fgets(dump
, sizeof(dump
), fp
)) {
562 * Read a whole line from the file. If the line is too long
563 * or is not terminated, reports an error and exit.
565 if (dump
[len
- 1] != '\n') {
567 "Line %d not corrected terminated or too long\n",
573 /* Drop ending line feed / carriage return */
575 if (len
&& dump
[len
- 1] == '\r')
578 /* Skip comment or empty lines */
579 if (len
== 0 || dump
[0] == '#')
583 * Search for variable's name,
584 * remove leading whitespaces
586 name
= skip_blanks(dump
);
590 /* The first white space is the end of variable name */
591 val
= skip_chars(name
);
595 if ((val
- name
) < len
)
596 val
= skip_blanks(val
);
602 fprintf(stderr
, "Setting %s : %s\n",
603 name
, val
? val
: " removed");
606 if (env_flags_validate_type(name
, val
) < 0) {
612 * If there is an error setting a variable,
613 * try to save the environment and returns an error
615 if (fw_env_write(name
, val
)) {
617 "fw_env_write returns with error : %s\n",
625 /* Close file if not stdin */
626 if (strcmp(fname
, "-") != 0)
629 ret
|= fw_env_close();
636 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
639 * < 0 - failed to test
641 static int flash_bad_block (int fd
, uint8_t mtd_type
, loff_t
*blockstart
)
643 if (mtd_type
== MTD_NANDFLASH
) {
644 int badblock
= ioctl (fd
, MEMGETBADBLOCK
, blockstart
);
647 perror ("Cannot read bad block mark");
653 fprintf (stderr
, "Bad block at 0x%llx, "
654 "skipping\n", *blockstart
);
664 * Read data from flash at an offset into a provided buffer. On NAND it skips
665 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
666 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
668 static int flash_read_buf (int dev
, int fd
, void *buf
, size_t count
,
669 off_t offset
, uint8_t mtd_type
)
671 size_t blocklen
; /* erase / write length - one block on NAND,
673 size_t processed
= 0; /* progress counter */
674 size_t readlen
= count
; /* current read length */
675 off_t top_of_range
; /* end of the last block we may use */
676 off_t block_seek
; /* offset inside the current block to the start
678 loff_t blockstart
; /* running start of the current block -
679 MEMGETBADBLOCK needs 64 bits */
682 blockstart
= (offset
/ DEVESIZE (dev
)) * DEVESIZE (dev
);
684 /* Offset inside a block */
685 block_seek
= offset
- blockstart
;
687 if (mtd_type
== MTD_NANDFLASH
) {
689 * NAND: calculate which blocks we are reading. We have
690 * to read one block at a time to skip bad blocks.
692 blocklen
= DEVESIZE (dev
);
695 * To calculate the top of the range, we have to use the
696 * global DEVOFFSET (dev), which can be different from offset
698 top_of_range
= ((DEVOFFSET(dev
) / blocklen
) +
699 ENVSECTORS (dev
)) * blocklen
;
701 /* Limit to one block for the first read */
702 if (readlen
> blocklen
- block_seek
)
703 readlen
= blocklen
- block_seek
;
706 top_of_range
= offset
+ count
;
709 /* This only runs once on NOR flash */
710 while (processed
< count
) {
711 rc
= flash_bad_block (fd
, mtd_type
, &blockstart
);
712 if (rc
< 0) /* block test failed */
715 if (blockstart
+ block_seek
+ readlen
> top_of_range
) {
716 /* End of range is reached */
718 "Too few good blocks within range\n");
722 if (rc
) { /* block is bad */
723 blockstart
+= blocklen
;
728 * If a block is bad, we retry in the next block at the same
729 * offset - see common/env_nand.c::writeenv()
731 lseek (fd
, blockstart
+ block_seek
, SEEK_SET
);
733 rc
= read (fd
, buf
+ processed
, readlen
);
735 fprintf (stderr
, "Read error on %s: %s\n",
736 DEVNAME (dev
), strerror (errno
));
740 fprintf(stderr
, "Read 0x%x bytes at 0x%llx on %s\n",
741 rc
, blockstart
+ block_seek
, DEVNAME(dev
));
743 processed
+= readlen
;
744 readlen
= min (blocklen
, count
- processed
);
746 blockstart
+= blocklen
;
753 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
754 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
755 * erase and write the whole data at once.
757 static int flash_write_buf (int dev
, int fd
, void *buf
, size_t count
,
758 off_t offset
, uint8_t mtd_type
)
761 struct erase_info_user erase
;
762 size_t blocklen
; /* length of NAND block / NOR erase sector */
763 size_t erase_len
; /* whole area that can be erased - may include
765 size_t erasesize
; /* erase / write length - one block on NAND,
767 size_t processed
= 0; /* progress counter */
768 size_t write_total
; /* total size to actually write - excluding
770 off_t erase_offset
; /* offset to the first erase block (aligned)
772 off_t block_seek
; /* offset inside the erase block to the start
774 off_t top_of_range
; /* end of the last block we may use */
775 loff_t blockstart
; /* running start of the current block -
776 MEMGETBADBLOCK needs 64 bits */
780 * For mtd devices only offset and size of the environment do matter
782 if (mtd_type
== MTD_ABSENT
) {
784 top_of_range
= offset
+ count
;
785 erase_len
= blocklen
;
788 write_total
= blocklen
;
790 blocklen
= DEVESIZE(dev
);
792 top_of_range
= ((DEVOFFSET(dev
) / blocklen
) +
793 ENVSECTORS(dev
)) * blocklen
;
795 erase_offset
= (offset
/ blocklen
) * blocklen
;
797 /* Maximum area we may use */
798 erase_len
= top_of_range
- erase_offset
;
800 blockstart
= erase_offset
;
801 /* Offset inside a block */
802 block_seek
= offset
- erase_offset
;
805 * Data size we actually write: from the start of the block
806 * to the start of the data, then count bytes of data, and
807 * to the end of the block
809 write_total
= ((block_seek
+ count
+ blocklen
- 1) /
810 blocklen
) * blocklen
;
814 * Support data anywhere within erase sectors: read out the complete
815 * area to be erased, replace the environment image, write the whole
818 if (write_total
> count
) {
819 data
= malloc (erase_len
);
822 "Cannot malloc %zu bytes: %s\n",
823 erase_len
, strerror (errno
));
827 rc
= flash_read_buf (dev
, fd
, data
, write_total
, erase_offset
,
829 if (write_total
!= rc
)
833 fprintf(stderr
, "Preserving data ");
835 fprintf(stderr
, "0x%x - 0x%lx", 0, block_seek
- 1);
836 if (block_seek
+ count
!= write_total
) {
838 fprintf(stderr
, " and ");
839 fprintf(stderr
, "0x%lx - 0x%x",
840 block_seek
+ count
, write_total
- 1);
842 fprintf(stderr
, "\n");
844 /* Overwrite the old environment */
845 memcpy (data
+ block_seek
, buf
, count
);
848 * We get here, iff offset is block-aligned and count is a
849 * multiple of blocklen - see write_total calculation above
854 if (mtd_type
== MTD_NANDFLASH
) {
856 * NAND: calculate which blocks we are writing. We have
857 * to write one block at a time to skip bad blocks.
859 erasesize
= blocklen
;
861 erasesize
= erase_len
;
864 erase
.length
= erasesize
;
866 /* This only runs once on NOR flash and SPI-dataflash */
867 while (processed
< write_total
) {
868 rc
= flash_bad_block (fd
, mtd_type
, &blockstart
);
869 if (rc
< 0) /* block test failed */
872 if (blockstart
+ erasesize
> top_of_range
) {
873 fprintf (stderr
, "End of range reached, aborting\n");
877 if (rc
) { /* block is bad */
878 blockstart
+= blocklen
;
882 if (mtd_type
!= MTD_ABSENT
) {
883 erase
.start
= blockstart
;
884 ioctl(fd
, MEMUNLOCK
, &erase
);
885 /* These do not need an explicit erase cycle */
886 if (mtd_type
!= MTD_DATAFLASH
)
887 if (ioctl(fd
, MEMERASE
, &erase
) != 0) {
889 "MTD erase error on %s: %s\n",
890 DEVNAME(dev
), strerror(errno
));
895 if (lseek (fd
, blockstart
, SEEK_SET
) == -1) {
897 "Seek error on %s: %s\n",
898 DEVNAME (dev
), strerror (errno
));
903 fprintf(stderr
, "Write 0x%x bytes at 0x%llx\n", erasesize
,
906 if (write (fd
, data
+ processed
, erasesize
) != erasesize
) {
907 fprintf (stderr
, "Write error on %s: %s\n",
908 DEVNAME (dev
), strerror (errno
));
912 if (mtd_type
!= MTD_ABSENT
)
913 ioctl(fd
, MEMLOCK
, &erase
);
915 processed
+= erasesize
;
917 blockstart
+= erasesize
;
920 if (write_total
> count
)
927 * Set obsolete flag at offset - NOR flash only
929 static int flash_flag_obsolete (int dev
, int fd
, off_t offset
)
932 struct erase_info_user erase
;
934 erase
.start
= DEVOFFSET (dev
);
935 erase
.length
= DEVESIZE (dev
);
936 /* This relies on the fact, that obsolete_flag == 0 */
937 rc
= lseek (fd
, offset
, SEEK_SET
);
939 fprintf (stderr
, "Cannot seek to set the flag on %s \n",
943 ioctl (fd
, MEMUNLOCK
, &erase
);
944 rc
= write (fd
, &obsolete_flag
, sizeof (obsolete_flag
));
945 ioctl (fd
, MEMLOCK
, &erase
);
947 perror ("Could not set obsolete flag");
952 /* Encrypt or decrypt the environment before writing or reading it. */
953 static int env_aes_cbc_crypt(char *payload
, const int enc
, uint8_t *key
)
955 uint8_t *data
= (uint8_t *)payload
;
956 const int len
= getenvsize();
957 uint8_t key_exp
[AES_EXPAND_KEY_LENGTH
];
960 /* First we expand the key. */
961 aes_expand_key(key
, key_exp
);
963 /* Calculate the number of AES blocks to encrypt. */
964 aes_blocks
= DIV_ROUND_UP(len
, AES_KEY_LENGTH
);
967 aes_cbc_encrypt_blocks(key_exp
, data
, data
, aes_blocks
);
969 aes_cbc_decrypt_blocks(key_exp
, data
, data
, aes_blocks
);
974 static int flash_write (int fd_current
, int fd_target
, int dev_target
)
978 switch (environment
.flag_scheme
) {
981 case FLAG_INCREMENTAL
:
982 (*environment
.flags
)++;
985 *environment
.flags
= active_flag
;
988 fprintf (stderr
, "Unimplemented flash scheme %u \n",
989 environment
.flag_scheme
);
994 fprintf(stderr
, "Writing new environment at 0x%lx on %s\n",
995 DEVOFFSET (dev_target
), DEVNAME (dev_target
));
998 rc
= flash_write_buf(dev_target
, fd_target
, environment
.image
,
999 CUR_ENVSIZE
, DEVOFFSET(dev_target
),
1000 DEVTYPE(dev_target
));
1004 if (environment
.flag_scheme
== FLAG_BOOLEAN
) {
1005 /* Have to set obsolete flag */
1006 off_t offset
= DEVOFFSET (dev_current
) +
1007 offsetof (struct env_image_redundant
, flags
);
1010 "Setting obsolete flag in environment at 0x%lx on %s\n",
1011 DEVOFFSET (dev_current
), DEVNAME (dev_current
));
1013 flash_flag_obsolete (dev_current
, fd_current
, offset
);
1019 static int flash_read (int fd
)
1021 struct mtd_info_user mtdinfo
;
1025 rc
= fstat(fd
, &st
);
1027 fprintf(stderr
, "Cannot stat the file %s\n",
1028 DEVNAME(dev_current
));
1032 if (S_ISCHR(st
.st_mode
)) {
1033 rc
= ioctl(fd
, MEMGETINFO
, &mtdinfo
);
1035 fprintf(stderr
, "Cannot get MTD information for %s\n",
1036 DEVNAME(dev_current
));
1039 if (mtdinfo
.type
!= MTD_NORFLASH
&&
1040 mtdinfo
.type
!= MTD_NANDFLASH
&&
1041 mtdinfo
.type
!= MTD_DATAFLASH
&&
1042 mtdinfo
.type
!= MTD_UBIVOLUME
) {
1043 fprintf (stderr
, "Unsupported flash type %u on %s\n",
1044 mtdinfo
.type
, DEVNAME(dev_current
));
1048 memset(&mtdinfo
, 0, sizeof(mtdinfo
));
1049 mtdinfo
.type
= MTD_ABSENT
;
1052 DEVTYPE(dev_current
) = mtdinfo
.type
;
1054 rc
= flash_read_buf(dev_current
, fd
, environment
.image
, CUR_ENVSIZE
,
1055 DEVOFFSET (dev_current
), mtdinfo
.type
);
1056 if (rc
!= CUR_ENVSIZE
)
1062 static int flash_io (int mode
)
1064 int fd_current
, fd_target
, rc
, dev_target
;
1066 /* dev_current: fd_current, erase_current */
1067 fd_current
= open (DEVNAME (dev_current
), mode
);
1068 if (fd_current
< 0) {
1070 "Can't open %s: %s\n",
1071 DEVNAME (dev_current
), strerror (errno
));
1075 if (mode
== O_RDWR
) {
1076 if (HaveRedundEnv
) {
1077 /* switch to next partition for writing */
1078 dev_target
= !dev_current
;
1079 /* dev_target: fd_target, erase_target */
1080 fd_target
= open (DEVNAME (dev_target
), mode
);
1081 if (fd_target
< 0) {
1083 "Can't open %s: %s\n",
1084 DEVNAME (dev_target
),
1090 dev_target
= dev_current
;
1091 fd_target
= fd_current
;
1094 rc
= flash_write (fd_current
, fd_target
, dev_target
);
1096 if (HaveRedundEnv
) {
1097 if (close (fd_target
)) {
1099 "I/O error on %s: %s\n",
1100 DEVNAME (dev_target
),
1106 rc
= flash_read (fd_current
);
1110 if (close (fd_current
)) {
1112 "I/O error on %s: %s\n",
1113 DEVNAME (dev_current
), strerror (errno
));
1121 * s1 is either a simple 'name', or a 'name=value' pair.
1122 * s2 is a 'name=value' pair.
1123 * If the names match, return the value of s2, else NULL.
1126 static char *envmatch (char * s1
, char * s2
)
1128 if (s1
== NULL
|| s2
== NULL
)
1131 while (*s1
== *s2
++)
1134 if (*s1
== '\0' && *(s2
- 1) == '=')
1140 * Prevent confusion if running from erased flash memory
1142 int fw_env_open(void)
1145 unsigned char flag0
;
1149 unsigned char flag1
;
1154 struct env_image_single
*single
;
1155 struct env_image_redundant
*redundant
;
1157 if (parse_config ()) /* should fill envdevices */
1160 addr0
= calloc(1, CUR_ENVSIZE
);
1161 if (addr0
== NULL
) {
1163 "Not enough memory for environment (%ld bytes)\n",
1168 /* read environment from FLASH to local buffer */
1169 environment
.image
= addr0
;
1171 if (HaveRedundEnv
) {
1173 environment
.crc
= &redundant
->crc
;
1174 environment
.flags
= &redundant
->flags
;
1175 environment
.data
= redundant
->data
;
1178 environment
.crc
= &single
->crc
;
1179 environment
.flags
= NULL
;
1180 environment
.data
= single
->data
;
1184 if (flash_io (O_RDONLY
))
1187 crc0
= crc32 (0, (uint8_t *) environment
.data
, ENV_SIZE
);
1189 if (common_args
.aes_flag
) {
1190 ret
= env_aes_cbc_crypt(environment
.data
, 0,
1191 common_args
.aes_key
);
1196 crc0_ok
= (crc0
== *environment
.crc
);
1197 if (!HaveRedundEnv
) {
1200 "Warning: Bad CRC, using default environment\n");
1201 memcpy(environment
.data
, default_environment
, sizeof default_environment
);
1204 flag0
= *environment
.flags
;
1207 addr1
= calloc(1, CUR_ENVSIZE
);
1208 if (addr1
== NULL
) {
1210 "Not enough memory for environment (%ld bytes)\n",
1217 * have to set environment.image for flash_read(), careful -
1218 * other pointers in environment still point inside addr0
1220 environment
.image
= addr1
;
1221 if (flash_io (O_RDONLY
))
1224 /* Check flag scheme compatibility */
1225 if (DEVTYPE(dev_current
) == MTD_NORFLASH
&&
1226 DEVTYPE(!dev_current
) == MTD_NORFLASH
) {
1227 environment
.flag_scheme
= FLAG_BOOLEAN
;
1228 } else if (DEVTYPE(dev_current
) == MTD_NANDFLASH
&&
1229 DEVTYPE(!dev_current
) == MTD_NANDFLASH
) {
1230 environment
.flag_scheme
= FLAG_INCREMENTAL
;
1231 } else if (DEVTYPE(dev_current
) == MTD_DATAFLASH
&&
1232 DEVTYPE(!dev_current
) == MTD_DATAFLASH
) {
1233 environment
.flag_scheme
= FLAG_BOOLEAN
;
1234 } else if (DEVTYPE(dev_current
) == MTD_UBIVOLUME
&&
1235 DEVTYPE(!dev_current
) == MTD_UBIVOLUME
) {
1236 environment
.flag_scheme
= FLAG_INCREMENTAL
;
1237 } else if (DEVTYPE(dev_current
) == MTD_ABSENT
&&
1238 DEVTYPE(!dev_current
) == MTD_ABSENT
) {
1239 environment
.flag_scheme
= FLAG_INCREMENTAL
;
1241 fprintf (stderr
, "Incompatible flash types!\n");
1245 crc1
= crc32 (0, (uint8_t *) redundant
->data
, ENV_SIZE
);
1247 if (common_args
.aes_flag
) {
1248 ret
= env_aes_cbc_crypt(redundant
->data
, 0,
1249 common_args
.aes_key
);
1254 crc1_ok
= (crc1
== redundant
->crc
);
1255 flag1
= redundant
->flags
;
1257 if (crc0_ok
&& !crc1_ok
) {
1259 } else if (!crc0_ok
&& crc1_ok
) {
1261 } else if (!crc0_ok
&& !crc1_ok
) {
1263 "Warning: Bad CRC, using default environment\n");
1264 memcpy (environment
.data
, default_environment
,
1265 sizeof default_environment
);
1268 switch (environment
.flag_scheme
) {
1270 if (flag0
== active_flag
&&
1271 flag1
== obsolete_flag
) {
1273 } else if (flag0
== obsolete_flag
&&
1274 flag1
== active_flag
) {
1276 } else if (flag0
== flag1
) {
1278 } else if (flag0
== 0xFF) {
1280 } else if (flag1
== 0xFF) {
1286 case FLAG_INCREMENTAL
:
1287 if (flag0
== 255 && flag1
== 0)
1289 else if ((flag1
== 255 && flag0
== 0) ||
1292 else /* flag1 > flag0 */
1296 fprintf (stderr
, "Unknown flag scheme %u \n",
1297 environment
.flag_scheme
);
1303 * If we are reading, we don't need the flag and the CRC any
1304 * more, if we are writing, we will re-calculate CRC and update
1305 * flags before writing out
1308 environment
.image
= addr1
;
1309 environment
.crc
= &redundant
->crc
;
1310 environment
.flags
= &redundant
->flags
;
1311 environment
.data
= redundant
->data
;
1314 environment
.image
= addr0
;
1315 /* Other pointers are already set */
1319 fprintf(stderr
, "Selected env in %s\n", DEVNAME(dev_current
));
1326 static int parse_config ()
1330 #if defined(CONFIG_FILE)
1331 if (!common_args
.config_file
)
1332 common_args
.config_file
= CONFIG_FILE
;
1334 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1335 if (get_config(common_args
.config_file
)) {
1336 fprintf(stderr
, "Cannot parse config file '%s': %m\n",
1337 common_args
.config_file
);
1341 DEVNAME (0) = DEVICE1_NAME
;
1342 DEVOFFSET (0) = DEVICE1_OFFSET
;
1343 ENVSIZE (0) = ENV1_SIZE
;
1344 /* Default values are: erase-size=env-size */
1345 DEVESIZE (0) = ENVSIZE (0);
1346 /* #sectors=env-size/erase-size (rounded up) */
1347 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1348 #ifdef DEVICE1_ESIZE
1349 DEVESIZE (0) = DEVICE1_ESIZE
;
1351 #ifdef DEVICE1_ENVSECTORS
1352 ENVSECTORS (0) = DEVICE1_ENVSECTORS
;
1356 DEVNAME (1) = DEVICE2_NAME
;
1357 DEVOFFSET (1) = DEVICE2_OFFSET
;
1358 ENVSIZE (1) = ENV2_SIZE
;
1359 /* Default values are: erase-size=env-size */
1360 DEVESIZE (1) = ENVSIZE (1);
1361 /* #sectors=env-size/erase-size (rounded up) */
1362 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1363 #ifdef DEVICE2_ESIZE
1364 DEVESIZE (1) = DEVICE2_ESIZE
;
1366 #ifdef DEVICE2_ENVSECTORS
1367 ENVSECTORS (1) = DEVICE2_ENVSECTORS
;
1372 if (stat (DEVNAME (0), &st
)) {
1374 "Cannot access MTD device %s: %s\n",
1375 DEVNAME (0), strerror (errno
));
1379 if (HaveRedundEnv
&& stat (DEVNAME (1), &st
)) {
1381 "Cannot access MTD device %s: %s\n",
1382 DEVNAME (1), strerror (errno
));
1388 #if defined(CONFIG_FILE)
1389 static int get_config (char *fname
)
1397 fp
= fopen (fname
, "r");
1401 while (i
< 2 && fgets (dump
, sizeof (dump
), fp
)) {
1402 /* Skip incomplete conversions and comment strings */
1406 rc
= sscanf (dump
, "%ms %lx %lx %lx %lx",
1416 DEVNAME(i
) = devname
;
1419 /* Assume the erase size is the same as the env-size */
1420 DEVESIZE(i
) = ENVSIZE(i
);
1423 /* Assume enough env sectors to cover the environment */
1424 ENVSECTORS (i
) = (ENVSIZE(i
) + DEVESIZE(i
) - 1) / DEVESIZE(i
);
1430 HaveRedundEnv
= i
- 1;
1431 if (!i
) { /* No valid entries found */