fw_env.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  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. /* These do not need an explicit erase cycle */
  725. if (mtd_type != MTD_ABSENT &&
  726. mtd_type != MTD_DATAFLASH)
  727. if (ioctl (fd, MEMERASE, &erase) != 0) {
  728. fprintf (stderr, "MTD erase error on %s: %s\n",
  729. DEVNAME (dev),
  730. strerror (errno));
  731. return -1;
  732. }
  733. if (lseek (fd, blockstart, SEEK_SET) == -1) {
  734. fprintf (stderr,
  735. "Seek error on %s: %s\n",
  736. DEVNAME (dev), strerror (errno));
  737. return -1;
  738. }
  739. #ifdef DEBUG
  740. fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
  741. blockstart);
  742. #endif
  743. if (write (fd, data + processed, erasesize) != erasesize) {
  744. fprintf (stderr, "Write error on %s: %s\n",
  745. DEVNAME (dev), strerror (errno));
  746. return -1;
  747. }
  748. ioctl (fd, MEMLOCK, &erase);
  749. processed += blocklen;
  750. block_seek = 0;
  751. blockstart += blocklen;
  752. }
  753. if (write_total > count)
  754. free (data);
  755. return processed;
  756. }
  757. /*
  758. * Set obsolete flag at offset - NOR flash only
  759. */
  760. static int flash_flag_obsolete (int dev, int fd, off_t offset)
  761. {
  762. int rc;
  763. struct erase_info_user erase;
  764. erase.start = DEVOFFSET (dev);
  765. erase.length = DEVESIZE (dev);
  766. /* This relies on the fact, that obsolete_flag == 0 */
  767. rc = lseek (fd, offset, SEEK_SET);
  768. if (rc < 0) {
  769. fprintf (stderr, "Cannot seek to set the flag on %s \n",
  770. DEVNAME (dev));
  771. return rc;
  772. }
  773. ioctl (fd, MEMUNLOCK, &erase);
  774. rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
  775. ioctl (fd, MEMLOCK, &erase);
  776. if (rc < 0)
  777. perror ("Could not set obsolete flag");
  778. return rc;
  779. }
  780. static int flash_write (int fd_current, int fd_target, int dev_target)
  781. {
  782. int rc;
  783. switch (environment.flag_scheme) {
  784. case FLAG_NONE:
  785. break;
  786. case FLAG_INCREMENTAL:
  787. (*environment.flags)++;
  788. break;
  789. case FLAG_BOOLEAN:
  790. *environment.flags = active_flag;
  791. break;
  792. default:
  793. fprintf (stderr, "Unimplemented flash scheme %u \n",
  794. environment.flag_scheme);
  795. return -1;
  796. }
  797. #ifdef DEBUG
  798. fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
  799. DEVOFFSET (dev_target), DEVNAME (dev_target));
  800. #endif
  801. rc = flash_write_buf(dev_target, fd_target, environment.image,
  802. CUR_ENVSIZE, DEVOFFSET(dev_target),
  803. DEVTYPE(dev_target));
  804. if (rc < 0)
  805. return rc;
  806. if (environment.flag_scheme == FLAG_BOOLEAN) {
  807. /* Have to set obsolete flag */
  808. off_t offset = DEVOFFSET (dev_current) +
  809. offsetof (struct env_image_redundant, flags);
  810. #ifdef DEBUG
  811. fprintf(stderr,
  812. "Setting obsolete flag in environment at 0x%lx on %s\n",
  813. DEVOFFSET (dev_current), DEVNAME (dev_current));
  814. #endif
  815. flash_flag_obsolete (dev_current, fd_current, offset);
  816. }
  817. return 0;
  818. }
  819. static int flash_read (int fd)
  820. {
  821. struct mtd_info_user mtdinfo;
  822. struct stat st;
  823. int rc;
  824. rc = fstat(fd, &st);
  825. if (rc < 0) {
  826. fprintf(stderr, "Cannot stat the file %s\n",
  827. DEVNAME(dev_current));
  828. return -1;
  829. }
  830. if (S_ISCHR(st.st_mode)) {
  831. rc = ioctl(fd, MEMGETINFO, &mtdinfo);
  832. if (rc < 0) {
  833. fprintf(stderr, "Cannot get MTD information for %s\n",
  834. DEVNAME(dev_current));
  835. return -1;
  836. }
  837. if (mtdinfo.type != MTD_NORFLASH &&
  838. mtdinfo.type != MTD_NANDFLASH &&
  839. mtdinfo.type != MTD_DATAFLASH &&
  840. mtdinfo.type != MTD_UBIVOLUME) {
  841. fprintf (stderr, "Unsupported flash type %u on %s\n",
  842. mtdinfo.type, DEVNAME(dev_current));
  843. return -1;
  844. }
  845. } else {
  846. memset(&mtdinfo, 0, sizeof(mtdinfo));
  847. mtdinfo.type = MTD_ABSENT;
  848. }
  849. DEVTYPE(dev_current) = mtdinfo.type;
  850. rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
  851. DEVOFFSET (dev_current), mtdinfo.type);
  852. return (rc != CUR_ENVSIZE) ? -1 : 0;
  853. }
  854. static int flash_io (int mode)
  855. {
  856. int fd_current, fd_target, rc, dev_target;
  857. /* dev_current: fd_current, erase_current */
  858. fd_current = open (DEVNAME (dev_current), mode);
  859. if (fd_current < 0) {
  860. fprintf (stderr,
  861. "Can't open %s: %s\n",
  862. DEVNAME (dev_current), strerror (errno));
  863. return -1;
  864. }
  865. if (mode == O_RDWR) {
  866. if (HaveRedundEnv) {
  867. /* switch to next partition for writing */
  868. dev_target = !dev_current;
  869. /* dev_target: fd_target, erase_target */
  870. fd_target = open (DEVNAME (dev_target), mode);
  871. if (fd_target < 0) {
  872. fprintf (stderr,
  873. "Can't open %s: %s\n",
  874. DEVNAME (dev_target),
  875. strerror (errno));
  876. rc = -1;
  877. goto exit;
  878. }
  879. } else {
  880. dev_target = dev_current;
  881. fd_target = fd_current;
  882. }
  883. rc = flash_write (fd_current, fd_target, dev_target);
  884. if (HaveRedundEnv) {
  885. if (close (fd_target)) {
  886. fprintf (stderr,
  887. "I/O error on %s: %s\n",
  888. DEVNAME (dev_target),
  889. strerror (errno));
  890. rc = -1;
  891. }
  892. }
  893. } else {
  894. rc = flash_read (fd_current);
  895. }
  896. exit:
  897. if (close (fd_current)) {
  898. fprintf (stderr,
  899. "I/O error on %s: %s\n",
  900. DEVNAME (dev_current), strerror (errno));
  901. return -1;
  902. }
  903. return rc;
  904. }
  905. /*
  906. * s1 is either a simple 'name', or a 'name=value' pair.
  907. * s2 is a 'name=value' pair.
  908. * If the names match, return the value of s2, else NULL.
  909. */
  910. static char *envmatch (char * s1, char * s2)
  911. {
  912. if (s1 == NULL || s2 == NULL)
  913. return NULL;
  914. while (*s1 == *s2++)
  915. if (*s1++ == '=')
  916. return s2;
  917. if (*s1 == '\0' && *(s2 - 1) == '=')
  918. return s2;
  919. return NULL;
  920. }
  921. /*
  922. * Prevent confusion if running from erased flash memory
  923. */
  924. int fw_env_open(void)
  925. {
  926. int crc0, crc0_ok;
  927. unsigned char flag0;
  928. void *addr0;
  929. int crc1, crc1_ok;
  930. unsigned char flag1;
  931. void *addr1;
  932. struct env_image_single *single;
  933. struct env_image_redundant *redundant;
  934. if (parse_config ()) /* should fill envdevices */
  935. return -1;
  936. addr0 = calloc(1, CUR_ENVSIZE);
  937. if (addr0 == NULL) {
  938. fprintf(stderr,
  939. "Not enough memory for environment (%ld bytes)\n",
  940. CUR_ENVSIZE);
  941. return -1;
  942. }
  943. /* read environment from FLASH to local buffer */
  944. environment.image = addr0;
  945. if (HaveRedundEnv) {
  946. redundant = addr0;
  947. environment.crc = &redundant->crc;
  948. environment.flags = &redundant->flags;
  949. environment.data = redundant->data;
  950. } else {
  951. single = addr0;
  952. environment.crc = &single->crc;
  953. environment.flags = NULL;
  954. environment.data = single->data;
  955. }
  956. dev_current = 0;
  957. if (flash_io (O_RDONLY))
  958. return -1;
  959. crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
  960. crc0_ok = (crc0 == *environment.crc);
  961. if (!HaveRedundEnv) {
  962. if (!crc0_ok) {
  963. fprintf (stderr,
  964. "Warning: Bad CRC, using default environment\n");
  965. memcpy(environment.data, default_environment, sizeof default_environment);
  966. }
  967. } else {
  968. flag0 = *environment.flags;
  969. dev_current = 1;
  970. addr1 = calloc(1, CUR_ENVSIZE);
  971. if (addr1 == NULL) {
  972. fprintf(stderr,
  973. "Not enough memory for environment (%ld bytes)\n",
  974. CUR_ENVSIZE);
  975. return -1;
  976. }
  977. redundant = addr1;
  978. /*
  979. * have to set environment.image for flash_read(), careful -
  980. * other pointers in environment still point inside addr0
  981. */
  982. environment.image = addr1;
  983. if (flash_io (O_RDONLY))
  984. return -1;
  985. /* Check flag scheme compatibility */
  986. if (DEVTYPE(dev_current) == MTD_NORFLASH &&
  987. DEVTYPE(!dev_current) == MTD_NORFLASH) {
  988. environment.flag_scheme = FLAG_BOOLEAN;
  989. } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
  990. DEVTYPE(!dev_current) == MTD_NANDFLASH) {
  991. environment.flag_scheme = FLAG_INCREMENTAL;
  992. } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
  993. DEVTYPE(!dev_current) == MTD_DATAFLASH) {
  994. environment.flag_scheme = FLAG_BOOLEAN;
  995. } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
  996. DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
  997. environment.flag_scheme = FLAG_INCREMENTAL;
  998. } else {
  999. fprintf (stderr, "Incompatible flash types!\n");
  1000. return -1;
  1001. }
  1002. crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
  1003. crc1_ok = (crc1 == redundant->crc);
  1004. flag1 = redundant->flags;
  1005. if (crc0_ok && !crc1_ok) {
  1006. dev_current = 0;
  1007. } else if (!crc0_ok && crc1_ok) {
  1008. dev_current = 1;
  1009. } else if (!crc0_ok && !crc1_ok) {
  1010. fprintf (stderr,
  1011. "Warning: Bad CRC, using default environment\n");
  1012. memcpy (environment.data, default_environment,
  1013. sizeof default_environment);
  1014. dev_current = 0;
  1015. } else {
  1016. switch (environment.flag_scheme) {
  1017. case FLAG_BOOLEAN:
  1018. if (flag0 == active_flag &&
  1019. flag1 == obsolete_flag) {
  1020. dev_current = 0;
  1021. } else if (flag0 == obsolete_flag &&
  1022. flag1 == active_flag) {
  1023. dev_current = 1;
  1024. } else if (flag0 == flag1) {
  1025. dev_current = 0;
  1026. } else if (flag0 == 0xFF) {
  1027. dev_current = 0;
  1028. } else if (flag1 == 0xFF) {
  1029. dev_current = 1;
  1030. } else {
  1031. dev_current = 0;
  1032. }
  1033. break;
  1034. case FLAG_INCREMENTAL:
  1035. if (flag0 == 255 && flag1 == 0)
  1036. dev_current = 1;
  1037. else if ((flag1 == 255 && flag0 == 0) ||
  1038. flag0 >= flag1)
  1039. dev_current = 0;
  1040. else /* flag1 > flag0 */
  1041. dev_current = 1;
  1042. break;
  1043. default:
  1044. fprintf (stderr, "Unknown flag scheme %u \n",
  1045. environment.flag_scheme);
  1046. return -1;
  1047. }
  1048. }
  1049. /*
  1050. * If we are reading, we don't need the flag and the CRC any
  1051. * more, if we are writing, we will re-calculate CRC and update
  1052. * flags before writing out
  1053. */
  1054. if (dev_current) {
  1055. environment.image = addr1;
  1056. environment.crc = &redundant->crc;
  1057. environment.flags = &redundant->flags;
  1058. environment.data = redundant->data;
  1059. free (addr0);
  1060. } else {
  1061. environment.image = addr0;
  1062. /* Other pointers are already set */
  1063. free (addr1);
  1064. }
  1065. #ifdef DEBUG
  1066. fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
  1067. #endif
  1068. }
  1069. return 0;
  1070. }
  1071. static int parse_config ()
  1072. {
  1073. struct stat st;
  1074. #if defined(CONFIG_FILE)
  1075. /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
  1076. if (get_config (CONFIG_FILE)) {
  1077. fprintf (stderr,
  1078. "Cannot parse config file: %s\n", strerror (errno));
  1079. return -1;
  1080. }
  1081. #else
  1082. strcpy (DEVNAME (0), DEVICE1_NAME);
  1083. DEVOFFSET (0) = DEVICE1_OFFSET;
  1084. ENVSIZE (0) = ENV1_SIZE;
  1085. /* Default values are: erase-size=env-size, #sectors=1 */
  1086. DEVESIZE (0) = ENVSIZE (0);
  1087. ENVSECTORS (0) = 1;
  1088. #ifdef DEVICE1_ESIZE
  1089. DEVESIZE (0) = DEVICE1_ESIZE;
  1090. #endif
  1091. #ifdef DEVICE1_ENVSECTORS
  1092. ENVSECTORS (0) = DEVICE1_ENVSECTORS;
  1093. #endif
  1094. #ifdef HAVE_REDUND
  1095. strcpy (DEVNAME (1), DEVICE2_NAME);
  1096. DEVOFFSET (1) = DEVICE2_OFFSET;
  1097. ENVSIZE (1) = ENV2_SIZE;
  1098. /* Default values are: erase-size=env-size, #sectors=1 */
  1099. DEVESIZE (1) = ENVSIZE (1);
  1100. ENVSECTORS (1) = 1;
  1101. #ifdef DEVICE2_ESIZE
  1102. DEVESIZE (1) = DEVICE2_ESIZE;
  1103. #endif
  1104. #ifdef DEVICE2_ENVSECTORS
  1105. ENVSECTORS (1) = DEVICE2_ENVSECTORS;
  1106. #endif
  1107. HaveRedundEnv = 1;
  1108. #endif
  1109. #endif
  1110. if (stat (DEVNAME (0), &st)) {
  1111. fprintf (stderr,
  1112. "Cannot access MTD device %s: %s\n",
  1113. DEVNAME (0), strerror (errno));
  1114. return -1;
  1115. }
  1116. if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
  1117. fprintf (stderr,
  1118. "Cannot access MTD device %s: %s\n",
  1119. DEVNAME (1), strerror (errno));
  1120. return -1;
  1121. }
  1122. return 0;
  1123. }
  1124. #if defined(CONFIG_FILE)
  1125. static int get_config (char *fname)
  1126. {
  1127. FILE *fp;
  1128. int i = 0;
  1129. int rc;
  1130. char dump[128];
  1131. fp = fopen (fname, "r");
  1132. if (fp == NULL)
  1133. return -1;
  1134. while (i < 2 && fgets (dump, sizeof (dump), fp)) {
  1135. /* Skip incomplete conversions and comment strings */
  1136. if (dump[0] == '#')
  1137. continue;
  1138. rc = sscanf (dump, "%s %lx %lx %lx %lx",
  1139. DEVNAME (i),
  1140. &DEVOFFSET (i),
  1141. &ENVSIZE (i),
  1142. &DEVESIZE (i),
  1143. &ENVSECTORS (i));
  1144. if (rc < 3)
  1145. continue;
  1146. if (rc < 4)
  1147. /* Assume the erase size is the same as the env-size */
  1148. DEVESIZE(i) = ENVSIZE(i);
  1149. if (rc < 5)
  1150. /* Default - 1 sector */
  1151. ENVSECTORS (i) = 1;
  1152. i++;
  1153. }
  1154. fclose (fp);
  1155. HaveRedundEnv = i - 1;
  1156. if (!i) { /* No valid entries found */
  1157. errno = EINVAL;
  1158. return -1;
  1159. } else
  1160. return 0;
  1161. }
  1162. #endif