fw_env.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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. blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
  594. /* Offset inside a block */
  595. block_seek = offset - blockstart;
  596. if (mtd_type == MTD_NANDFLASH) {
  597. /*
  598. * NAND: calculate which blocks we are reading. We have
  599. * to read one block at a time to skip bad blocks.
  600. */
  601. blocklen = DEVESIZE (dev);
  602. /*
  603. * To calculate the top of the range, we have to use the
  604. * global DEVOFFSET (dev), which can be different from offset
  605. */
  606. top_of_range = ((DEVOFFSET(dev) / blocklen) +
  607. ENVSECTORS (dev)) * blocklen;
  608. /* Limit to one block for the first read */
  609. if (readlen > blocklen - block_seek)
  610. readlen = blocklen - block_seek;
  611. } else {
  612. blocklen = 0;
  613. top_of_range = offset + count;
  614. }
  615. /* This only runs once on NOR flash */
  616. while (processed < count) {
  617. rc = flash_bad_block (fd, mtd_type, &blockstart);
  618. if (rc < 0) /* block test failed */
  619. return -1;
  620. if (blockstart + block_seek + readlen > top_of_range) {
  621. /* End of range is reached */
  622. fprintf (stderr,
  623. "Too few good blocks within range\n");
  624. return -1;
  625. }
  626. if (rc) { /* block is bad */
  627. blockstart += blocklen;
  628. continue;
  629. }
  630. /*
  631. * If a block is bad, we retry in the next block at the same
  632. * offset - see common/env_nand.c::writeenv()
  633. */
  634. lseek (fd, blockstart + block_seek, SEEK_SET);
  635. rc = read (fd, buf + processed, readlen);
  636. if (rc != readlen) {
  637. fprintf (stderr, "Read error on %s: %s\n",
  638. DEVNAME (dev), strerror (errno));
  639. return -1;
  640. }
  641. #ifdef DEBUG
  642. fprintf (stderr, "Read 0x%x bytes at 0x%llx\n",
  643. rc, blockstart + block_seek);
  644. #endif
  645. processed += readlen;
  646. readlen = min (blocklen, count - processed);
  647. block_seek = 0;
  648. blockstart += blocklen;
  649. }
  650. return processed;
  651. }
  652. /*
  653. * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
  654. * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
  655. * erase and write the whole data at once.
  656. */
  657. static int flash_write_buf (int dev, int fd, void *buf, size_t count,
  658. off_t offset, uint8_t mtd_type)
  659. {
  660. void *data;
  661. struct erase_info_user erase;
  662. size_t blocklen; /* length of NAND block / NOR erase sector */
  663. size_t erase_len; /* whole area that can be erased - may include
  664. bad blocks */
  665. size_t erasesize; /* erase / write length - one block on NAND,
  666. whole area on NOR */
  667. size_t processed = 0; /* progress counter */
  668. size_t write_total; /* total size to actually write - excluding
  669. bad blocks */
  670. off_t erase_offset; /* offset to the first erase block (aligned)
  671. below offset */
  672. off_t block_seek; /* offset inside the erase block to the start
  673. of the data */
  674. off_t top_of_range; /* end of the last block we may use */
  675. loff_t blockstart; /* running start of the current block -
  676. MEMGETBADBLOCK needs 64 bits */
  677. int rc;
  678. blocklen = DEVESIZE (dev);
  679. top_of_range = ((DEVOFFSET(dev) / blocklen) +
  680. ENVSECTORS (dev)) * blocklen;
  681. erase_offset = (offset / blocklen) * blocklen;
  682. /* Maximum area we may use */
  683. erase_len = top_of_range - erase_offset;
  684. blockstart = erase_offset;
  685. /* Offset inside a block */
  686. block_seek = offset - erase_offset;
  687. /*
  688. * Data size we actually have to write: from the start of the block
  689. * to the start of the data, then count bytes of data, and to the
  690. * end of the block
  691. */
  692. write_total = ((block_seek + count + blocklen - 1) /
  693. blocklen) * blocklen;
  694. /*
  695. * Support data anywhere within erase sectors: read out the complete
  696. * area to be erased, replace the environment image, write the whole
  697. * block back again.
  698. */
  699. if (write_total > count) {
  700. data = malloc (erase_len);
  701. if (!data) {
  702. fprintf (stderr,
  703. "Cannot malloc %u bytes: %s\n",
  704. erase_len, strerror (errno));
  705. return -1;
  706. }
  707. rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
  708. mtd_type);
  709. if (write_total != rc)
  710. return -1;
  711. /* Overwrite the old environment */
  712. memcpy (data + block_seek, buf, count);
  713. } else {
  714. /*
  715. * We get here, iff offset is block-aligned and count is a
  716. * multiple of blocklen - see write_total calculation above
  717. */
  718. data = buf;
  719. }
  720. if (mtd_type == MTD_NANDFLASH) {
  721. /*
  722. * NAND: calculate which blocks we are writing. We have
  723. * to write one block at a time to skip bad blocks.
  724. */
  725. erasesize = blocklen;
  726. } else {
  727. erasesize = erase_len;
  728. }
  729. erase.length = erasesize;
  730. /* This only runs once on NOR flash and SPI-dataflash */
  731. while (processed < write_total) {
  732. rc = flash_bad_block (fd, mtd_type, &blockstart);
  733. if (rc < 0) /* block test failed */
  734. return rc;
  735. if (blockstart + erasesize > top_of_range) {
  736. fprintf (stderr, "End of range reached, aborting\n");
  737. return -1;
  738. }
  739. if (rc) { /* block is bad */
  740. blockstart += blocklen;
  741. continue;
  742. }
  743. erase.start = blockstart;
  744. ioctl (fd, MEMUNLOCK, &erase);
  745. /* Dataflash does not need an explicit erase cycle */
  746. if (mtd_type != MTD_DATAFLASH)
  747. if (ioctl (fd, MEMERASE, &erase) != 0) {
  748. fprintf (stderr, "MTD erase error on %s: %s\n",
  749. DEVNAME (dev),
  750. strerror (errno));
  751. return -1;
  752. }
  753. if (lseek (fd, blockstart, SEEK_SET) == -1) {
  754. fprintf (stderr,
  755. "Seek error on %s: %s\n",
  756. DEVNAME (dev), strerror (errno));
  757. return -1;
  758. }
  759. #ifdef DEBUG
  760. printf ("Write 0x%x bytes at 0x%llx\n", erasesize, blockstart);
  761. #endif
  762. if (write (fd, data + processed, erasesize) != erasesize) {
  763. fprintf (stderr, "Write error on %s: %s\n",
  764. DEVNAME (dev), strerror (errno));
  765. return -1;
  766. }
  767. ioctl (fd, MEMLOCK, &erase);
  768. processed += blocklen;
  769. block_seek = 0;
  770. blockstart += blocklen;
  771. }
  772. if (write_total > count)
  773. free (data);
  774. return processed;
  775. }
  776. /*
  777. * Set obsolete flag at offset - NOR flash only
  778. */
  779. static int flash_flag_obsolete (int dev, int fd, off_t offset)
  780. {
  781. int rc;
  782. struct erase_info_user erase;
  783. erase.start = DEVOFFSET (dev);
  784. erase.length = DEVESIZE (dev);
  785. /* This relies on the fact, that obsolete_flag == 0 */
  786. rc = lseek (fd, offset, SEEK_SET);
  787. if (rc < 0) {
  788. fprintf (stderr, "Cannot seek to set the flag on %s \n",
  789. DEVNAME (dev));
  790. return rc;
  791. }
  792. ioctl (fd, MEMUNLOCK, &erase);
  793. rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
  794. ioctl (fd, MEMLOCK, &erase);
  795. if (rc < 0)
  796. perror ("Could not set obsolete flag");
  797. return rc;
  798. }
  799. static int flash_write (int fd_current, int fd_target, int dev_target)
  800. {
  801. int rc;
  802. switch (environment.flag_scheme) {
  803. case FLAG_NONE:
  804. break;
  805. case FLAG_INCREMENTAL:
  806. (*environment.flags)++;
  807. break;
  808. case FLAG_BOOLEAN:
  809. *environment.flags = active_flag;
  810. break;
  811. default:
  812. fprintf (stderr, "Unimplemented flash scheme %u \n",
  813. environment.flag_scheme);
  814. return -1;
  815. }
  816. #ifdef DEBUG
  817. printf ("Writing new environment at 0x%lx on %s\n",
  818. DEVOFFSET (dev_target), DEVNAME (dev_target));
  819. #endif
  820. rc = flash_write_buf (dev_target, fd_target, environment.image,
  821. CONFIG_ENV_SIZE, DEVOFFSET (dev_target),
  822. DEVTYPE(dev_target));
  823. if (rc < 0)
  824. return rc;
  825. if (environment.flag_scheme == FLAG_BOOLEAN) {
  826. /* Have to set obsolete flag */
  827. off_t offset = DEVOFFSET (dev_current) +
  828. offsetof (struct env_image_redundant, flags);
  829. #ifdef DEBUG
  830. printf ("Setting obsolete flag in environment at 0x%lx on %s\n",
  831. DEVOFFSET (dev_current), DEVNAME (dev_current));
  832. #endif
  833. flash_flag_obsolete (dev_current, fd_current, offset);
  834. }
  835. return 0;
  836. }
  837. static int flash_read (int fd)
  838. {
  839. struct mtd_info_user mtdinfo;
  840. int rc;
  841. rc = ioctl (fd, MEMGETINFO, &mtdinfo);
  842. if (rc < 0) {
  843. perror ("Cannot get MTD information");
  844. return -1;
  845. }
  846. if (mtdinfo.type != MTD_NORFLASH &&
  847. mtdinfo.type != MTD_NANDFLASH &&
  848. mtdinfo.type != MTD_DATAFLASH) {
  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 if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
  994. DEVTYPE(!dev_current) == MTD_DATAFLASH) {
  995. environment.flag_scheme = FLAG_BOOLEAN;
  996. } else {
  997. fprintf (stderr, "Incompatible flash types!\n");
  998. return -1;
  999. }
  1000. crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
  1001. crc1_ok = (crc1 == redundant->crc);
  1002. flag1 = redundant->flags;
  1003. if (crc0_ok && !crc1_ok) {
  1004. dev_current = 0;
  1005. } else if (!crc0_ok && crc1_ok) {
  1006. dev_current = 1;
  1007. } else if (!crc0_ok && !crc1_ok) {
  1008. fprintf (stderr,
  1009. "Warning: Bad CRC, using default environment\n");
  1010. memcpy (environment.data, default_environment,
  1011. sizeof default_environment);
  1012. dev_current = 0;
  1013. } else {
  1014. switch (environment.flag_scheme) {
  1015. case FLAG_BOOLEAN:
  1016. if (flag0 == active_flag &&
  1017. flag1 == obsolete_flag) {
  1018. dev_current = 0;
  1019. } else if (flag0 == obsolete_flag &&
  1020. flag1 == active_flag) {
  1021. dev_current = 1;
  1022. } else if (flag0 == flag1) {
  1023. dev_current = 0;
  1024. } else if (flag0 == 0xFF) {
  1025. dev_current = 0;
  1026. } else if (flag1 == 0xFF) {
  1027. dev_current = 1;
  1028. } else {
  1029. dev_current = 0;
  1030. }
  1031. break;
  1032. case FLAG_INCREMENTAL:
  1033. if ((flag0 == 255 && flag1 == 0) ||
  1034. flag1 > flag0)
  1035. dev_current = 1;
  1036. else if ((flag1 == 255 && flag0 == 0) ||
  1037. flag0 > flag1)
  1038. dev_current = 0;
  1039. else /* flags are equal - almost impossible */
  1040. dev_current = 0;
  1041. break;
  1042. default:
  1043. fprintf (stderr, "Unknown flag scheme %u \n",
  1044. environment.flag_scheme);
  1045. return -1;
  1046. }
  1047. }
  1048. /*
  1049. * If we are reading, we don't need the flag and the CRC any
  1050. * more, if we are writing, we will re-calculate CRC and update
  1051. * flags before writing out
  1052. */
  1053. if (dev_current) {
  1054. environment.image = addr1;
  1055. environment.crc = &redundant->crc;
  1056. environment.flags = &redundant->flags;
  1057. environment.data = redundant->data;
  1058. free (addr0);
  1059. } else {
  1060. environment.image = addr0;
  1061. /* Other pointers are already set */
  1062. free (addr1);
  1063. }
  1064. }
  1065. return 0;
  1066. }
  1067. static int parse_config ()
  1068. {
  1069. struct stat st;
  1070. #if defined(CONFIG_FILE)
  1071. /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
  1072. if (get_config (CONFIG_FILE)) {
  1073. fprintf (stderr,
  1074. "Cannot parse config file: %s\n", strerror (errno));
  1075. return -1;
  1076. }
  1077. #else
  1078. strcpy (DEVNAME (0), DEVICE1_NAME);
  1079. DEVOFFSET (0) = DEVICE1_OFFSET;
  1080. ENVSIZE (0) = ENV1_SIZE;
  1081. /* Default values are: erase-size=env-size, #sectors=1 */
  1082. DEVESIZE (0) = ENVSIZE (0);
  1083. ENVSECTORS (0) = 1;
  1084. #ifdef DEVICE1_ESIZE
  1085. DEVESIZE (0) = DEVICE1_ESIZE;
  1086. #endif
  1087. #ifdef DEVICE1_ENVSECTORS
  1088. ENVSECTORS (0) = DEVICE1_ENVSECTORS;
  1089. #endif
  1090. #ifdef HAVE_REDUND
  1091. strcpy (DEVNAME (1), DEVICE2_NAME);
  1092. DEVOFFSET (1) = DEVICE2_OFFSET;
  1093. ENVSIZE (1) = ENV2_SIZE;
  1094. /* Default values are: erase-size=env-size, #sectors=1 */
  1095. DEVESIZE (1) = ENVSIZE (1);
  1096. ENVSECTORS (1) = 1;
  1097. #ifdef DEVICE2_ESIZE
  1098. DEVESIZE (1) = DEVICE2_ESIZE;
  1099. #endif
  1100. #ifdef DEVICE2_ENVSECTORS
  1101. ENVSECTORS (1) = DEVICE2_ENVSECTORS;
  1102. #endif
  1103. HaveRedundEnv = 1;
  1104. #endif
  1105. #endif
  1106. if (stat (DEVNAME (0), &st)) {
  1107. fprintf (stderr,
  1108. "Cannot access MTD device %s: %s\n",
  1109. DEVNAME (0), strerror (errno));
  1110. return -1;
  1111. }
  1112. if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
  1113. fprintf (stderr,
  1114. "Cannot access MTD device %s: %s\n",
  1115. DEVNAME (1), strerror (errno));
  1116. return -1;
  1117. }
  1118. return 0;
  1119. }
  1120. #if defined(CONFIG_FILE)
  1121. static int get_config (char *fname)
  1122. {
  1123. FILE *fp;
  1124. int i = 0;
  1125. int rc;
  1126. char dump[128];
  1127. fp = fopen (fname, "r");
  1128. if (fp == NULL)
  1129. return -1;
  1130. while (i < 2 && fgets (dump, sizeof (dump), fp)) {
  1131. /* Skip incomplete conversions and comment strings */
  1132. if (dump[0] == '#')
  1133. continue;
  1134. rc = sscanf (dump, "%s %lx %lx %lx %lx",
  1135. DEVNAME (i),
  1136. &DEVOFFSET (i),
  1137. &ENVSIZE (i),
  1138. &DEVESIZE (i),
  1139. &ENVSECTORS (i));
  1140. if (rc < 3)
  1141. continue;
  1142. if (rc < 4)
  1143. /* Assume the erase size is the same as the env-size */
  1144. DEVESIZE(i) = ENVSIZE(i);
  1145. if (rc < 5)
  1146. /* Default - 1 sector */
  1147. ENVSECTORS (i) = 1;
  1148. i++;
  1149. }
  1150. fclose (fp);
  1151. HaveRedundEnv = i - 1;
  1152. if (!i) { /* No valid entries found */
  1153. errno = EINVAL;
  1154. return -1;
  1155. } else
  1156. return 0;
  1157. }
  1158. #endif