fw_env.c 30 KB

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