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