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 static unsigned long usable_envsize;
79 #define ENV_SIZE usable_envsize
81 struct env_image_single {
82 uint32_t crc; /* CRC32 over data bytes */
86 struct env_image_redundant {
87 uint32_t crc; /* CRC32 over data bytes */
88 unsigned char flags; /* active or obsolete */
101 unsigned char *flags;
103 enum flag_scheme flag_scheme;
106 static struct environment environment = {
107 .flag_scheme = FLAG_NONE,
110 static int env_aes_cbc_crypt(char *data, const int enc, uint8_t *key);
112 static int HaveRedundEnv = 0;
114 static unsigned char active_flag = 1;
115 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
116 static unsigned char obsolete_flag = 0;
118 #define DEFAULT_ENV_INSTANCE_STATIC
119 #include <env_default.h>
121 static int flash_io (int mode);
122 static char *envmatch (char * s1, char * s2);
123 static int parse_config (void);
125 #if defined(CONFIG_FILE)
126 static int get_config (char *);
129 static char *skip_chars(char *s)
131 for (; *s != '\0'; s++) {
138 static char *skip_blanks(char *s)
140 for (; *s != '\0'; s++) {
148 * Search the environment for a variable.
149 * Return the value, if found, or NULL, if not found.
151 char *fw_getenv (char *name)
155 for (env = environment.data; *env; env = nxt + 1) {
158 for (nxt = env; *nxt; ++nxt) {
159 if (nxt >= &environment.data[ENV_SIZE]) {
160 fprintf (stderr, "## Error: "
161 "environment not terminated\n");
165 val = envmatch (name, env);
174 * Search the default environment for a variable.
175 * Return the value, if found, or NULL, if not found.
177 char *fw_getdefenv(char *name)
181 for (env = default_environment; *env; env = nxt + 1) {
184 for (nxt = env; *nxt; ++nxt) {
185 if (nxt >= &default_environment[ENV_SIZE]) {
186 fprintf(stderr, "## Error: "
187 "default environment not terminated\n");
191 val = envmatch(name, env);
199 int parse_aes_key(char *key, uint8_t *bin_key)
201 char tmp[5] = { '0', 'x', 0, 0, 0 };
205 if (strnlen(key, 64) != 32) {
207 "## Error: '-a' option requires 16-byte AES key\n");
211 for (i = 0; i < 16; i++) {
215 ul = strtoul(tmp, NULL, 16);
218 "## Error: '-a' option requires valid AES key\n");
221 bin_key[i] = ul & 0xff;
228 * Print the current definition of one, or more, or all
229 * environment variables
231 int fw_printenv(int argc, char *argv[], int value_only)
239 if (argc == 0) { /* Print all env variables */
240 for (env = environment.data; *env; env = nxt + 1) {
241 for (nxt = env; *nxt; ++nxt) {
242 if (nxt >= &environment.data[ENV_SIZE]) {
243 fprintf (stderr, "## Error: "
244 "environment not terminated\n");
249 printf ("%s\n", env);
254 if (value_only && argc != 1) {
256 "## Error: `-n' option requires exactly one argument\n");
260 for (i = 0; i < argc; ++i) { /* print single env variables */
261 char *name = argv[i];
264 for (env = environment.data; *env; env = nxt + 1) {
266 for (nxt = env; *nxt; ++nxt) {
267 if (nxt >= &environment.data[ENV_SIZE]) {
268 fprintf (stderr, "## Error: "
269 "environment not terminated\n");
273 val = envmatch (name, env);
276 fputs (name, stdout);
284 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
292 int fw_env_close(void)
295 if (common_args.aes_flag) {
296 ret = env_aes_cbc_crypt(environment.data, 1,
297 common_args.aes_key);
300 "Error: can't encrypt env for flash\n");
308 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
310 /* write environment back to flash */
311 if (flash_io(O_RDWR)) {
313 "Error: can't write fw_env to flash\n");
322 * Set/Clear a single variable in the environment.
323 * This is called in sequence to update the environment
324 * in RAM without updating the copy in flash after each set
326 int fw_env_write(char *name, char *value)
331 int deleting, creating, overwriting;
334 * search if variable with this name already exists
336 for (nxt = env = environment.data; *env; env = nxt + 1) {
337 for (nxt = env; *nxt; ++nxt) {
338 if (nxt >= &environment.data[ENV_SIZE]) {
339 fprintf(stderr, "## Error: "
340 "environment not terminated\n");
345 if ((oldval = envmatch (name, env)) != NULL)
349 deleting = (oldval && !(value && strlen(value)));
350 creating = (!oldval && (value && strlen(value)));
351 overwriting = (oldval && (value && strlen(value)));
353 /* check for permission */
355 if (env_flags_validate_varaccess(name,
356 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
357 printf("Can't delete \"%s\"\n", name);
361 } else if (overwriting) {
362 if (env_flags_validate_varaccess(name,
363 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
364 printf("Can't overwrite \"%s\"\n", name);
367 } else if (env_flags_validate_varaccess(name,
368 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
369 const char *defval = fw_getdefenv(name);
373 if (strcmp(oldval, defval)
375 printf("Can't overwrite \"%s\"\n", name);
380 } else if (creating) {
381 if (env_flags_validate_varaccess(name,
382 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
383 printf("Can't create \"%s\"\n", name);
391 if (deleting || overwriting) {
392 if (*++nxt == '\0') {
397 if ((*env == '\0') && (*nxt == '\0'))
406 if (!value || !strlen(value))
410 * Append new definition at the end
412 for (env = environment.data; *env || *(env + 1); ++env);
413 if (env > environment.data)
417 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
419 len = strlen (name) + 2;
420 /* add '=' for first arg, ' ' for all others */
421 len += strlen(value) + 1;
423 if (len > (&environment.data[ENV_SIZE] - env)) {
425 "Error: environment overflow, \"%s\" deleted\n",
430 while ((*env = *name++) != '\0')
433 while ((*++env = *value++) != '\0')
436 /* end is marked with double '\0' */
443 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
445 * EINVAL - need at least 1 argument
446 * EROFS - certain variables ("ethaddr", "serial#") cannot be
447 * modified or deleted
450 int fw_setenv(int argc, char *argv[])
459 fprintf(stderr, "## Error: variable name missing\n");
465 fprintf(stderr, "Error: environment not initialized\n");
473 if (env_flags_validate_env_set_params(name, valv, valc) < 0)
477 for (i = 0; i < valc; ++i) {
479 size_t val_len = strlen(val);
482 value[len - 1] = ' ';
483 value = realloc(value, len + val_len + 1);
486 "Cannot malloc %zu bytes: %s\n",
487 len, strerror(errno));
491 memcpy(value + len, val, val_len);
496 fw_env_write(name, value);
500 return fw_env_close();
504 * Parse a file and configure the u-boot variables.
505 * The script file has a very simple format, as follows:
507 * Each line has a couple with name, value:
508 * <white spaces>variable_name<white spaces>variable_value
510 * Both variable_name and variable_value are interpreted as strings.
511 * Any character after <white spaces> and before ending \r\n is interpreted
512 * as variable's value (no comment allowed on these lines !)
514 * Comments are allowed if the first character in the line is #
516 * Returns -1 and sets errno error codes:
520 int fw_parse_script(char *fname)
523 char dump[1024]; /* Maximum line length in the file */
531 fprintf(stderr, "Error: environment not initialized\n");
535 if (strcmp(fname, "-") == 0)
538 fp = fopen(fname, "r");
540 fprintf(stderr, "I cannot open %s for reading\n",
546 while (fgets(dump, sizeof(dump), fp)) {
551 * Read a whole line from the file. If the line is too long
552 * or is not terminated, reports an error and exit.
554 if (dump[len - 1] != '\n') {
556 "Line %d not corrected terminated or too long\n",
562 /* Drop ending line feed / carriage return */
564 if (len && dump[len - 1] == '\r')
567 /* Skip comment or empty lines */
568 if (len == 0 || dump[0] == '#')
572 * Search for variable's name,
573 * remove leading whitespaces
575 name = skip_blanks(dump);
579 /* The first white space is the end of variable name */
580 val = skip_chars(name);
584 if ((val - name) < len)
585 val = skip_blanks(val);
591 fprintf(stderr, "Setting %s : %s\n",
592 name, val ? val : " removed");
595 if (env_flags_validate_type(name, val) < 0) {
601 * If there is an error setting a variable,
602 * try to save the environment and returns an error
604 if (fw_env_write(name, val)) {
606 "fw_env_write returns with error : %s\n",
614 /* Close file if not stdin */
615 if (strcmp(fname, "-") != 0)
618 ret |= fw_env_close();
625 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
628 * < 0 - failed to test
630 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
632 if (mtd_type == MTD_NANDFLASH) {
633 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
636 perror ("Cannot read bad block mark");
642 fprintf (stderr, "Bad block at 0x%llx, "
643 "skipping\n", *blockstart);
653 * Read data from flash at an offset into a provided buffer. On NAND it skips
654 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
655 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
657 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
658 off_t offset, uint8_t mtd_type)
660 size_t blocklen; /* erase / write length - one block on NAND,
662 size_t processed = 0; /* progress counter */
663 size_t readlen = count; /* current read length */
664 off_t top_of_range; /* end of the last block we may use */
665 off_t block_seek; /* offset inside the current block to the start
667 loff_t blockstart; /* running start of the current block -
668 MEMGETBADBLOCK needs 64 bits */
671 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
673 /* Offset inside a block */
674 block_seek = offset - blockstart;
676 if (mtd_type == MTD_NANDFLASH) {
678 * NAND: calculate which blocks we are reading. We have
679 * to read one block at a time to skip bad blocks.
681 blocklen = DEVESIZE (dev);
684 * To calculate the top of the range, we have to use the
685 * global DEVOFFSET (dev), which can be different from offset
687 top_of_range = ((DEVOFFSET(dev) / blocklen) +
688 ENVSECTORS (dev)) * blocklen;
690 /* Limit to one block for the first read */
691 if (readlen > blocklen - block_seek)
692 readlen = blocklen - block_seek;
695 top_of_range = offset + count;
698 /* This only runs once on NOR flash */
699 while (processed < count) {
700 rc = flash_bad_block (fd, mtd_type, &blockstart);
701 if (rc < 0) /* block test failed */
704 if (blockstart + block_seek + readlen > top_of_range) {
705 /* End of range is reached */
707 "Too few good blocks within range\n");
711 if (rc) { /* block is bad */
712 blockstart += blocklen;
717 * If a block is bad, we retry in the next block at the same
718 * offset - see common/env_nand.c::writeenv()
720 lseek (fd, blockstart + block_seek, SEEK_SET);
722 rc = read (fd, buf + processed, readlen);
724 fprintf (stderr, "Read error on %s: %s\n",
725 DEVNAME (dev), strerror (errno));
729 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
730 rc, blockstart + block_seek, DEVNAME(dev));
732 processed += readlen;
733 readlen = min (blocklen, count - processed);
735 blockstart += blocklen;
742 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
743 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
744 * erase and write the whole data at once.
746 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
747 off_t offset, uint8_t mtd_type)
750 struct erase_info_user erase;
751 size_t blocklen; /* length of NAND block / NOR erase sector */
752 size_t erase_len; /* whole area that can be erased - may include
754 size_t erasesize; /* erase / write length - one block on NAND,
756 size_t processed = 0; /* progress counter */
757 size_t write_total; /* total size to actually write - excluding
759 off_t erase_offset; /* offset to the first erase block (aligned)
761 off_t block_seek; /* offset inside the erase block to the start
763 off_t top_of_range; /* end of the last block we may use */
764 loff_t blockstart; /* running start of the current block -
765 MEMGETBADBLOCK needs 64 bits */
769 * For mtd devices only offset and size of the environment do matter
771 if (mtd_type == MTD_ABSENT) {
773 top_of_range = offset + count;
774 erase_len = blocklen;
777 write_total = blocklen;
779 blocklen = DEVESIZE(dev);
781 top_of_range = ((DEVOFFSET(dev) / blocklen) +
782 ENVSECTORS(dev)) * blocklen;
784 erase_offset = (offset / blocklen) * blocklen;
786 /* Maximum area we may use */
787 erase_len = top_of_range - erase_offset;
789 blockstart = erase_offset;
790 /* Offset inside a block */
791 block_seek = offset - erase_offset;
794 * Data size we actually write: from the start of the block
795 * to the start of the data, then count bytes of data, and
796 * to the end of the block
798 write_total = ((block_seek + count + blocklen - 1) /
799 blocklen) * blocklen;
803 * Support data anywhere within erase sectors: read out the complete
804 * area to be erased, replace the environment image, write the whole
807 if (write_total > count) {
808 data = malloc (erase_len);
811 "Cannot malloc %zu bytes: %s\n",
812 erase_len, strerror (errno));
816 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
818 if (write_total != rc)
822 fprintf(stderr, "Preserving data ");
824 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
825 if (block_seek + count != write_total) {
827 fprintf(stderr, " and ");
828 fprintf(stderr, "0x%lx - 0x%x",
829 block_seek + count, write_total - 1);
831 fprintf(stderr, "\n");
833 /* Overwrite the old environment */
834 memcpy (data + block_seek, buf, count);
837 * We get here, iff offset is block-aligned and count is a
838 * multiple of blocklen - see write_total calculation above
843 if (mtd_type == MTD_NANDFLASH) {
845 * NAND: calculate which blocks we are writing. We have
846 * to write one block at a time to skip bad blocks.
848 erasesize = blocklen;
850 erasesize = erase_len;
853 erase.length = erasesize;
855 /* This only runs once on NOR flash and SPI-dataflash */
856 while (processed < write_total) {
857 rc = flash_bad_block (fd, mtd_type, &blockstart);
858 if (rc < 0) /* block test failed */
861 if (blockstart + erasesize > top_of_range) {
862 fprintf (stderr, "End of range reached, aborting\n");
866 if (rc) { /* block is bad */
867 blockstart += blocklen;
871 if (mtd_type != MTD_ABSENT) {
872 erase.start = blockstart;
873 ioctl(fd, MEMUNLOCK, &erase);
874 /* These do not need an explicit erase cycle */
875 if (mtd_type != MTD_DATAFLASH)
876 if (ioctl(fd, MEMERASE, &erase) != 0) {
878 "MTD erase error on %s: %s\n",
879 DEVNAME(dev), strerror(errno));
884 if (lseek (fd, blockstart, SEEK_SET) == -1) {
886 "Seek error on %s: %s\n",
887 DEVNAME (dev), strerror (errno));
892 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
895 if (write (fd, data + processed, erasesize) != erasesize) {
896 fprintf (stderr, "Write error on %s: %s\n",
897 DEVNAME (dev), strerror (errno));
901 if (mtd_type != MTD_ABSENT)
902 ioctl(fd, MEMLOCK, &erase);
904 processed += erasesize;
906 blockstart += erasesize;
909 if (write_total > count)
916 * Set obsolete flag at offset - NOR flash only
918 static int flash_flag_obsolete (int dev, int fd, off_t offset)
921 struct erase_info_user erase;
923 erase.start = DEVOFFSET (dev);
924 erase.length = DEVESIZE (dev);
925 /* This relies on the fact, that obsolete_flag == 0 */
926 rc = lseek (fd, offset, SEEK_SET);
928 fprintf (stderr, "Cannot seek to set the flag on %s \n",
932 ioctl (fd, MEMUNLOCK, &erase);
933 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
934 ioctl (fd, MEMLOCK, &erase);
936 perror ("Could not set obsolete flag");
941 /* Encrypt or decrypt the environment before writing or reading it. */
942 static int env_aes_cbc_crypt(char *payload, const int enc, uint8_t *key)
944 uint8_t *data = (uint8_t *)payload;
945 const int len = usable_envsize;
946 uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
949 /* First we expand the key. */
950 aes_expand_key(key, key_exp);
952 /* Calculate the number of AES blocks to encrypt. */
953 aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
956 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
958 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
963 static int flash_write (int fd_current, int fd_target, int dev_target)
967 switch (environment.flag_scheme) {
970 case FLAG_INCREMENTAL:
971 (*environment.flags)++;
974 *environment.flags = active_flag;
977 fprintf (stderr, "Unimplemented flash scheme %u \n",
978 environment.flag_scheme);
983 fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
984 DEVOFFSET (dev_target), DEVNAME (dev_target));
987 rc = flash_write_buf(dev_target, fd_target, environment.image,
988 CUR_ENVSIZE, DEVOFFSET(dev_target),
989 DEVTYPE(dev_target));
993 if (environment.flag_scheme == FLAG_BOOLEAN) {
994 /* Have to set obsolete flag */
995 off_t offset = DEVOFFSET (dev_current) +
996 offsetof (struct env_image_redundant, flags);
999 "Setting obsolete flag in environment at 0x%lx on %s\n",
1000 DEVOFFSET (dev_current), DEVNAME (dev_current));
1002 flash_flag_obsolete (dev_current, fd_current, offset);
1008 static int flash_read (int fd)
1010 struct mtd_info_user mtdinfo;
1014 rc = fstat(fd, &st);
1016 fprintf(stderr, "Cannot stat the file %s\n",
1017 DEVNAME(dev_current));
1021 if (S_ISCHR(st.st_mode)) {
1022 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1024 fprintf(stderr, "Cannot get MTD information for %s\n",
1025 DEVNAME(dev_current));
1028 if (mtdinfo.type != MTD_NORFLASH &&
1029 mtdinfo.type != MTD_NANDFLASH &&
1030 mtdinfo.type != MTD_DATAFLASH &&
1031 mtdinfo.type != MTD_UBIVOLUME) {
1032 fprintf (stderr, "Unsupported flash type %u on %s\n",
1033 mtdinfo.type, DEVNAME(dev_current));
1037 memset(&mtdinfo, 0, sizeof(mtdinfo));
1038 mtdinfo.type = MTD_ABSENT;
1041 DEVTYPE(dev_current) = mtdinfo.type;
1043 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1044 DEVOFFSET (dev_current), mtdinfo.type);
1045 if (rc != CUR_ENVSIZE)
1051 static int flash_io (int mode)
1053 int fd_current, fd_target, rc, dev_target;
1055 /* dev_current: fd_current, erase_current */
1056 fd_current = open (DEVNAME (dev_current), mode);
1057 if (fd_current < 0) {
1059 "Can't open %s: %s\n",
1060 DEVNAME (dev_current), strerror (errno));
1064 if (mode == O_RDWR) {
1065 if (HaveRedundEnv) {
1066 /* switch to next partition for writing */
1067 dev_target = !dev_current;
1068 /* dev_target: fd_target, erase_target */
1069 fd_target = open (DEVNAME (dev_target), mode);
1070 if (fd_target < 0) {
1072 "Can't open %s: %s\n",
1073 DEVNAME (dev_target),
1079 dev_target = dev_current;
1080 fd_target = fd_current;
1083 rc = flash_write (fd_current, fd_target, dev_target);
1085 if (HaveRedundEnv) {
1086 if (close (fd_target)) {
1088 "I/O error on %s: %s\n",
1089 DEVNAME (dev_target),
1095 rc = flash_read (fd_current);
1099 if (close (fd_current)) {
1101 "I/O error on %s: %s\n",
1102 DEVNAME (dev_current), strerror (errno));
1110 * s1 is either a simple 'name', or a 'name=value' pair.
1111 * s2 is a 'name=value' pair.
1112 * If the names match, return the value of s2, else NULL.
1115 static char *envmatch (char * s1, char * s2)
1117 if (s1 == NULL || s2 == NULL)
1120 while (*s1 == *s2++)
1123 if (*s1 == '\0' && *(s2 - 1) == '=')
1129 * Prevent confusion if running from erased flash memory
1131 int fw_env_open(void)
1134 unsigned char flag0;
1138 unsigned char flag1;
1143 struct env_image_single *single;
1144 struct env_image_redundant *redundant;
1146 if (parse_config ()) /* should fill envdevices */
1149 addr0 = calloc(1, CUR_ENVSIZE);
1150 if (addr0 == NULL) {
1152 "Not enough memory for environment (%ld bytes)\n",
1157 /* read environment from FLASH to local buffer */
1158 environment.image = addr0;
1160 if (HaveRedundEnv) {
1162 environment.crc = &redundant->crc;
1163 environment.flags = &redundant->flags;
1164 environment.data = redundant->data;
1167 environment.crc = &single->crc;
1168 environment.flags = NULL;
1169 environment.data = single->data;
1173 if (flash_io (O_RDONLY))
1176 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1178 if (common_args.aes_flag) {
1179 ret = env_aes_cbc_crypt(environment.data, 0,
1180 common_args.aes_key);
1185 crc0_ok = (crc0 == *environment.crc);
1186 if (!HaveRedundEnv) {
1189 "Warning: Bad CRC, using default environment\n");
1190 memcpy(environment.data, default_environment, sizeof default_environment);
1193 flag0 = *environment.flags;
1196 addr1 = calloc(1, CUR_ENVSIZE);
1197 if (addr1 == NULL) {
1199 "Not enough memory for environment (%ld bytes)\n",
1206 * have to set environment.image for flash_read(), careful -
1207 * other pointers in environment still point inside addr0
1209 environment.image = addr1;
1210 if (flash_io (O_RDONLY))
1213 /* Check flag scheme compatibility */
1214 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1215 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1216 environment.flag_scheme = FLAG_BOOLEAN;
1217 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1218 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1219 environment.flag_scheme = FLAG_INCREMENTAL;
1220 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1221 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1222 environment.flag_scheme = FLAG_BOOLEAN;
1223 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1224 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1225 environment.flag_scheme = FLAG_INCREMENTAL;
1226 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1227 DEVTYPE(!dev_current) == MTD_ABSENT) {
1228 environment.flag_scheme = FLAG_INCREMENTAL;
1230 fprintf (stderr, "Incompatible flash types!\n");
1234 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1236 if (common_args.aes_flag) {
1237 ret = env_aes_cbc_crypt(redundant->data, 0,
1238 common_args.aes_key);
1243 crc1_ok = (crc1 == redundant->crc);
1244 flag1 = redundant->flags;
1246 if (crc0_ok && !crc1_ok) {
1248 } else if (!crc0_ok && crc1_ok) {
1250 } else if (!crc0_ok && !crc1_ok) {
1252 "Warning: Bad CRC, using default environment\n");
1253 memcpy (environment.data, default_environment,
1254 sizeof default_environment);
1257 switch (environment.flag_scheme) {
1259 if (flag0 == active_flag &&
1260 flag1 == obsolete_flag) {
1262 } else if (flag0 == obsolete_flag &&
1263 flag1 == active_flag) {
1265 } else if (flag0 == flag1) {
1267 } else if (flag0 == 0xFF) {
1269 } else if (flag1 == 0xFF) {
1275 case FLAG_INCREMENTAL:
1276 if (flag0 == 255 && flag1 == 0)
1278 else if ((flag1 == 255 && flag0 == 0) ||
1281 else /* flag1 > flag0 */
1285 fprintf (stderr, "Unknown flag scheme %u \n",
1286 environment.flag_scheme);
1292 * If we are reading, we don't need the flag and the CRC any
1293 * more, if we are writing, we will re-calculate CRC and update
1294 * flags before writing out
1297 environment.image = addr1;
1298 environment.crc = &redundant->crc;
1299 environment.flags = &redundant->flags;
1300 environment.data = redundant->data;
1303 environment.image = addr0;
1304 /* Other pointers are already set */
1308 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1315 static int parse_config ()
1319 #if defined(CONFIG_FILE)
1320 if (!common_args.config_file)
1321 common_args.config_file = CONFIG_FILE;
1323 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1324 if (get_config(common_args.config_file)) {
1325 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1326 common_args.config_file);
1330 DEVNAME (0) = DEVICE1_NAME;
1331 DEVOFFSET (0) = DEVICE1_OFFSET;
1332 ENVSIZE (0) = ENV1_SIZE;
1333 /* Default values are: erase-size=env-size */
1334 DEVESIZE (0) = ENVSIZE (0);
1335 /* #sectors=env-size/erase-size (rounded up) */
1336 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1337 #ifdef DEVICE1_ESIZE
1338 DEVESIZE (0) = DEVICE1_ESIZE;
1340 #ifdef DEVICE1_ENVSECTORS
1341 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1345 DEVNAME (1) = DEVICE2_NAME;
1346 DEVOFFSET (1) = DEVICE2_OFFSET;
1347 ENVSIZE (1) = ENV2_SIZE;
1348 /* Default values are: erase-size=env-size */
1349 DEVESIZE (1) = ENVSIZE (1);
1350 /* #sectors=env-size/erase-size (rounded up) */
1351 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1352 #ifdef DEVICE2_ESIZE
1353 DEVESIZE (1) = DEVICE2_ESIZE;
1355 #ifdef DEVICE2_ENVSECTORS
1356 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1361 if (stat (DEVNAME (0), &st)) {
1363 "Cannot access MTD device %s: %s\n",
1364 DEVNAME (0), strerror (errno));
1368 if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
1370 "Cannot access MTD device %s: %s\n",
1371 DEVNAME (1), strerror (errno));
1375 if (HaveRedundEnv && ENVSIZE(0) != ENVSIZE(1)) {
1376 ENVSIZE(0) = ENVSIZE(1) = min(ENVSIZE(0), ENVSIZE(1));
1378 "Redundant environments have inequal size, set to 0x%08lx\n",
1382 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1384 usable_envsize -= sizeof(char);
1386 if (common_args.aes_flag)
1387 usable_envsize &= ~(AES_KEY_LENGTH - 1);
1392 #if defined(CONFIG_FILE)
1393 static int get_config (char *fname)
1401 fp = fopen (fname, "r");
1405 while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1406 /* Skip incomplete conversions and comment strings */
1410 rc = sscanf (dump, "%ms %lx %lx %lx %lx",
1420 DEVNAME(i) = devname;
1423 /* Assume the erase size is the same as the env-size */
1424 DEVESIZE(i) = ENVSIZE(i);
1427 /* Assume enough env sectors to cover the environment */
1428 ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1434 HaveRedundEnv = i - 1;
1435 if (!i) { /* No valid entries found */