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