fw_env.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  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 <linux/stringify.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <stddef.h>
  32. #include <string.h>
  33. #include <sys/types.h>
  34. #include <sys/ioctl.h>
  35. #include <sys/stat.h>
  36. #include <unistd.h>
  37. #ifdef MTD_OLD
  38. # include <stdint.h>
  39. # include <linux/mtd/mtd.h>
  40. #else
  41. # define __user /* nothing */
  42. # include <mtd/mtd-user.h>
  43. #endif
  44. #include "fw_env.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 CUR_ENVSIZE 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 = CUR_ENVSIZE - 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. for (env = environment.data; *env; env = nxt + 1) {
  233. char *val;
  234. for (nxt = env; *nxt; ++nxt) {
  235. if (nxt >= &environment.data[ENV_SIZE]) {
  236. fprintf (stderr, "## Error: "
  237. "environment not terminated\n");
  238. return NULL;
  239. }
  240. }
  241. val = envmatch (name, env);
  242. if (!val)
  243. continue;
  244. return val;
  245. }
  246. return NULL;
  247. }
  248. /*
  249. * Print the current definition of one, or more, or all
  250. * environment variables
  251. */
  252. int fw_printenv (int argc, char *argv[])
  253. {
  254. char *env, *nxt;
  255. int i, n_flag;
  256. int rc = 0;
  257. if (fw_env_open())
  258. return -1;
  259. if (argc == 1) { /* Print all env variables */
  260. for (env = environment.data; *env; env = nxt + 1) {
  261. for (nxt = env; *nxt; ++nxt) {
  262. if (nxt >= &environment.data[ENV_SIZE]) {
  263. fprintf (stderr, "## Error: "
  264. "environment not terminated\n");
  265. return -1;
  266. }
  267. }
  268. printf ("%s\n", env);
  269. }
  270. return 0;
  271. }
  272. if (strcmp (argv[1], "-n") == 0) {
  273. n_flag = 1;
  274. ++argv;
  275. --argc;
  276. if (argc != 2) {
  277. fprintf (stderr, "## Error: "
  278. "`-n' option requires exactly one argument\n");
  279. return -1;
  280. }
  281. } else {
  282. n_flag = 0;
  283. }
  284. for (i = 1; i < argc; ++i) { /* print single env variables */
  285. char *name = argv[i];
  286. char *val = NULL;
  287. for (env = environment.data; *env; env = nxt + 1) {
  288. for (nxt = env; *nxt; ++nxt) {
  289. if (nxt >= &environment.data[ENV_SIZE]) {
  290. fprintf (stderr, "## Error: "
  291. "environment not terminated\n");
  292. return -1;
  293. }
  294. }
  295. val = envmatch (name, env);
  296. if (val) {
  297. if (!n_flag) {
  298. fputs (name, stdout);
  299. putc ('=', stdout);
  300. }
  301. puts (val);
  302. break;
  303. }
  304. }
  305. if (!val) {
  306. fprintf (stderr, "## Error: \"%s\" not defined\n", name);
  307. rc = -1;
  308. }
  309. }
  310. return rc;
  311. }
  312. int fw_env_close(void)
  313. {
  314. /*
  315. * Update CRC
  316. */
  317. *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
  318. /* write environment back to flash */
  319. if (flash_io(O_RDWR)) {
  320. fprintf(stderr,
  321. "Error: can't write fw_env to flash\n");
  322. return -1;
  323. }
  324. return 0;
  325. }
  326. /*
  327. * Set/Clear a single variable in the environment.
  328. * This is called in sequence to update the environment
  329. * in RAM without updating the copy in flash after each set
  330. */
  331. int fw_env_write(char *name, char *value)
  332. {
  333. int len;
  334. char *env, *nxt;
  335. char *oldval = NULL;
  336. /*
  337. * search if variable with this name already exists
  338. */
  339. for (nxt = env = environment.data; *env; env = nxt + 1) {
  340. for (nxt = env; *nxt; ++nxt) {
  341. if (nxt >= &environment.data[ENV_SIZE]) {
  342. fprintf(stderr, "## Error: "
  343. "environment not terminated\n");
  344. errno = EINVAL;
  345. return -1;
  346. }
  347. }
  348. if ((oldval = envmatch (name, env)) != NULL)
  349. break;
  350. }
  351. /*
  352. * Delete any existing definition
  353. */
  354. if (oldval) {
  355. #ifndef CONFIG_ENV_OVERWRITE
  356. /*
  357. * Ethernet Address and serial# can be set only once
  358. */
  359. if (
  360. (strcmp(name, "serial#") == 0) ||
  361. ((strcmp(name, "ethaddr") == 0)
  362. #if defined(CONFIG_OVERWRITE_ETHADDR_ONCE) && defined(CONFIG_ETHADDR)
  363. && (strcmp(oldval, __stringify(CONFIG_ETHADDR)) != 0)
  364. #endif /* CONFIG_OVERWRITE_ETHADDR_ONCE && CONFIG_ETHADDR */
  365. ) ) {
  366. fprintf (stderr, "Can't overwrite \"%s\"\n", name);
  367. errno = EROFS;
  368. return -1;
  369. }
  370. #endif /* CONFIG_ENV_OVERWRITE */
  371. if (*++nxt == '\0') {
  372. *env = '\0';
  373. } else {
  374. for (;;) {
  375. *env = *nxt++;
  376. if ((*env == '\0') && (*nxt == '\0'))
  377. break;
  378. ++env;
  379. }
  380. }
  381. *++env = '\0';
  382. }
  383. /* Delete only ? */
  384. if (!value || !strlen(value))
  385. return 0;
  386. /*
  387. * Append new definition at the end
  388. */
  389. for (env = environment.data; *env || *(env + 1); ++env);
  390. if (env > environment.data)
  391. ++env;
  392. /*
  393. * Overflow when:
  394. * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
  395. */
  396. len = strlen (name) + 2;
  397. /* add '=' for first arg, ' ' for all others */
  398. len += strlen(value) + 1;
  399. if (len > (&environment.data[ENV_SIZE] - env)) {
  400. fprintf (stderr,
  401. "Error: environment overflow, \"%s\" deleted\n",
  402. name);
  403. return -1;
  404. }
  405. while ((*env = *name++) != '\0')
  406. env++;
  407. *env = '=';
  408. while ((*++env = *value++) != '\0')
  409. ;
  410. /* end is marked with double '\0' */
  411. *++env = '\0';
  412. return 0;
  413. }
  414. /*
  415. * Deletes or sets environment variables. Returns -1 and sets errno error codes:
  416. * 0 - OK
  417. * EINVAL - need at least 1 argument
  418. * EROFS - certain variables ("ethaddr", "serial#") cannot be
  419. * modified or deleted
  420. *
  421. */
  422. int fw_setenv(int argc, char *argv[])
  423. {
  424. int i, len;
  425. char *name;
  426. char *value = NULL;
  427. if (argc < 2) {
  428. errno = EINVAL;
  429. return -1;
  430. }
  431. if (fw_env_open()) {
  432. fprintf(stderr, "Error: environment not initialized\n");
  433. return -1;
  434. }
  435. name = argv[1];
  436. len = 0;
  437. for (i = 2; i < argc; ++i) {
  438. char *val = argv[i];
  439. size_t val_len = strlen(val);
  440. if (value)
  441. value[len - 1] = ' ';
  442. value = realloc(value, len + val_len + 1);
  443. if (!value) {
  444. fprintf(stderr,
  445. "Cannot malloc %zu bytes: %s\n",
  446. len, strerror(errno));
  447. return -1;
  448. }
  449. memcpy(value + len, val, val_len);
  450. len += val_len;
  451. value[len++] = '\0';
  452. }
  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 on %s\n",
  651. rc, blockstart + block_seek, DEVNAME(dev));
  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. #ifdef DEBUG
  720. fprintf(stderr, "Preserving data ");
  721. if (block_seek != 0)
  722. fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
  723. if (block_seek + count != write_total) {
  724. if (block_seek != 0)
  725. fprintf(stderr, " and ");
  726. fprintf(stderr, "0x%lx - 0x%x",
  727. block_seek + count, write_total - 1);
  728. }
  729. fprintf(stderr, "\n");
  730. #endif
  731. /* Overwrite the old environment */
  732. memcpy (data + block_seek, buf, count);
  733. } else {
  734. /*
  735. * We get here, iff offset is block-aligned and count is a
  736. * multiple of blocklen - see write_total calculation above
  737. */
  738. data = buf;
  739. }
  740. if (mtd_type == MTD_NANDFLASH) {
  741. /*
  742. * NAND: calculate which blocks we are writing. We have
  743. * to write one block at a time to skip bad blocks.
  744. */
  745. erasesize = blocklen;
  746. } else {
  747. erasesize = erase_len;
  748. }
  749. erase.length = erasesize;
  750. /* This only runs once on NOR flash and SPI-dataflash */
  751. while (processed < write_total) {
  752. rc = flash_bad_block (fd, mtd_type, &blockstart);
  753. if (rc < 0) /* block test failed */
  754. return rc;
  755. if (blockstart + erasesize > top_of_range) {
  756. fprintf (stderr, "End of range reached, aborting\n");
  757. return -1;
  758. }
  759. if (rc) { /* block is bad */
  760. blockstart += blocklen;
  761. continue;
  762. }
  763. erase.start = blockstart;
  764. ioctl (fd, MEMUNLOCK, &erase);
  765. /* Dataflash does not need an explicit erase cycle */
  766. if (mtd_type != MTD_DATAFLASH)
  767. if (ioctl (fd, MEMERASE, &erase) != 0) {
  768. fprintf (stderr, "MTD erase error on %s: %s\n",
  769. DEVNAME (dev),
  770. strerror (errno));
  771. return -1;
  772. }
  773. if (lseek (fd, blockstart, SEEK_SET) == -1) {
  774. fprintf (stderr,
  775. "Seek error on %s: %s\n",
  776. DEVNAME (dev), strerror (errno));
  777. return -1;
  778. }
  779. #ifdef DEBUG
  780. fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
  781. blockstart);
  782. #endif
  783. if (write (fd, data + processed, erasesize) != erasesize) {
  784. fprintf (stderr, "Write error on %s: %s\n",
  785. DEVNAME (dev), strerror (errno));
  786. return -1;
  787. }
  788. ioctl (fd, MEMLOCK, &erase);
  789. processed += blocklen;
  790. block_seek = 0;
  791. blockstart += blocklen;
  792. }
  793. if (write_total > count)
  794. free (data);
  795. return processed;
  796. }
  797. /*
  798. * Set obsolete flag at offset - NOR flash only
  799. */
  800. static int flash_flag_obsolete (int dev, int fd, off_t offset)
  801. {
  802. int rc;
  803. struct erase_info_user erase;
  804. erase.start = DEVOFFSET (dev);
  805. erase.length = DEVESIZE (dev);
  806. /* This relies on the fact, that obsolete_flag == 0 */
  807. rc = lseek (fd, offset, SEEK_SET);
  808. if (rc < 0) {
  809. fprintf (stderr, "Cannot seek to set the flag on %s \n",
  810. DEVNAME (dev));
  811. return rc;
  812. }
  813. ioctl (fd, MEMUNLOCK, &erase);
  814. rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
  815. ioctl (fd, MEMLOCK, &erase);
  816. if (rc < 0)
  817. perror ("Could not set obsolete flag");
  818. return rc;
  819. }
  820. static int flash_write (int fd_current, int fd_target, int dev_target)
  821. {
  822. int rc;
  823. switch (environment.flag_scheme) {
  824. case FLAG_NONE:
  825. break;
  826. case FLAG_INCREMENTAL:
  827. (*environment.flags)++;
  828. break;
  829. case FLAG_BOOLEAN:
  830. *environment.flags = active_flag;
  831. break;
  832. default:
  833. fprintf (stderr, "Unimplemented flash scheme %u \n",
  834. environment.flag_scheme);
  835. return -1;
  836. }
  837. #ifdef DEBUG
  838. fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
  839. DEVOFFSET (dev_target), DEVNAME (dev_target));
  840. #endif
  841. rc = flash_write_buf(dev_target, fd_target, environment.image,
  842. CUR_ENVSIZE, DEVOFFSET(dev_target),
  843. DEVTYPE(dev_target));
  844. if (rc < 0)
  845. return rc;
  846. if (environment.flag_scheme == FLAG_BOOLEAN) {
  847. /* Have to set obsolete flag */
  848. off_t offset = DEVOFFSET (dev_current) +
  849. offsetof (struct env_image_redundant, flags);
  850. #ifdef DEBUG
  851. fprintf(stderr,
  852. "Setting obsolete flag in environment at 0x%lx on %s\n",
  853. DEVOFFSET (dev_current), DEVNAME (dev_current));
  854. #endif
  855. flash_flag_obsolete (dev_current, fd_current, offset);
  856. }
  857. return 0;
  858. }
  859. static int flash_read (int fd)
  860. {
  861. struct mtd_info_user mtdinfo;
  862. int rc;
  863. rc = ioctl (fd, MEMGETINFO, &mtdinfo);
  864. if (rc < 0) {
  865. perror ("Cannot get MTD information");
  866. return -1;
  867. }
  868. if (mtdinfo.type != MTD_NORFLASH &&
  869. mtdinfo.type != MTD_NANDFLASH &&
  870. mtdinfo.type != MTD_DATAFLASH) {
  871. fprintf (stderr, "Unsupported flash type %u\n", mtdinfo.type);
  872. return -1;
  873. }
  874. DEVTYPE(dev_current) = mtdinfo.type;
  875. rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
  876. DEVOFFSET (dev_current), mtdinfo.type);
  877. return (rc != CUR_ENVSIZE) ? -1 : 0;
  878. }
  879. static int flash_io (int mode)
  880. {
  881. int fd_current, fd_target, rc, dev_target;
  882. /* dev_current: fd_current, erase_current */
  883. fd_current = open (DEVNAME (dev_current), mode);
  884. if (fd_current < 0) {
  885. fprintf (stderr,
  886. "Can't open %s: %s\n",
  887. DEVNAME (dev_current), strerror (errno));
  888. return -1;
  889. }
  890. if (mode == O_RDWR) {
  891. if (HaveRedundEnv) {
  892. /* switch to next partition for writing */
  893. dev_target = !dev_current;
  894. /* dev_target: fd_target, erase_target */
  895. fd_target = open (DEVNAME (dev_target), mode);
  896. if (fd_target < 0) {
  897. fprintf (stderr,
  898. "Can't open %s: %s\n",
  899. DEVNAME (dev_target),
  900. strerror (errno));
  901. rc = -1;
  902. goto exit;
  903. }
  904. } else {
  905. dev_target = dev_current;
  906. fd_target = fd_current;
  907. }
  908. rc = flash_write (fd_current, fd_target, dev_target);
  909. if (HaveRedundEnv) {
  910. if (close (fd_target)) {
  911. fprintf (stderr,
  912. "I/O error on %s: %s\n",
  913. DEVNAME (dev_target),
  914. strerror (errno));
  915. rc = -1;
  916. }
  917. }
  918. } else {
  919. rc = flash_read (fd_current);
  920. }
  921. exit:
  922. if (close (fd_current)) {
  923. fprintf (stderr,
  924. "I/O error on %s: %s\n",
  925. DEVNAME (dev_current), strerror (errno));
  926. return -1;
  927. }
  928. return rc;
  929. }
  930. /*
  931. * s1 is either a simple 'name', or a 'name=value' pair.
  932. * s2 is a 'name=value' pair.
  933. * If the names match, return the value of s2, else NULL.
  934. */
  935. static char *envmatch (char * s1, char * s2)
  936. {
  937. if (s1 == NULL || s2 == NULL)
  938. return NULL;
  939. while (*s1 == *s2++)
  940. if (*s1++ == '=')
  941. return s2;
  942. if (*s1 == '\0' && *(s2 - 1) == '=')
  943. return s2;
  944. return NULL;
  945. }
  946. /*
  947. * Prevent confusion if running from erased flash memory
  948. */
  949. int fw_env_open(void)
  950. {
  951. int crc0, crc0_ok;
  952. unsigned char flag0;
  953. void *addr0;
  954. int crc1, crc1_ok;
  955. unsigned char flag1;
  956. void *addr1;
  957. struct env_image_single *single;
  958. struct env_image_redundant *redundant;
  959. if (parse_config ()) /* should fill envdevices */
  960. return -1;
  961. addr0 = calloc(1, CUR_ENVSIZE);
  962. if (addr0 == NULL) {
  963. fprintf(stderr,
  964. "Not enough memory for environment (%ld bytes)\n",
  965. CUR_ENVSIZE);
  966. return -1;
  967. }
  968. /* read environment from FLASH to local buffer */
  969. environment.image = addr0;
  970. if (HaveRedundEnv) {
  971. redundant = addr0;
  972. environment.crc = &redundant->crc;
  973. environment.flags = &redundant->flags;
  974. environment.data = redundant->data;
  975. } else {
  976. single = addr0;
  977. environment.crc = &single->crc;
  978. environment.flags = NULL;
  979. environment.data = single->data;
  980. }
  981. dev_current = 0;
  982. if (flash_io (O_RDONLY))
  983. return -1;
  984. crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
  985. crc0_ok = (crc0 == *environment.crc);
  986. if (!HaveRedundEnv) {
  987. if (!crc0_ok) {
  988. fprintf (stderr,
  989. "Warning: Bad CRC, using default environment\n");
  990. memcpy(environment.data, default_environment, sizeof default_environment);
  991. }
  992. } else {
  993. flag0 = *environment.flags;
  994. dev_current = 1;
  995. addr1 = calloc(1, CUR_ENVSIZE);
  996. if (addr1 == NULL) {
  997. fprintf(stderr,
  998. "Not enough memory for environment (%ld bytes)\n",
  999. CUR_ENVSIZE);
  1000. return -1;
  1001. }
  1002. redundant = addr1;
  1003. /*
  1004. * have to set environment.image for flash_read(), careful -
  1005. * other pointers in environment still point inside addr0
  1006. */
  1007. environment.image = addr1;
  1008. if (flash_io (O_RDONLY))
  1009. return -1;
  1010. /* Check flag scheme compatibility */
  1011. if (DEVTYPE(dev_current) == MTD_NORFLASH &&
  1012. DEVTYPE(!dev_current) == MTD_NORFLASH) {
  1013. environment.flag_scheme = FLAG_BOOLEAN;
  1014. } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
  1015. DEVTYPE(!dev_current) == MTD_NANDFLASH) {
  1016. environment.flag_scheme = FLAG_INCREMENTAL;
  1017. } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
  1018. DEVTYPE(!dev_current) == MTD_DATAFLASH) {
  1019. environment.flag_scheme = FLAG_BOOLEAN;
  1020. } else {
  1021. fprintf (stderr, "Incompatible flash types!\n");
  1022. return -1;
  1023. }
  1024. crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
  1025. crc1_ok = (crc1 == redundant->crc);
  1026. flag1 = redundant->flags;
  1027. if (crc0_ok && !crc1_ok) {
  1028. dev_current = 0;
  1029. } else if (!crc0_ok && crc1_ok) {
  1030. dev_current = 1;
  1031. } else if (!crc0_ok && !crc1_ok) {
  1032. fprintf (stderr,
  1033. "Warning: Bad CRC, using default environment\n");
  1034. memcpy (environment.data, default_environment,
  1035. sizeof default_environment);
  1036. dev_current = 0;
  1037. } else {
  1038. switch (environment.flag_scheme) {
  1039. case FLAG_BOOLEAN:
  1040. if (flag0 == active_flag &&
  1041. flag1 == obsolete_flag) {
  1042. dev_current = 0;
  1043. } else if (flag0 == obsolete_flag &&
  1044. flag1 == active_flag) {
  1045. dev_current = 1;
  1046. } else if (flag0 == flag1) {
  1047. dev_current = 0;
  1048. } else if (flag0 == 0xFF) {
  1049. dev_current = 0;
  1050. } else if (flag1 == 0xFF) {
  1051. dev_current = 1;
  1052. } else {
  1053. dev_current = 0;
  1054. }
  1055. break;
  1056. case FLAG_INCREMENTAL:
  1057. if (flag0 == 255 && flag1 == 0)
  1058. dev_current = 1;
  1059. else if ((flag1 == 255 && flag0 == 0) ||
  1060. flag0 >= flag1)
  1061. dev_current = 0;
  1062. else /* flag1 > flag0 */
  1063. dev_current = 1;
  1064. break;
  1065. default:
  1066. fprintf (stderr, "Unknown flag scheme %u \n",
  1067. environment.flag_scheme);
  1068. return -1;
  1069. }
  1070. }
  1071. /*
  1072. * If we are reading, we don't need the flag and the CRC any
  1073. * more, if we are writing, we will re-calculate CRC and update
  1074. * flags before writing out
  1075. */
  1076. if (dev_current) {
  1077. environment.image = addr1;
  1078. environment.crc = &redundant->crc;
  1079. environment.flags = &redundant->flags;
  1080. environment.data = redundant->data;
  1081. free (addr0);
  1082. } else {
  1083. environment.image = addr0;
  1084. /* Other pointers are already set */
  1085. free (addr1);
  1086. }
  1087. #ifdef DEBUG
  1088. fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
  1089. #endif
  1090. }
  1091. return 0;
  1092. }
  1093. static int parse_config ()
  1094. {
  1095. struct stat st;
  1096. #if defined(CONFIG_FILE)
  1097. /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
  1098. if (get_config (CONFIG_FILE)) {
  1099. fprintf (stderr,
  1100. "Cannot parse config file: %s\n", strerror (errno));
  1101. return -1;
  1102. }
  1103. #else
  1104. strcpy (DEVNAME (0), DEVICE1_NAME);
  1105. DEVOFFSET (0) = DEVICE1_OFFSET;
  1106. ENVSIZE (0) = ENV1_SIZE;
  1107. /* Default values are: erase-size=env-size, #sectors=1 */
  1108. DEVESIZE (0) = ENVSIZE (0);
  1109. ENVSECTORS (0) = 1;
  1110. #ifdef DEVICE1_ESIZE
  1111. DEVESIZE (0) = DEVICE1_ESIZE;
  1112. #endif
  1113. #ifdef DEVICE1_ENVSECTORS
  1114. ENVSECTORS (0) = DEVICE1_ENVSECTORS;
  1115. #endif
  1116. #ifdef HAVE_REDUND
  1117. strcpy (DEVNAME (1), DEVICE2_NAME);
  1118. DEVOFFSET (1) = DEVICE2_OFFSET;
  1119. ENVSIZE (1) = ENV2_SIZE;
  1120. /* Default values are: erase-size=env-size, #sectors=1 */
  1121. DEVESIZE (1) = ENVSIZE (1);
  1122. ENVSECTORS (1) = 1;
  1123. #ifdef DEVICE2_ESIZE
  1124. DEVESIZE (1) = DEVICE2_ESIZE;
  1125. #endif
  1126. #ifdef DEVICE2_ENVSECTORS
  1127. ENVSECTORS (1) = DEVICE2_ENVSECTORS;
  1128. #endif
  1129. HaveRedundEnv = 1;
  1130. #endif
  1131. #endif
  1132. if (stat (DEVNAME (0), &st)) {
  1133. fprintf (stderr,
  1134. "Cannot access MTD device %s: %s\n",
  1135. DEVNAME (0), strerror (errno));
  1136. return -1;
  1137. }
  1138. if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
  1139. fprintf (stderr,
  1140. "Cannot access MTD device %s: %s\n",
  1141. DEVNAME (1), strerror (errno));
  1142. return -1;
  1143. }
  1144. return 0;
  1145. }
  1146. #if defined(CONFIG_FILE)
  1147. static int get_config (char *fname)
  1148. {
  1149. FILE *fp;
  1150. int i = 0;
  1151. int rc;
  1152. char dump[128];
  1153. fp = fopen (fname, "r");
  1154. if (fp == NULL)
  1155. return -1;
  1156. while (i < 2 && fgets (dump, sizeof (dump), fp)) {
  1157. /* Skip incomplete conversions and comment strings */
  1158. if (dump[0] == '#')
  1159. continue;
  1160. rc = sscanf (dump, "%s %lx %lx %lx %lx",
  1161. DEVNAME (i),
  1162. &DEVOFFSET (i),
  1163. &ENVSIZE (i),
  1164. &DEVESIZE (i),
  1165. &ENVSECTORS (i));
  1166. if (rc < 3)
  1167. continue;
  1168. if (rc < 4)
  1169. /* Assume the erase size is the same as the env-size */
  1170. DEVESIZE(i) = ENVSIZE(i);
  1171. if (rc < 5)
  1172. /* Default - 1 sector */
  1173. ENVSECTORS (i) = 1;
  1174. i++;
  1175. }
  1176. fclose (fp);
  1177. HaveRedundEnv = i - 1;
  1178. if (!i) { /* No valid entries found */
  1179. errno = EINVAL;
  1180. return -1;
  1181. } else
  1182. return 0;
  1183. }
  1184. #endif