fw_env.c 38 KB

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