fw_env.c 30 KB

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