fw_env.c 29 KB

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