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 *fw_string_blank(char *s, int noblank) 137 { 138 int i; 139 int len = strlen(s); 140 141 for (i = 0; i < len; i++, s++) { 142 if ((noblank && !isblank(*s)) || 143 (!noblank && isblank(*s))) 144 break; 145 } 146 if (i == len) 147 return NULL; 148 149 return s; 150 } 151 152 /* 153 * Search the environment for a variable. 154 * Return the value, if found, or NULL, if not found. 155 */ 156 char *fw_getenv (char *name) 157 { 158 char *env, *nxt; 159 160 for (env = environment.data; *env; env = nxt + 1) { 161 char *val; 162 163 for (nxt = env; *nxt; ++nxt) { 164 if (nxt >= &environment.data[ENV_SIZE]) { 165 fprintf (stderr, "## Error: " 166 "environment not terminated\n"); 167 return NULL; 168 } 169 } 170 val = envmatch (name, env); 171 if (!val) 172 continue; 173 return val; 174 } 175 return NULL; 176 } 177 178 /* 179 * Search the default environment for a variable. 180 * Return the value, if found, or NULL, if not found. 181 */ 182 char *fw_getdefenv(char *name) 183 { 184 char *env, *nxt; 185 186 for (env = default_environment; *env; env = nxt + 1) { 187 char *val; 188 189 for (nxt = env; *nxt; ++nxt) { 190 if (nxt >= &default_environment[ENV_SIZE]) { 191 fprintf(stderr, "## Error: " 192 "default environment not terminated\n"); 193 return NULL; 194 } 195 } 196 val = envmatch(name, env); 197 if (!val) 198 continue; 199 return val; 200 } 201 return NULL; 202 } 203 204 int parse_aes_key(char *key, uint8_t *bin_key) 205 { 206 char tmp[5] = { '0', 'x', 0, 0, 0 }; 207 unsigned long ul; 208 int i; 209 210 if (strnlen(key, 64) != 32) { 211 fprintf(stderr, 212 "## Error: '-a' option requires 16-byte AES key\n"); 213 return -1; 214 } 215 216 for (i = 0; i < 16; i++) { 217 tmp[2] = key[0]; 218 tmp[3] = key[1]; 219 errno = 0; 220 ul = strtoul(tmp, NULL, 16); 221 if (errno) { 222 fprintf(stderr, 223 "## Error: '-a' option requires valid AES key\n"); 224 return -1; 225 } 226 bin_key[i] = ul & 0xff; 227 key += 2; 228 } 229 return 0; 230 } 231 232 /* 233 * Print the current definition of one, or more, or all 234 * environment variables 235 */ 236 int fw_printenv (int argc, char *argv[]) 237 { 238 char *env, *nxt; 239 int i, rc = 0; 240 241 if (fw_env_open()) 242 return -1; 243 244 if (argc == 0) { /* Print all env variables */ 245 for (env = environment.data; *env; env = nxt + 1) { 246 for (nxt = env; *nxt; ++nxt) { 247 if (nxt >= &environment.data[ENV_SIZE]) { 248 fprintf (stderr, "## Error: " 249 "environment not terminated\n"); 250 return -1; 251 } 252 } 253 254 printf ("%s\n", env); 255 } 256 return 0; 257 } 258 259 if (printenv_args.name_suppress && argc != 1) { 260 fprintf(stderr, 261 "## Error: `-n' option requires exactly one argument\n"); 262 return -1; 263 } 264 265 for (i = 0; i < argc; ++i) { /* print single env variables */ 266 char *name = argv[i]; 267 char *val = NULL; 268 269 for (env = environment.data; *env; env = nxt + 1) { 270 271 for (nxt = env; *nxt; ++nxt) { 272 if (nxt >= &environment.data[ENV_SIZE]) { 273 fprintf (stderr, "## Error: " 274 "environment not terminated\n"); 275 return -1; 276 } 277 } 278 val = envmatch (name, env); 279 if (val) { 280 if (!printenv_args.name_suppress) { 281 fputs (name, stdout); 282 putc ('=', stdout); 283 } 284 puts (val); 285 break; 286 } 287 } 288 if (!val) { 289 fprintf (stderr, "## Error: \"%s\" not defined\n", name); 290 rc = -1; 291 } 292 } 293 294 return rc; 295 } 296 297 int fw_env_close(void) 298 { 299 int ret; 300 if (common_args.aes_flag) { 301 ret = env_aes_cbc_crypt(environment.data, 1); 302 if (ret) { 303 fprintf(stderr, 304 "Error: can't encrypt env for flash\n"); 305 return ret; 306 } 307 } 308 309 /* 310 * Update CRC 311 */ 312 *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE); 313 314 /* write environment back to flash */ 315 if (flash_io(O_RDWR)) { 316 fprintf(stderr, 317 "Error: can't write fw_env to flash\n"); 318 return -1; 319 } 320 321 return 0; 322 } 323 324 325 /* 326 * Set/Clear a single variable in the environment. 327 * This is called in sequence to update the environment 328 * in RAM without updating the copy in flash after each set 329 */ 330 int fw_env_write(char *name, char *value) 331 { 332 int len; 333 char *env, *nxt; 334 char *oldval = NULL; 335 int deleting, creating, overwriting; 336 337 /* 338 * search if variable with this name already exists 339 */ 340 for (nxt = env = environment.data; *env; env = nxt + 1) { 341 for (nxt = env; *nxt; ++nxt) { 342 if (nxt >= &environment.data[ENV_SIZE]) { 343 fprintf(stderr, "## Error: " 344 "environment not terminated\n"); 345 errno = EINVAL; 346 return -1; 347 } 348 } 349 if ((oldval = envmatch (name, env)) != NULL) 350 break; 351 } 352 353 deleting = (oldval && !(value && strlen(value))); 354 creating = (!oldval && (value && strlen(value))); 355 overwriting = (oldval && (value && strlen(value))); 356 357 /* check for permission */ 358 if (deleting) { 359 if (env_flags_validate_varaccess(name, 360 ENV_FLAGS_VARACCESS_PREVENT_DELETE)) { 361 printf("Can't delete \"%s\"\n", name); 362 errno = EROFS; 363 return -1; 364 } 365 } else if (overwriting) { 366 if (env_flags_validate_varaccess(name, 367 ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) { 368 printf("Can't overwrite \"%s\"\n", name); 369 errno = EROFS; 370 return -1; 371 } else if (env_flags_validate_varaccess(name, 372 ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) { 373 const char *defval = fw_getdefenv(name); 374 375 if (defval == NULL) 376 defval = ""; 377 if (strcmp(oldval, defval) 378 != 0) { 379 printf("Can't overwrite \"%s\"\n", name); 380 errno = EROFS; 381 return -1; 382 } 383 } 384 } else if (creating) { 385 if (env_flags_validate_varaccess(name, 386 ENV_FLAGS_VARACCESS_PREVENT_CREATE)) { 387 printf("Can't create \"%s\"\n", name); 388 errno = EROFS; 389 return -1; 390 } 391 } else 392 /* Nothing to do */ 393 return 0; 394 395 if (deleting || overwriting) { 396 if (*++nxt == '\0') { 397 *env = '\0'; 398 } else { 399 for (;;) { 400 *env = *nxt++; 401 if ((*env == '\0') && (*nxt == '\0')) 402 break; 403 ++env; 404 } 405 } 406 *++env = '\0'; 407 } 408 409 /* Delete only ? */ 410 if (!value || !strlen(value)) 411 return 0; 412 413 /* 414 * Append new definition at the end 415 */ 416 for (env = environment.data; *env || *(env + 1); ++env); 417 if (env > environment.data) 418 ++env; 419 /* 420 * Overflow when: 421 * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment) 422 */ 423 len = strlen (name) + 2; 424 /* add '=' for first arg, ' ' for all others */ 425 len += strlen(value) + 1; 426 427 if (len > (&environment.data[ENV_SIZE] - env)) { 428 fprintf (stderr, 429 "Error: environment overflow, \"%s\" deleted\n", 430 name); 431 return -1; 432 } 433 434 while ((*env = *name++) != '\0') 435 env++; 436 *env = '='; 437 while ((*++env = *value++) != '\0') 438 ; 439 440 /* end is marked with double '\0' */ 441 *++env = '\0'; 442 443 return 0; 444 } 445 446 /* 447 * Deletes or sets environment variables. Returns -1 and sets errno error codes: 448 * 0 - OK 449 * EINVAL - need at least 1 argument 450 * EROFS - certain variables ("ethaddr", "serial#") cannot be 451 * modified or deleted 452 * 453 */ 454 int fw_setenv(int argc, char *argv[]) 455 { 456 int i; 457 size_t len; 458 char *name, **valv; 459 char *value = NULL; 460 int valc; 461 462 if (argc < 1) { 463 fprintf(stderr, "## Error: variable name missing\n"); 464 errno = EINVAL; 465 return -1; 466 } 467 468 if (fw_env_open()) { 469 fprintf(stderr, "Error: environment not initialized\n"); 470 return -1; 471 } 472 473 name = argv[0]; 474 valv = argv + 1; 475 valc = argc - 1; 476 477 if (env_flags_validate_env_set_params(name, valv, valc) < 0) 478 return 1; 479 480 len = 0; 481 for (i = 0; i < valc; ++i) { 482 char *val = valv[i]; 483 size_t val_len = strlen(val); 484 485 if (value) 486 value[len - 1] = ' '; 487 value = realloc(value, len + val_len + 1); 488 if (!value) { 489 fprintf(stderr, 490 "Cannot malloc %zu bytes: %s\n", 491 len, strerror(errno)); 492 return -1; 493 } 494 495 memcpy(value + len, val, val_len); 496 len += val_len; 497 value[len++] = '\0'; 498 } 499 500 fw_env_write(name, value); 501 502 free(value); 503 504 return fw_env_close(); 505 } 506 507 /* 508 * Parse a file and configure the u-boot variables. 509 * The script file has a very simple format, as follows: 510 * 511 * Each line has a couple with name, value: 512 * <white spaces>variable_name<white spaces>variable_value 513 * 514 * Both variable_name and variable_value are interpreted as strings. 515 * Any character after <white spaces> and before ending \r\n is interpreted 516 * as variable's value (no comment allowed on these lines !) 517 * 518 * Comments are allowed if the first character in the line is # 519 * 520 * Returns -1 and sets errno error codes: 521 * 0 - OK 522 * -1 - Error 523 */ 524 int fw_parse_script(char *fname) 525 { 526 FILE *fp; 527 char dump[1024]; /* Maximum line length in the file */ 528 char *name; 529 char *val; 530 int lineno = 0; 531 int len; 532 int ret = 0; 533 534 if (fw_env_open()) { 535 fprintf(stderr, "Error: environment not initialized\n"); 536 return -1; 537 } 538 539 if (strcmp(fname, "-") == 0) 540 fp = stdin; 541 else { 542 fp = fopen(fname, "r"); 543 if (fp == NULL) { 544 fprintf(stderr, "I cannot open %s for reading\n", 545 fname); 546 return -1; 547 } 548 } 549 550 while (fgets(dump, sizeof(dump), fp)) { 551 lineno++; 552 len = strlen(dump); 553 554 /* 555 * Read a whole line from the file. If the line is too long 556 * or is not terminated, reports an error and exit. 557 */ 558 if (dump[len - 1] != '\n') { 559 fprintf(stderr, 560 "Line %d not corrected terminated or too long\n", 561 lineno); 562 ret = -1; 563 break; 564 } 565 566 /* Drop ending line feed / carriage return */ 567 while (len > 0 && (dump[len - 1] == '\n' || 568 dump[len - 1] == '\r')) { 569 dump[len - 1] = '\0'; 570 len--; 571 } 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 = fw_string_blank(dump, 1); 582 if (!name) 583 continue; 584 585 /* The first white space is the end of variable name */ 586 val = fw_string_blank(name, 0); 587 len = strlen(name); 588 if (val) { 589 *val++ = '\0'; 590 if ((val - name) < len) 591 val = fw_string_blank(val, 1); 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