fw_env.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819
  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 != readlen) {
  802. fprintf(stderr, "Read error on %s: %s\n",
  803. DEVNAME(dev), strerror(errno));
  804. return -1;
  805. }
  806. #ifdef DEBUG
  807. fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
  808. rc, (unsigned long long)blockstart + block_seek,
  809. DEVNAME(dev));
  810. #endif
  811. processed += readlen;
  812. readlen = min(blocklen, count - processed);
  813. block_seek = 0;
  814. blockstart += blocklen;
  815. }
  816. return processed;
  817. }
  818. /*
  819. * Write count bytes from begin of environment, but stay within
  820. * ENVSECTORS(dev) sectors of
  821. * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
  822. * erase and write the whole data at once.
  823. */
  824. static int flash_write_buf(int dev, int fd, void *buf, size_t count)
  825. {
  826. void *data;
  827. struct erase_info_user erase;
  828. size_t blocklen; /* length of NAND block / NOR erase sector */
  829. size_t erase_len; /* whole area that can be erased - may include
  830. bad blocks */
  831. size_t erasesize; /* erase / write length - one block on NAND,
  832. whole area on NOR */
  833. size_t processed = 0; /* progress counter */
  834. size_t write_total; /* total size to actually write - excluding
  835. bad blocks */
  836. off_t erase_offset; /* offset to the first erase block (aligned)
  837. below offset */
  838. off_t block_seek; /* offset inside the erase block to the start
  839. of the data */
  840. loff_t blockstart; /* running start of the current block -
  841. MEMGETBADBLOCK needs 64 bits */
  842. int rc;
  843. /*
  844. * For mtd devices only offset and size of the environment do matter
  845. */
  846. if (DEVTYPE(dev) == MTD_ABSENT) {
  847. blocklen = count;
  848. erase_len = blocklen;
  849. blockstart = DEVOFFSET(dev);
  850. block_seek = 0;
  851. write_total = blocklen;
  852. } else {
  853. blocklen = DEVESIZE(dev);
  854. erase_offset = DEVOFFSET(dev);
  855. /* Maximum area we may use */
  856. erase_len = environment_end(dev) - erase_offset;
  857. blockstart = erase_offset;
  858. /* Offset inside a block */
  859. block_seek = DEVOFFSET(dev) - erase_offset;
  860. /*
  861. * Data size we actually write: from the start of the block
  862. * to the start of the data, then count bytes of data, and
  863. * to the end of the block
  864. */
  865. write_total = ((block_seek + count + blocklen - 1) /
  866. blocklen) * blocklen;
  867. }
  868. /*
  869. * Support data anywhere within erase sectors: read out the complete
  870. * area to be erased, replace the environment image, write the whole
  871. * block back again.
  872. */
  873. if (write_total > count) {
  874. data = malloc(erase_len);
  875. if (!data) {
  876. fprintf(stderr,
  877. "Cannot malloc %zu bytes: %s\n",
  878. erase_len, strerror(errno));
  879. return -1;
  880. }
  881. rc = flash_read_buf(dev, fd, data, write_total, erase_offset);
  882. if (write_total != rc)
  883. return -1;
  884. #ifdef DEBUG
  885. fprintf(stderr, "Preserving data ");
  886. if (block_seek != 0)
  887. fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
  888. if (block_seek + count != write_total) {
  889. if (block_seek != 0)
  890. fprintf(stderr, " and ");
  891. fprintf(stderr, "0x%lx - 0x%lx",
  892. (unsigned long)block_seek + count,
  893. (unsigned long)write_total - 1);
  894. }
  895. fprintf(stderr, "\n");
  896. #endif
  897. /* Overwrite the old environment */
  898. memcpy(data + block_seek, buf, count);
  899. } else {
  900. /*
  901. * We get here, iff offset is block-aligned and count is a
  902. * multiple of blocklen - see write_total calculation above
  903. */
  904. data = buf;
  905. }
  906. if (DEVTYPE(dev) == MTD_NANDFLASH) {
  907. /*
  908. * NAND: calculate which blocks we are writing. We have
  909. * to write one block at a time to skip bad blocks.
  910. */
  911. erasesize = blocklen;
  912. } else {
  913. erasesize = erase_len;
  914. }
  915. erase.length = erasesize;
  916. /* This only runs once on NOR flash and SPI-dataflash */
  917. while (processed < write_total) {
  918. rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
  919. if (rc < 0) /* block test failed */
  920. return rc;
  921. if (blockstart + erasesize > environment_end(dev)) {
  922. fprintf(stderr, "End of range reached, aborting\n");
  923. return -1;
  924. }
  925. if (rc) { /* block is bad */
  926. blockstart += blocklen;
  927. continue;
  928. }
  929. if (DEVTYPE(dev) != MTD_ABSENT) {
  930. erase.start = blockstart;
  931. ioctl(fd, MEMUNLOCK, &erase);
  932. /* These do not need an explicit erase cycle */
  933. if (DEVTYPE(dev) != MTD_DATAFLASH)
  934. if (ioctl(fd, MEMERASE, &erase) != 0) {
  935. fprintf(stderr,
  936. "MTD erase error on %s: %s\n",
  937. DEVNAME(dev), strerror(errno));
  938. return -1;
  939. }
  940. }
  941. if (lseek(fd, blockstart, SEEK_SET) == -1) {
  942. fprintf(stderr,
  943. "Seek error on %s: %s\n",
  944. DEVNAME(dev), strerror(errno));
  945. return -1;
  946. }
  947. #ifdef DEBUG
  948. fprintf(stderr, "Write 0x%llx bytes at 0x%llx\n",
  949. (unsigned long long)erasesize,
  950. (unsigned long long)blockstart);
  951. #endif
  952. if (write(fd, data + processed, erasesize) != erasesize) {
  953. fprintf(stderr, "Write error on %s: %s\n",
  954. DEVNAME(dev), strerror(errno));
  955. return -1;
  956. }
  957. if (DEVTYPE(dev) != MTD_ABSENT)
  958. ioctl(fd, MEMLOCK, &erase);
  959. processed += erasesize;
  960. block_seek = 0;
  961. blockstart += erasesize;
  962. }
  963. if (write_total > count)
  964. free(data);
  965. return processed;
  966. }
  967. /*
  968. * Set obsolete flag at offset - NOR flash only
  969. */
  970. static int flash_flag_obsolete(int dev, int fd, off_t offset)
  971. {
  972. int rc;
  973. struct erase_info_user erase;
  974. char tmp = ENV_REDUND_OBSOLETE;
  975. erase.start = DEVOFFSET(dev);
  976. erase.length = DEVESIZE(dev);
  977. /* This relies on the fact, that ENV_REDUND_OBSOLETE == 0 */
  978. rc = lseek(fd, offset, SEEK_SET);
  979. if (rc < 0) {
  980. fprintf(stderr, "Cannot seek to set the flag on %s\n",
  981. DEVNAME(dev));
  982. return rc;
  983. }
  984. ioctl(fd, MEMUNLOCK, &erase);
  985. rc = write(fd, &tmp, sizeof(tmp));
  986. ioctl(fd, MEMLOCK, &erase);
  987. if (rc < 0)
  988. perror("Could not set obsolete flag");
  989. return rc;
  990. }
  991. static int flash_write(int fd_current, int fd_target, int dev_target)
  992. {
  993. int rc;
  994. switch (environment.flag_scheme) {
  995. case FLAG_NONE:
  996. break;
  997. case FLAG_INCREMENTAL:
  998. (*environment.flags)++;
  999. break;
  1000. case FLAG_BOOLEAN:
  1001. *environment.flags = ENV_REDUND_ACTIVE;
  1002. break;
  1003. default:
  1004. fprintf(stderr, "Unimplemented flash scheme %u\n",
  1005. environment.flag_scheme);
  1006. return -1;
  1007. }
  1008. #ifdef DEBUG
  1009. fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
  1010. DEVOFFSET(dev_target), DEVNAME(dev_target));
  1011. #endif
  1012. if (IS_UBI(dev_target)) {
  1013. if (ubi_update_start(fd_target, CUR_ENVSIZE) < 0)
  1014. return 0;
  1015. return ubi_write(fd_target, environment.image, CUR_ENVSIZE);
  1016. }
  1017. rc = flash_write_buf(dev_target, fd_target, environment.image,
  1018. CUR_ENVSIZE);
  1019. if (rc < 0)
  1020. return rc;
  1021. if (environment.flag_scheme == FLAG_BOOLEAN) {
  1022. /* Have to set obsolete flag */
  1023. off_t offset = DEVOFFSET(dev_current) +
  1024. offsetof(struct env_image_redundant, flags);
  1025. #ifdef DEBUG
  1026. fprintf(stderr,
  1027. "Setting obsolete flag in environment at 0x%llx on %s\n",
  1028. DEVOFFSET(dev_current), DEVNAME(dev_current));
  1029. #endif
  1030. flash_flag_obsolete(dev_current, fd_current, offset);
  1031. }
  1032. return 0;
  1033. }
  1034. static int flash_read(int fd)
  1035. {
  1036. int rc;
  1037. if (IS_UBI(dev_current)) {
  1038. DEVTYPE(dev_current) = MTD_ABSENT;
  1039. return ubi_read(fd, environment.image, CUR_ENVSIZE);
  1040. }
  1041. rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
  1042. DEVOFFSET(dev_current));
  1043. if (rc != CUR_ENVSIZE)
  1044. return -1;
  1045. return 0;
  1046. }
  1047. static int flash_open_tempfile(const char **dname, const char **target_temp)
  1048. {
  1049. char *dup_name = strdup(DEVNAME(dev_current));
  1050. char *temp_name = NULL;
  1051. int rc = -1;
  1052. if (!dup_name)
  1053. return -1;
  1054. *dname = dirname(dup_name);
  1055. if (!*dname)
  1056. goto err;
  1057. rc = asprintf(&temp_name, "%s/XXXXXX", *dname);
  1058. if (rc == -1)
  1059. goto err;
  1060. rc = mkstemp(temp_name);
  1061. if (rc == -1) {
  1062. /* fall back to in place write */
  1063. fprintf(stderr,
  1064. "Can't create %s: %s\n", temp_name, strerror(errno));
  1065. free(temp_name);
  1066. } else {
  1067. *target_temp = temp_name;
  1068. /* deliberately leak dup_name as dname /might/ point into
  1069. * it and we need it for our caller
  1070. */
  1071. dup_name = NULL;
  1072. }
  1073. err:
  1074. if (dup_name)
  1075. free(dup_name);
  1076. return rc;
  1077. }
  1078. static int flash_io_write(int fd_current)
  1079. {
  1080. int fd_target = -1, rc, dev_target;
  1081. const char *dname, *target_temp = NULL;
  1082. if (have_redund_env) {
  1083. /* switch to next partition for writing */
  1084. dev_target = !dev_current;
  1085. /* dev_target: fd_target, erase_target */
  1086. fd_target = open(DEVNAME(dev_target), O_RDWR);
  1087. if (fd_target < 0) {
  1088. fprintf(stderr,
  1089. "Can't open %s: %s\n",
  1090. DEVNAME(dev_target), strerror(errno));
  1091. rc = -1;
  1092. goto exit;
  1093. }
  1094. } else {
  1095. struct stat sb;
  1096. if (fstat(fd_current, &sb) == 0 && S_ISREG(sb.st_mode)) {
  1097. /* if any part of flash_open_tempfile() fails we fall
  1098. * back to in-place writes
  1099. */
  1100. fd_target = flash_open_tempfile(&dname, &target_temp);
  1101. }
  1102. dev_target = dev_current;
  1103. if (fd_target == -1)
  1104. fd_target = fd_current;
  1105. }
  1106. rc = flash_write(fd_current, fd_target, dev_target);
  1107. if (fsync(fd_current) && !(errno == EINVAL || errno == EROFS)) {
  1108. fprintf(stderr,
  1109. "fsync failed on %s: %s\n",
  1110. DEVNAME(dev_current), strerror(errno));
  1111. }
  1112. if (fd_current != fd_target) {
  1113. if (fsync(fd_target) &&
  1114. !(errno == EINVAL || errno == EROFS)) {
  1115. fprintf(stderr,
  1116. "fsync failed on %s: %s\n",
  1117. DEVNAME(dev_current), strerror(errno));
  1118. }
  1119. if (close(fd_target)) {
  1120. fprintf(stderr,
  1121. "I/O error on %s: %s\n",
  1122. DEVNAME(dev_target), strerror(errno));
  1123. rc = -1;
  1124. }
  1125. if (rc >= 0 && target_temp) {
  1126. int dir_fd;
  1127. dir_fd = open(dname, O_DIRECTORY | O_RDONLY);
  1128. if (dir_fd == -1)
  1129. fprintf(stderr,
  1130. "Can't open %s: %s\n",
  1131. dname, strerror(errno));
  1132. if (rename(target_temp, DEVNAME(dev_target))) {
  1133. fprintf(stderr,
  1134. "rename failed %s => %s: %s\n",
  1135. target_temp, DEVNAME(dev_target),
  1136. strerror(errno));
  1137. rc = -1;
  1138. }
  1139. if (dir_fd != -1 && fsync(dir_fd))
  1140. fprintf(stderr,
  1141. "fsync failed on %s: %s\n",
  1142. dname, strerror(errno));
  1143. if (dir_fd != -1 && close(dir_fd))
  1144. fprintf(stderr,
  1145. "I/O error on %s: %s\n",
  1146. dname, strerror(errno));
  1147. }
  1148. }
  1149. exit:
  1150. return rc;
  1151. }
  1152. static int flash_io(int mode)
  1153. {
  1154. int fd_current, rc;
  1155. /* dev_current: fd_current, erase_current */
  1156. fd_current = open(DEVNAME(dev_current), mode);
  1157. if (fd_current < 0) {
  1158. fprintf(stderr,
  1159. "Can't open %s: %s\n",
  1160. DEVNAME(dev_current), strerror(errno));
  1161. return -1;
  1162. }
  1163. if (mode == O_RDWR) {
  1164. rc = flash_io_write(fd_current);
  1165. } else {
  1166. rc = flash_read(fd_current);
  1167. }
  1168. if (close(fd_current)) {
  1169. fprintf(stderr,
  1170. "I/O error on %s: %s\n",
  1171. DEVNAME(dev_current), strerror(errno));
  1172. return -1;
  1173. }
  1174. return rc;
  1175. }
  1176. /*
  1177. * Prevent confusion if running from erased flash memory
  1178. */
  1179. int fw_env_open(struct env_opts *opts)
  1180. {
  1181. int crc0, crc0_ok;
  1182. unsigned char flag0;
  1183. void *addr0 = NULL;
  1184. int crc1, crc1_ok;
  1185. unsigned char flag1;
  1186. void *addr1 = NULL;
  1187. int ret;
  1188. struct env_image_single *single;
  1189. struct env_image_redundant *redundant;
  1190. if (!opts)
  1191. opts = &default_opts;
  1192. if (parse_config(opts)) /* should fill envdevices */
  1193. return -EINVAL;
  1194. addr0 = calloc(1, CUR_ENVSIZE);
  1195. if (addr0 == NULL) {
  1196. fprintf(stderr,
  1197. "Not enough memory for environment (%ld bytes)\n",
  1198. CUR_ENVSIZE);
  1199. ret = -ENOMEM;
  1200. goto open_cleanup;
  1201. }
  1202. /* read environment from FLASH to local buffer */
  1203. environment.image = addr0;
  1204. if (have_redund_env) {
  1205. redundant = addr0;
  1206. environment.crc = &redundant->crc;
  1207. environment.flags = &redundant->flags;
  1208. environment.data = redundant->data;
  1209. } else {
  1210. single = addr0;
  1211. environment.crc = &single->crc;
  1212. environment.flags = NULL;
  1213. environment.data = single->data;
  1214. }
  1215. dev_current = 0;
  1216. if (flash_io(O_RDONLY)) {
  1217. ret = -EIO;
  1218. goto open_cleanup;
  1219. }
  1220. crc0 = crc32(0, (uint8_t *)environment.data, ENV_SIZE);
  1221. crc0_ok = (crc0 == *environment.crc);
  1222. if (!have_redund_env) {
  1223. if (!crc0_ok) {
  1224. fprintf(stderr,
  1225. "Warning: Bad CRC, using default environment\n");
  1226. memcpy(environment.data, default_environment,
  1227. sizeof(default_environment));
  1228. environment.dirty = 1;
  1229. }
  1230. } else {
  1231. flag0 = *environment.flags;
  1232. dev_current = 1;
  1233. addr1 = calloc(1, CUR_ENVSIZE);
  1234. if (addr1 == NULL) {
  1235. fprintf(stderr,
  1236. "Not enough memory for environment (%ld bytes)\n",
  1237. CUR_ENVSIZE);
  1238. ret = -ENOMEM;
  1239. goto open_cleanup;
  1240. }
  1241. redundant = addr1;
  1242. /*
  1243. * have to set environment.image for flash_read(), careful -
  1244. * other pointers in environment still point inside addr0
  1245. */
  1246. environment.image = addr1;
  1247. if (flash_io(O_RDONLY)) {
  1248. ret = -EIO;
  1249. goto open_cleanup;
  1250. }
  1251. /* Check flag scheme compatibility */
  1252. if (DEVTYPE(dev_current) == MTD_NORFLASH &&
  1253. DEVTYPE(!dev_current) == MTD_NORFLASH) {
  1254. environment.flag_scheme = FLAG_BOOLEAN;
  1255. } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
  1256. DEVTYPE(!dev_current) == MTD_NANDFLASH) {
  1257. environment.flag_scheme = FLAG_INCREMENTAL;
  1258. } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
  1259. DEVTYPE(!dev_current) == MTD_DATAFLASH) {
  1260. environment.flag_scheme = FLAG_BOOLEAN;
  1261. } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
  1262. DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
  1263. environment.flag_scheme = FLAG_INCREMENTAL;
  1264. } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
  1265. DEVTYPE(!dev_current) == MTD_ABSENT &&
  1266. IS_UBI(dev_current) == IS_UBI(!dev_current)) {
  1267. environment.flag_scheme = FLAG_INCREMENTAL;
  1268. } else {
  1269. fprintf(stderr, "Incompatible flash types!\n");
  1270. ret = -EINVAL;
  1271. goto open_cleanup;
  1272. }
  1273. crc1 = crc32(0, (uint8_t *)redundant->data, ENV_SIZE);
  1274. crc1_ok = (crc1 == redundant->crc);
  1275. flag1 = redundant->flags;
  1276. /*
  1277. * environment.data still points to ((struct
  1278. * env_image_redundant *)addr0)->data. If the two
  1279. * environments differ, or one has bad crc, force a
  1280. * write-out by marking the environment dirty.
  1281. */
  1282. if (memcmp(environment.data, redundant->data, ENV_SIZE) ||
  1283. !crc0_ok || !crc1_ok)
  1284. environment.dirty = 1;
  1285. if (crc0_ok && !crc1_ok) {
  1286. dev_current = 0;
  1287. } else if (!crc0_ok && crc1_ok) {
  1288. dev_current = 1;
  1289. } else if (!crc0_ok && !crc1_ok) {
  1290. fprintf(stderr,
  1291. "Warning: Bad CRC, using default environment\n");
  1292. memcpy(environment.data, default_environment,
  1293. sizeof(default_environment));
  1294. environment.dirty = 1;
  1295. dev_current = 0;
  1296. } else {
  1297. switch (environment.flag_scheme) {
  1298. case FLAG_BOOLEAN:
  1299. if (flag0 == ENV_REDUND_ACTIVE &&
  1300. flag1 == ENV_REDUND_OBSOLETE) {
  1301. dev_current = 0;
  1302. } else if (flag0 == ENV_REDUND_OBSOLETE &&
  1303. flag1 == ENV_REDUND_ACTIVE) {
  1304. dev_current = 1;
  1305. } else if (flag0 == flag1) {
  1306. dev_current = 0;
  1307. } else if (flag0 == 0xFF) {
  1308. dev_current = 0;
  1309. } else if (flag1 == 0xFF) {
  1310. dev_current = 1;
  1311. } else {
  1312. dev_current = 0;
  1313. }
  1314. break;
  1315. case FLAG_INCREMENTAL:
  1316. if (flag0 == 255 && flag1 == 0)
  1317. dev_current = 1;
  1318. else if ((flag1 == 255 && flag0 == 0) ||
  1319. flag0 >= flag1)
  1320. dev_current = 0;
  1321. else /* flag1 > flag0 */
  1322. dev_current = 1;
  1323. break;
  1324. default:
  1325. fprintf(stderr, "Unknown flag scheme %u\n",
  1326. environment.flag_scheme);
  1327. return -1;
  1328. }
  1329. }
  1330. /*
  1331. * If we are reading, we don't need the flag and the CRC any
  1332. * more, if we are writing, we will re-calculate CRC and update
  1333. * flags before writing out
  1334. */
  1335. if (dev_current) {
  1336. environment.image = addr1;
  1337. environment.crc = &redundant->crc;
  1338. environment.flags = &redundant->flags;
  1339. environment.data = redundant->data;
  1340. free(addr0);
  1341. } else {
  1342. environment.image = addr0;
  1343. /* Other pointers are already set */
  1344. free(addr1);
  1345. }
  1346. #ifdef DEBUG
  1347. fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
  1348. #endif
  1349. }
  1350. return 0;
  1351. open_cleanup:
  1352. if (addr0)
  1353. free(addr0);
  1354. if (addr1)
  1355. free(addr1);
  1356. return ret;
  1357. }
  1358. /*
  1359. * Simply free allocated buffer with environment
  1360. */
  1361. int fw_env_close(struct env_opts *opts)
  1362. {
  1363. if (environment.image)
  1364. free(environment.image);
  1365. environment.image = NULL;
  1366. return 0;
  1367. }
  1368. static int check_device_config(int dev)
  1369. {
  1370. struct stat st;
  1371. int32_t lnum = 0;
  1372. int fd, rc = 0;
  1373. /* Fills in IS_UBI(), converts DEVNAME() with ubi volume name */
  1374. ubi_check_dev(dev);
  1375. fd = open(DEVNAME(dev), O_RDONLY);
  1376. if (fd < 0) {
  1377. fprintf(stderr,
  1378. "Cannot open %s: %s\n", DEVNAME(dev), strerror(errno));
  1379. return -1;
  1380. }
  1381. rc = fstat(fd, &st);
  1382. if (rc < 0) {
  1383. fprintf(stderr, "Cannot stat the file %s\n", DEVNAME(dev));
  1384. goto err;
  1385. }
  1386. if (IS_UBI(dev)) {
  1387. rc = ioctl(fd, UBI_IOCEBISMAP, &lnum);
  1388. if (rc < 0) {
  1389. fprintf(stderr, "Cannot get UBI information for %s\n",
  1390. DEVNAME(dev));
  1391. goto err;
  1392. }
  1393. } else if (S_ISCHR(st.st_mode)) {
  1394. struct mtd_info_user mtdinfo;
  1395. rc = ioctl(fd, MEMGETINFO, &mtdinfo);
  1396. if (rc < 0) {
  1397. fprintf(stderr, "Cannot get MTD information for %s\n",
  1398. DEVNAME(dev));
  1399. goto err;
  1400. }
  1401. if (mtdinfo.type != MTD_NORFLASH &&
  1402. mtdinfo.type != MTD_NANDFLASH &&
  1403. mtdinfo.type != MTD_DATAFLASH &&
  1404. mtdinfo.type != MTD_UBIVOLUME) {
  1405. fprintf(stderr, "Unsupported flash type %u on %s\n",
  1406. mtdinfo.type, DEVNAME(dev));
  1407. goto err;
  1408. }
  1409. DEVTYPE(dev) = mtdinfo.type;
  1410. if (DEVESIZE(dev) == 0)
  1411. /* Assume the erase size is the same as the env-size */
  1412. DEVESIZE(dev) = ENVSIZE(dev);
  1413. } else {
  1414. uint64_t size;
  1415. DEVTYPE(dev) = MTD_ABSENT;
  1416. if (DEVESIZE(dev) == 0)
  1417. /* Assume the erase size to be 512 bytes */
  1418. DEVESIZE(dev) = 0x200;
  1419. /*
  1420. * Check for negative offsets, treat it as backwards offset
  1421. * from the end of the block device
  1422. */
  1423. if (DEVOFFSET(dev) < 0) {
  1424. rc = ioctl(fd, BLKGETSIZE64, &size);
  1425. if (rc < 0) {
  1426. fprintf(stderr,
  1427. "Could not get block device size on %s\n",
  1428. DEVNAME(dev));
  1429. goto err;
  1430. }
  1431. DEVOFFSET(dev) = DEVOFFSET(dev) + size;
  1432. #ifdef DEBUG
  1433. fprintf(stderr,
  1434. "Calculated device offset 0x%llx on %s\n",
  1435. DEVOFFSET(dev), DEVNAME(dev));
  1436. #endif
  1437. }
  1438. }
  1439. if (ENVSECTORS(dev) == 0)
  1440. /* Assume enough sectors to cover the environment */
  1441. ENVSECTORS(dev) = DIV_ROUND_UP(ENVSIZE(dev), DEVESIZE(dev));
  1442. if (DEVOFFSET(dev) % DEVESIZE(dev) != 0) {
  1443. fprintf(stderr,
  1444. "Environment does not start on (erase) block boundary\n");
  1445. errno = EINVAL;
  1446. return -1;
  1447. }
  1448. if (ENVSIZE(dev) > ENVSECTORS(dev) * DEVESIZE(dev)) {
  1449. fprintf(stderr,
  1450. "Environment does not fit into available sectors\n");
  1451. errno = EINVAL;
  1452. return -1;
  1453. }
  1454. err:
  1455. close(fd);
  1456. return rc;
  1457. }
  1458. static int parse_config(struct env_opts *opts)
  1459. {
  1460. int rc;
  1461. if (!opts)
  1462. opts = &default_opts;
  1463. #if defined(CONFIG_FILE)
  1464. /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
  1465. if (get_config(opts->config_file)) {
  1466. fprintf(stderr, "Cannot parse config file '%s': %m\n",
  1467. opts->config_file);
  1468. return -1;
  1469. }
  1470. #else
  1471. DEVNAME(0) = DEVICE1_NAME;
  1472. DEVOFFSET(0) = DEVICE1_OFFSET;
  1473. ENVSIZE(0) = ENV1_SIZE;
  1474. /* Set defaults for DEVESIZE, ENVSECTORS later once we
  1475. * know DEVTYPE
  1476. */
  1477. #ifdef DEVICE1_ESIZE
  1478. DEVESIZE(0) = DEVICE1_ESIZE;
  1479. #endif
  1480. #ifdef DEVICE1_ENVSECTORS
  1481. ENVSECTORS(0) = DEVICE1_ENVSECTORS;
  1482. #endif
  1483. #ifdef HAVE_REDUND
  1484. DEVNAME(1) = DEVICE2_NAME;
  1485. DEVOFFSET(1) = DEVICE2_OFFSET;
  1486. ENVSIZE(1) = ENV2_SIZE;
  1487. /* Set defaults for DEVESIZE, ENVSECTORS later once we
  1488. * know DEVTYPE
  1489. */
  1490. #ifdef DEVICE2_ESIZE
  1491. DEVESIZE(1) = DEVICE2_ESIZE;
  1492. #endif
  1493. #ifdef DEVICE2_ENVSECTORS
  1494. ENVSECTORS(1) = DEVICE2_ENVSECTORS;
  1495. #endif
  1496. have_redund_env = 1;
  1497. #endif
  1498. #endif
  1499. rc = check_device_config(0);
  1500. if (rc < 0)
  1501. return rc;
  1502. if (have_redund_env) {
  1503. rc = check_device_config(1);
  1504. if (rc < 0)
  1505. return rc;
  1506. if (ENVSIZE(0) != ENVSIZE(1)) {
  1507. fprintf(stderr,
  1508. "Redundant environments have unequal size\n");
  1509. return -1;
  1510. }
  1511. }
  1512. usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
  1513. if (have_redund_env)
  1514. usable_envsize -= sizeof(char);
  1515. return 0;
  1516. }
  1517. #if defined(CONFIG_FILE)
  1518. static int get_config(char *fname)
  1519. {
  1520. FILE *fp;
  1521. int i = 0;
  1522. int rc;
  1523. char *line = NULL;
  1524. size_t linesize = 0;
  1525. char *devname;
  1526. fp = fopen(fname, "r");
  1527. if (fp == NULL)
  1528. return -1;
  1529. while (i < 2 && getline(&line, &linesize, fp) != -1) {
  1530. /* Skip comment strings */
  1531. if (line[0] == '#')
  1532. continue;
  1533. rc = sscanf(line, "%ms %lli %lx %lx %lx",
  1534. &devname,
  1535. &DEVOFFSET(i),
  1536. &ENVSIZE(i), &DEVESIZE(i), &ENVSECTORS(i));
  1537. if (rc < 3)
  1538. continue;
  1539. DEVNAME(i) = devname;
  1540. /* Set defaults for DEVESIZE, ENVSECTORS later once we
  1541. * know DEVTYPE
  1542. */
  1543. i++;
  1544. }
  1545. free(line);
  1546. fclose(fp);
  1547. have_redund_env = i - 1;
  1548. if (!i) { /* No valid entries found */
  1549. errno = EINVAL;
  1550. return -1;
  1551. } else
  1552. return 0;
  1553. }
  1554. #endif