fw_env.c 30 KB

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