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