]> git.ipfire.org Git - people/ms/u-boot.git/blob - tools/env/fw_env.c
Merge git://git.denx.de/u-boot-dm
[people/ms/u-boot.git] / tools / env / fw_env.c
1 /*
2 * (C) Copyright 2000-2010
3 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
4 *
5 * (C) Copyright 2008
6 * Guennadi Liakhovetski, DENX Software Engineering, lg@denx.de.
7 *
8 * SPDX-License-Identifier: GPL-2.0+
9 */
10
11 #define _GNU_SOURCE
12
13 #include <compiler.h>
14 #include <errno.h>
15 #include <env_flags.h>
16 #include <fcntl.h>
17 #include <linux/stringify.h>
18 #include <ctype.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <stddef.h>
22 #include <string.h>
23 #include <sys/types.h>
24 #include <sys/ioctl.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27
28 #ifdef MTD_OLD
29 # include <stdint.h>
30 # include <linux/mtd/mtd.h>
31 #else
32 # define __user /* nothing */
33 # include <mtd/mtd-user.h>
34 #endif
35
36 #include "fw_env.h"
37
38 #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
39
40 #define min(x, y) ({ \
41 typeof(x) _min1 = (x); \
42 typeof(y) _min2 = (y); \
43 (void) (&_min1 == &_min2); \
44 _min1 < _min2 ? _min1 : _min2; })
45
46 struct envdev_s {
47 const char *devname; /* Device name */
48 ulong devoff; /* Device offset */
49 ulong env_size; /* environment size */
50 ulong erase_size; /* device erase size */
51 ulong env_sectors; /* number of environment sectors */
52 uint8_t mtd_type; /* type of the MTD device */
53 };
54
55 static struct envdev_s envdevices[2] =
56 {
57 {
58 .mtd_type = MTD_ABSENT,
59 }, {
60 .mtd_type = MTD_ABSENT,
61 },
62 };
63 static int dev_current;
64
65 #define DEVNAME(i) envdevices[(i)].devname
66 #define DEVOFFSET(i) envdevices[(i)].devoff
67 #define ENVSIZE(i) envdevices[(i)].env_size
68 #define DEVESIZE(i) envdevices[(i)].erase_size
69 #define ENVSECTORS(i) envdevices[(i)].env_sectors
70 #define DEVTYPE(i) envdevices[(i)].mtd_type
71
72 #define CUR_ENVSIZE ENVSIZE(dev_current)
73
74 static unsigned long usable_envsize;
75 #define ENV_SIZE usable_envsize
76
77 struct env_image_single {
78 uint32_t crc; /* CRC32 over data bytes */
79 char data[];
80 };
81
82 struct env_image_redundant {
83 uint32_t crc; /* CRC32 over data bytes */
84 unsigned char flags; /* active or obsolete */
85 char data[];
86 };
87
88 enum flag_scheme {
89 FLAG_NONE,
90 FLAG_BOOLEAN,
91 FLAG_INCREMENTAL,
92 };
93
94 struct environment {
95 void *image;
96 uint32_t *crc;
97 unsigned char *flags;
98 char *data;
99 enum flag_scheme flag_scheme;
100 };
101
102 static struct environment environment = {
103 .flag_scheme = FLAG_NONE,
104 };
105
106 static int env_aes_cbc_crypt(char *data, const int enc, uint8_t *key);
107
108 static int HaveRedundEnv = 0;
109
110 static unsigned char active_flag = 1;
111 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
112 static unsigned char obsolete_flag = 0;
113
114 #define DEFAULT_ENV_INSTANCE_STATIC
115 #include <env_default.h>
116
117 static int flash_io (int mode);
118 static char *envmatch (char * s1, char * s2);
119 static int parse_config(struct env_opts *opts);
120
121 #if defined(CONFIG_FILE)
122 static int get_config (char *);
123 #endif
124
125 static char *skip_chars(char *s)
126 {
127 for (; *s != '\0'; s++) {
128 if (isblank(*s))
129 return s;
130 }
131 return NULL;
132 }
133
134 static char *skip_blanks(char *s)
135 {
136 for (; *s != '\0'; s++) {
137 if (!isblank(*s))
138 return s;
139 }
140 return NULL;
141 }
142
143 /*
144 * Search the environment for a variable.
145 * Return the value, if found, or NULL, if not found.
146 */
147 char *fw_getenv (char *name)
148 {
149 char *env, *nxt;
150
151 for (env = environment.data; *env; env = nxt + 1) {
152 char *val;
153
154 for (nxt = env; *nxt; ++nxt) {
155 if (nxt >= &environment.data[ENV_SIZE]) {
156 fprintf (stderr, "## Error: "
157 "environment not terminated\n");
158 return NULL;
159 }
160 }
161 val = envmatch (name, env);
162 if (!val)
163 continue;
164 return val;
165 }
166 return NULL;
167 }
168
169 /*
170 * Search the default environment for a variable.
171 * Return the value, if found, or NULL, if not found.
172 */
173 char *fw_getdefenv(char *name)
174 {
175 char *env, *nxt;
176
177 for (env = default_environment; *env; env = nxt + 1) {
178 char *val;
179
180 for (nxt = env; *nxt; ++nxt) {
181 if (nxt >= &default_environment[ENV_SIZE]) {
182 fprintf(stderr, "## Error: "
183 "default environment not terminated\n");
184 return NULL;
185 }
186 }
187 val = envmatch(name, env);
188 if (!val)
189 continue;
190 return val;
191 }
192 return NULL;
193 }
194
195 int parse_aes_key(char *key, uint8_t *bin_key)
196 {
197 char tmp[5] = { '0', 'x', 0, 0, 0 };
198 unsigned long ul;
199 int i;
200
201 if (strnlen(key, 64) != 32) {
202 fprintf(stderr,
203 "## Error: '-a' option requires 16-byte AES key\n");
204 return -1;
205 }
206
207 for (i = 0; i < 16; i++) {
208 tmp[2] = key[0];
209 tmp[3] = key[1];
210 errno = 0;
211 ul = strtoul(tmp, NULL, 16);
212 if (errno) {
213 fprintf(stderr,
214 "## Error: '-a' option requires valid AES key\n");
215 return -1;
216 }
217 bin_key[i] = ul & 0xff;
218 key += 2;
219 }
220 return 0;
221 }
222
223 /*
224 * Print the current definition of one, or more, or all
225 * environment variables
226 */
227 int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
228 {
229 char *env, *nxt;
230 int i, rc = 0;
231
232 if (fw_env_open(opts))
233 return -1;
234
235 if (argc == 0) { /* Print all env variables */
236 for (env = environment.data; *env; env = nxt + 1) {
237 for (nxt = env; *nxt; ++nxt) {
238 if (nxt >= &environment.data[ENV_SIZE]) {
239 fprintf (stderr, "## Error: "
240 "environment not terminated\n");
241 return -1;
242 }
243 }
244
245 printf ("%s\n", env);
246 }
247 return 0;
248 }
249
250 if (value_only && argc != 1) {
251 fprintf(stderr,
252 "## Error: `-n' option requires exactly one argument\n");
253 return -1;
254 }
255
256 for (i = 0; i < argc; ++i) { /* print single env variables */
257 char *name = argv[i];
258 char *val = NULL;
259
260 for (env = environment.data; *env; env = nxt + 1) {
261
262 for (nxt = env; *nxt; ++nxt) {
263 if (nxt >= &environment.data[ENV_SIZE]) {
264 fprintf (stderr, "## Error: "
265 "environment not terminated\n");
266 return -1;
267 }
268 }
269 val = envmatch (name, env);
270 if (val) {
271 if (!value_only) {
272 fputs (name, stdout);
273 putc ('=', stdout);
274 }
275 puts (val);
276 break;
277 }
278 }
279 if (!val) {
280 fprintf (stderr, "## Error: \"%s\" not defined\n", name);
281 rc = -1;
282 }
283 }
284
285 return rc;
286 }
287
288 int fw_env_close(struct env_opts *opts)
289 {
290 int ret;
291
292 if (opts->aes_flag) {
293 ret = env_aes_cbc_crypt(environment.data, 1,
294 opts->aes_key);
295 if (ret) {
296 fprintf(stderr,
297 "Error: can't encrypt env for flash\n");
298 return ret;
299 }
300 }
301
302 /*
303 * Update CRC
304 */
305 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
306
307 /* write environment back to flash */
308 if (flash_io(O_RDWR)) {
309 fprintf(stderr,
310 "Error: can't write fw_env to flash\n");
311 return -1;
312 }
313
314 return 0;
315 }
316
317
318 /*
319 * Set/Clear a single variable in the environment.
320 * This is called in sequence to update the environment
321 * in RAM without updating the copy in flash after each set
322 */
323 int fw_env_write(char *name, char *value)
324 {
325 int len;
326 char *env, *nxt;
327 char *oldval = NULL;
328 int deleting, creating, overwriting;
329
330 /*
331 * search if variable with this name already exists
332 */
333 for (nxt = env = environment.data; *env; env = nxt + 1) {
334 for (nxt = env; *nxt; ++nxt) {
335 if (nxt >= &environment.data[ENV_SIZE]) {
336 fprintf(stderr, "## Error: "
337 "environment not terminated\n");
338 errno = EINVAL;
339 return -1;
340 }
341 }
342 if ((oldval = envmatch (name, env)) != NULL)
343 break;
344 }
345
346 deleting = (oldval && !(value && strlen(value)));
347 creating = (!oldval && (value && strlen(value)));
348 overwriting = (oldval && (value && strlen(value)));
349
350 /* check for permission */
351 if (deleting) {
352 if (env_flags_validate_varaccess(name,
353 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
354 printf("Can't delete \"%s\"\n", name);
355 errno = EROFS;
356 return -1;
357 }
358 } else if (overwriting) {
359 if (env_flags_validate_varaccess(name,
360 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
361 printf("Can't overwrite \"%s\"\n", name);
362 errno = EROFS;
363 return -1;
364 } else if (env_flags_validate_varaccess(name,
365 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
366 const char *defval = fw_getdefenv(name);
367
368 if (defval == NULL)
369 defval = "";
370 if (strcmp(oldval, defval)
371 != 0) {
372 printf("Can't overwrite \"%s\"\n", name);
373 errno = EROFS;
374 return -1;
375 }
376 }
377 } else if (creating) {
378 if (env_flags_validate_varaccess(name,
379 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
380 printf("Can't create \"%s\"\n", name);
381 errno = EROFS;
382 return -1;
383 }
384 } else
385 /* Nothing to do */
386 return 0;
387
388 if (deleting || overwriting) {
389 if (*++nxt == '\0') {
390 *env = '\0';
391 } else {
392 for (;;) {
393 *env = *nxt++;
394 if ((*env == '\0') && (*nxt == '\0'))
395 break;
396 ++env;
397 }
398 }
399 *++env = '\0';
400 }
401
402 /* Delete only ? */
403 if (!value || !strlen(value))
404 return 0;
405
406 /*
407 * Append new definition at the end
408 */
409 for (env = environment.data; *env || *(env + 1); ++env);
410 if (env > environment.data)
411 ++env;
412 /*
413 * Overflow when:
414 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
415 */
416 len = strlen (name) + 2;
417 /* add '=' for first arg, ' ' for all others */
418 len += strlen(value) + 1;
419
420 if (len > (&environment.data[ENV_SIZE] - env)) {
421 fprintf (stderr,
422 "Error: environment overflow, \"%s\" deleted\n",
423 name);
424 return -1;
425 }
426
427 while ((*env = *name++) != '\0')
428 env++;
429 *env = '=';
430 while ((*++env = *value++) != '\0')
431 ;
432
433 /* end is marked with double '\0' */
434 *++env = '\0';
435
436 return 0;
437 }
438
439 /*
440 * Deletes or sets environment variables. Returns -1 and sets errno error codes:
441 * 0 - OK
442 * EINVAL - need at least 1 argument
443 * EROFS - certain variables ("ethaddr", "serial#") cannot be
444 * modified or deleted
445 *
446 */
447 int fw_setenv(int argc, char *argv[], struct env_opts *opts)
448 {
449 int i;
450 size_t len;
451 char *name, **valv;
452 char *value = NULL;
453 int valc;
454
455 if (argc < 1) {
456 fprintf(stderr, "## Error: variable name missing\n");
457 errno = EINVAL;
458 return -1;
459 }
460
461 if (fw_env_open(opts)) {
462 fprintf(stderr, "Error: environment not initialized\n");
463 return -1;
464 }
465
466 name = argv[0];
467 valv = argv + 1;
468 valc = argc - 1;
469
470 if (env_flags_validate_env_set_params(name, valv, valc) < 0)
471 return 1;
472
473 len = 0;
474 for (i = 0; i < valc; ++i) {
475 char *val = valv[i];
476 size_t val_len = strlen(val);
477
478 if (value)
479 value[len - 1] = ' ';
480 value = realloc(value, len + val_len + 1);
481 if (!value) {
482 fprintf(stderr,
483 "Cannot malloc %zu bytes: %s\n",
484 len, strerror(errno));
485 return -1;
486 }
487
488 memcpy(value + len, val, val_len);
489 len += val_len;
490 value[len++] = '\0';
491 }
492
493 fw_env_write(name, value);
494
495 free(value);
496
497 return fw_env_close(opts);
498 }
499
500 /*
501 * Parse a file and configure the u-boot variables.
502 * The script file has a very simple format, as follows:
503 *
504 * Each line has a couple with name, value:
505 * <white spaces>variable_name<white spaces>variable_value
506 *
507 * Both variable_name and variable_value are interpreted as strings.
508 * Any character after <white spaces> and before ending \r\n is interpreted
509 * as variable's value (no comment allowed on these lines !)
510 *
511 * Comments are allowed if the first character in the line is #
512 *
513 * Returns -1 and sets errno error codes:
514 * 0 - OK
515 * -1 - Error
516 */
517 int fw_parse_script(char *fname, struct env_opts *opts)
518 {
519 FILE *fp;
520 char dump[1024]; /* Maximum line length in the file */
521 char *name;
522 char *val;
523 int lineno = 0;
524 int len;
525 int ret = 0;
526
527 if (fw_env_open(opts)) {
528 fprintf(stderr, "Error: environment not initialized\n");
529 return -1;
530 }
531
532 if (strcmp(fname, "-") == 0)
533 fp = stdin;
534 else {
535 fp = fopen(fname, "r");
536 if (fp == NULL) {
537 fprintf(stderr, "I cannot open %s for reading\n",
538 fname);
539 return -1;
540 }
541 }
542
543 while (fgets(dump, sizeof(dump), fp)) {
544 lineno++;
545 len = strlen(dump);
546
547 /*
548 * Read a whole line from the file. If the line is too long
549 * or is not terminated, reports an error and exit.
550 */
551 if (dump[len - 1] != '\n') {
552 fprintf(stderr,
553 "Line %d not corrected terminated or too long\n",
554 lineno);
555 ret = -1;
556 break;
557 }
558
559 /* Drop ending line feed / carriage return */
560 dump[--len] = '\0';
561 if (len && dump[len - 1] == '\r')
562 dump[--len] = '\0';
563
564 /* Skip comment or empty lines */
565 if (len == 0 || dump[0] == '#')
566 continue;
567
568 /*
569 * Search for variable's name,
570 * remove leading whitespaces
571 */
572 name = skip_blanks(dump);
573 if (!name)
574 continue;
575
576 /* The first white space is the end of variable name */
577 val = skip_chars(name);
578 len = strlen(name);
579 if (val) {
580 *val++ = '\0';
581 if ((val - name) < len)
582 val = skip_blanks(val);
583 else
584 val = NULL;
585 }
586
587 #ifdef DEBUG
588 fprintf(stderr, "Setting %s : %s\n",
589 name, val ? val : " removed");
590 #endif
591
592 if (env_flags_validate_type(name, val) < 0) {
593 ret = -1;
594 break;
595 }
596
597 /*
598 * If there is an error setting a variable,
599 * try to save the environment and returns an error
600 */
601 if (fw_env_write(name, val)) {
602 fprintf(stderr,
603 "fw_env_write returns with error : %s\n",
604 strerror(errno));
605 ret = -1;
606 break;
607 }
608
609 }
610
611 /* Close file if not stdin */
612 if (strcmp(fname, "-") != 0)
613 fclose(fp);
614
615 ret |= fw_env_close(opts);
616
617 return ret;
618 }
619
620 /*
621 * Test for bad block on NAND, just returns 0 on NOR, on NAND:
622 * 0 - block is good
623 * > 0 - block is bad
624 * < 0 - failed to test
625 */
626 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
627 {
628 if (mtd_type == MTD_NANDFLASH) {
629 int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
630
631 if (badblock < 0) {
632 perror ("Cannot read bad block mark");
633 return badblock;
634 }
635
636 if (badblock) {
637 #ifdef DEBUG
638 fprintf (stderr, "Bad block at 0x%llx, "
639 "skipping\n", *blockstart);
640 #endif
641 return badblock;
642 }
643 }
644
645 return 0;
646 }
647
648 /*
649 * Read data from flash at an offset into a provided buffer. On NAND it skips
650 * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
651 * the DEVOFFSET (dev) block. On NOR the loop is only run once.
652 */
653 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
654 off_t offset, uint8_t mtd_type)
655 {
656 size_t blocklen; /* erase / write length - one block on NAND,
657 0 on NOR */
658 size_t processed = 0; /* progress counter */
659 size_t readlen = count; /* current read length */
660 off_t top_of_range; /* end of the last block we may use */
661 off_t block_seek; /* offset inside the current block to the start
662 of the data */
663 loff_t blockstart; /* running start of the current block -
664 MEMGETBADBLOCK needs 64 bits */
665 int rc;
666
667 blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
668
669 /* Offset inside a block */
670 block_seek = offset - blockstart;
671
672 if (mtd_type == MTD_NANDFLASH) {
673 /*
674 * NAND: calculate which blocks we are reading. We have
675 * to read one block at a time to skip bad blocks.
676 */
677 blocklen = DEVESIZE (dev);
678
679 /*
680 * To calculate the top of the range, we have to use the
681 * global DEVOFFSET (dev), which can be different from offset
682 */
683 top_of_range = ((DEVOFFSET(dev) / blocklen) +
684 ENVSECTORS (dev)) * blocklen;
685
686 /* Limit to one block for the first read */
687 if (readlen > blocklen - block_seek)
688 readlen = blocklen - block_seek;
689 } else {
690 blocklen = 0;
691 top_of_range = offset + count;
692 }
693
694 /* This only runs once on NOR flash */
695 while (processed < count) {
696 rc = flash_bad_block (fd, mtd_type, &blockstart);
697 if (rc < 0) /* block test failed */
698 return -1;
699
700 if (blockstart + block_seek + readlen > top_of_range) {
701 /* End of range is reached */
702 fprintf (stderr,
703 "Too few good blocks within range\n");
704 return -1;
705 }
706
707 if (rc) { /* block is bad */
708 blockstart += blocklen;
709 continue;
710 }
711
712 /*
713 * If a block is bad, we retry in the next block at the same
714 * offset - see common/env_nand.c::writeenv()
715 */
716 lseek (fd, blockstart + block_seek, SEEK_SET);
717
718 rc = read (fd, buf + processed, readlen);
719 if (rc != readlen) {
720 fprintf (stderr, "Read error on %s: %s\n",
721 DEVNAME (dev), strerror (errno));
722 return -1;
723 }
724 #ifdef DEBUG
725 fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
726 rc, blockstart + block_seek, DEVNAME(dev));
727 #endif
728 processed += readlen;
729 readlen = min (blocklen, count - processed);
730 block_seek = 0;
731 blockstart += blocklen;
732 }
733
734 return processed;
735 }
736
737 /*
738 * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
739 * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
740 * erase and write the whole data at once.
741 */
742 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
743 off_t offset, uint8_t mtd_type)
744 {
745 void *data;
746 struct erase_info_user erase;
747 size_t blocklen; /* length of NAND block / NOR erase sector */
748 size_t erase_len; /* whole area that can be erased - may include
749 bad blocks */
750 size_t erasesize; /* erase / write length - one block on NAND,
751 whole area on NOR */
752 size_t processed = 0; /* progress counter */
753 size_t write_total; /* total size to actually write - excluding
754 bad blocks */
755 off_t erase_offset; /* offset to the first erase block (aligned)
756 below offset */
757 off_t block_seek; /* offset inside the erase block to the start
758 of the data */
759 off_t top_of_range; /* end of the last block we may use */
760 loff_t blockstart; /* running start of the current block -
761 MEMGETBADBLOCK needs 64 bits */
762 int rc;
763
764 /*
765 * For mtd devices only offset and size of the environment do matter
766 */
767 if (mtd_type == MTD_ABSENT) {
768 blocklen = count;
769 top_of_range = offset + count;
770 erase_len = blocklen;
771 blockstart = offset;
772 block_seek = 0;
773 write_total = blocklen;
774 } else {
775 blocklen = DEVESIZE(dev);
776
777 top_of_range = ((DEVOFFSET(dev) / blocklen) +
778 ENVSECTORS(dev)) * blocklen;
779
780 erase_offset = (offset / blocklen) * blocklen;
781
782 /* Maximum area we may use */
783 erase_len = top_of_range - erase_offset;
784
785 blockstart = erase_offset;
786 /* Offset inside a block */
787 block_seek = offset - erase_offset;
788
789 /*
790 * Data size we actually write: from the start of the block
791 * to the start of the data, then count bytes of data, and
792 * to the end of the block
793 */
794 write_total = ((block_seek + count + blocklen - 1) /
795 blocklen) * blocklen;
796 }
797
798 /*
799 * Support data anywhere within erase sectors: read out the complete
800 * area to be erased, replace the environment image, write the whole
801 * block back again.
802 */
803 if (write_total > count) {
804 data = malloc (erase_len);
805 if (!data) {
806 fprintf (stderr,
807 "Cannot malloc %zu bytes: %s\n",
808 erase_len, strerror (errno));
809 return -1;
810 }
811
812 rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
813 mtd_type);
814 if (write_total != rc)
815 return -1;
816
817 #ifdef DEBUG
818 fprintf(stderr, "Preserving data ");
819 if (block_seek != 0)
820 fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
821 if (block_seek + count != write_total) {
822 if (block_seek != 0)
823 fprintf(stderr, " and ");
824 fprintf(stderr, "0x%lx - 0x%x",
825 block_seek + count, write_total - 1);
826 }
827 fprintf(stderr, "\n");
828 #endif
829 /* Overwrite the old environment */
830 memcpy (data + block_seek, buf, count);
831 } else {
832 /*
833 * We get here, iff offset is block-aligned and count is a
834 * multiple of blocklen - see write_total calculation above
835 */
836 data = buf;
837 }
838
839 if (mtd_type == MTD_NANDFLASH) {
840 /*
841 * NAND: calculate which blocks we are writing. We have
842 * to write one block at a time to skip bad blocks.
843 */
844 erasesize = blocklen;
845 } else {
846 erasesize = erase_len;
847 }
848
849 erase.length = erasesize;
850
851 /* This only runs once on NOR flash and SPI-dataflash */
852 while (processed < write_total) {
853 rc = flash_bad_block (fd, mtd_type, &blockstart);
854 if (rc < 0) /* block test failed */
855 return rc;
856
857 if (blockstart + erasesize > top_of_range) {
858 fprintf (stderr, "End of range reached, aborting\n");
859 return -1;
860 }
861
862 if (rc) { /* block is bad */
863 blockstart += blocklen;
864 continue;
865 }
866
867 if (mtd_type != MTD_ABSENT) {
868 erase.start = blockstart;
869 ioctl(fd, MEMUNLOCK, &erase);
870 /* These do not need an explicit erase cycle */
871 if (mtd_type != MTD_DATAFLASH)
872 if (ioctl(fd, MEMERASE, &erase) != 0) {
873 fprintf(stderr,
874 "MTD erase error on %s: %s\n",
875 DEVNAME(dev), strerror(errno));
876 return -1;
877 }
878 }
879
880 if (lseek (fd, blockstart, SEEK_SET) == -1) {
881 fprintf (stderr,
882 "Seek error on %s: %s\n",
883 DEVNAME (dev), strerror (errno));
884 return -1;
885 }
886
887 #ifdef DEBUG
888 fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
889 blockstart);
890 #endif
891 if (write (fd, data + processed, erasesize) != erasesize) {
892 fprintf (stderr, "Write error on %s: %s\n",
893 DEVNAME (dev), strerror (errno));
894 return -1;
895 }
896
897 if (mtd_type != MTD_ABSENT)
898 ioctl(fd, MEMLOCK, &erase);
899
900 processed += erasesize;
901 block_seek = 0;
902 blockstart += erasesize;
903 }
904
905 if (write_total > count)
906 free (data);
907
908 return processed;
909 }
910
911 /*
912 * Set obsolete flag at offset - NOR flash only
913 */
914 static int flash_flag_obsolete (int dev, int fd, off_t offset)
915 {
916 int rc;
917 struct erase_info_user erase;
918
919 erase.start = DEVOFFSET (dev);
920 erase.length = DEVESIZE (dev);
921 /* This relies on the fact, that obsolete_flag == 0 */
922 rc = lseek (fd, offset, SEEK_SET);
923 if (rc < 0) {
924 fprintf (stderr, "Cannot seek to set the flag on %s \n",
925 DEVNAME (dev));
926 return rc;
927 }
928 ioctl (fd, MEMUNLOCK, &erase);
929 rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
930 ioctl (fd, MEMLOCK, &erase);
931 if (rc < 0)
932 perror ("Could not set obsolete flag");
933
934 return rc;
935 }
936
937 /* Encrypt or decrypt the environment before writing or reading it. */
938 static int env_aes_cbc_crypt(char *payload, const int enc, uint8_t *key)
939 {
940 uint8_t *data = (uint8_t *)payload;
941 const int len = usable_envsize;
942 uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
943 uint32_t aes_blocks;
944
945 /* First we expand the key. */
946 aes_expand_key(key, key_exp);
947
948 /* Calculate the number of AES blocks to encrypt. */
949 aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
950
951 if (enc)
952 aes_cbc_encrypt_blocks(key_exp, data, data, aes_blocks);
953 else
954 aes_cbc_decrypt_blocks(key_exp, data, data, aes_blocks);
955
956 return 0;
957 }
958
959 static int flash_write (int fd_current, int fd_target, int dev_target)
960 {
961 int rc;
962
963 switch (environment.flag_scheme) {
964 case FLAG_NONE:
965 break;
966 case FLAG_INCREMENTAL:
967 (*environment.flags)++;
968 break;
969 case FLAG_BOOLEAN:
970 *environment.flags = active_flag;
971 break;
972 default:
973 fprintf (stderr, "Unimplemented flash scheme %u \n",
974 environment.flag_scheme);
975 return -1;
976 }
977
978 #ifdef DEBUG
979 fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
980 DEVOFFSET (dev_target), DEVNAME (dev_target));
981 #endif
982
983 rc = flash_write_buf(dev_target, fd_target, environment.image,
984 CUR_ENVSIZE, DEVOFFSET(dev_target),
985 DEVTYPE(dev_target));
986 if (rc < 0)
987 return rc;
988
989 if (environment.flag_scheme == FLAG_BOOLEAN) {
990 /* Have to set obsolete flag */
991 off_t offset = DEVOFFSET (dev_current) +
992 offsetof (struct env_image_redundant, flags);
993 #ifdef DEBUG
994 fprintf(stderr,
995 "Setting obsolete flag in environment at 0x%lx on %s\n",
996 DEVOFFSET (dev_current), DEVNAME (dev_current));
997 #endif
998 flash_flag_obsolete (dev_current, fd_current, offset);
999 }
1000
1001 return 0;
1002 }
1003
1004 static int flash_read (int fd)
1005 {
1006 struct mtd_info_user mtdinfo;
1007 struct stat st;
1008 int rc;
1009
1010 rc = fstat(fd, &st);
1011 if (rc < 0) {
1012 fprintf(stderr, "Cannot stat the file %s\n",
1013 DEVNAME(dev_current));
1014 return -1;
1015 }
1016
1017 if (S_ISCHR(st.st_mode)) {
1018 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1019 if (rc < 0) {
1020 fprintf(stderr, "Cannot get MTD information for %s\n",
1021 DEVNAME(dev_current));
1022 return -1;
1023 }
1024 if (mtdinfo.type != MTD_NORFLASH &&
1025 mtdinfo.type != MTD_NANDFLASH &&
1026 mtdinfo.type != MTD_DATAFLASH &&
1027 mtdinfo.type != MTD_UBIVOLUME) {
1028 fprintf (stderr, "Unsupported flash type %u on %s\n",
1029 mtdinfo.type, DEVNAME(dev_current));
1030 return -1;
1031 }
1032 } else {
1033 memset(&mtdinfo, 0, sizeof(mtdinfo));
1034 mtdinfo.type = MTD_ABSENT;
1035 }
1036
1037 DEVTYPE(dev_current) = mtdinfo.type;
1038
1039 rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1040 DEVOFFSET (dev_current), mtdinfo.type);
1041 if (rc != CUR_ENVSIZE)
1042 return -1;
1043
1044 return 0;
1045 }
1046
1047 static int flash_io (int mode)
1048 {
1049 int fd_current, fd_target, rc, dev_target;
1050
1051 /* dev_current: fd_current, erase_current */
1052 fd_current = open (DEVNAME (dev_current), mode);
1053 if (fd_current < 0) {
1054 fprintf (stderr,
1055 "Can't open %s: %s\n",
1056 DEVNAME (dev_current), strerror (errno));
1057 return -1;
1058 }
1059
1060 if (mode == O_RDWR) {
1061 if (HaveRedundEnv) {
1062 /* switch to next partition for writing */
1063 dev_target = !dev_current;
1064 /* dev_target: fd_target, erase_target */
1065 fd_target = open (DEVNAME (dev_target), mode);
1066 if (fd_target < 0) {
1067 fprintf (stderr,
1068 "Can't open %s: %s\n",
1069 DEVNAME (dev_target),
1070 strerror (errno));
1071 rc = -1;
1072 goto exit;
1073 }
1074 } else {
1075 dev_target = dev_current;
1076 fd_target = fd_current;
1077 }
1078
1079 rc = flash_write (fd_current, fd_target, dev_target);
1080
1081 if (HaveRedundEnv) {
1082 if (close (fd_target)) {
1083 fprintf (stderr,
1084 "I/O error on %s: %s\n",
1085 DEVNAME (dev_target),
1086 strerror (errno));
1087 rc = -1;
1088 }
1089 }
1090 } else {
1091 rc = flash_read (fd_current);
1092 }
1093
1094 exit:
1095 if (close (fd_current)) {
1096 fprintf (stderr,
1097 "I/O error on %s: %s\n",
1098 DEVNAME (dev_current), strerror (errno));
1099 return -1;
1100 }
1101
1102 return rc;
1103 }
1104
1105 /*
1106 * s1 is either a simple 'name', or a 'name=value' pair.
1107 * s2 is a 'name=value' pair.
1108 * If the names match, return the value of s2, else NULL.
1109 */
1110
1111 static char *envmatch (char * s1, char * s2)
1112 {
1113 if (s1 == NULL || s2 == NULL)
1114 return NULL;
1115
1116 while (*s1 == *s2++)
1117 if (*s1++ == '=')
1118 return s2;
1119 if (*s1 == '\0' && *(s2 - 1) == '=')
1120 return s2;
1121 return NULL;
1122 }
1123
1124 /*
1125 * Prevent confusion if running from erased flash memory
1126 */
1127 int fw_env_open(struct env_opts *opts)
1128 {
1129 int crc0, crc0_ok;
1130 unsigned char flag0;
1131 void *addr0;
1132
1133 int crc1, crc1_ok;
1134 unsigned char flag1;
1135 void *addr1;
1136
1137 int ret;
1138
1139 struct env_image_single *single;
1140 struct env_image_redundant *redundant;
1141
1142 if (parse_config(opts)) /* should fill envdevices */
1143 return -1;
1144
1145 addr0 = calloc(1, CUR_ENVSIZE);
1146 if (addr0 == NULL) {
1147 fprintf(stderr,
1148 "Not enough memory for environment (%ld bytes)\n",
1149 CUR_ENVSIZE);
1150 return -1;
1151 }
1152
1153 /* read environment from FLASH to local buffer */
1154 environment.image = addr0;
1155
1156 if (HaveRedundEnv) {
1157 redundant = addr0;
1158 environment.crc = &redundant->crc;
1159 environment.flags = &redundant->flags;
1160 environment.data = redundant->data;
1161 } else {
1162 single = addr0;
1163 environment.crc = &single->crc;
1164 environment.flags = NULL;
1165 environment.data = single->data;
1166 }
1167
1168 dev_current = 0;
1169 if (flash_io (O_RDONLY))
1170 return -1;
1171
1172 crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1173
1174 if (opts->aes_flag) {
1175 ret = env_aes_cbc_crypt(environment.data, 0,
1176 opts->aes_key);
1177 if (ret)
1178 return ret;
1179 }
1180
1181 crc0_ok = (crc0 == *environment.crc);
1182 if (!HaveRedundEnv) {
1183 if (!crc0_ok) {
1184 fprintf (stderr,
1185 "Warning: Bad CRC, using default environment\n");
1186 memcpy(environment.data, default_environment, sizeof default_environment);
1187 }
1188 } else {
1189 flag0 = *environment.flags;
1190
1191 dev_current = 1;
1192 addr1 = calloc(1, CUR_ENVSIZE);
1193 if (addr1 == NULL) {
1194 fprintf(stderr,
1195 "Not enough memory for environment (%ld bytes)\n",
1196 CUR_ENVSIZE);
1197 return -1;
1198 }
1199 redundant = addr1;
1200
1201 /*
1202 * have to set environment.image for flash_read(), careful -
1203 * other pointers in environment still point inside addr0
1204 */
1205 environment.image = addr1;
1206 if (flash_io (O_RDONLY))
1207 return -1;
1208
1209 /* Check flag scheme compatibility */
1210 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1211 DEVTYPE(!dev_current) == MTD_NORFLASH) {
1212 environment.flag_scheme = FLAG_BOOLEAN;
1213 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1214 DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1215 environment.flag_scheme = FLAG_INCREMENTAL;
1216 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1217 DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1218 environment.flag_scheme = FLAG_BOOLEAN;
1219 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1220 DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1221 environment.flag_scheme = FLAG_INCREMENTAL;
1222 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1223 DEVTYPE(!dev_current) == MTD_ABSENT) {
1224 environment.flag_scheme = FLAG_INCREMENTAL;
1225 } else {
1226 fprintf (stderr, "Incompatible flash types!\n");
1227 return -1;
1228 }
1229
1230 crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1231
1232 if (opts->aes_flag) {
1233 ret = env_aes_cbc_crypt(redundant->data, 0,
1234 opts->aes_key);
1235 if (ret)
1236 return ret;
1237 }
1238
1239 crc1_ok = (crc1 == redundant->crc);
1240 flag1 = redundant->flags;
1241
1242 if (crc0_ok && !crc1_ok) {
1243 dev_current = 0;
1244 } else if (!crc0_ok && crc1_ok) {
1245 dev_current = 1;
1246 } else if (!crc0_ok && !crc1_ok) {
1247 fprintf (stderr,
1248 "Warning: Bad CRC, using default environment\n");
1249 memcpy (environment.data, default_environment,
1250 sizeof default_environment);
1251 dev_current = 0;
1252 } else {
1253 switch (environment.flag_scheme) {
1254 case FLAG_BOOLEAN:
1255 if (flag0 == active_flag &&
1256 flag1 == obsolete_flag) {
1257 dev_current = 0;
1258 } else if (flag0 == obsolete_flag &&
1259 flag1 == active_flag) {
1260 dev_current = 1;
1261 } else if (flag0 == flag1) {
1262 dev_current = 0;
1263 } else if (flag0 == 0xFF) {
1264 dev_current = 0;
1265 } else if (flag1 == 0xFF) {
1266 dev_current = 1;
1267 } else {
1268 dev_current = 0;
1269 }
1270 break;
1271 case FLAG_INCREMENTAL:
1272 if (flag0 == 255 && flag1 == 0)
1273 dev_current = 1;
1274 else if ((flag1 == 255 && flag0 == 0) ||
1275 flag0 >= flag1)
1276 dev_current = 0;
1277 else /* flag1 > flag0 */
1278 dev_current = 1;
1279 break;
1280 default:
1281 fprintf (stderr, "Unknown flag scheme %u \n",
1282 environment.flag_scheme);
1283 return -1;
1284 }
1285 }
1286
1287 /*
1288 * If we are reading, we don't need the flag and the CRC any
1289 * more, if we are writing, we will re-calculate CRC and update
1290 * flags before writing out
1291 */
1292 if (dev_current) {
1293 environment.image = addr1;
1294 environment.crc = &redundant->crc;
1295 environment.flags = &redundant->flags;
1296 environment.data = redundant->data;
1297 free (addr0);
1298 } else {
1299 environment.image = addr0;
1300 /* Other pointers are already set */
1301 free (addr1);
1302 }
1303 #ifdef DEBUG
1304 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1305 #endif
1306 }
1307 return 0;
1308 }
1309
1310
1311 static int parse_config(struct env_opts *opts)
1312 {
1313 struct stat st;
1314
1315 #if defined(CONFIG_FILE)
1316 if (!common_args.config_file)
1317 common_args.config_file = CONFIG_FILE;
1318
1319 /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1320 if (get_config(opts->config_file)) {
1321 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1322 opts->config_file);
1323 return -1;
1324 }
1325 #else
1326 DEVNAME (0) = DEVICE1_NAME;
1327 DEVOFFSET (0) = DEVICE1_OFFSET;
1328 ENVSIZE (0) = ENV1_SIZE;
1329 /* Default values are: erase-size=env-size */
1330 DEVESIZE (0) = ENVSIZE (0);
1331 /* #sectors=env-size/erase-size (rounded up) */
1332 ENVSECTORS (0) = (ENVSIZE(0) + DEVESIZE(0) - 1) / DEVESIZE(0);
1333 #ifdef DEVICE1_ESIZE
1334 DEVESIZE (0) = DEVICE1_ESIZE;
1335 #endif
1336 #ifdef DEVICE1_ENVSECTORS
1337 ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1338 #endif
1339
1340 #ifdef HAVE_REDUND
1341 DEVNAME (1) = DEVICE2_NAME;
1342 DEVOFFSET (1) = DEVICE2_OFFSET;
1343 ENVSIZE (1) = ENV2_SIZE;
1344 /* Default values are: erase-size=env-size */
1345 DEVESIZE (1) = ENVSIZE (1);
1346 /* #sectors=env-size/erase-size (rounded up) */
1347 ENVSECTORS (1) = (ENVSIZE(1) + DEVESIZE(1) - 1) / DEVESIZE(1);
1348 #ifdef DEVICE2_ESIZE
1349 DEVESIZE (1) = DEVICE2_ESIZE;
1350 #endif
1351 #ifdef DEVICE2_ENVSECTORS
1352 ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1353 #endif
1354 HaveRedundEnv = 1;
1355 #endif
1356 #endif
1357 if (stat (DEVNAME (0), &st)) {
1358 fprintf (stderr,
1359 "Cannot access MTD device %s: %s\n",
1360 DEVNAME (0), strerror (errno));
1361 return -1;
1362 }
1363
1364 if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
1365 fprintf (stderr,
1366 "Cannot access MTD device %s: %s\n",
1367 DEVNAME (1), strerror (errno));
1368 return -1;
1369 }
1370
1371 if (HaveRedundEnv && ENVSIZE(0) != ENVSIZE(1)) {
1372 ENVSIZE(0) = ENVSIZE(1) = min(ENVSIZE(0), ENVSIZE(1));
1373 fprintf(stderr,
1374 "Redundant environments have inequal size, set to 0x%08lx\n",
1375 ENVSIZE(1));
1376 }
1377
1378 usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1379 if (HaveRedundEnv)
1380 usable_envsize -= sizeof(char);
1381
1382 if (opts->aes_flag)
1383 usable_envsize &= ~(AES_KEY_LENGTH - 1);
1384
1385 return 0;
1386 }
1387
1388 #if defined(CONFIG_FILE)
1389 static int get_config (char *fname)
1390 {
1391 FILE *fp;
1392 int i = 0;
1393 int rc;
1394 char dump[128];
1395 char *devname;
1396
1397 fp = fopen (fname, "r");
1398 if (fp == NULL)
1399 return -1;
1400
1401 while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1402 /* Skip incomplete conversions and comment strings */
1403 if (dump[0] == '#')
1404 continue;
1405
1406 rc = sscanf (dump, "%ms %lx %lx %lx %lx",
1407 &devname,
1408 &DEVOFFSET (i),
1409 &ENVSIZE (i),
1410 &DEVESIZE (i),
1411 &ENVSECTORS (i));
1412
1413 if (rc < 3)
1414 continue;
1415
1416 DEVNAME(i) = devname;
1417
1418 if (rc < 4)
1419 /* Assume the erase size is the same as the env-size */
1420 DEVESIZE(i) = ENVSIZE(i);
1421
1422 if (rc < 5)
1423 /* Assume enough env sectors to cover the environment */
1424 ENVSECTORS (i) = (ENVSIZE(i) + DEVESIZE(i) - 1) / DEVESIZE(i);
1425
1426 i++;
1427 }
1428 fclose (fp);
1429
1430 HaveRedundEnv = i - 1;
1431 if (!i) { /* No valid entries found */
1432 errno = EINVAL;
1433 return -1;
1434 } else
1435 return 0;
1436 }
1437 #endif