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