fw_env.c 28 KB

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