fw_env.c 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * (C) Copyright 2000-2010
  4. * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
  5. *
  6. * (C) Copyright 2008
  7. * Guennadi Liakhovetski, DENX Software Engineering, lg@denx.de.
  8. */
  9. #define _GNU_SOURCE
  10. #include <compiler.h>
  11. #include <errno.h>
  12. #include <env_flags.h>
  13. #include <fcntl.h>
  14. #include <libgen.h>
  15. #include <linux/fs.h>
  16. #include <linux/stringify.h>
  17. #include <ctype.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <stddef.h>
  21. #include <string.h>
  22. #include <sys/types.h>
  23. #include <sys/ioctl.h>
  24. #include <sys/stat.h>
  25. #include <unistd.h>
  26. #include <dirent.h>
  27. #ifdef MTD_OLD
  28. # include <stdint.h>
  29. # include <linux/mtd/mtd.h>
  30. #else
  31. # define __user /* nothing */
  32. # include <mtd/mtd-user.h>
  33. #endif
  34. #include <mtd/ubi-user.h>
  35. #include "fw_env_private.h"
  36. #include "fw_env.h"
  37. struct env_opts default_opts = {
  38. #ifdef CONFIG_FILE
  39. .config_file = CONFIG_FILE
  40. #endif
  41. };
  42. #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
  43. #define min(x, y) ({ \
  44. typeof(x) _min1 = (x); \
  45. typeof(y) _min2 = (y); \
  46. (void) (&_min1 == &_min2); \
  47. _min1 < _min2 ? _min1 : _min2; })
  48. struct envdev_s {
  49. const char *devname; /* Device name */
  50. long long devoff; /* Device offset */
  51. ulong env_size; /* environment size */
  52. ulong erase_size; /* device erase size */
  53. ulong env_sectors; /* number of environment sectors */
  54. uint8_t mtd_type; /* type of the MTD device */
  55. int is_ubi; /* set if we use UBI volume */
  56. };
  57. static struct envdev_s envdevices[2] = {
  58. {
  59. .mtd_type = MTD_ABSENT,
  60. }, {
  61. .mtd_type = MTD_ABSENT,
  62. },
  63. };
  64. static int dev_current;
  65. #define DEVNAME(i) envdevices[(i)].devname
  66. #define DEVOFFSET(i) envdevices[(i)].devoff
  67. #define ENVSIZE(i) envdevices[(i)].env_size
  68. #define DEVESIZE(i) envdevices[(i)].erase_size
  69. #define ENVSECTORS(i) envdevices[(i)].env_sectors
  70. #define DEVTYPE(i) envdevices[(i)].mtd_type
  71. #define IS_UBI(i) envdevices[(i)].is_ubi
  72. #define CUR_ENVSIZE ENVSIZE(dev_current)
  73. static unsigned long usable_envsize;
  74. #define ENV_SIZE usable_envsize
  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 have_redund_env;
  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 DEFAULT_ENV_INSTANCE_STATIC
  104. #include <env_default.h>
  105. #define UBI_DEV_START "/dev/ubi"
  106. #define UBI_SYSFS "/sys/class/ubi"
  107. #define UBI_VOL_NAME_PATT "ubi%d_%d"
  108. static int is_ubi_devname(const char *devname)
  109. {
  110. return !strncmp(devname, UBI_DEV_START, sizeof(UBI_DEV_START) - 1);
  111. }
  112. static int ubi_check_volume_sysfs_name(const char *volume_sysfs_name,
  113. const char *volname)
  114. {
  115. char path[256];
  116. FILE *file;
  117. char *name;
  118. int ret;
  119. strcpy(path, UBI_SYSFS "/");
  120. strcat(path, volume_sysfs_name);
  121. strcat(path, "/name");
  122. file = fopen(path, "r");
  123. if (!file)
  124. return -1;
  125. ret = fscanf(file, "%ms", &name);
  126. fclose(file);
  127. if (ret <= 0 || !name) {
  128. fprintf(stderr,
  129. "Failed to read from file %s, ret = %d, name = %s\n",
  130. path, ret, name);
  131. return -1;
  132. }
  133. if (!strcmp(name, volname)) {
  134. free(name);
  135. return 0;
  136. }
  137. free(name);
  138. return -1;
  139. }
  140. static int ubi_get_volnum_by_name(int devnum, const char *volname)
  141. {
  142. DIR *sysfs_ubi;
  143. struct dirent *dirent;
  144. int ret;
  145. int tmp_devnum;
  146. int volnum;
  147. sysfs_ubi = opendir(UBI_SYSFS);
  148. if (!sysfs_ubi)
  149. return -1;
  150. #ifdef DEBUG
  151. fprintf(stderr, "Looking for volume name \"%s\"\n", volname);
  152. #endif
  153. while (1) {
  154. dirent = readdir(sysfs_ubi);
  155. if (!dirent)
  156. return -1;
  157. ret = sscanf(dirent->d_name, UBI_VOL_NAME_PATT,
  158. &tmp_devnum, &volnum);
  159. if (ret == 2 && devnum == tmp_devnum) {
  160. if (ubi_check_volume_sysfs_name(dirent->d_name,
  161. volname) == 0)
  162. return volnum;
  163. }
  164. }
  165. return -1;
  166. }
  167. static int ubi_get_devnum_by_devname(const char *devname)
  168. {
  169. int devnum;
  170. int ret;
  171. ret = sscanf(devname + sizeof(UBI_DEV_START) - 1, "%d", &devnum);
  172. if (ret != 1)
  173. return -1;
  174. return devnum;
  175. }
  176. static const char *ubi_get_volume_devname(const char *devname,
  177. const char *volname)
  178. {
  179. char *volume_devname;
  180. int volnum;
  181. int devnum;
  182. int ret;
  183. devnum = ubi_get_devnum_by_devname(devname);
  184. if (devnum < 0)
  185. return NULL;
  186. volnum = ubi_get_volnum_by_name(devnum, volname);
  187. if (volnum < 0)
  188. return NULL;
  189. ret = asprintf(&volume_devname, "%s_%d", devname, volnum);
  190. if (ret < 0)
  191. return NULL;
  192. #ifdef DEBUG
  193. fprintf(stderr, "Found ubi volume \"%s:%s\" -> %s\n",
  194. devname, volname, volume_devname);
  195. #endif
  196. return volume_devname;
  197. }
  198. static void ubi_check_dev(unsigned int dev_id)
  199. {
  200. char *devname = (char *)DEVNAME(dev_id);
  201. char *pname;
  202. const char *volname = NULL;
  203. const char *volume_devname;
  204. if (!is_ubi_devname(DEVNAME(dev_id)))
  205. return;
  206. IS_UBI(dev_id) = 1;
  207. for (pname = devname; *pname != '\0'; pname++) {
  208. if (*pname == ':') {
  209. *pname = '\0';
  210. volname = pname + 1;
  211. break;
  212. }
  213. }
  214. if (volname) {
  215. /* Let's find real volume device name */
  216. volume_devname = ubi_get_volume_devname(devname, volname);
  217. if (!volume_devname) {
  218. fprintf(stderr, "Didn't found ubi volume \"%s\"\n",
  219. volname);
  220. return;
  221. }
  222. free(devname);
  223. DEVNAME(dev_id) = volume_devname;
  224. }
  225. }
  226. static int ubi_update_start(int fd, int64_t bytes)
  227. {
  228. if (ioctl(fd, UBI_IOCVOLUP, &bytes))
  229. return -1;
  230. return 0;
  231. }
  232. static int ubi_read(int fd, void *buf, size_t count)
  233. {
  234. ssize_t ret;
  235. while (count > 0) {
  236. ret = read(fd, buf, count);
  237. if (ret > 0) {
  238. count -= ret;
  239. buf += ret;
  240. continue;
  241. }
  242. if (ret == 0) {
  243. /*
  244. * Happens in case of too short volume data size. If we
  245. * return error status we will fail it will be treated
  246. * as UBI device error.
  247. *
  248. * Leave catching this error to CRC check.
  249. */
  250. fprintf(stderr, "Warning: end of data on ubi volume\n");
  251. return 0;
  252. } else if (errno == EBADF) {
  253. /*
  254. * Happens in case of corrupted volume. The same as
  255. * above, we cannot return error now, as we will still
  256. * be able to successfully write environment later.
  257. */
  258. fprintf(stderr, "Warning: corrupted volume?\n");
  259. return 0;
  260. } else if (errno == EINTR) {
  261. continue;
  262. }
  263. fprintf(stderr, "Cannot read %u bytes from ubi volume, %s\n",
  264. (unsigned int)count, strerror(errno));
  265. return -1;
  266. }
  267. return 0;
  268. }
  269. static int ubi_write(int fd, const void *buf, size_t count)
  270. {
  271. ssize_t ret;
  272. while (count > 0) {
  273. ret = write(fd, buf, count);
  274. if (ret <= 0) {
  275. if (ret < 0 && errno == EINTR)
  276. continue;
  277. fprintf(stderr, "Cannot write %u bytes to ubi volume\n",
  278. (unsigned int)count);
  279. return -1;
  280. }
  281. count -= ret;
  282. buf += ret;
  283. }
  284. return 0;
  285. }
  286. static int flash_io(int mode);
  287. static int parse_config(struct env_opts *opts);
  288. #if defined(CONFIG_FILE)
  289. static int get_config(char *);
  290. #endif
  291. static char *skip_chars(char *s)
  292. {
  293. for (; *s != '\0'; s++) {
  294. if (isblank(*s) || *s == '=')
  295. return s;
  296. }
  297. return NULL;
  298. }
  299. static char *skip_blanks(char *s)
  300. {
  301. for (; *s != '\0'; s++) {
  302. if (!isblank(*s))
  303. return s;
  304. }
  305. return NULL;
  306. }
  307. /*
  308. * s1 is either a simple 'name', or a 'name=value' pair.
  309. * s2 is a 'name=value' pair.
  310. * If the names match, return the value of s2, else NULL.
  311. */
  312. static char *envmatch(char *s1, char *s2)
  313. {
  314. if (s1 == NULL || s2 == NULL)
  315. return NULL;
  316. while (*s1 == *s2++)
  317. if (*s1++ == '=')
  318. return s2;
  319. if (*s1 == '\0' && *(s2 - 1) == '=')
  320. return s2;
  321. return NULL;
  322. }
  323. /**
  324. * Search the environment for a variable.
  325. * Return the value, if found, or NULL, if not found.
  326. */
  327. char *fw_getenv(char *name)
  328. {
  329. char *env, *nxt;
  330. for (env = environment.data; *env; env = nxt + 1) {
  331. char *val;
  332. for (nxt = env; *nxt; ++nxt) {
  333. if (nxt >= &environment.data[ENV_SIZE]) {
  334. fprintf(stderr, "## Error: "
  335. "environment not terminated\n");
  336. return NULL;
  337. }
  338. }
  339. val = envmatch(name, env);
  340. if (!val)
  341. continue;
  342. return val;
  343. }
  344. return NULL;
  345. }
  346. /*
  347. * Search the default environment for a variable.
  348. * Return the value, if found, or NULL, if not found.
  349. */
  350. char *fw_getdefenv(char *name)
  351. {
  352. char *env, *nxt;
  353. for (env = default_environment; *env; env = nxt + 1) {
  354. char *val;
  355. for (nxt = env; *nxt; ++nxt) {
  356. if (nxt >= &default_environment[ENV_SIZE]) {
  357. fprintf(stderr, "## Error: "
  358. "default environment not terminated\n");
  359. return NULL;
  360. }
  361. }
  362. val = envmatch(name, env);
  363. if (!val)
  364. continue;
  365. return val;
  366. }
  367. return NULL;
  368. }
  369. /*
  370. * Print the current definition of one, or more, or all
  371. * environment variables
  372. */
  373. int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
  374. {
  375. int i, rc = 0;
  376. if (value_only && argc != 1) {
  377. fprintf(stderr,
  378. "## Error: `-n'/`--noheader' option requires exactly one argument\n");
  379. return -1;
  380. }
  381. if (!opts)
  382. opts = &default_opts;
  383. if (fw_env_open(opts))
  384. return -1;
  385. if (argc == 0) { /* Print all env variables */
  386. char *env, *nxt;
  387. for (env = environment.data; *env; env = nxt + 1) {
  388. for (nxt = env; *nxt; ++nxt) {
  389. if (nxt >= &environment.data[ENV_SIZE]) {
  390. fprintf(stderr, "## Error: "
  391. "environment not terminated\n");
  392. return -1;
  393. }
  394. }
  395. printf("%s\n", env);
  396. }
  397. fw_env_close(opts);
  398. return 0;
  399. }
  400. for (i = 0; i < argc; ++i) { /* print a subset of env variables */
  401. char *name = argv[i];
  402. char *val = NULL;
  403. val = fw_getenv(name);
  404. if (!val) {
  405. fprintf(stderr, "## Error: \"%s\" not defined\n", name);
  406. rc = -1;
  407. continue;
  408. }
  409. if (value_only) {
  410. puts(val);
  411. break;
  412. }
  413. printf("%s=%s\n", name, val);
  414. }
  415. fw_env_close(opts);
  416. return rc;
  417. }
  418. int fw_env_flush(struct env_opts *opts)
  419. {
  420. if (!opts)
  421. opts = &default_opts;
  422. /*
  423. * Update CRC
  424. */
  425. *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
  426. /* write environment back to flash */
  427. if (flash_io(O_RDWR)) {
  428. fprintf(stderr, "Error: can't write fw_env to flash\n");
  429. return -1;
  430. }
  431. return 0;
  432. }
  433. /*
  434. * Set/Clear a single variable in the environment.
  435. * This is called in sequence to update the environment
  436. * in RAM without updating the copy in flash after each set
  437. */
  438. int fw_env_write(char *name, char *value)
  439. {
  440. int len;
  441. char *env, *nxt;
  442. char *oldval = NULL;
  443. int deleting, creating, overwriting;
  444. /*
  445. * search if variable with this name already exists
  446. */
  447. for (nxt = env = environment.data; *env; env = nxt + 1) {
  448. for (nxt = env; *nxt; ++nxt) {
  449. if (nxt >= &environment.data[ENV_SIZE]) {
  450. fprintf(stderr, "## Error: "
  451. "environment not terminated\n");
  452. errno = EINVAL;
  453. return -1;
  454. }
  455. }
  456. oldval = envmatch(name, env);
  457. if (oldval)
  458. break;
  459. }
  460. deleting = (oldval && !(value && strlen(value)));
  461. creating = (!oldval && (value && strlen(value)));
  462. overwriting = (oldval && (value && strlen(value)));
  463. /* check for permission */
  464. if (deleting) {
  465. if (env_flags_validate_varaccess(name,
  466. ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
  467. printf("Can't delete \"%s\"\n", name);
  468. errno = EROFS;
  469. return -1;
  470. }
  471. } else if (overwriting) {
  472. if (env_flags_validate_varaccess(name,
  473. ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
  474. printf("Can't overwrite \"%s\"\n", name);
  475. errno = EROFS;
  476. return -1;
  477. } else if (env_flags_validate_varaccess(name,
  478. ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
  479. const char *defval = fw_getdefenv(name);
  480. if (defval == NULL)
  481. defval = "";
  482. if (strcmp(oldval, defval)
  483. != 0) {
  484. printf("Can't overwrite \"%s\"\n", name);
  485. errno = EROFS;
  486. return -1;
  487. }
  488. }
  489. } else if (creating) {
  490. if (env_flags_validate_varaccess(name,
  491. ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
  492. printf("Can't create \"%s\"\n", name);
  493. errno = EROFS;
  494. return -1;
  495. }
  496. } else
  497. /* Nothing to do */
  498. return 0;
  499. if (deleting || overwriting) {
  500. if (*++nxt == '\0') {
  501. *env = '\0';
  502. } else {
  503. for (;;) {
  504. *env = *nxt++;
  505. if ((*env == '\0') && (*nxt == '\0'))
  506. break;
  507. ++env;
  508. }
  509. }
  510. *++env = '\0';
  511. }
  512. /* Delete only ? */
  513. if (!value || !strlen(value))
  514. return 0;
  515. /*
  516. * Append new definition at the end
  517. */
  518. for (env = environment.data; *env || *(env + 1); ++env)
  519. ;
  520. if (env > environment.data)
  521. ++env;
  522. /*
  523. * Overflow when:
  524. * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
  525. */
  526. len = strlen(name) + 2;
  527. /* add '=' for first arg, ' ' for all others */
  528. len += strlen(value) + 1;
  529. if (len > (&environment.data[ENV_SIZE] - env)) {
  530. fprintf(stderr,
  531. "Error: environment overflow, \"%s\" deleted\n", name);
  532. return -1;
  533. }
  534. while ((*env = *name++) != '\0')
  535. env++;
  536. *env = '=';
  537. while ((*++env = *value++) != '\0')
  538. ;
  539. /* end is marked with double '\0' */
  540. *++env = '\0';
  541. return 0;
  542. }
  543. /*
  544. * Deletes or sets environment variables. Returns -1 and sets errno error codes:
  545. * 0 - OK
  546. * EINVAL - need at least 1 argument
  547. * EROFS - certain variables ("ethaddr", "serial#") cannot be
  548. * modified or deleted
  549. *
  550. */
  551. int fw_env_set(int argc, char *argv[], struct env_opts *opts)
  552. {
  553. int i;
  554. size_t len;
  555. char *name, **valv;
  556. char *oldval;
  557. char *value = NULL;
  558. int valc;
  559. int ret;
  560. if (!opts)
  561. opts = &default_opts;
  562. if (argc < 1) {
  563. fprintf(stderr, "## Error: variable name missing\n");
  564. errno = EINVAL;
  565. return -1;
  566. }
  567. if (fw_env_open(opts)) {
  568. fprintf(stderr, "Error: environment not initialized\n");
  569. return -1;
  570. }
  571. name = argv[0];
  572. valv = argv + 1;
  573. valc = argc - 1;
  574. if (env_flags_validate_env_set_params(name, valv, valc) < 0) {
  575. fw_env_close(opts);
  576. return -1;
  577. }
  578. len = 0;
  579. for (i = 0; i < valc; ++i) {
  580. char *val = valv[i];
  581. size_t val_len = strlen(val);
  582. if (value)
  583. value[len - 1] = ' ';
  584. oldval = value;
  585. value = realloc(value, len + val_len + 1);
  586. if (!value) {
  587. fprintf(stderr,
  588. "Cannot malloc %zu bytes: %s\n",
  589. len, strerror(errno));
  590. free(oldval);
  591. return -1;
  592. }
  593. memcpy(value + len, val, val_len);
  594. len += val_len;
  595. value[len++] = '\0';
  596. }
  597. fw_env_write(name, value);
  598. free(value);
  599. ret = fw_env_flush(opts);
  600. fw_env_close(opts);
  601. return ret;
  602. }
  603. /*
  604. * Parse a file and configure the u-boot variables.
  605. * The script file has a very simple format, as follows:
  606. *
  607. * Each line has a couple with name, value:
  608. * <white spaces>variable_name<white spaces>variable_value
  609. *
  610. * Both variable_name and variable_value are interpreted as strings.
  611. * Any character after <white spaces> and before ending \r\n is interpreted
  612. * as variable's value (no comment allowed on these lines !)
  613. *
  614. * Comments are allowed if the first character in the line is #
  615. *
  616. * Returns -1 and sets errno error codes:
  617. * 0 - OK
  618. * -1 - Error
  619. */
  620. int fw_parse_script(char *fname, struct env_opts *opts)
  621. {
  622. FILE *fp;
  623. char *line = NULL;
  624. size_t linesize = 0;
  625. char *name;
  626. char *val;
  627. int lineno = 0;
  628. int len;
  629. int ret = 0;
  630. if (!opts)
  631. opts = &default_opts;
  632. if (fw_env_open(opts)) {
  633. fprintf(stderr, "Error: environment not initialized\n");
  634. return -1;
  635. }
  636. if (strcmp(fname, "-") == 0)
  637. fp = stdin;
  638. else {
  639. fp = fopen(fname, "r");
  640. if (fp == NULL) {
  641. fprintf(stderr, "I cannot open %s for reading\n",
  642. fname);
  643. return -1;
  644. }
  645. }
  646. while ((len = getline(&line, &linesize, fp)) != -1) {
  647. lineno++;
  648. /*
  649. * Read a whole line from the file. If the line is not
  650. * terminated, reports an error and exit.
  651. */
  652. if (line[len - 1] != '\n') {
  653. fprintf(stderr,
  654. "Line %d not correctly terminated\n",
  655. lineno);
  656. ret = -1;
  657. break;
  658. }
  659. /* Drop ending line feed / carriage return */
  660. line[--len] = '\0';
  661. if (len && line[len - 1] == '\r')
  662. line[--len] = '\0';
  663. /* Skip comment or empty lines */
  664. if (len == 0 || line[0] == '#')
  665. continue;
  666. /*
  667. * Search for variable's name remove leading whitespaces
  668. */
  669. name = skip_blanks(line);
  670. if (!name)
  671. continue;
  672. /* The first white space is the end of variable name */
  673. val = skip_chars(name);
  674. len = strlen(name);
  675. if (val) {
  676. *val++ = '\0';
  677. if ((val - name) < len)
  678. val = skip_blanks(val);
  679. else
  680. val = NULL;
  681. }
  682. #ifdef DEBUG
  683. fprintf(stderr, "Setting %s : %s\n",
  684. name, val ? val : " removed");
  685. #endif
  686. if (env_flags_validate_type(name, val) < 0) {
  687. ret = -1;
  688. break;
  689. }
  690. /*
  691. * If there is an error setting a variable,
  692. * try to save the environment and returns an error
  693. */
  694. if (fw_env_write(name, val)) {
  695. fprintf(stderr,
  696. "fw_env_write returns with error : %s\n",
  697. strerror(errno));
  698. ret = -1;
  699. break;
  700. }
  701. }
  702. free(line);
  703. /* Close file if not stdin */
  704. if (strcmp(fname, "-") != 0)
  705. fclose(fp);
  706. ret |= fw_env_flush(opts);
  707. fw_env_close(opts);
  708. return ret;
  709. }
  710. /**
  711. * environment_end() - compute offset of first byte right after environment
  712. * @dev - index of enviroment buffer
  713. * Return:
  714. * device offset of first byte right after environment
  715. */
  716. off_t environment_end(int dev)
  717. {
  718. /* environment is block aligned */
  719. return DEVOFFSET(dev) + ENVSECTORS(dev) * DEVESIZE(dev);
  720. }
  721. /*
  722. * Test for bad block on NAND, just returns 0 on NOR, on NAND:
  723. * 0 - block is good
  724. * > 0 - block is bad
  725. * < 0 - failed to test
  726. */
  727. static int flash_bad_block(int fd, uint8_t mtd_type, loff_t blockstart)
  728. {
  729. if (mtd_type == MTD_NANDFLASH) {
  730. int badblock = ioctl(fd, MEMGETBADBLOCK, &blockstart);
  731. if (badblock < 0) {
  732. perror("Cannot read bad block mark");
  733. return badblock;
  734. }
  735. if (badblock) {
  736. #ifdef DEBUG
  737. fprintf(stderr, "Bad block at 0x%llx, skipping\n",
  738. (unsigned long long)blockstart);
  739. #endif
  740. return badblock;
  741. }
  742. }
  743. return 0;
  744. }
  745. /*
  746. * Read data from flash at an offset into a provided buffer. On NAND it skips
  747. * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
  748. * the DEVOFFSET (dev) block. On NOR the loop is only run once.
  749. */
  750. static int flash_read_buf(int dev, int fd, void *buf, size_t count,
  751. off_t offset)
  752. {
  753. size_t blocklen; /* erase / write length - one block on NAND,
  754. 0 on NOR */
  755. size_t processed = 0; /* progress counter */
  756. size_t readlen = count; /* current read length */
  757. off_t block_seek; /* offset inside the current block to the start
  758. of the data */
  759. loff_t blockstart; /* running start of the current block -
  760. MEMGETBADBLOCK needs 64 bits */
  761. int rc;
  762. blockstart = (offset / DEVESIZE(dev)) * DEVESIZE(dev);
  763. /* Offset inside a block */
  764. block_seek = offset - blockstart;
  765. if (DEVTYPE(dev) == MTD_NANDFLASH) {
  766. /*
  767. * NAND: calculate which blocks we are reading. We have
  768. * to read one block at a time to skip bad blocks.
  769. */
  770. blocklen = DEVESIZE(dev);
  771. /* Limit to one block for the first read */
  772. if (readlen > blocklen - block_seek)
  773. readlen = blocklen - block_seek;
  774. } else {
  775. blocklen = 0;
  776. }
  777. /* This only runs once on NOR flash */
  778. while (processed < count) {
  779. rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
  780. if (rc < 0) /* block test failed */
  781. return -1;
  782. if (blockstart + block_seek + readlen > environment_end(dev)) {
  783. /* End of range is reached */
  784. fprintf(stderr, "Too few good blocks within range\n");
  785. return -1;
  786. }
  787. if (rc) { /* block is bad */
  788. blockstart += blocklen;
  789. continue;
  790. }
  791. /*
  792. * If a block is bad, we retry in the next block at the same
  793. * offset - see env/nand.c::writeenv()
  794. */
  795. lseek(fd, blockstart + block_seek, SEEK_SET);
  796. rc = read(fd, buf + processed, readlen);
  797. if (rc != readlen) {
  798. fprintf(stderr, "Read error on %s: %s\n",
  799. DEVNAME(dev), strerror(errno));
  800. return -1;
  801. }
  802. #ifdef DEBUG
  803. fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
  804. rc, (unsigned long long)blockstart + block_seek,
  805. DEVNAME(dev));
  806. #endif
  807. processed += readlen;
  808. readlen = min(blocklen, count - processed);
  809. block_seek = 0;
  810. blockstart += blocklen;
  811. }
  812. return processed;
  813. }
  814. /*
  815. * Write count bytes from begin of environment, but stay within
  816. * ENVSECTORS(dev) sectors of
  817. * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
  818. * erase and write the whole data at once.
  819. */
  820. static int flash_write_buf(int dev, int fd, void *buf, size_t count)
  821. {
  822. void *data;
  823. struct erase_info_user erase;
  824. size_t blocklen; /* length of NAND block / NOR erase sector */
  825. size_t erase_len; /* whole area that can be erased - may include
  826. bad blocks */
  827. size_t erasesize; /* erase / write length - one block on NAND,
  828. whole area on NOR */
  829. size_t processed = 0; /* progress counter */
  830. size_t write_total; /* total size to actually write - excluding
  831. bad blocks */
  832. off_t erase_offset; /* offset to the first erase block (aligned)
  833. below offset */
  834. off_t block_seek; /* offset inside the erase block to the start
  835. of the data */
  836. loff_t blockstart; /* running start of the current block -
  837. MEMGETBADBLOCK needs 64 bits */
  838. int rc;
  839. /*
  840. * For mtd devices only offset and size of the environment do matter
  841. */
  842. if (DEVTYPE(dev) == MTD_ABSENT) {
  843. blocklen = count;
  844. erase_len = blocklen;
  845. blockstart = DEVOFFSET(dev);
  846. block_seek = 0;
  847. write_total = blocklen;
  848. } else {
  849. blocklen = DEVESIZE(dev);
  850. erase_offset = DEVOFFSET(dev);
  851. /* Maximum area we may use */
  852. erase_len = environment_end(dev) - erase_offset;
  853. blockstart = erase_offset;
  854. /* Offset inside a block */
  855. block_seek = DEVOFFSET(dev) - erase_offset;
  856. /*
  857. * Data size we actually write: from the start of the block
  858. * to the start of the data, then count bytes of data, and
  859. * to the end of the block
  860. */
  861. write_total = ((block_seek + count + blocklen - 1) /
  862. blocklen) * blocklen;
  863. }
  864. /*
  865. * Support data anywhere within erase sectors: read out the complete
  866. * area to be erased, replace the environment image, write the whole
  867. * block back again.
  868. */
  869. if (write_total > count) {
  870. data = malloc(erase_len);
  871. if (!data) {
  872. fprintf(stderr,
  873. "Cannot malloc %zu bytes: %s\n",
  874. erase_len, strerror(errno));
  875. return -1;
  876. }
  877. rc = flash_read_buf(dev, fd, data, write_total, erase_offset);
  878. if (write_total != rc)
  879. return -1;
  880. #ifdef DEBUG
  881. fprintf(stderr, "Preserving data ");
  882. if (block_seek != 0)
  883. fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
  884. if (block_seek + count != write_total) {
  885. if (block_seek != 0)
  886. fprintf(stderr, " and ");
  887. fprintf(stderr, "0x%lx - 0x%lx",
  888. (unsigned long)block_seek + count,
  889. (unsigned long)write_total - 1);
  890. }
  891. fprintf(stderr, "\n");
  892. #endif
  893. /* Overwrite the old environment */
  894. memcpy(data + block_seek, buf, count);
  895. } else {
  896. /*
  897. * We get here, iff offset is block-aligned and count is a
  898. * multiple of blocklen - see write_total calculation above
  899. */
  900. data = buf;
  901. }
  902. if (DEVTYPE(dev) == MTD_NANDFLASH) {
  903. /*
  904. * NAND: calculate which blocks we are writing. We have
  905. * to write one block at a time to skip bad blocks.
  906. */
  907. erasesize = blocklen;
  908. } else {
  909. erasesize = erase_len;
  910. }
  911. erase.length = erasesize;
  912. /* This only runs once on NOR flash and SPI-dataflash */
  913. while (processed < write_total) {
  914. rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
  915. if (rc < 0) /* block test failed */
  916. return rc;
  917. if (blockstart + erasesize > environment_end(dev)) {
  918. fprintf(stderr, "End of range reached, aborting\n");
  919. return -1;
  920. }
  921. if (rc) { /* block is bad */
  922. blockstart += blocklen;
  923. continue;
  924. }
  925. if (DEVTYPE(dev) != MTD_ABSENT) {
  926. erase.start = blockstart;
  927. ioctl(fd, MEMUNLOCK, &erase);
  928. /* These do not need an explicit erase cycle */
  929. if (DEVTYPE(dev) != MTD_DATAFLASH)
  930. if (ioctl(fd, MEMERASE, &erase) != 0) {
  931. fprintf(stderr,
  932. "MTD erase error on %s: %s\n",
  933. DEVNAME(dev), strerror(errno));
  934. return -1;
  935. }
  936. }
  937. if (lseek(fd, blockstart, SEEK_SET) == -1) {
  938. fprintf(stderr,
  939. "Seek error on %s: %s\n",
  940. DEVNAME(dev), strerror(errno));
  941. return -1;
  942. }
  943. #ifdef DEBUG
  944. fprintf(stderr, "Write 0x%llx bytes at 0x%llx\n",
  945. (unsigned long long)erasesize,
  946. (unsigned long long)blockstart);
  947. #endif
  948. if (write(fd, data + processed, erasesize) != erasesize) {
  949. fprintf(stderr, "Write error on %s: %s\n",
  950. DEVNAME(dev), strerror(errno));
  951. return -1;
  952. }
  953. if (DEVTYPE(dev) != MTD_ABSENT)
  954. ioctl(fd, MEMLOCK, &erase);
  955. processed += erasesize;
  956. block_seek = 0;
  957. blockstart += erasesize;
  958. }
  959. if (write_total > count)
  960. free(data);
  961. return processed;
  962. }
  963. /*
  964. * Set obsolete flag at offset - NOR flash only
  965. */
  966. static int flash_flag_obsolete(int dev, int fd, off_t offset)
  967. {
  968. int rc;
  969. struct erase_info_user erase;
  970. erase.start = DEVOFFSET(dev);
  971. erase.length = DEVESIZE(dev);
  972. /* This relies on the fact, that obsolete_flag == 0 */
  973. rc = lseek(fd, offset, SEEK_SET);
  974. if (rc < 0) {
  975. fprintf(stderr, "Cannot seek to set the flag on %s\n",
  976. DEVNAME(dev));
  977. return rc;
  978. }
  979. ioctl(fd, MEMUNLOCK, &erase);
  980. rc = write(fd, &obsolete_flag, sizeof(obsolete_flag));
  981. ioctl(fd, MEMLOCK, &erase);
  982. if (rc < 0)
  983. perror("Could not set obsolete flag");
  984. return rc;
  985. }
  986. static int flash_write(int fd_current, int fd_target, int dev_target)
  987. {
  988. int rc;
  989. switch (environment.flag_scheme) {
  990. case FLAG_NONE:
  991. break;
  992. case FLAG_INCREMENTAL:
  993. (*environment.flags)++;
  994. break;
  995. case FLAG_BOOLEAN:
  996. *environment.flags = active_flag;
  997. break;
  998. default:
  999. fprintf(stderr, "Unimplemented flash scheme %u\n",
  1000. environment.flag_scheme);
  1001. return -1;
  1002. }
  1003. #ifdef DEBUG
  1004. fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
  1005. DEVOFFSET(dev_target), DEVNAME(dev_target));
  1006. #endif
  1007. if (IS_UBI(dev_target)) {
  1008. if (ubi_update_start(fd_target, CUR_ENVSIZE) < 0)
  1009. return 0;
  1010. return ubi_write(fd_target, environment.image, CUR_ENVSIZE);
  1011. }
  1012. rc = flash_write_buf(dev_target, fd_target, environment.image,
  1013. CUR_ENVSIZE);
  1014. if (rc < 0)
  1015. return rc;
  1016. if (environment.flag_scheme == FLAG_BOOLEAN) {
  1017. /* Have to set obsolete flag */
  1018. off_t offset = DEVOFFSET(dev_current) +
  1019. offsetof(struct env_image_redundant, flags);
  1020. #ifdef DEBUG
  1021. fprintf(stderr,
  1022. "Setting obsolete flag in environment at 0x%llx on %s\n",
  1023. DEVOFFSET(dev_current), DEVNAME(dev_current));
  1024. #endif
  1025. flash_flag_obsolete(dev_current, fd_current, offset);
  1026. }
  1027. return 0;
  1028. }
  1029. static int flash_read(int fd)
  1030. {
  1031. int rc;
  1032. if (IS_UBI(dev_current)) {
  1033. DEVTYPE(dev_current) = MTD_ABSENT;
  1034. return ubi_read(fd, environment.image, CUR_ENVSIZE);
  1035. }
  1036. rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
  1037. DEVOFFSET(dev_current));
  1038. if (rc != CUR_ENVSIZE)
  1039. return -1;
  1040. return 0;
  1041. }
  1042. static int flash_open_tempfile(const char **dname, const char **target_temp)
  1043. {
  1044. char *dup_name = strdup(DEVNAME(dev_current));
  1045. char *temp_name = NULL;
  1046. int rc = -1;
  1047. if (!dup_name)
  1048. return -1;
  1049. *dname = dirname(dup_name);
  1050. if (!*dname)
  1051. goto err;
  1052. rc = asprintf(&temp_name, "%s/XXXXXX", *dname);
  1053. if (rc == -1)
  1054. goto err;
  1055. rc = mkstemp(temp_name);
  1056. if (rc == -1) {
  1057. /* fall back to in place write */
  1058. fprintf(stderr,
  1059. "Can't create %s: %s\n", temp_name, strerror(errno));
  1060. free(temp_name);
  1061. } else {
  1062. *target_temp = temp_name;
  1063. /* deliberately leak dup_name as dname /might/ point into
  1064. * it and we need it for our caller
  1065. */
  1066. dup_name = NULL;
  1067. }
  1068. err:
  1069. if (dup_name)
  1070. free(dup_name);
  1071. return rc;
  1072. }
  1073. static int flash_io_write(int fd_current)
  1074. {
  1075. int fd_target = -1, rc, dev_target;
  1076. const char *dname, *target_temp = NULL;
  1077. if (have_redund_env) {
  1078. /* switch to next partition for writing */
  1079. dev_target = !dev_current;
  1080. /* dev_target: fd_target, erase_target */
  1081. fd_target = open(DEVNAME(dev_target), O_RDWR);
  1082. if (fd_target < 0) {
  1083. fprintf(stderr,
  1084. "Can't open %s: %s\n",
  1085. DEVNAME(dev_target), strerror(errno));
  1086. rc = -1;
  1087. goto exit;
  1088. }
  1089. } else {
  1090. struct stat sb;
  1091. if (fstat(fd_current, &sb) == 0 && S_ISREG(sb.st_mode)) {
  1092. /* if any part of flash_open_tempfile() fails we fall
  1093. * back to in-place writes
  1094. */
  1095. fd_target = flash_open_tempfile(&dname, &target_temp);
  1096. }
  1097. dev_target = dev_current;
  1098. if (fd_target == -1)
  1099. fd_target = fd_current;
  1100. }
  1101. rc = flash_write(fd_current, fd_target, dev_target);
  1102. if (fsync(fd_current) && !(errno == EINVAL || errno == EROFS)) {
  1103. fprintf(stderr,
  1104. "fsync failed on %s: %s\n",
  1105. DEVNAME(dev_current), strerror(errno));
  1106. }
  1107. if (fd_current != fd_target) {
  1108. if (fsync(fd_target) &&
  1109. !(errno == EINVAL || errno == EROFS)) {
  1110. fprintf(stderr,
  1111. "fsync failed on %s: %s\n",
  1112. DEVNAME(dev_current), strerror(errno));
  1113. }
  1114. if (close(fd_target)) {
  1115. fprintf(stderr,
  1116. "I/O error on %s: %s\n",
  1117. DEVNAME(dev_target), strerror(errno));
  1118. rc = -1;
  1119. }
  1120. if (target_temp) {
  1121. int dir_fd;
  1122. dir_fd = open(dname, O_DIRECTORY | O_RDONLY);
  1123. if (dir_fd == -1)
  1124. fprintf(stderr,
  1125. "Can't open %s: %s\n",
  1126. dname, strerror(errno));
  1127. if (rename(target_temp, DEVNAME(dev_target))) {
  1128. fprintf(stderr,
  1129. "rename failed %s => %s: %s\n",
  1130. target_temp, DEVNAME(dev_target),
  1131. strerror(errno));
  1132. rc = -1;
  1133. }
  1134. if (dir_fd != -1 && fsync(dir_fd))
  1135. fprintf(stderr,
  1136. "fsync failed on %s: %s\n",
  1137. dname, strerror(errno));
  1138. if (dir_fd != -1 && close(dir_fd))
  1139. fprintf(stderr,
  1140. "I/O error on %s: %s\n",
  1141. dname, strerror(errno));
  1142. }
  1143. }
  1144. exit:
  1145. return rc;
  1146. }
  1147. static int flash_io(int mode)
  1148. {
  1149. int fd_current, rc;
  1150. /* dev_current: fd_current, erase_current */
  1151. fd_current = open(DEVNAME(dev_current), mode);
  1152. if (fd_current < 0) {
  1153. fprintf(stderr,
  1154. "Can't open %s: %s\n",
  1155. DEVNAME(dev_current), strerror(errno));
  1156. return -1;
  1157. }
  1158. if (mode == O_RDWR) {
  1159. rc = flash_io_write(fd_current);
  1160. } else {
  1161. rc = flash_read(fd_current);
  1162. }
  1163. if (close(fd_current)) {
  1164. fprintf(stderr,
  1165. "I/O error on %s: %s\n",
  1166. DEVNAME(dev_current), strerror(errno));
  1167. return -1;
  1168. }
  1169. return rc;
  1170. }
  1171. /*
  1172. * Prevent confusion if running from erased flash memory
  1173. */
  1174. int fw_env_open(struct env_opts *opts)
  1175. {
  1176. int crc0, crc0_ok;
  1177. unsigned char flag0;
  1178. void *addr0 = NULL;
  1179. int crc1, crc1_ok;
  1180. unsigned char flag1;
  1181. void *addr1 = NULL;
  1182. int ret;
  1183. struct env_image_single *single;
  1184. struct env_image_redundant *redundant;
  1185. if (!opts)
  1186. opts = &default_opts;
  1187. if (parse_config(opts)) /* should fill envdevices */
  1188. return -EINVAL;
  1189. addr0 = calloc(1, CUR_ENVSIZE);
  1190. if (addr0 == NULL) {
  1191. fprintf(stderr,
  1192. "Not enough memory for environment (%ld bytes)\n",
  1193. CUR_ENVSIZE);
  1194. ret = -ENOMEM;
  1195. goto open_cleanup;
  1196. }
  1197. /* read environment from FLASH to local buffer */
  1198. environment.image = addr0;
  1199. if (have_redund_env) {
  1200. redundant = addr0;
  1201. environment.crc = &redundant->crc;
  1202. environment.flags = &redundant->flags;
  1203. environment.data = redundant->data;
  1204. } else {
  1205. single = addr0;
  1206. environment.crc = &single->crc;
  1207. environment.flags = NULL;
  1208. environment.data = single->data;
  1209. }
  1210. dev_current = 0;
  1211. if (flash_io(O_RDONLY)) {
  1212. ret = -EIO;
  1213. goto open_cleanup;
  1214. }
  1215. crc0 = crc32(0, (uint8_t *)environment.data, ENV_SIZE);
  1216. crc0_ok = (crc0 == *environment.crc);
  1217. if (!have_redund_env) {
  1218. if (!crc0_ok) {
  1219. fprintf(stderr,
  1220. "Warning: Bad CRC, using default environment\n");
  1221. memcpy(environment.data, default_environment,
  1222. sizeof(default_environment));
  1223. }
  1224. } else {
  1225. flag0 = *environment.flags;
  1226. dev_current = 1;
  1227. addr1 = calloc(1, CUR_ENVSIZE);
  1228. if (addr1 == NULL) {
  1229. fprintf(stderr,
  1230. "Not enough memory for environment (%ld bytes)\n",
  1231. CUR_ENVSIZE);
  1232. ret = -ENOMEM;
  1233. goto open_cleanup;
  1234. }
  1235. redundant = addr1;
  1236. /*
  1237. * have to set environment.image for flash_read(), careful -
  1238. * other pointers in environment still point inside addr0
  1239. */
  1240. environment.image = addr1;
  1241. if (flash_io(O_RDONLY)) {
  1242. ret = -EIO;
  1243. goto open_cleanup;
  1244. }
  1245. /* Check flag scheme compatibility */
  1246. if (DEVTYPE(dev_current) == MTD_NORFLASH &&
  1247. DEVTYPE(!dev_current) == MTD_NORFLASH) {
  1248. environment.flag_scheme = FLAG_BOOLEAN;
  1249. } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
  1250. DEVTYPE(!dev_current) == MTD_NANDFLASH) {
  1251. environment.flag_scheme = FLAG_INCREMENTAL;
  1252. } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
  1253. DEVTYPE(!dev_current) == MTD_DATAFLASH) {
  1254. environment.flag_scheme = FLAG_BOOLEAN;
  1255. } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
  1256. DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
  1257. environment.flag_scheme = FLAG_INCREMENTAL;
  1258. } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
  1259. DEVTYPE(!dev_current) == MTD_ABSENT &&
  1260. IS_UBI(dev_current) == IS_UBI(!dev_current)) {
  1261. environment.flag_scheme = FLAG_INCREMENTAL;
  1262. } else {
  1263. fprintf(stderr, "Incompatible flash types!\n");
  1264. ret = -EINVAL;
  1265. goto open_cleanup;
  1266. }
  1267. crc1 = crc32(0, (uint8_t *)redundant->data, ENV_SIZE);
  1268. crc1_ok = (crc1 == redundant->crc);
  1269. flag1 = redundant->flags;
  1270. if (crc0_ok && !crc1_ok) {
  1271. dev_current = 0;
  1272. } else if (!crc0_ok && crc1_ok) {
  1273. dev_current = 1;
  1274. } else if (!crc0_ok && !crc1_ok) {
  1275. fprintf(stderr,
  1276. "Warning: Bad CRC, using default environment\n");
  1277. memcpy(environment.data, default_environment,
  1278. sizeof(default_environment));
  1279. dev_current = 0;
  1280. } else {
  1281. switch (environment.flag_scheme) {
  1282. case FLAG_BOOLEAN:
  1283. if (flag0 == active_flag &&
  1284. flag1 == obsolete_flag) {
  1285. dev_current = 0;
  1286. } else if (flag0 == obsolete_flag &&
  1287. flag1 == active_flag) {
  1288. dev_current = 1;
  1289. } else if (flag0 == flag1) {
  1290. dev_current = 0;
  1291. } else if (flag0 == 0xFF) {
  1292. dev_current = 0;
  1293. } else if (flag1 == 0xFF) {
  1294. dev_current = 1;
  1295. } else {
  1296. dev_current = 0;
  1297. }
  1298. break;
  1299. case FLAG_INCREMENTAL:
  1300. if (flag0 == 255 && flag1 == 0)
  1301. dev_current = 1;
  1302. else if ((flag1 == 255 && flag0 == 0) ||
  1303. flag0 >= flag1)
  1304. dev_current = 0;
  1305. else /* flag1 > flag0 */
  1306. dev_current = 1;
  1307. break;
  1308. default:
  1309. fprintf(stderr, "Unknown flag scheme %u\n",
  1310. environment.flag_scheme);
  1311. return -1;
  1312. }
  1313. }
  1314. /*
  1315. * If we are reading, we don't need the flag and the CRC any
  1316. * more, if we are writing, we will re-calculate CRC and update
  1317. * flags before writing out
  1318. */
  1319. if (dev_current) {
  1320. environment.image = addr1;
  1321. environment.crc = &redundant->crc;
  1322. environment.flags = &redundant->flags;
  1323. environment.data = redundant->data;
  1324. free(addr0);
  1325. } else {
  1326. environment.image = addr0;
  1327. /* Other pointers are already set */
  1328. free(addr1);
  1329. }
  1330. #ifdef DEBUG
  1331. fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
  1332. #endif
  1333. }
  1334. return 0;
  1335. open_cleanup:
  1336. if (addr0)
  1337. free(addr0);
  1338. if (addr1)
  1339. free(addr0);
  1340. return ret;
  1341. }
  1342. /*
  1343. * Simply free allocated buffer with environment
  1344. */
  1345. int fw_env_close(struct env_opts *opts)
  1346. {
  1347. if (environment.image)
  1348. free(environment.image);
  1349. environment.image = NULL;
  1350. return 0;
  1351. }
  1352. static int check_device_config(int dev)
  1353. {
  1354. struct stat st;
  1355. int32_t lnum = 0;
  1356. int fd, rc = 0;
  1357. /* Fills in IS_UBI(), converts DEVNAME() with ubi volume name */
  1358. ubi_check_dev(dev);
  1359. fd = open(DEVNAME(dev), O_RDONLY);
  1360. if (fd < 0) {
  1361. fprintf(stderr,
  1362. "Cannot open %s: %s\n", DEVNAME(dev), strerror(errno));
  1363. return -1;
  1364. }
  1365. rc = fstat(fd, &st);
  1366. if (rc < 0) {
  1367. fprintf(stderr, "Cannot stat the file %s\n", DEVNAME(dev));
  1368. goto err;
  1369. }
  1370. if (IS_UBI(dev)) {
  1371. rc = ioctl(fd, UBI_IOCEBISMAP, &lnum);
  1372. if (rc < 0) {
  1373. fprintf(stderr, "Cannot get UBI information for %s\n",
  1374. DEVNAME(dev));
  1375. goto err;
  1376. }
  1377. } else if (S_ISCHR(st.st_mode)) {
  1378. struct mtd_info_user mtdinfo;
  1379. rc = ioctl(fd, MEMGETINFO, &mtdinfo);
  1380. if (rc < 0) {
  1381. fprintf(stderr, "Cannot get MTD information for %s\n",
  1382. DEVNAME(dev));
  1383. goto err;
  1384. }
  1385. if (mtdinfo.type != MTD_NORFLASH &&
  1386. mtdinfo.type != MTD_NANDFLASH &&
  1387. mtdinfo.type != MTD_DATAFLASH &&
  1388. mtdinfo.type != MTD_UBIVOLUME) {
  1389. fprintf(stderr, "Unsupported flash type %u on %s\n",
  1390. mtdinfo.type, DEVNAME(dev));
  1391. goto err;
  1392. }
  1393. DEVTYPE(dev) = mtdinfo.type;
  1394. if (DEVESIZE(dev) == 0)
  1395. /* Assume the erase size is the same as the env-size */
  1396. DEVESIZE(dev) = ENVSIZE(dev);
  1397. } else {
  1398. uint64_t size;
  1399. DEVTYPE(dev) = MTD_ABSENT;
  1400. if (DEVESIZE(dev) == 0)
  1401. /* Assume the erase size to be 512 bytes */
  1402. DEVESIZE(dev) = 0x200;
  1403. /*
  1404. * Check for negative offsets, treat it as backwards offset
  1405. * from the end of the block device
  1406. */
  1407. if (DEVOFFSET(dev) < 0) {
  1408. rc = ioctl(fd, BLKGETSIZE64, &size);
  1409. if (rc < 0) {
  1410. fprintf(stderr,
  1411. "Could not get block device size on %s\n",
  1412. DEVNAME(dev));
  1413. goto err;
  1414. }
  1415. DEVOFFSET(dev) = DEVOFFSET(dev) + size;
  1416. #ifdef DEBUG
  1417. fprintf(stderr,
  1418. "Calculated device offset 0x%llx on %s\n",
  1419. DEVOFFSET(dev), DEVNAME(dev));
  1420. #endif
  1421. }
  1422. }
  1423. if (ENVSECTORS(dev) == 0)
  1424. /* Assume enough sectors to cover the environment */
  1425. ENVSECTORS(dev) = DIV_ROUND_UP(ENVSIZE(dev), DEVESIZE(dev));
  1426. if (DEVOFFSET(dev) % DEVESIZE(dev) != 0) {
  1427. fprintf(stderr,
  1428. "Environment does not start on (erase) block boundary\n");
  1429. errno = EINVAL;
  1430. return -1;
  1431. }
  1432. if (ENVSIZE(dev) > ENVSECTORS(dev) * DEVESIZE(dev)) {
  1433. fprintf(stderr,
  1434. "Environment does not fit into available sectors\n");
  1435. errno = EINVAL;
  1436. return -1;
  1437. }
  1438. err:
  1439. close(fd);
  1440. return rc;
  1441. }
  1442. static int parse_config(struct env_opts *opts)
  1443. {
  1444. int rc;
  1445. if (!opts)
  1446. opts = &default_opts;
  1447. #if defined(CONFIG_FILE)
  1448. /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
  1449. if (get_config(opts->config_file)) {
  1450. fprintf(stderr, "Cannot parse config file '%s': %m\n",
  1451. opts->config_file);
  1452. return -1;
  1453. }
  1454. #else
  1455. DEVNAME(0) = DEVICE1_NAME;
  1456. DEVOFFSET(0) = DEVICE1_OFFSET;
  1457. ENVSIZE(0) = ENV1_SIZE;
  1458. /* Set defaults for DEVESIZE, ENVSECTORS later once we
  1459. * know DEVTYPE
  1460. */
  1461. #ifdef DEVICE1_ESIZE
  1462. DEVESIZE(0) = DEVICE1_ESIZE;
  1463. #endif
  1464. #ifdef DEVICE1_ENVSECTORS
  1465. ENVSECTORS(0) = DEVICE1_ENVSECTORS;
  1466. #endif
  1467. #ifdef HAVE_REDUND
  1468. DEVNAME(1) = DEVICE2_NAME;
  1469. DEVOFFSET(1) = DEVICE2_OFFSET;
  1470. ENVSIZE(1) = ENV2_SIZE;
  1471. /* Set defaults for DEVESIZE, ENVSECTORS later once we
  1472. * know DEVTYPE
  1473. */
  1474. #ifdef DEVICE2_ESIZE
  1475. DEVESIZE(1) = DEVICE2_ESIZE;
  1476. #endif
  1477. #ifdef DEVICE2_ENVSECTORS
  1478. ENVSECTORS(1) = DEVICE2_ENVSECTORS;
  1479. #endif
  1480. have_redund_env = 1;
  1481. #endif
  1482. #endif
  1483. rc = check_device_config(0);
  1484. if (rc < 0)
  1485. return rc;
  1486. if (have_redund_env) {
  1487. rc = check_device_config(1);
  1488. if (rc < 0)
  1489. return rc;
  1490. if (ENVSIZE(0) != ENVSIZE(1)) {
  1491. fprintf(stderr,
  1492. "Redundant environments have unequal size");
  1493. return -1;
  1494. }
  1495. }
  1496. usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
  1497. if (have_redund_env)
  1498. usable_envsize -= sizeof(char);
  1499. return 0;
  1500. }
  1501. #if defined(CONFIG_FILE)
  1502. static int get_config(char *fname)
  1503. {
  1504. FILE *fp;
  1505. int i = 0;
  1506. int rc;
  1507. char *line = NULL;
  1508. size_t linesize = 0;
  1509. char *devname;
  1510. fp = fopen(fname, "r");
  1511. if (fp == NULL)
  1512. return -1;
  1513. while (i < 2 && getline(&line, &linesize, fp) != -1) {
  1514. /* Skip comment strings */
  1515. if (line[0] == '#')
  1516. continue;
  1517. rc = sscanf(line, "%ms %lli %lx %lx %lx",
  1518. &devname,
  1519. &DEVOFFSET(i),
  1520. &ENVSIZE(i), &DEVESIZE(i), &ENVSECTORS(i));
  1521. if (rc < 3)
  1522. continue;
  1523. DEVNAME(i) = devname;
  1524. /* Set defaults for DEVESIZE, ENVSECTORS later once we
  1525. * know DEVTYPE
  1526. */
  1527. i++;
  1528. }
  1529. free(line);
  1530. fclose(fp);
  1531. have_redund_env = i - 1;
  1532. if (!i) { /* No valid entries found */
  1533. errno = EINVAL;
  1534. return -1;
  1535. } else
  1536. return 0;
  1537. }
  1538. #endif