fw_env.c 29 KB

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