fw_env.c 32 KB

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