fw_env.c 28 KB

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