fw_env.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. /*
  2. * (C) Copyright 2000-2008
  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 <fcntl.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <stddef.h>
  31. #include <string.h>
  32. #include <sys/types.h>
  33. #include <sys/ioctl.h>
  34. #include <sys/stat.h>
  35. #include <unistd.h>
  36. #ifdef MTD_OLD
  37. # include <stdint.h>
  38. # include <linux/mtd/mtd.h>
  39. #else
  40. # define __user /* nothing */
  41. # include <mtd/mtd-user.h>
  42. #endif
  43. #include "fw_env.h"
  44. #define CMD_GETENV "fw_printenv"
  45. #define CMD_SETENV "fw_setenv"
  46. #define min(x, y) ({ \
  47. typeof(x) _min1 = (x); \
  48. typeof(y) _min2 = (y); \
  49. (void) (&_min1 == &_min2); \
  50. _min1 < _min2 ? _min1 : _min2; })
  51. struct envdev_s {
  52. char devname[16]; /* Device name */
  53. ulong devoff; /* Device offset */
  54. ulong env_size; /* environment size */
  55. ulong erase_size; /* device erase size */
  56. ulong env_sectors; /* number of environment sectors */
  57. uint8_t mtd_type; /* type of the MTD device */
  58. };
  59. static struct envdev_s envdevices[2] =
  60. {
  61. {
  62. .mtd_type = MTD_ABSENT,
  63. }, {
  64. .mtd_type = MTD_ABSENT,
  65. },
  66. };
  67. static int dev_current;
  68. #define DEVNAME(i) envdevices[(i)].devname
  69. #define DEVOFFSET(i) envdevices[(i)].devoff
  70. #define ENVSIZE(i) envdevices[(i)].env_size
  71. #define DEVESIZE(i) envdevices[(i)].erase_size
  72. #define ENVSECTORS(i) envdevices[(i)].env_sectors
  73. #define DEVTYPE(i) envdevices[(i)].mtd_type
  74. #define CONFIG_ENV_SIZE ENVSIZE(dev_current)
  75. #define ENV_SIZE getenvsize()
  76. struct env_image_single {
  77. uint32_t crc; /* CRC32 over data bytes */
  78. char data[];
  79. };
  80. struct env_image_redundant {
  81. uint32_t crc; /* CRC32 over data bytes */
  82. unsigned char flags; /* active or obsolete */
  83. char data[];
  84. };
  85. enum flag_scheme {
  86. FLAG_NONE,
  87. FLAG_BOOLEAN,
  88. FLAG_INCREMENTAL,
  89. };
  90. struct environment {
  91. void *image;
  92. uint32_t *crc;
  93. unsigned char *flags;
  94. char *data;
  95. enum flag_scheme flag_scheme;
  96. };
  97. static struct environment environment = {
  98. .flag_scheme = FLAG_NONE,
  99. };
  100. static int HaveRedundEnv = 0;
  101. static unsigned char active_flag = 1;
  102. /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
  103. static unsigned char obsolete_flag = 0;
  104. #define XMK_STR(x) #x
  105. #define MK_STR(x) XMK_STR(x)
  106. static char default_environment[] = {
  107. #if defined(CONFIG_BOOTARGS)
  108. "bootargs=" CONFIG_BOOTARGS "\0"
  109. #endif
  110. #if defined(CONFIG_BOOTCOMMAND)
  111. "bootcmd=" CONFIG_BOOTCOMMAND "\0"
  112. #endif
  113. #if defined(CONFIG_RAMBOOTCOMMAND)
  114. "ramboot=" CONFIG_RAMBOOTCOMMAND "\0"
  115. #endif
  116. #if defined(CONFIG_NFSBOOTCOMMAND)
  117. "nfsboot=" CONFIG_NFSBOOTCOMMAND "\0"
  118. #endif
  119. #if defined(CONFIG_BOOTDELAY) && (CONFIG_BOOTDELAY >= 0)
  120. "bootdelay=" MK_STR (CONFIG_BOOTDELAY) "\0"
  121. #endif
  122. #if defined(CONFIG_BAUDRATE) && (CONFIG_BAUDRATE >= 0)
  123. "baudrate=" MK_STR (CONFIG_BAUDRATE) "\0"
  124. #endif
  125. #ifdef CONFIG_LOADS_ECHO
  126. "loads_echo=" MK_STR (CONFIG_LOADS_ECHO) "\0"
  127. #endif
  128. #ifdef CONFIG_ETHADDR
  129. "ethaddr=" MK_STR (CONFIG_ETHADDR) "\0"
  130. #endif
  131. #ifdef CONFIG_ETH1ADDR
  132. "eth1addr=" MK_STR (CONFIG_ETH1ADDR) "\0"
  133. #endif
  134. #ifdef CONFIG_ETH2ADDR
  135. "eth2addr=" MK_STR (CONFIG_ETH2ADDR) "\0"
  136. #endif
  137. #ifdef CONFIG_ETH3ADDR
  138. "eth3addr=" MK_STR (CONFIG_ETH3ADDR) "\0"
  139. #endif
  140. #ifdef CONFIG_ETH4ADDR
  141. "eth4addr=" MK_STR (CONFIG_ETH4ADDR) "\0"
  142. #endif
  143. #ifdef CONFIG_ETH5ADDR
  144. "eth5addr=" MK_STR (CONFIG_ETH5ADDR) "\0"
  145. #endif
  146. #ifdef CONFIG_ETHPRIME
  147. "ethprime=" CONFIG_ETHPRIME "\0"
  148. #endif
  149. #ifdef CONFIG_IPADDR
  150. "ipaddr=" MK_STR (CONFIG_IPADDR) "\0"
  151. #endif
  152. #ifdef CONFIG_SERVERIP
  153. "serverip=" MK_STR (CONFIG_SERVERIP) "\0"
  154. #endif
  155. #ifdef CFG_AUTOLOAD
  156. "autoload=" CFG_AUTOLOAD "\0"
  157. #endif
  158. #ifdef CONFIG_ROOTPATH
  159. "rootpath=" MK_STR (CONFIG_ROOTPATH) "\0"
  160. #endif
  161. #ifdef CONFIG_GATEWAYIP
  162. "gatewayip=" MK_STR (CONFIG_GATEWAYIP) "\0"
  163. #endif
  164. #ifdef CONFIG_NETMASK
  165. "netmask=" MK_STR (CONFIG_NETMASK) "\0"
  166. #endif
  167. #ifdef CONFIG_HOSTNAME
  168. "hostname=" MK_STR (CONFIG_HOSTNAME) "\0"
  169. #endif
  170. #ifdef CONFIG_BOOTFILE
  171. "bootfile=" MK_STR (CONFIG_BOOTFILE) "\0"
  172. #endif
  173. #ifdef CONFIG_LOADADDR
  174. "loadaddr=" MK_STR (CONFIG_LOADADDR) "\0"
  175. #endif
  176. #ifdef CONFIG_PREBOOT
  177. "preboot=" CONFIG_PREBOOT "\0"
  178. #endif
  179. #ifdef CONFIG_CLOCKS_IN_MHZ
  180. "clocks_in_mhz=" "1" "\0"
  181. #endif
  182. #if defined(CONFIG_PCI_BOOTDELAY) && (CONFIG_PCI_BOOTDELAY > 0)
  183. "pcidelay=" MK_STR (CONFIG_PCI_BOOTDELAY) "\0"
  184. #endif
  185. #ifdef CONFIG_EXTRA_ENV_SETTINGS
  186. CONFIG_EXTRA_ENV_SETTINGS
  187. #endif
  188. "\0" /* Termimate struct environment data with 2 NULs */
  189. };
  190. static int flash_io (int mode);
  191. static char *envmatch (char * s1, char * s2);
  192. static int env_init (void);
  193. static int parse_config (void);
  194. #if defined(CONFIG_FILE)
  195. static int get_config (char *);
  196. #endif
  197. static inline ulong getenvsize (void)
  198. {
  199. ulong rc = CONFIG_ENV_SIZE - sizeof (long);
  200. if (HaveRedundEnv)
  201. rc -= sizeof (char);
  202. return rc;
  203. }
  204. /*
  205. * Search the environment for a variable.
  206. * Return the value, if found, or NULL, if not found.
  207. */
  208. char *fw_getenv (char *name)
  209. {
  210. char *env, *nxt;
  211. if (env_init ())
  212. return NULL;
  213. for (env = environment.data; *env; env = nxt + 1) {
  214. char *val;
  215. for (nxt = env; *nxt; ++nxt) {
  216. if (nxt >= &environment.data[ENV_SIZE]) {
  217. fprintf (stderr, "## Error: "
  218. "environment not terminated\n");
  219. return NULL;
  220. }
  221. }
  222. val = envmatch (name, env);
  223. if (!val)
  224. continue;
  225. return val;
  226. }
  227. return NULL;
  228. }
  229. /*
  230. * Print the current definition of one, or more, or all
  231. * environment variables
  232. */
  233. int fw_printenv (int argc, char *argv[])
  234. {
  235. char *env, *nxt;
  236. int i, n_flag;
  237. int rc = 0;
  238. if (env_init ())
  239. return -1;
  240. if (argc == 1) { /* Print all env variables */
  241. for (env = environment.data; *env; env = nxt + 1) {
  242. for (nxt = env; *nxt; ++nxt) {
  243. if (nxt >= &environment.data[ENV_SIZE]) {
  244. fprintf (stderr, "## Error: "
  245. "environment not terminated\n");
  246. return -1;
  247. }
  248. }
  249. printf ("%s\n", env);
  250. }
  251. return 0;
  252. }
  253. if (strcmp (argv[1], "-n") == 0) {
  254. n_flag = 1;
  255. ++argv;
  256. --argc;
  257. if (argc != 2) {
  258. fprintf (stderr, "## Error: "
  259. "`-n' option requires exactly one argument\n");
  260. return -1;
  261. }
  262. } else {
  263. n_flag = 0;
  264. }
  265. for (i = 1; i < argc; ++i) { /* print single env variables */
  266. char *name = argv[i];
  267. char *val = NULL;
  268. for (env = environment.data; *env; env = nxt + 1) {
  269. for (nxt = env; *nxt; ++nxt) {
  270. if (nxt >= &environment.data[ENV_SIZE]) {
  271. fprintf (stderr, "## Error: "
  272. "environment not terminated\n");
  273. return -1;
  274. }
  275. }
  276. val = envmatch (name, env);
  277. if (val) {
  278. if (!n_flag) {
  279. fputs (name, stdout);
  280. putc ('=', stdout);
  281. }
  282. puts (val);
  283. break;
  284. }
  285. }
  286. if (!val) {
  287. fprintf (stderr, "## Error: \"%s\" not defined\n", name);
  288. rc = -1;
  289. }
  290. }
  291. return rc;
  292. }
  293. /*
  294. * Deletes or sets environment variables. Returns -1 and sets errno error codes:
  295. * 0 - OK
  296. * EINVAL - need at least 1 argument
  297. * EROFS - certain variables ("ethaddr", "serial#") cannot be
  298. * modified or deleted
  299. *
  300. */
  301. int fw_setenv (int argc, char *argv[])
  302. {
  303. int i, len;
  304. char *env, *nxt;
  305. char *oldval = NULL;
  306. char *name;
  307. if (argc < 2) {
  308. errno = EINVAL;
  309. return -1;
  310. }
  311. if (env_init ())
  312. return -1;
  313. name = argv[1];
  314. /*
  315. * search if variable with this name already exists
  316. */
  317. for (nxt = env = environment.data; *env; env = nxt + 1) {
  318. for (nxt = env; *nxt; ++nxt) {
  319. if (nxt >= &environment.data[ENV_SIZE]) {
  320. fprintf (stderr, "## Error: "
  321. "environment not terminated\n");
  322. errno = EINVAL;
  323. return -1;
  324. }
  325. }
  326. if ((oldval = envmatch (name, env)) != NULL)
  327. break;
  328. }
  329. /*
  330. * Delete any existing definition
  331. */
  332. if (oldval) {
  333. /*
  334. * Ethernet Address and serial# can be set only once
  335. */
  336. if ((strcmp (name, "ethaddr") == 0) ||
  337. (strcmp (name, "serial#") == 0)) {
  338. fprintf (stderr, "Can't overwrite \"%s\"\n", name);
  339. errno = EROFS;
  340. return -1;
  341. }
  342. if (*++nxt == '\0') {
  343. *env = '\0';
  344. } else {
  345. for (;;) {
  346. *env = *nxt++;
  347. if ((*env == '\0') && (*nxt == '\0'))
  348. break;
  349. ++env;
  350. }
  351. }
  352. *++env = '\0';
  353. }
  354. /* Delete only ? */
  355. if (argc < 3)
  356. goto WRITE_FLASH;
  357. /*
  358. * Append new definition at the end
  359. */
  360. for (env = environment.data; *env || *(env + 1); ++env);
  361. if (env > environment.data)
  362. ++env;
  363. /*
  364. * Overflow when:
  365. * "name" + "=" + "val" +"\0\0" > CONFIG_ENV_SIZE - (env-environment)
  366. */
  367. len = strlen (name) + 2;
  368. /* add '=' for first arg, ' ' for all others */
  369. for (i = 2; i < argc; ++i) {
  370. len += strlen (argv[i]) + 1;
  371. }
  372. if (len > (&environment.data[ENV_SIZE] - env)) {
  373. fprintf (stderr,
  374. "Error: environment overflow, \"%s\" deleted\n",
  375. name);
  376. return -1;
  377. }
  378. while ((*env = *name++) != '\0')
  379. env++;
  380. for (i = 2; i < argc; ++i) {
  381. char *val = argv[i];
  382. *env = (i == 2) ? '=' : ' ';
  383. while ((*++env = *val++) != '\0');
  384. }
  385. /* end is marked with double '\0' */
  386. *++env = '\0';
  387. WRITE_FLASH:
  388. /*
  389. * Update CRC
  390. */
  391. *environment.crc = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
  392. /* write environment back to flash */
  393. if (flash_io (O_RDWR)) {
  394. fprintf (stderr, "Error: can't write fw_env to flash\n");
  395. return -1;
  396. }
  397. return 0;
  398. }
  399. /*
  400. * Test for bad block on NAND, just returns 0 on NOR, on NAND:
  401. * 0 - block is good
  402. * > 0 - block is bad
  403. * < 0 - failed to test
  404. */
  405. static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
  406. {
  407. if (mtd_type == MTD_NANDFLASH) {
  408. int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
  409. if (badblock < 0) {
  410. perror ("Cannot read bad block mark");
  411. return badblock;
  412. }
  413. if (badblock) {
  414. #ifdef DEBUG
  415. fprintf (stderr, "Bad block at 0x%llx, "
  416. "skipping\n", *blockstart);
  417. #endif
  418. return badblock;
  419. }
  420. }
  421. return 0;
  422. }
  423. /*
  424. * Read data from flash at an offset into a provided buffer. On NAND it skips
  425. * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
  426. * the DEVOFFSET (dev) block. On NOR the loop is only run once.
  427. */
  428. static int flash_read_buf (int dev, int fd, void *buf, size_t count,
  429. off_t offset, uint8_t mtd_type)
  430. {
  431. size_t blocklen; /* erase / write length - one block on NAND,
  432. 0 on NOR */
  433. size_t processed = 0; /* progress counter */
  434. size_t readlen = count; /* current read length */
  435. off_t top_of_range; /* end of the last block we may use */
  436. off_t block_seek; /* offset inside the current block to the start
  437. of the data */
  438. loff_t blockstart; /* running start of the current block -
  439. MEMGETBADBLOCK needs 64 bits */
  440. int rc;
  441. /*
  442. * Start of the first block to be read, relies on the fact, that
  443. * erase sector size is always a power of 2
  444. */
  445. blockstart = offset & ~(DEVESIZE (dev) - 1);
  446. /* Offset inside a block */
  447. block_seek = offset - blockstart;
  448. if (mtd_type == MTD_NANDFLASH) {
  449. /*
  450. * NAND: calculate which blocks we are reading. We have
  451. * to read one block at a time to skip bad blocks.
  452. */
  453. blocklen = DEVESIZE (dev);
  454. /*
  455. * To calculate the top of the range, we have to use the
  456. * global DEVOFFSET (dev), which can be different from offset
  457. */
  458. top_of_range = (DEVOFFSET (dev) & ~(blocklen - 1)) +
  459. ENVSECTORS (dev) * blocklen;
  460. /* Limit to one block for the first read */
  461. if (readlen > blocklen - block_seek)
  462. readlen = blocklen - block_seek;
  463. } else {
  464. blocklen = 0;
  465. top_of_range = offset + count;
  466. }
  467. /* This only runs once on NOR flash */
  468. while (processed < count) {
  469. rc = flash_bad_block (fd, mtd_type, &blockstart);
  470. if (rc < 0) /* block test failed */
  471. return -1;
  472. if (blockstart + block_seek + readlen > top_of_range) {
  473. /* End of range is reached */
  474. fprintf (stderr,
  475. "Too few good blocks within range\n");
  476. return -1;
  477. }
  478. if (rc) { /* block is bad */
  479. blockstart += blocklen;
  480. continue;
  481. }
  482. /*
  483. * If a block is bad, we retry in the next block at the same
  484. * offset - see common/env_nand.c::writeenv()
  485. */
  486. lseek (fd, blockstart + block_seek, SEEK_SET);
  487. rc = read (fd, buf + processed, readlen);
  488. if (rc != readlen) {
  489. fprintf (stderr, "Read error on %s: %s\n",
  490. DEVNAME (dev), strerror (errno));
  491. return -1;
  492. }
  493. #ifdef DEBUG
  494. fprintf (stderr, "Read 0x%x bytes at 0x%llx\n",
  495. rc, blockstart + block_seek);
  496. #endif
  497. processed += readlen;
  498. readlen = min (blocklen, count - processed);
  499. block_seek = 0;
  500. blockstart += blocklen;
  501. }
  502. return processed;
  503. }
  504. /*
  505. * Write count bytes at offset, but stay within ENVSETCORS (dev) sectors of
  506. * DEVOFFSET (dev). Similar to the read case above, on NOR we erase and write
  507. * the whole data at once.
  508. */
  509. static int flash_write_buf (int dev, int fd, void *buf, size_t count,
  510. off_t offset, uint8_t mtd_type)
  511. {
  512. void *data;
  513. struct erase_info_user erase;
  514. size_t blocklen; /* length of NAND block / NOR erase sector */
  515. size_t erase_len; /* whole area that can be erased - may include
  516. bad blocks */
  517. size_t erasesize; /* erase / write length - one block on NAND,
  518. whole area on NOR */
  519. size_t processed = 0; /* progress counter */
  520. size_t write_total; /* total size to actually write - excludinig
  521. bad blocks */
  522. off_t erase_offset; /* offset to the first erase block (aligned)
  523. below offset */
  524. off_t block_seek; /* offset inside the erase block to the start
  525. of the data */
  526. off_t top_of_range; /* end of the last block we may use */
  527. loff_t blockstart; /* running start of the current block -
  528. MEMGETBADBLOCK needs 64 bits */
  529. int rc;
  530. blocklen = DEVESIZE (dev);
  531. /* Erase sector size is always a power of 2 */
  532. top_of_range = (DEVOFFSET (dev) & ~(blocklen - 1)) +
  533. ENVSECTORS (dev) * blocklen;
  534. erase_offset = offset & ~(blocklen - 1);
  535. /* Maximum area we may use */
  536. erase_len = top_of_range - erase_offset;
  537. blockstart = erase_offset;
  538. /* Offset inside a block */
  539. block_seek = offset - erase_offset;
  540. /*
  541. * Data size we actually have to write: from the start of the block
  542. * to the start of the data, then count bytes of data, and to the
  543. * end of the block
  544. */
  545. write_total = (block_seek + count + blocklen - 1) & ~(blocklen - 1);
  546. /*
  547. * Support data anywhere within erase sectors: read out the complete
  548. * area to be erased, replace the environment image, write the whole
  549. * block back again.
  550. */
  551. if (write_total > count) {
  552. data = malloc (erase_len);
  553. if (!data) {
  554. fprintf (stderr,
  555. "Cannot malloc %u bytes: %s\n",
  556. erase_len, strerror (errno));
  557. return -1;
  558. }
  559. rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
  560. mtd_type);
  561. if (write_total != rc)
  562. return -1;
  563. /* Overwrite the old environment */
  564. memcpy (data + block_seek, buf, count);
  565. } else {
  566. /*
  567. * We get here, iff offset is block-aligned and count is a
  568. * multiple of blocklen - see write_total calculation above
  569. */
  570. data = buf;
  571. }
  572. if (mtd_type == MTD_NANDFLASH) {
  573. /*
  574. * NAND: calculate which blocks we are writing. We have
  575. * to write one block at a time to skip bad blocks.
  576. */
  577. erasesize = blocklen;
  578. } else {
  579. erasesize = erase_len;
  580. }
  581. erase.length = erasesize;
  582. /* This only runs once on NOR flash */
  583. while (processed < write_total) {
  584. rc = flash_bad_block (fd, mtd_type, &blockstart);
  585. if (rc < 0) /* block test failed */
  586. return rc;
  587. if (blockstart + erasesize > top_of_range) {
  588. fprintf (stderr, "End of range reached, aborting\n");
  589. return -1;
  590. }
  591. if (rc) { /* block is bad */
  592. blockstart += blocklen;
  593. continue;
  594. }
  595. erase.start = blockstart;
  596. ioctl (fd, MEMUNLOCK, &erase);
  597. if (ioctl (fd, MEMERASE, &erase) != 0) {
  598. fprintf (stderr, "MTD erase error on %s: %s\n",
  599. DEVNAME (dev),
  600. strerror (errno));
  601. return -1;
  602. }
  603. if (lseek (fd, blockstart, SEEK_SET) == -1) {
  604. fprintf (stderr,
  605. "Seek error on %s: %s\n",
  606. DEVNAME (dev), strerror (errno));
  607. return -1;
  608. }
  609. #ifdef DEBUG
  610. printf ("Write 0x%x bytes at 0x%llx\n", erasesize, blockstart);
  611. #endif
  612. if (write (fd, data + processed, erasesize) != erasesize) {
  613. fprintf (stderr, "Write error on %s: %s\n",
  614. DEVNAME (dev), strerror (errno));
  615. return -1;
  616. }
  617. ioctl (fd, MEMLOCK, &erase);
  618. processed += blocklen;
  619. block_seek = 0;
  620. blockstart += blocklen;
  621. }
  622. if (write_total > count)
  623. free (data);
  624. return processed;
  625. }
  626. /*
  627. * Set obsolete flag at offset - NOR flash only
  628. */
  629. static int flash_flag_obsolete (int dev, int fd, off_t offset)
  630. {
  631. int rc;
  632. /* This relies on the fact, that obsolete_flag == 0 */
  633. rc = lseek (fd, offset, SEEK_SET);
  634. if (rc < 0) {
  635. fprintf (stderr, "Cannot seek to set the flag on %s \n",
  636. DEVNAME (dev));
  637. return rc;
  638. }
  639. rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
  640. if (rc < 0)
  641. perror ("Could not set obsolete flag");
  642. return rc;
  643. }
  644. static int flash_write (int fd_current, int fd_target, int dev_target)
  645. {
  646. int rc;
  647. switch (environment.flag_scheme) {
  648. case FLAG_NONE:
  649. break;
  650. case FLAG_INCREMENTAL:
  651. (*environment.flags)++;
  652. break;
  653. case FLAG_BOOLEAN:
  654. *environment.flags = active_flag;
  655. break;
  656. default:
  657. fprintf (stderr, "Unimplemented flash scheme %u \n",
  658. environment.flag_scheme);
  659. return -1;
  660. }
  661. #ifdef DEBUG
  662. printf ("Writing new environment at 0x%lx on %s\n",
  663. DEVOFFSET (dev_target), DEVNAME (dev_target));
  664. #endif
  665. rc = flash_write_buf (dev_target, fd_target, environment.image,
  666. CONFIG_ENV_SIZE, DEVOFFSET (dev_target),
  667. DEVTYPE(dev_target));
  668. if (rc < 0)
  669. return rc;
  670. if (environment.flag_scheme == FLAG_BOOLEAN) {
  671. /* Have to set obsolete flag */
  672. off_t offset = DEVOFFSET (dev_current) +
  673. offsetof (struct env_image_redundant, flags);
  674. #ifdef DEBUG
  675. printf ("Setting obsolete flag in environment at 0x%lx on %s\n",
  676. DEVOFFSET (dev_current), DEVNAME (dev_current));
  677. #endif
  678. flash_flag_obsolete (dev_current, fd_current, offset);
  679. }
  680. return 0;
  681. }
  682. static int flash_read (int fd)
  683. {
  684. struct mtd_info_user mtdinfo;
  685. int rc;
  686. rc = ioctl (fd, MEMGETINFO, &mtdinfo);
  687. if (rc < 0) {
  688. perror ("Cannot get MTD information");
  689. return -1;
  690. }
  691. if (mtdinfo.type != MTD_NORFLASH && mtdinfo.type != MTD_NANDFLASH) {
  692. fprintf (stderr, "Unsupported flash type %u\n", mtdinfo.type);
  693. return -1;
  694. }
  695. DEVTYPE(dev_current) = mtdinfo.type;
  696. rc = flash_read_buf (dev_current, fd, environment.image, CONFIG_ENV_SIZE,
  697. DEVOFFSET (dev_current), mtdinfo.type);
  698. return (rc != CONFIG_ENV_SIZE) ? -1 : 0;
  699. }
  700. static int flash_io (int mode)
  701. {
  702. int fd_current, fd_target, rc, dev_target;
  703. /* dev_current: fd_current, erase_current */
  704. fd_current = open (DEVNAME (dev_current), mode);
  705. if (fd_current < 0) {
  706. fprintf (stderr,
  707. "Can't open %s: %s\n",
  708. DEVNAME (dev_current), strerror (errno));
  709. return -1;
  710. }
  711. if (mode == O_RDWR) {
  712. if (HaveRedundEnv) {
  713. /* switch to next partition for writing */
  714. dev_target = !dev_current;
  715. /* dev_target: fd_target, erase_target */
  716. fd_target = open (DEVNAME (dev_target), mode);
  717. if (fd_target < 0) {
  718. fprintf (stderr,
  719. "Can't open %s: %s\n",
  720. DEVNAME (dev_target),
  721. strerror (errno));
  722. rc = -1;
  723. goto exit;
  724. }
  725. } else {
  726. dev_target = dev_current;
  727. fd_target = fd_current;
  728. }
  729. rc = flash_write (fd_current, fd_target, dev_target);
  730. if (HaveRedundEnv) {
  731. if (close (fd_target)) {
  732. fprintf (stderr,
  733. "I/O error on %s: %s\n",
  734. DEVNAME (dev_target),
  735. strerror (errno));
  736. rc = -1;
  737. }
  738. }
  739. } else {
  740. rc = flash_read (fd_current);
  741. }
  742. exit:
  743. if (close (fd_current)) {
  744. fprintf (stderr,
  745. "I/O error on %s: %s\n",
  746. DEVNAME (dev_current), strerror (errno));
  747. return -1;
  748. }
  749. return rc;
  750. }
  751. /*
  752. * s1 is either a simple 'name', or a 'name=value' pair.
  753. * s2 is a 'name=value' pair.
  754. * If the names match, return the value of s2, else NULL.
  755. */
  756. static char *envmatch (char * s1, char * s2)
  757. {
  758. while (*s1 == *s2++)
  759. if (*s1++ == '=')
  760. return s2;
  761. if (*s1 == '\0' && *(s2 - 1) == '=')
  762. return s2;
  763. return NULL;
  764. }
  765. /*
  766. * Prevent confusion if running from erased flash memory
  767. */
  768. static int env_init (void)
  769. {
  770. int crc0, crc0_ok;
  771. char flag0;
  772. void *addr0;
  773. int crc1, crc1_ok;
  774. char flag1;
  775. void *addr1;
  776. struct env_image_single *single;
  777. struct env_image_redundant *redundant;
  778. if (parse_config ()) /* should fill envdevices */
  779. return -1;
  780. addr0 = calloc (1, CONFIG_ENV_SIZE);
  781. if (addr0 == NULL) {
  782. fprintf (stderr,
  783. "Not enough memory for environment (%ld bytes)\n",
  784. CONFIG_ENV_SIZE);
  785. return -1;
  786. }
  787. /* read environment from FLASH to local buffer */
  788. environment.image = addr0;
  789. if (HaveRedundEnv) {
  790. redundant = addr0;
  791. environment.crc = &redundant->crc;
  792. environment.flags = &redundant->flags;
  793. environment.data = redundant->data;
  794. } else {
  795. single = addr0;
  796. environment.crc = &single->crc;
  797. environment.flags = NULL;
  798. environment.data = single->data;
  799. }
  800. dev_current = 0;
  801. if (flash_io (O_RDONLY))
  802. return -1;
  803. crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
  804. crc0_ok = (crc0 == *environment.crc);
  805. if (!HaveRedundEnv) {
  806. if (!crc0_ok) {
  807. fprintf (stderr,
  808. "Warning: Bad CRC, using default environment\n");
  809. memcpy(environment.data, default_environment, sizeof default_environment);
  810. }
  811. } else {
  812. flag0 = *environment.flags;
  813. dev_current = 1;
  814. addr1 = calloc (1, CONFIG_ENV_SIZE);
  815. if (addr1 == NULL) {
  816. fprintf (stderr,
  817. "Not enough memory for environment (%ld bytes)\n",
  818. CONFIG_ENV_SIZE);
  819. return -1;
  820. }
  821. redundant = addr1;
  822. /*
  823. * have to set environment.image for flash_read(), careful -
  824. * other pointers in environment still point inside addr0
  825. */
  826. environment.image = addr1;
  827. if (flash_io (O_RDONLY))
  828. return -1;
  829. /* Check flag scheme compatibility */
  830. if (DEVTYPE(dev_current) == MTD_NORFLASH &&
  831. DEVTYPE(!dev_current) == MTD_NORFLASH) {
  832. environment.flag_scheme = FLAG_BOOLEAN;
  833. } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
  834. DEVTYPE(!dev_current) == MTD_NANDFLASH) {
  835. environment.flag_scheme = FLAG_INCREMENTAL;
  836. } else {
  837. fprintf (stderr, "Incompatible flash types!\n");
  838. return -1;
  839. }
  840. crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
  841. crc1_ok = (crc1 == redundant->crc);
  842. flag1 = redundant->flags;
  843. if (crc0_ok && !crc1_ok) {
  844. dev_current = 0;
  845. } else if (!crc0_ok && crc1_ok) {
  846. dev_current = 1;
  847. } else if (!crc0_ok && !crc1_ok) {
  848. fprintf (stderr,
  849. "Warning: Bad CRC, using default environment\n");
  850. memcpy (environment.data, default_environment,
  851. sizeof default_environment);
  852. dev_current = 0;
  853. } else {
  854. switch (environment.flag_scheme) {
  855. case FLAG_BOOLEAN:
  856. if (flag0 == active_flag &&
  857. flag1 == obsolete_flag) {
  858. dev_current = 0;
  859. } else if (flag0 == obsolete_flag &&
  860. flag1 == active_flag) {
  861. dev_current = 1;
  862. } else if (flag0 == flag1) {
  863. dev_current = 0;
  864. } else if (flag0 == 0xFF) {
  865. dev_current = 0;
  866. } else if (flag1 == 0xFF) {
  867. dev_current = 1;
  868. } else {
  869. dev_current = 0;
  870. }
  871. break;
  872. case FLAG_INCREMENTAL:
  873. if ((flag0 == 255 && flag1 == 0) ||
  874. flag1 > flag0)
  875. dev_current = 1;
  876. else if ((flag1 == 255 && flag0 == 0) ||
  877. flag0 > flag1)
  878. dev_current = 0;
  879. else /* flags are equal - almost impossible */
  880. dev_current = 0;
  881. break;
  882. default:
  883. fprintf (stderr, "Unknown flag scheme %u \n",
  884. environment.flag_scheme);
  885. return -1;
  886. }
  887. }
  888. /*
  889. * If we are reading, we don't need the flag and the CRC any
  890. * more, if we are writing, we will re-calculate CRC and update
  891. * flags before writing out
  892. */
  893. if (dev_current) {
  894. environment.image = addr1;
  895. environment.crc = &redundant->crc;
  896. environment.flags = &redundant->flags;
  897. environment.data = redundant->data;
  898. free (addr0);
  899. } else {
  900. environment.image = addr0;
  901. /* Other pointers are already set */
  902. free (addr1);
  903. }
  904. }
  905. return 0;
  906. }
  907. static int parse_config ()
  908. {
  909. struct stat st;
  910. #if defined(CONFIG_FILE)
  911. /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
  912. if (get_config (CONFIG_FILE)) {
  913. fprintf (stderr,
  914. "Cannot parse config file: %s\n", strerror (errno));
  915. return -1;
  916. }
  917. #else
  918. strcpy (DEVNAME (0), DEVICE1_NAME);
  919. DEVOFFSET (0) = DEVICE1_OFFSET;
  920. ENVSIZE (0) = ENV1_SIZE;
  921. DEVESIZE (0) = DEVICE1_ESIZE;
  922. ENVSECTORS (0) = DEVICE1_ENVSECTORS;
  923. #ifdef HAVE_REDUND
  924. strcpy (DEVNAME (1), DEVICE2_NAME);
  925. DEVOFFSET (1) = DEVICE2_OFFSET;
  926. ENVSIZE (1) = ENV2_SIZE;
  927. DEVESIZE (1) = DEVICE2_ESIZE;
  928. ENVSECTORS (1) = DEVICE2_ENVSECTORS;
  929. HaveRedundEnv = 1;
  930. #endif
  931. #endif
  932. if (stat (DEVNAME (0), &st)) {
  933. fprintf (stderr,
  934. "Cannot access MTD device %s: %s\n",
  935. DEVNAME (0), strerror (errno));
  936. return -1;
  937. }
  938. if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
  939. fprintf (stderr,
  940. "Cannot access MTD device %s: %s\n",
  941. DEVNAME (1), strerror (errno));
  942. return -1;
  943. }
  944. return 0;
  945. }
  946. #if defined(CONFIG_FILE)
  947. static int get_config (char *fname)
  948. {
  949. FILE *fp;
  950. int i = 0;
  951. int rc;
  952. char dump[128];
  953. fp = fopen (fname, "r");
  954. if (fp == NULL)
  955. return -1;
  956. while (i < 2 && fgets (dump, sizeof (dump), fp)) {
  957. /* Skip incomplete conversions and comment strings */
  958. if (dump[0] == '#')
  959. continue;
  960. rc = sscanf (dump, "%s %lx %lx %lx %lx",
  961. DEVNAME (i),
  962. &DEVOFFSET (i),
  963. &ENVSIZE (i),
  964. &DEVESIZE (i),
  965. &ENVSECTORS (i));
  966. if (rc < 4)
  967. continue;
  968. if (rc < 5)
  969. /* Default - 1 sector */
  970. ENVSECTORS (i) = 1;
  971. i++;
  972. }
  973. fclose (fp);
  974. HaveRedundEnv = i - 1;
  975. if (!i) { /* No valid entries found */
  976. errno = EINVAL;
  977. return -1;
  978. } else
  979. return 0;
  980. }
  981. #endif