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