fw_env.c 30 KB

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