fw_env.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  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 <env.h>
  12. #include <errno.h>
  13. #include <env_flags.h>
  14. #include <fcntl.h>
  15. #include <libgen.h>
  16. #include <linux/fs.h>
  17. #include <linux/stringify.h>
  18. #include <ctype.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <stddef.h>
  22. #include <string.h>
  23. #include <sys/types.h>
  24. #include <sys/ioctl.h>
  25. #include <sys/stat.h>
  26. #include <u-boot/crc.h>
  27. #include <unistd.h>
  28. #include <dirent.h>
  29. #ifdef MTD_OLD
  30. # include <stdint.h>
  31. # include <linux/mtd/mtd.h>
  32. #else
  33. # define __user /* nothing */
  34. # include <mtd/mtd-user.h>
  35. #endif
  36. #include <mtd/ubi-user.h>
  37. #include "fw_env_private.h"
  38. #include "fw_env.h"
  39. struct env_opts default_opts = {
  40. #ifdef CONFIG_FILE
  41. .config_file = CONFIG_FILE
  42. #endif
  43. };
  44. #define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
  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. const char *devname; /* Device name */
  52. long long 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. int is_ubi; /* set if we use UBI volume */
  58. };
  59. static struct envdev_s envdevices[2] = {
  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 IS_UBI(i) envdevices[(i)].is_ubi
  74. #define CUR_ENVSIZE ENVSIZE(dev_current)
  75. static unsigned long usable_envsize;
  76. #define ENV_SIZE usable_envsize
  77. struct env_image_single {
  78. uint32_t crc; /* CRC32 over data bytes */
  79. char data[];
  80. };
  81. struct env_image_redundant {
  82. uint32_t crc; /* CRC32 over data bytes */
  83. unsigned char flags; /* active or obsolete */
  84. char data[];
  85. };
  86. enum flag_scheme {
  87. FLAG_NONE,
  88. FLAG_BOOLEAN,
  89. FLAG_INCREMENTAL,
  90. };
  91. struct environment {
  92. void *image;
  93. uint32_t *crc;
  94. unsigned char *flags;
  95. char *data;
  96. enum flag_scheme flag_scheme;
  97. int dirty;
  98. };
  99. static struct environment environment = {
  100. .flag_scheme = FLAG_NONE,
  101. };
  102. static int have_redund_env;
  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. if (!environment.dirty)
  423. return 0;
  424. /*
  425. * Update CRC
  426. */
  427. *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
  428. /* write environment back to flash */
  429. if (flash_io(O_RDWR)) {
  430. fprintf(stderr, "Error: can't write fw_env to flash\n");
  431. return -1;
  432. }
  433. return 0;
  434. }
  435. /*
  436. * Set/Clear a single variable in the environment.
  437. * This is called in sequence to update the environment
  438. * in RAM without updating the copy in flash after each set
  439. */
  440. int fw_env_write(char *name, char *value)
  441. {
  442. int len;
  443. char *env, *nxt;
  444. char *oldval = NULL;
  445. int deleting, creating, overwriting;
  446. /*
  447. * search if variable with this name already exists
  448. */
  449. for (nxt = env = environment.data; *env; env = nxt + 1) {
  450. for (nxt = env; *nxt; ++nxt) {
  451. if (nxt >= &environment.data[ENV_SIZE]) {
  452. fprintf(stderr, "## Error: "
  453. "environment not terminated\n");
  454. errno = EINVAL;
  455. return -1;
  456. }
  457. }
  458. oldval = envmatch(name, env);
  459. if (oldval)
  460. break;
  461. }
  462. deleting = (oldval && !(value && strlen(value)));
  463. creating = (!oldval && (value && strlen(value)));
  464. overwriting = (oldval && (value && strlen(value) &&
  465. strcmp(oldval, value)));
  466. /* check for permission */
  467. if (deleting) {
  468. if (env_flags_validate_varaccess(name,
  469. ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
  470. printf("Can't delete \"%s\"\n", name);
  471. errno = EROFS;
  472. return -1;
  473. }
  474. } else if (overwriting) {
  475. if (env_flags_validate_varaccess(name,
  476. ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
  477. printf("Can't overwrite \"%s\"\n", name);
  478. errno = EROFS;
  479. return -1;
  480. } else if (env_flags_validate_varaccess(name,
  481. ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
  482. const char *defval = fw_getdefenv(name);
  483. if (defval == NULL)
  484. defval = "";
  485. if (strcmp(oldval, defval)
  486. != 0) {
  487. printf("Can't overwrite \"%s\"\n", name);
  488. errno = EROFS;
  489. return -1;
  490. }
  491. }
  492. } else if (creating) {
  493. if (env_flags_validate_varaccess(name,
  494. ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
  495. printf("Can't create \"%s\"\n", name);
  496. errno = EROFS;
  497. return -1;
  498. }
  499. } else
  500. /* Nothing to do */
  501. return 0;
  502. environment.dirty = 1;
  503. if (deleting || overwriting) {
  504. if (*++nxt == '\0') {
  505. *env = '\0';
  506. } else {
  507. for (;;) {
  508. *env = *nxt++;
  509. if ((*env == '\0') && (*nxt == '\0'))
  510. break;
  511. ++env;
  512. }
  513. }
  514. *++env = '\0';
  515. }
  516. /* Delete only ? */
  517. if (!value || !strlen(value))
  518. return 0;
  519. /*
  520. * Append new definition at the end
  521. */
  522. for (env = environment.data; *env || *(env + 1); ++env)
  523. ;
  524. if (env > environment.data)
  525. ++env;
  526. /*
  527. * Overflow when:
  528. * "name" + "=" + "val" +"\0\0" > CUR_ENVSIZE - (env-environment)
  529. */
  530. len = strlen(name) + 2;
  531. /* add '=' for first arg, ' ' for all others */
  532. len += strlen(value) + 1;
  533. if (len > (&environment.data[ENV_SIZE] - env)) {
  534. fprintf(stderr,
  535. "Error: environment overflow, \"%s\" deleted\n", name);
  536. return -1;
  537. }
  538. while ((*env = *name++) != '\0')
  539. env++;
  540. *env = '=';
  541. while ((*++env = *value++) != '\0')
  542. ;
  543. /* end is marked with double '\0' */
  544. *++env = '\0';
  545. return 0;
  546. }
  547. /*
  548. * Deletes or sets environment variables. Returns -1 and sets errno error codes:
  549. * 0 - OK
  550. * EINVAL - need at least 1 argument
  551. * EROFS - certain variables ("ethaddr", "serial#") cannot be
  552. * modified or deleted
  553. *
  554. */
  555. int fw_env_set(int argc, char *argv[], struct env_opts *opts)
  556. {
  557. int i;
  558. size_t len;
  559. char *name, **valv;
  560. char *oldval;
  561. char *value = NULL;
  562. int valc;
  563. int ret;
  564. if (!opts)
  565. opts = &default_opts;
  566. if (argc < 1) {
  567. fprintf(stderr, "## Error: variable name missing\n");
  568. errno = EINVAL;
  569. return -1;
  570. }
  571. if (fw_env_open(opts)) {
  572. fprintf(stderr, "Error: environment not initialized\n");
  573. return -1;
  574. }
  575. name = argv[0];
  576. valv = argv + 1;
  577. valc = argc - 1;
  578. if (env_flags_validate_env_set_params(name, valv, valc) < 0) {
  579. fw_env_close(opts);
  580. return -1;
  581. }
  582. len = 0;
  583. for (i = 0; i < valc; ++i) {
  584. char *val = valv[i];
  585. size_t val_len = strlen(val);
  586. if (value)
  587. value[len - 1] = ' ';
  588. oldval = value;
  589. value = realloc(value, len + val_len + 1);
  590. if (!value) {
  591. fprintf(stderr,
  592. "Cannot malloc %zu bytes: %s\n",
  593. len, strerror(errno));
  594. free(oldval);
  595. return -1;
  596. }
  597. memcpy(value + len, val, val_len);
  598. len += val_len;
  599. value[len++] = '\0';
  600. }
  601. fw_env_write(name, value);
  602. free(value);
  603. ret = fw_env_flush(opts);
  604. fw_env_close(opts);
  605. return ret;
  606. }
  607. /*
  608. * Parse a file and configure the u-boot variables.
  609. * The script file has a very simple format, as follows:
  610. *
  611. * Each line has a couple with name, value:
  612. * <white spaces>variable_name<white spaces>variable_value
  613. *
  614. * Both variable_name and variable_value are interpreted as strings.
  615. * Any character after <white spaces> and before ending \r\n is interpreted
  616. * as variable's value (no comment allowed on these lines !)
  617. *
  618. * Comments are allowed if the first character in the line is #
  619. *
  620. * Returns -1 and sets errno error codes:
  621. * 0 - OK
  622. * -1 - Error
  623. */
  624. int fw_parse_script(char *fname, struct env_opts *opts)
  625. {
  626. FILE *fp;
  627. char *line = NULL;
  628. size_t linesize = 0;
  629. char *name;
  630. char *val;
  631. int lineno = 0;
  632. int len;
  633. int ret = 0;
  634. if (!opts)
  635. opts = &default_opts;
  636. if (fw_env_open(opts)) {
  637. fprintf(stderr, "Error: environment not initialized\n");
  638. return -1;
  639. }
  640. if (strcmp(fname, "-") == 0)
  641. fp = stdin;
  642. else {
  643. fp = fopen(fname, "r");
  644. if (fp == NULL) {
  645. fprintf(stderr, "I cannot open %s for reading\n",
  646. fname);
  647. return -1;
  648. }
  649. }
  650. while ((len = getline(&line, &linesize, fp)) != -1) {
  651. lineno++;
  652. /*
  653. * Read a whole line from the file. If the line is not
  654. * terminated, reports an error and exit.
  655. */
  656. if (line[len - 1] != '\n') {
  657. fprintf(stderr,
  658. "Line %d not correctly terminated\n",
  659. lineno);
  660. ret = -1;
  661. break;
  662. }
  663. /* Drop ending line feed / carriage return */
  664. line[--len] = '\0';
  665. if (len && line[len - 1] == '\r')
  666. line[--len] = '\0';
  667. /* Skip comment or empty lines */
  668. if (len == 0 || line[0] == '#')
  669. continue;
  670. /*
  671. * Search for variable's name remove leading whitespaces
  672. */
  673. name = skip_blanks(line);
  674. if (!name)
  675. continue;
  676. /* The first white space is the end of variable name */
  677. val = skip_chars(name);
  678. len = strlen(name);
  679. if (val) {
  680. *val++ = '\0';
  681. if ((val - name) < len)
  682. val = skip_blanks(val);
  683. else
  684. val = NULL;
  685. }
  686. #ifdef DEBUG
  687. fprintf(stderr, "Setting %s : %s\n",
  688. name, val ? val : " removed");
  689. #endif
  690. if (env_flags_validate_type(name, val) < 0) {
  691. ret = -1;
  692. break;
  693. }
  694. /*
  695. * If there is an error setting a variable,
  696. * try to save the environment and returns an error
  697. */
  698. if (fw_env_write(name, val)) {
  699. fprintf(stderr,
  700. "fw_env_write returns with error : %s\n",
  701. strerror(errno));
  702. ret = -1;
  703. break;
  704. }
  705. }
  706. free(line);
  707. /* Close file if not stdin */
  708. if (strcmp(fname, "-") != 0)
  709. fclose(fp);
  710. ret |= fw_env_flush(opts);
  711. fw_env_close(opts);
  712. return ret;
  713. }
  714. /**
  715. * environment_end() - compute offset of first byte right after environment
  716. * @dev - index of enviroment buffer
  717. * Return:
  718. * device offset of first byte right after environment
  719. */
  720. off_t environment_end(int dev)
  721. {
  722. /* environment is block aligned */
  723. return DEVOFFSET(dev) + ENVSECTORS(dev) * DEVESIZE(dev);
  724. }
  725. /*
  726. * Test for bad block on NAND, just returns 0 on NOR, on NAND:
  727. * 0 - block is good
  728. * > 0 - block is bad
  729. * < 0 - failed to test
  730. */
  731. static int flash_bad_block(int fd, uint8_t mtd_type, loff_t blockstart)
  732. {
  733. if (mtd_type == MTD_NANDFLASH) {
  734. int badblock = ioctl(fd, MEMGETBADBLOCK, &blockstart);
  735. if (badblock < 0) {
  736. perror("Cannot read bad block mark");
  737. return badblock;
  738. }
  739. if (badblock) {
  740. #ifdef DEBUG
  741. fprintf(stderr, "Bad block at 0x%llx, skipping\n",
  742. (unsigned long long)blockstart);
  743. #endif
  744. return badblock;
  745. }
  746. }
  747. return 0;
  748. }
  749. /*
  750. * Read data from flash at an offset into a provided buffer. On NAND it skips
  751. * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
  752. * the DEVOFFSET (dev) block. On NOR the loop is only run once.
  753. */
  754. static int flash_read_buf(int dev, int fd, void *buf, size_t count,
  755. off_t offset)
  756. {
  757. size_t blocklen; /* erase / write length - one block on NAND,
  758. 0 on NOR */
  759. size_t processed = 0; /* progress counter */
  760. size_t readlen = count; /* current read length */
  761. off_t block_seek; /* offset inside the current block to the start
  762. of the data */
  763. loff_t blockstart; /* running start of the current block -
  764. MEMGETBADBLOCK needs 64 bits */
  765. int rc;
  766. blockstart = (offset / DEVESIZE(dev)) * DEVESIZE(dev);
  767. /* Offset inside a block */
  768. block_seek = offset - blockstart;
  769. if (DEVTYPE(dev) == MTD_NANDFLASH) {
  770. /*
  771. * NAND: calculate which blocks we are reading. We have
  772. * to read one block at a time to skip bad blocks.
  773. */
  774. blocklen = DEVESIZE(dev);
  775. /* Limit to one block for the first read */
  776. if (readlen > blocklen - block_seek)
  777. readlen = blocklen - block_seek;
  778. } else {
  779. blocklen = 0;
  780. }
  781. /* This only runs once on NOR flash */
  782. while (processed < count) {
  783. rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
  784. if (rc < 0) /* block test failed */
  785. return -1;
  786. if (blockstart + block_seek + readlen > environment_end(dev)) {
  787. /* End of range is reached */
  788. fprintf(stderr, "Too few good blocks within range\n");
  789. return -1;
  790. }
  791. if (rc) { /* block is bad */
  792. blockstart += blocklen;
  793. continue;
  794. }
  795. /*
  796. * If a block is bad, we retry in the next block at the same
  797. * offset - see env/nand.c::writeenv()
  798. */
  799. lseek(fd, blockstart + block_seek, SEEK_SET);
  800. rc = read(fd, buf + processed, readlen);
  801. if (rc == -1) {
  802. fprintf(stderr, "Read error on %s: %s\n",
  803. DEVNAME(dev), strerror(errno));
  804. return -1;
  805. }
  806. if (rc != readlen) {
  807. fprintf(stderr,
  808. "Read error on %s: Attempted to read %zd bytes but got %d\n",
  809. DEVNAME(dev), readlen, rc);
  810. return -1;
  811. }
  812. #ifdef DEBUG
  813. fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
  814. rc, (unsigned long long)blockstart + block_seek,
  815. DEVNAME(dev));
  816. #endif
  817. processed += readlen;
  818. readlen = min(blocklen, count - processed);
  819. block_seek = 0;
  820. blockstart += blocklen;
  821. }
  822. return processed;
  823. }
  824. /*
  825. * Write count bytes from begin of environment, but stay within
  826. * ENVSECTORS(dev) sectors of
  827. * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
  828. * erase and write the whole data at once.
  829. */
  830. static int flash_write_buf(int dev, int fd, void *buf, size_t count)
  831. {
  832. void *data;
  833. struct erase_info_user erase;
  834. size_t blocklen; /* length of NAND block / NOR erase sector */
  835. size_t erase_len; /* whole area that can be erased - may include
  836. bad blocks */
  837. size_t erasesize; /* erase / write length - one block on NAND,
  838. whole area on NOR */
  839. size_t processed = 0; /* progress counter */
  840. size_t write_total; /* total size to actually write - excluding
  841. bad blocks */
  842. off_t erase_offset; /* offset to the first erase block (aligned)
  843. below offset */
  844. off_t block_seek; /* offset inside the erase block to the start
  845. of the data */
  846. loff_t blockstart; /* running start of the current block -
  847. MEMGETBADBLOCK needs 64 bits */
  848. int was_locked = 0; /* flash lock flag */
  849. int rc;
  850. /*
  851. * For mtd devices only offset and size of the environment do matter
  852. */
  853. if (DEVTYPE(dev) == MTD_ABSENT) {
  854. blocklen = count;
  855. erase_len = blocklen;
  856. blockstart = DEVOFFSET(dev);
  857. block_seek = 0;
  858. write_total = blocklen;
  859. } else {
  860. blocklen = DEVESIZE(dev);
  861. erase_offset = DEVOFFSET(dev);
  862. /* Maximum area we may use */
  863. erase_len = environment_end(dev) - erase_offset;
  864. blockstart = erase_offset;
  865. /* Offset inside a block */
  866. block_seek = DEVOFFSET(dev) - erase_offset;
  867. /*
  868. * Data size we actually write: from the start of the block
  869. * to the start of the data, then count bytes of data, and
  870. * to the end of the block
  871. */
  872. write_total = ((block_seek + count + blocklen - 1) /
  873. blocklen) * blocklen;
  874. }
  875. /*
  876. * Support data anywhere within erase sectors: read out the complete
  877. * area to be erased, replace the environment image, write the whole
  878. * block back again.
  879. */
  880. if (write_total > count) {
  881. data = malloc(erase_len);
  882. if (!data) {
  883. fprintf(stderr,
  884. "Cannot malloc %zu bytes: %s\n",
  885. erase_len, strerror(errno));
  886. return -1;
  887. }
  888. rc = flash_read_buf(dev, fd, data, write_total, erase_offset);
  889. if (write_total != rc)
  890. return -1;
  891. #ifdef DEBUG
  892. fprintf(stderr, "Preserving data ");
  893. if (block_seek != 0)
  894. fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
  895. if (block_seek + count != write_total) {
  896. if (block_seek != 0)
  897. fprintf(stderr, " and ");
  898. fprintf(stderr, "0x%lx - 0x%lx",
  899. (unsigned long)block_seek + count,
  900. (unsigned long)write_total - 1);
  901. }
  902. fprintf(stderr, "\n");
  903. #endif
  904. /* Overwrite the old environment */
  905. memcpy(data + block_seek, buf, count);
  906. } else {
  907. /*
  908. * We get here, iff offset is block-aligned and count is a
  909. * multiple of blocklen - see write_total calculation above
  910. */
  911. data = buf;
  912. }
  913. if (DEVTYPE(dev) == MTD_NANDFLASH) {
  914. /*
  915. * NAND: calculate which blocks we are writing. We have
  916. * to write one block at a time to skip bad blocks.
  917. */
  918. erasesize = blocklen;
  919. } else {
  920. erasesize = erase_len;
  921. }
  922. erase.length = erasesize;
  923. if (DEVTYPE(dev) != MTD_ABSENT) {
  924. was_locked = ioctl(fd, MEMISLOCKED, &erase);
  925. /* treat any errors as unlocked flash */
  926. if (was_locked < 0)
  927. was_locked = 0;
  928. }
  929. /* This only runs once on NOR flash and SPI-dataflash */
  930. while (processed < write_total) {
  931. rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
  932. if (rc < 0) /* block test failed */
  933. return rc;
  934. if (blockstart + erasesize > environment_end(dev)) {
  935. fprintf(stderr, "End of range reached, aborting\n");
  936. return -1;
  937. }
  938. if (rc) { /* block is bad */
  939. blockstart += blocklen;
  940. continue;
  941. }
  942. if (DEVTYPE(dev) != MTD_ABSENT) {
  943. erase.start = blockstart;
  944. if (was_locked)
  945. ioctl(fd, MEMUNLOCK, &erase);
  946. /* These do not need an explicit erase cycle */
  947. if (DEVTYPE(dev) != MTD_DATAFLASH)
  948. if (ioctl(fd, MEMERASE, &erase) != 0) {
  949. fprintf(stderr,
  950. "MTD erase error on %s: %s\n",
  951. DEVNAME(dev), strerror(errno));
  952. return -1;
  953. }
  954. }
  955. if (lseek(fd, blockstart, SEEK_SET) == -1) {
  956. fprintf(stderr,
  957. "Seek error on %s: %s\n",
  958. DEVNAME(dev), strerror(errno));
  959. return -1;
  960. }
  961. #ifdef DEBUG
  962. fprintf(stderr, "Write 0x%llx bytes at 0x%llx\n",
  963. (unsigned long long)erasesize,
  964. (unsigned long long)blockstart);
  965. #endif
  966. if (write(fd, data + processed, erasesize) != erasesize) {
  967. fprintf(stderr, "Write error on %s: %s\n",
  968. DEVNAME(dev), strerror(errno));
  969. return -1;
  970. }
  971. if (DEVTYPE(dev) != MTD_ABSENT) {
  972. if (was_locked)
  973. ioctl(fd, MEMLOCK, &erase);
  974. }
  975. processed += erasesize;
  976. block_seek = 0;
  977. blockstart += erasesize;
  978. }
  979. if (write_total > count)
  980. free(data);
  981. return processed;
  982. }
  983. /*
  984. * Set obsolete flag at offset - NOR flash only
  985. */
  986. static int flash_flag_obsolete(int dev, int fd, off_t offset)
  987. {
  988. int rc;
  989. struct erase_info_user erase;
  990. char tmp = ENV_REDUND_OBSOLETE;
  991. int was_locked; /* flash lock flag */
  992. was_locked = ioctl(fd, MEMISLOCKED, &erase);
  993. erase.start = DEVOFFSET(dev);
  994. erase.length = DEVESIZE(dev);
  995. /* This relies on the fact, that ENV_REDUND_OBSOLETE == 0 */
  996. rc = lseek(fd, offset, SEEK_SET);
  997. if (rc < 0) {
  998. fprintf(stderr, "Cannot seek to set the flag on %s\n",
  999. DEVNAME(dev));
  1000. return rc;
  1001. }
  1002. if (was_locked)
  1003. ioctl(fd, MEMUNLOCK, &erase);
  1004. rc = write(fd, &tmp, sizeof(tmp));
  1005. if (was_locked)
  1006. ioctl(fd, MEMLOCK, &erase);
  1007. if (rc < 0)
  1008. perror("Could not set obsolete flag");
  1009. return rc;
  1010. }
  1011. static int flash_write(int fd_current, int fd_target, int dev_target)
  1012. {
  1013. int rc;
  1014. switch (environment.flag_scheme) {
  1015. case FLAG_NONE:
  1016. break;
  1017. case FLAG_INCREMENTAL:
  1018. (*environment.flags)++;
  1019. break;
  1020. case FLAG_BOOLEAN:
  1021. *environment.flags = ENV_REDUND_ACTIVE;
  1022. break;
  1023. default:
  1024. fprintf(stderr, "Unimplemented flash scheme %u\n",
  1025. environment.flag_scheme);
  1026. return -1;
  1027. }
  1028. #ifdef DEBUG
  1029. fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
  1030. DEVOFFSET(dev_target), DEVNAME(dev_target));
  1031. #endif
  1032. if (IS_UBI(dev_target)) {
  1033. if (ubi_update_start(fd_target, CUR_ENVSIZE) < 0)
  1034. return -1;
  1035. return ubi_write(fd_target, environment.image, CUR_ENVSIZE);
  1036. }
  1037. rc = flash_write_buf(dev_target, fd_target, environment.image,
  1038. CUR_ENVSIZE);
  1039. if (rc < 0)
  1040. return rc;
  1041. if (environment.flag_scheme == FLAG_BOOLEAN) {
  1042. /* Have to set obsolete flag */
  1043. off_t offset = DEVOFFSET(dev_current) +
  1044. offsetof(struct env_image_redundant, flags);
  1045. #ifdef DEBUG
  1046. fprintf(stderr,
  1047. "Setting obsolete flag in environment at 0x%llx on %s\n",
  1048. DEVOFFSET(dev_current), DEVNAME(dev_current));
  1049. #endif
  1050. flash_flag_obsolete(dev_current, fd_current, offset);
  1051. }
  1052. return 0;
  1053. }
  1054. static int flash_read(int fd)
  1055. {
  1056. int rc;
  1057. if (IS_UBI(dev_current)) {
  1058. DEVTYPE(dev_current) = MTD_ABSENT;
  1059. return ubi_read(fd, environment.image, CUR_ENVSIZE);
  1060. }
  1061. rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
  1062. DEVOFFSET(dev_current));
  1063. if (rc != CUR_ENVSIZE)
  1064. return -1;
  1065. return 0;
  1066. }
  1067. static int flash_open_tempfile(const char **dname, const char **target_temp)
  1068. {
  1069. char *dup_name = strdup(DEVNAME(dev_current));
  1070. char *temp_name = NULL;
  1071. int rc = -1;
  1072. if (!dup_name)
  1073. return -1;
  1074. *dname = dirname(dup_name);
  1075. if (!*dname)
  1076. goto err;
  1077. rc = asprintf(&temp_name, "%s/XXXXXX", *dname);
  1078. if (rc == -1)
  1079. goto err;
  1080. rc = mkstemp(temp_name);
  1081. if (rc == -1) {
  1082. /* fall back to in place write */
  1083. fprintf(stderr,
  1084. "Can't create %s: %s\n", temp_name, strerror(errno));
  1085. free(temp_name);
  1086. } else {
  1087. *target_temp = temp_name;
  1088. /* deliberately leak dup_name as dname /might/ point into
  1089. * it and we need it for our caller
  1090. */
  1091. dup_name = NULL;
  1092. }
  1093. err:
  1094. if (dup_name)
  1095. free(dup_name);
  1096. return rc;
  1097. }
  1098. static int flash_io_write(int fd_current)
  1099. {
  1100. int fd_target = -1, rc, dev_target;
  1101. const char *dname, *target_temp = NULL;
  1102. if (have_redund_env) {
  1103. /* switch to next partition for writing */
  1104. dev_target = !dev_current;
  1105. /* dev_target: fd_target, erase_target */
  1106. fd_target = open(DEVNAME(dev_target), O_RDWR);
  1107. if (fd_target < 0) {
  1108. fprintf(stderr,
  1109. "Can't open %s: %s\n",
  1110. DEVNAME(dev_target), strerror(errno));
  1111. rc = -1;
  1112. goto exit;
  1113. }
  1114. } else {
  1115. struct stat sb;
  1116. if (fstat(fd_current, &sb) == 0 && S_ISREG(sb.st_mode)) {
  1117. /* if any part of flash_open_tempfile() fails we fall
  1118. * back to in-place writes
  1119. */
  1120. fd_target = flash_open_tempfile(&dname, &target_temp);
  1121. }
  1122. dev_target = dev_current;
  1123. if (fd_target == -1)
  1124. fd_target = fd_current;
  1125. }
  1126. rc = flash_write(fd_current, fd_target, dev_target);
  1127. if (fsync(fd_current) && !(errno == EINVAL || errno == EROFS)) {
  1128. fprintf(stderr,
  1129. "fsync failed on %s: %s\n",
  1130. DEVNAME(dev_current), strerror(errno));
  1131. }
  1132. if (fd_current != fd_target) {
  1133. if (fsync(fd_target) &&
  1134. !(errno == EINVAL || errno == EROFS)) {
  1135. fprintf(stderr,
  1136. "fsync failed on %s: %s\n",
  1137. DEVNAME(dev_current), strerror(errno));
  1138. }
  1139. if (close(fd_target)) {
  1140. fprintf(stderr,
  1141. "I/O error on %s: %s\n",
  1142. DEVNAME(dev_target), strerror(errno));
  1143. rc = -1;
  1144. }
  1145. if (rc >= 0 && target_temp) {
  1146. int dir_fd;
  1147. dir_fd = open(dname, O_DIRECTORY | O_RDONLY);
  1148. if (dir_fd == -1)
  1149. fprintf(stderr,
  1150. "Can't open %s: %s\n",
  1151. dname, strerror(errno));
  1152. if (rename(target_temp, DEVNAME(dev_target))) {
  1153. fprintf(stderr,
  1154. "rename failed %s => %s: %s\n",
  1155. target_temp, DEVNAME(dev_target),
  1156. strerror(errno));
  1157. rc = -1;
  1158. }
  1159. if (dir_fd != -1 && fsync(dir_fd))
  1160. fprintf(stderr,
  1161. "fsync failed on %s: %s\n",
  1162. dname, strerror(errno));
  1163. if (dir_fd != -1 && close(dir_fd))
  1164. fprintf(stderr,
  1165. "I/O error on %s: %s\n",
  1166. dname, strerror(errno));
  1167. }
  1168. }
  1169. exit:
  1170. return rc;
  1171. }
  1172. static int flash_io(int mode)
  1173. {
  1174. int fd_current, rc;
  1175. /* dev_current: fd_current, erase_current */
  1176. fd_current = open(DEVNAME(dev_current), mode);
  1177. if (fd_current < 0) {
  1178. fprintf(stderr,
  1179. "Can't open %s: %s\n",
  1180. DEVNAME(dev_current), strerror(errno));
  1181. return -1;
  1182. }
  1183. if (mode == O_RDWR) {
  1184. rc = flash_io_write(fd_current);
  1185. } else {
  1186. rc = flash_read(fd_current);
  1187. }
  1188. if (close(fd_current)) {
  1189. fprintf(stderr,
  1190. "I/O error on %s: %s\n",
  1191. DEVNAME(dev_current), strerror(errno));
  1192. return -1;
  1193. }
  1194. return rc;
  1195. }
  1196. /*
  1197. * Prevent confusion if running from erased flash memory
  1198. */
  1199. int fw_env_open(struct env_opts *opts)
  1200. {
  1201. int crc0, crc0_ok;
  1202. unsigned char flag0;
  1203. void *addr0 = NULL;
  1204. int crc1, crc1_ok;
  1205. unsigned char flag1;
  1206. void *addr1 = NULL;
  1207. int ret;
  1208. struct env_image_single *single;
  1209. struct env_image_redundant *redundant;
  1210. if (!opts)
  1211. opts = &default_opts;
  1212. if (parse_config(opts)) /* should fill envdevices */
  1213. return -EINVAL;
  1214. addr0 = calloc(1, CUR_ENVSIZE);
  1215. if (addr0 == NULL) {
  1216. fprintf(stderr,
  1217. "Not enough memory for environment (%ld bytes)\n",
  1218. CUR_ENVSIZE);
  1219. ret = -ENOMEM;
  1220. goto open_cleanup;
  1221. }
  1222. /* read environment from FLASH to local buffer */
  1223. environment.image = addr0;
  1224. if (have_redund_env) {
  1225. redundant = addr0;
  1226. environment.crc = &redundant->crc;
  1227. environment.flags = &redundant->flags;
  1228. environment.data = redundant->data;
  1229. } else {
  1230. single = addr0;
  1231. environment.crc = &single->crc;
  1232. environment.flags = NULL;
  1233. environment.data = single->data;
  1234. }
  1235. dev_current = 0;
  1236. if (flash_io(O_RDONLY)) {
  1237. ret = -EIO;
  1238. goto open_cleanup;
  1239. }
  1240. crc0 = crc32(0, (uint8_t *)environment.data, ENV_SIZE);
  1241. crc0_ok = (crc0 == *environment.crc);
  1242. if (!have_redund_env) {
  1243. if (!crc0_ok) {
  1244. fprintf(stderr,
  1245. "Warning: Bad CRC, using default environment\n");
  1246. memcpy(environment.data, default_environment,
  1247. sizeof(default_environment));
  1248. environment.dirty = 1;
  1249. }
  1250. } else {
  1251. flag0 = *environment.flags;
  1252. dev_current = 1;
  1253. addr1 = calloc(1, CUR_ENVSIZE);
  1254. if (addr1 == NULL) {
  1255. fprintf(stderr,
  1256. "Not enough memory for environment (%ld bytes)\n",
  1257. CUR_ENVSIZE);
  1258. ret = -ENOMEM;
  1259. goto open_cleanup;
  1260. }
  1261. redundant = addr1;
  1262. /*
  1263. * have to set environment.image for flash_read(), careful -
  1264. * other pointers in environment still point inside addr0
  1265. */
  1266. environment.image = addr1;
  1267. if (flash_io(O_RDONLY)) {
  1268. ret = -EIO;
  1269. goto open_cleanup;
  1270. }
  1271. /* Check flag scheme compatibility */
  1272. if (DEVTYPE(dev_current) == MTD_NORFLASH &&
  1273. DEVTYPE(!dev_current) == MTD_NORFLASH) {
  1274. environment.flag_scheme = FLAG_BOOLEAN;
  1275. } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
  1276. DEVTYPE(!dev_current) == MTD_NANDFLASH) {
  1277. environment.flag_scheme = FLAG_INCREMENTAL;
  1278. } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
  1279. DEVTYPE(!dev_current) == MTD_DATAFLASH) {
  1280. environment.flag_scheme = FLAG_BOOLEAN;
  1281. } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
  1282. DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
  1283. environment.flag_scheme = FLAG_INCREMENTAL;
  1284. } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
  1285. DEVTYPE(!dev_current) == MTD_ABSENT &&
  1286. IS_UBI(dev_current) == IS_UBI(!dev_current)) {
  1287. environment.flag_scheme = FLAG_INCREMENTAL;
  1288. } else {
  1289. fprintf(stderr, "Incompatible flash types!\n");
  1290. ret = -EINVAL;
  1291. goto open_cleanup;
  1292. }
  1293. crc1 = crc32(0, (uint8_t *)redundant->data, ENV_SIZE);
  1294. crc1_ok = (crc1 == redundant->crc);
  1295. flag1 = redundant->flags;
  1296. /*
  1297. * environment.data still points to ((struct
  1298. * env_image_redundant *)addr0)->data. If the two
  1299. * environments differ, or one has bad crc, force a
  1300. * write-out by marking the environment dirty.
  1301. */
  1302. if (memcmp(environment.data, redundant->data, ENV_SIZE) ||
  1303. !crc0_ok || !crc1_ok)
  1304. environment.dirty = 1;
  1305. if (crc0_ok && !crc1_ok) {
  1306. dev_current = 0;
  1307. } else if (!crc0_ok && crc1_ok) {
  1308. dev_current = 1;
  1309. } else if (!crc0_ok && !crc1_ok) {
  1310. fprintf(stderr,
  1311. "Warning: Bad CRC, using default environment\n");
  1312. memcpy(environment.data, default_environment,
  1313. sizeof(default_environment));
  1314. environment.dirty = 1;
  1315. dev_current = 0;
  1316. } else {
  1317. switch (environment.flag_scheme) {
  1318. case FLAG_BOOLEAN:
  1319. if (flag0 == ENV_REDUND_ACTIVE &&
  1320. flag1 == ENV_REDUND_OBSOLETE) {
  1321. dev_current = 0;
  1322. } else if (flag0 == ENV_REDUND_OBSOLETE &&
  1323. flag1 == ENV_REDUND_ACTIVE) {
  1324. dev_current = 1;
  1325. } else if (flag0 == flag1) {
  1326. dev_current = 0;
  1327. } else if (flag0 == 0xFF) {
  1328. dev_current = 0;
  1329. } else if (flag1 == 0xFF) {
  1330. dev_current = 1;
  1331. } else {
  1332. dev_current = 0;
  1333. }
  1334. break;
  1335. case FLAG_INCREMENTAL:
  1336. if (flag0 == 255 && flag1 == 0)
  1337. dev_current = 1;
  1338. else if ((flag1 == 255 && flag0 == 0) ||
  1339. flag0 >= flag1)
  1340. dev_current = 0;
  1341. else /* flag1 > flag0 */
  1342. dev_current = 1;
  1343. break;
  1344. default:
  1345. fprintf(stderr, "Unknown flag scheme %u\n",
  1346. environment.flag_scheme);
  1347. return -1;
  1348. }
  1349. }
  1350. /*
  1351. * If we are reading, we don't need the flag and the CRC any
  1352. * more, if we are writing, we will re-calculate CRC and update
  1353. * flags before writing out
  1354. */
  1355. if (dev_current) {
  1356. environment.image = addr1;
  1357. environment.crc = &redundant->crc;
  1358. environment.flags = &redundant->flags;
  1359. environment.data = redundant->data;
  1360. free(addr0);
  1361. } else {
  1362. environment.image = addr0;
  1363. /* Other pointers are already set */
  1364. free(addr1);
  1365. }
  1366. #ifdef DEBUG
  1367. fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
  1368. #endif
  1369. }
  1370. return 0;
  1371. open_cleanup:
  1372. if (addr0)
  1373. free(addr0);
  1374. if (addr1)
  1375. free(addr1);
  1376. return ret;
  1377. }
  1378. /*
  1379. * Simply free allocated buffer with environment
  1380. */
  1381. int fw_env_close(struct env_opts *opts)
  1382. {
  1383. if (environment.image)
  1384. free(environment.image);
  1385. environment.image = NULL;
  1386. return 0;
  1387. }
  1388. static int check_device_config(int dev)
  1389. {
  1390. struct stat st;
  1391. int32_t lnum = 0;
  1392. int fd, rc = 0;
  1393. /* Fills in IS_UBI(), converts DEVNAME() with ubi volume name */
  1394. ubi_check_dev(dev);
  1395. fd = open(DEVNAME(dev), O_RDONLY);
  1396. if (fd < 0) {
  1397. fprintf(stderr,
  1398. "Cannot open %s: %s\n", DEVNAME(dev), strerror(errno));
  1399. return -1;
  1400. }
  1401. rc = fstat(fd, &st);
  1402. if (rc < 0) {
  1403. fprintf(stderr, "Cannot stat the file %s\n", DEVNAME(dev));
  1404. goto err;
  1405. }
  1406. if (IS_UBI(dev)) {
  1407. rc = ioctl(fd, UBI_IOCEBISMAP, &lnum);
  1408. if (rc < 0) {
  1409. fprintf(stderr, "Cannot get UBI information for %s\n",
  1410. DEVNAME(dev));
  1411. goto err;
  1412. }
  1413. } else if (S_ISCHR(st.st_mode)) {
  1414. struct mtd_info_user mtdinfo;
  1415. rc = ioctl(fd, MEMGETINFO, &mtdinfo);
  1416. if (rc < 0) {
  1417. fprintf(stderr, "Cannot get MTD information for %s\n",
  1418. DEVNAME(dev));
  1419. goto err;
  1420. }
  1421. if (mtdinfo.type != MTD_NORFLASH &&
  1422. mtdinfo.type != MTD_NANDFLASH &&
  1423. mtdinfo.type != MTD_DATAFLASH &&
  1424. mtdinfo.type != MTD_UBIVOLUME) {
  1425. fprintf(stderr, "Unsupported flash type %u on %s\n",
  1426. mtdinfo.type, DEVNAME(dev));
  1427. goto err;
  1428. }
  1429. DEVTYPE(dev) = mtdinfo.type;
  1430. if (DEVESIZE(dev) == 0 && ENVSECTORS(dev) == 0 &&
  1431. mtdinfo.type == MTD_NORFLASH)
  1432. DEVESIZE(dev) = mtdinfo.erasesize;
  1433. if (DEVESIZE(dev) == 0)
  1434. /* Assume the erase size is the same as the env-size */
  1435. DEVESIZE(dev) = ENVSIZE(dev);
  1436. } else {
  1437. uint64_t size;
  1438. DEVTYPE(dev) = MTD_ABSENT;
  1439. if (DEVESIZE(dev) == 0)
  1440. /* Assume the erase size to be 512 bytes */
  1441. DEVESIZE(dev) = 0x200;
  1442. /*
  1443. * Check for negative offsets, treat it as backwards offset
  1444. * from the end of the block device
  1445. */
  1446. if (DEVOFFSET(dev) < 0) {
  1447. rc = ioctl(fd, BLKGETSIZE64, &size);
  1448. if (rc < 0) {
  1449. fprintf(stderr,
  1450. "Could not get block device size on %s\n",
  1451. DEVNAME(dev));
  1452. goto err;
  1453. }
  1454. DEVOFFSET(dev) = DEVOFFSET(dev) + size;
  1455. #ifdef DEBUG
  1456. fprintf(stderr,
  1457. "Calculated device offset 0x%llx on %s\n",
  1458. DEVOFFSET(dev), DEVNAME(dev));
  1459. #endif
  1460. }
  1461. }
  1462. if (ENVSECTORS(dev) == 0)
  1463. /* Assume enough sectors to cover the environment */
  1464. ENVSECTORS(dev) = DIV_ROUND_UP(ENVSIZE(dev), DEVESIZE(dev));
  1465. if (DEVOFFSET(dev) % DEVESIZE(dev) != 0) {
  1466. fprintf(stderr,
  1467. "Environment does not start on (erase) block boundary\n");
  1468. errno = EINVAL;
  1469. return -1;
  1470. }
  1471. if (ENVSIZE(dev) > ENVSECTORS(dev) * DEVESIZE(dev)) {
  1472. fprintf(stderr,
  1473. "Environment does not fit into available sectors\n");
  1474. errno = EINVAL;
  1475. return -1;
  1476. }
  1477. err:
  1478. close(fd);
  1479. return rc;
  1480. }
  1481. static int parse_config(struct env_opts *opts)
  1482. {
  1483. int rc;
  1484. if (!opts)
  1485. opts = &default_opts;
  1486. #if defined(CONFIG_FILE)
  1487. /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
  1488. if (get_config(opts->config_file)) {
  1489. fprintf(stderr, "Cannot parse config file '%s': %m\n",
  1490. opts->config_file);
  1491. return -1;
  1492. }
  1493. #else
  1494. DEVNAME(0) = DEVICE1_NAME;
  1495. DEVOFFSET(0) = DEVICE1_OFFSET;
  1496. ENVSIZE(0) = ENV1_SIZE;
  1497. /* Set defaults for DEVESIZE, ENVSECTORS later once we
  1498. * know DEVTYPE
  1499. */
  1500. #ifdef DEVICE1_ESIZE
  1501. DEVESIZE(0) = DEVICE1_ESIZE;
  1502. #endif
  1503. #ifdef DEVICE1_ENVSECTORS
  1504. ENVSECTORS(0) = DEVICE1_ENVSECTORS;
  1505. #endif
  1506. #ifdef HAVE_REDUND
  1507. DEVNAME(1) = DEVICE2_NAME;
  1508. DEVOFFSET(1) = DEVICE2_OFFSET;
  1509. ENVSIZE(1) = ENV2_SIZE;
  1510. /* Set defaults for DEVESIZE, ENVSECTORS later once we
  1511. * know DEVTYPE
  1512. */
  1513. #ifdef DEVICE2_ESIZE
  1514. DEVESIZE(1) = DEVICE2_ESIZE;
  1515. #endif
  1516. #ifdef DEVICE2_ENVSECTORS
  1517. ENVSECTORS(1) = DEVICE2_ENVSECTORS;
  1518. #endif
  1519. have_redund_env = 1;
  1520. #endif
  1521. #endif
  1522. rc = check_device_config(0);
  1523. if (rc < 0)
  1524. return rc;
  1525. if (have_redund_env) {
  1526. rc = check_device_config(1);
  1527. if (rc < 0)
  1528. return rc;
  1529. if (ENVSIZE(0) != ENVSIZE(1)) {
  1530. fprintf(stderr,
  1531. "Redundant environments have unequal size\n");
  1532. return -1;
  1533. }
  1534. }
  1535. usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
  1536. if (have_redund_env)
  1537. usable_envsize -= sizeof(char);
  1538. return 0;
  1539. }
  1540. #if defined(CONFIG_FILE)
  1541. static int get_config(char *fname)
  1542. {
  1543. FILE *fp;
  1544. int i = 0;
  1545. int rc;
  1546. char *line = NULL;
  1547. size_t linesize = 0;
  1548. char *devname;
  1549. fp = fopen(fname, "r");
  1550. if (fp == NULL)
  1551. return -1;
  1552. while (i < 2 && getline(&line, &linesize, fp) != -1) {
  1553. /* Skip comment strings */
  1554. if (line[0] == '#')
  1555. continue;
  1556. rc = sscanf(line, "%ms %lli %lx %lx %lx",
  1557. &devname,
  1558. &DEVOFFSET(i),
  1559. &ENVSIZE(i), &DEVESIZE(i), &ENVSECTORS(i));
  1560. if (rc < 3)
  1561. continue;
  1562. DEVNAME(i) = devname;
  1563. /* Set defaults for DEVESIZE, ENVSECTORS later once we
  1564. * know DEVTYPE
  1565. */
  1566. i++;
  1567. }
  1568. free(line);
  1569. fclose(fp);
  1570. have_redund_env = i - 1;
  1571. if (!i) { /* No valid entries found */
  1572. errno = EINVAL;
  1573. return -1;
  1574. } else
  1575. return 0;
  1576. }
  1577. #endif