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