fw_env.c 38 KB

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