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