fw_env.c 29 KB

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