fw_env.c 30 KB

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