fw_env.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334
  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. if (s1 == NULL || s2 == NULL)
  922. return NULL;
  923. while (*s1 == *s2++)
  924. if (*s1++ == '=')
  925. return s2;
  926. if (*s1 == '\0' && *(s2 - 1) == '=')
  927. return s2;
  928. return NULL;
  929. }
  930. /*
  931. * Prevent confusion if running from erased flash memory
  932. */
  933. int fw_env_open(void)
  934. {
  935. int crc0, crc0_ok;
  936. unsigned char flag0;
  937. void *addr0;
  938. int crc1, crc1_ok;
  939. unsigned char flag1;
  940. void *addr1;
  941. struct env_image_single *single;
  942. struct env_image_redundant *redundant;
  943. if (parse_config ()) /* should fill envdevices */
  944. return -1;
  945. addr0 = calloc(1, CUR_ENVSIZE);
  946. if (addr0 == NULL) {
  947. fprintf(stderr,
  948. "Not enough memory for environment (%ld bytes)\n",
  949. CUR_ENVSIZE);
  950. return -1;
  951. }
  952. /* read environment from FLASH to local buffer */
  953. environment.image = addr0;
  954. if (HaveRedundEnv) {
  955. redundant = addr0;
  956. environment.crc = &redundant->crc;
  957. environment.flags = &redundant->flags;
  958. environment.data = redundant->data;
  959. } else {
  960. single = addr0;
  961. environment.crc = &single->crc;
  962. environment.flags = NULL;
  963. environment.data = single->data;
  964. }
  965. dev_current = 0;
  966. if (flash_io (O_RDONLY))
  967. return -1;
  968. crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
  969. crc0_ok = (crc0 == *environment.crc);
  970. if (!HaveRedundEnv) {
  971. if (!crc0_ok) {
  972. fprintf (stderr,
  973. "Warning: Bad CRC, using default environment\n");
  974. memcpy(environment.data, default_environment, sizeof default_environment);
  975. }
  976. } else {
  977. flag0 = *environment.flags;
  978. dev_current = 1;
  979. addr1 = calloc(1, CUR_ENVSIZE);
  980. if (addr1 == NULL) {
  981. fprintf(stderr,
  982. "Not enough memory for environment (%ld bytes)\n",
  983. CUR_ENVSIZE);
  984. return -1;
  985. }
  986. redundant = addr1;
  987. /*
  988. * have to set environment.image for flash_read(), careful -
  989. * other pointers in environment still point inside addr0
  990. */
  991. environment.image = addr1;
  992. if (flash_io (O_RDONLY))
  993. return -1;
  994. /* Check flag scheme compatibility */
  995. if (DEVTYPE(dev_current) == MTD_NORFLASH &&
  996. DEVTYPE(!dev_current) == MTD_NORFLASH) {
  997. environment.flag_scheme = FLAG_BOOLEAN;
  998. } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
  999. DEVTYPE(!dev_current) == MTD_NANDFLASH) {
  1000. environment.flag_scheme = FLAG_INCREMENTAL;
  1001. } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
  1002. DEVTYPE(!dev_current) == MTD_DATAFLASH) {
  1003. environment.flag_scheme = FLAG_BOOLEAN;
  1004. } else {
  1005. fprintf (stderr, "Incompatible flash types!\n");
  1006. return -1;
  1007. }
  1008. crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
  1009. crc1_ok = (crc1 == redundant->crc);
  1010. flag1 = redundant->flags;
  1011. if (crc0_ok && !crc1_ok) {
  1012. dev_current = 0;
  1013. } else if (!crc0_ok && crc1_ok) {
  1014. dev_current = 1;
  1015. } else if (!crc0_ok && !crc1_ok) {
  1016. fprintf (stderr,
  1017. "Warning: Bad CRC, using default environment\n");
  1018. memcpy (environment.data, default_environment,
  1019. sizeof default_environment);
  1020. dev_current = 0;
  1021. } else {
  1022. switch (environment.flag_scheme) {
  1023. case FLAG_BOOLEAN:
  1024. if (flag0 == active_flag &&
  1025. flag1 == obsolete_flag) {
  1026. dev_current = 0;
  1027. } else if (flag0 == obsolete_flag &&
  1028. flag1 == active_flag) {
  1029. dev_current = 1;
  1030. } else if (flag0 == flag1) {
  1031. dev_current = 0;
  1032. } else if (flag0 == 0xFF) {
  1033. dev_current = 0;
  1034. } else if (flag1 == 0xFF) {
  1035. dev_current = 1;
  1036. } else {
  1037. dev_current = 0;
  1038. }
  1039. break;
  1040. case FLAG_INCREMENTAL:
  1041. if (flag0 == 255 && flag1 == 0)
  1042. dev_current = 1;
  1043. else if ((flag1 == 255 && flag0 == 0) ||
  1044. flag0 >= flag1)
  1045. dev_current = 0;
  1046. else /* flag1 > flag0 */
  1047. dev_current = 1;
  1048. break;
  1049. default:
  1050. fprintf (stderr, "Unknown flag scheme %u \n",
  1051. environment.flag_scheme);
  1052. return -1;
  1053. }
  1054. }
  1055. /*
  1056. * If we are reading, we don't need the flag and the CRC any
  1057. * more, if we are writing, we will re-calculate CRC and update
  1058. * flags before writing out
  1059. */
  1060. if (dev_current) {
  1061. environment.image = addr1;
  1062. environment.crc = &redundant->crc;
  1063. environment.flags = &redundant->flags;
  1064. environment.data = redundant->data;
  1065. free (addr0);
  1066. } else {
  1067. environment.image = addr0;
  1068. /* Other pointers are already set */
  1069. free (addr1);
  1070. }
  1071. }
  1072. return 0;
  1073. }
  1074. static int parse_config ()
  1075. {
  1076. struct stat st;
  1077. #if defined(CONFIG_FILE)
  1078. /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
  1079. if (get_config (CONFIG_FILE)) {
  1080. fprintf (stderr,
  1081. "Cannot parse config file: %s\n", strerror (errno));
  1082. return -1;
  1083. }
  1084. #else
  1085. strcpy (DEVNAME (0), DEVICE1_NAME);
  1086. DEVOFFSET (0) = DEVICE1_OFFSET;
  1087. ENVSIZE (0) = ENV1_SIZE;
  1088. /* Default values are: erase-size=env-size, #sectors=1 */
  1089. DEVESIZE (0) = ENVSIZE (0);
  1090. ENVSECTORS (0) = 1;
  1091. #ifdef DEVICE1_ESIZE
  1092. DEVESIZE (0) = DEVICE1_ESIZE;
  1093. #endif
  1094. #ifdef DEVICE1_ENVSECTORS
  1095. ENVSECTORS (0) = DEVICE1_ENVSECTORS;
  1096. #endif
  1097. #ifdef HAVE_REDUND
  1098. strcpy (DEVNAME (1), DEVICE2_NAME);
  1099. DEVOFFSET (1) = DEVICE2_OFFSET;
  1100. ENVSIZE (1) = ENV2_SIZE;
  1101. /* Default values are: erase-size=env-size, #sectors=1 */
  1102. DEVESIZE (1) = ENVSIZE (1);
  1103. ENVSECTORS (1) = 1;
  1104. #ifdef DEVICE2_ESIZE
  1105. DEVESIZE (1) = DEVICE2_ESIZE;
  1106. #endif
  1107. #ifdef DEVICE2_ENVSECTORS
  1108. ENVSECTORS (1) = DEVICE2_ENVSECTORS;
  1109. #endif
  1110. HaveRedundEnv = 1;
  1111. #endif
  1112. #endif
  1113. if (stat (DEVNAME (0), &st)) {
  1114. fprintf (stderr,
  1115. "Cannot access MTD device %s: %s\n",
  1116. DEVNAME (0), strerror (errno));
  1117. return -1;
  1118. }
  1119. if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
  1120. fprintf (stderr,
  1121. "Cannot access MTD device %s: %s\n",
  1122. DEVNAME (1), strerror (errno));
  1123. return -1;
  1124. }
  1125. return 0;
  1126. }
  1127. #if defined(CONFIG_FILE)
  1128. static int get_config (char *fname)
  1129. {
  1130. FILE *fp;
  1131. int i = 0;
  1132. int rc;
  1133. char dump[128];
  1134. fp = fopen (fname, "r");
  1135. if (fp == NULL)
  1136. return -1;
  1137. while (i < 2 && fgets (dump, sizeof (dump), fp)) {
  1138. /* Skip incomplete conversions and comment strings */
  1139. if (dump[0] == '#')
  1140. continue;
  1141. rc = sscanf (dump, "%s %lx %lx %lx %lx",
  1142. DEVNAME (i),
  1143. &DEVOFFSET (i),
  1144. &ENVSIZE (i),
  1145. &DEVESIZE (i),
  1146. &ENVSECTORS (i));
  1147. if (rc < 3)
  1148. continue;
  1149. if (rc < 4)
  1150. /* Assume the erase size is the same as the env-size */
  1151. DEVESIZE(i) = ENVSIZE(i);
  1152. if (rc < 5)
  1153. /* Default - 1 sector */
  1154. ENVSECTORS (i) = 1;
  1155. i++;
  1156. }
  1157. fclose (fp);
  1158. HaveRedundEnv = i - 1;
  1159. if (!i) { /* No valid entries found */
  1160. errno = EINVAL;
  1161. return -1;
  1162. } else
  1163. return 0;
  1164. }
  1165. #endif