fw_setenv: Unbreak fw_setenv caused by buggy MEMISLOCKED use
[platform/kernel/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 <u-boot/crc.h>
29 #include <unistd.h>
30 #include <dirent.h>
31
32 #ifdef MTD_OLD
33 # include <stdint.h>
34 # include <linux/mtd/mtd.h>
35 #else
36 # define  __user        /* nothing */
37 # include <mtd/mtd-user.h>
38 #endif
39
40 #include <mtd/ubi-user.h>
41
42 #include "fw_env_private.h"
43 #include "fw_env.h"
44
45 struct env_opts default_opts = {
46 #ifdef CONFIG_FILE
47         .config_file = CONFIG_FILE
48 #endif
49 };
50
51 #define DIV_ROUND_UP(n, d)      (((n) + (d) - 1) / (d))
52
53 #define min(x, y) ({                            \
54         typeof(x) _min1 = (x);                  \
55         typeof(y) _min2 = (y);                  \
56         (void) (&_min1 == &_min2);              \
57         _min1 < _min2 ? _min1 : _min2; })
58
59 struct envdev_s {
60         const char *devname;            /* Device name */
61         long long devoff;               /* Device offset */
62         ulong env_size;                 /* environment size */
63         ulong erase_size;               /* device erase size */
64         ulong env_sectors;              /* number of environment sectors */
65         uint8_t mtd_type;               /* type of the MTD device */
66         int is_ubi;                     /* set if we use UBI volume */
67 };
68
69 static struct envdev_s envdevices[2] = {
70         {
71                 .mtd_type = MTD_ABSENT,
72         }, {
73                 .mtd_type = MTD_ABSENT,
74         },
75 };
76
77 static int dev_current;
78
79 #define DEVNAME(i)    envdevices[(i)].devname
80 #define DEVOFFSET(i)  envdevices[(i)].devoff
81 #define ENVSIZE(i)    envdevices[(i)].env_size
82 #define DEVESIZE(i)   envdevices[(i)].erase_size
83 #define ENVSECTORS(i) envdevices[(i)].env_sectors
84 #define DEVTYPE(i)    envdevices[(i)].mtd_type
85 #define IS_UBI(i)     envdevices[(i)].is_ubi
86
87 #define CUR_ENVSIZE ENVSIZE(dev_current)
88
89 static unsigned long usable_envsize;
90 #define ENV_SIZE      usable_envsize
91
92 struct env_image_single {
93         uint32_t crc;           /* CRC32 over data bytes    */
94         char data[];
95 };
96
97 struct env_image_redundant {
98         uint32_t crc;           /* CRC32 over data bytes    */
99         unsigned char flags;    /* active or obsolete */
100         char data[];
101 };
102
103 enum flag_scheme {
104         FLAG_NONE,
105         FLAG_BOOLEAN,
106         FLAG_INCREMENTAL,
107 };
108
109 struct environment {
110         void *image;
111         uint32_t *crc;
112         unsigned char *flags;
113         char *data;
114         enum flag_scheme flag_scheme;
115         int dirty;
116 };
117
118 static struct environment environment = {
119         .flag_scheme = FLAG_NONE,
120 };
121
122 static int have_redund_env;
123
124 #define DEFAULT_ENV_INSTANCE_STATIC
125 #include <env_default.h>
126
127 #define UBI_DEV_START "/dev/ubi"
128 #define UBI_SYSFS "/sys/class/ubi"
129 #define UBI_VOL_NAME_PATT "ubi%d_%d"
130
131 static int is_ubi_devname(const char *devname)
132 {
133         return !strncmp(devname, UBI_DEV_START, sizeof(UBI_DEV_START) - 1);
134 }
135
136 static int ubi_check_volume_sysfs_name(const char *volume_sysfs_name,
137                                        const char *volname)
138 {
139         char path[256];
140         FILE *file;
141         char *name;
142         int ret;
143
144         strcpy(path, UBI_SYSFS "/");
145         strcat(path, volume_sysfs_name);
146         strcat(path, "/name");
147
148         file = fopen(path, "r");
149         if (!file)
150                 return -1;
151
152         ret = fscanf(file, "%ms", &name);
153         fclose(file);
154         if (ret <= 0 || !name) {
155                 fprintf(stderr,
156                         "Failed to read from file %s, ret = %d, name = %s\n",
157                         path, ret, name);
158                 return -1;
159         }
160
161         if (!strcmp(name, volname)) {
162                 free(name);
163                 return 0;
164         }
165         free(name);
166
167         return -1;
168 }
169
170 static int ubi_get_volnum_by_name(int devnum, const char *volname)
171 {
172         DIR *sysfs_ubi;
173         struct dirent *dirent;
174         int ret;
175         int tmp_devnum;
176         int volnum;
177
178         sysfs_ubi = opendir(UBI_SYSFS);
179         if (!sysfs_ubi)
180                 return -1;
181
182 #ifdef DEBUG
183         fprintf(stderr, "Looking for volume name \"%s\"\n", volname);
184 #endif
185
186         while (1) {
187                 dirent = readdir(sysfs_ubi);
188                 if (!dirent)
189                         return -1;
190
191                 ret = sscanf(dirent->d_name, UBI_VOL_NAME_PATT,
192                              &tmp_devnum, &volnum);
193                 if (ret == 2 && devnum == tmp_devnum) {
194                         if (ubi_check_volume_sysfs_name(dirent->d_name,
195                                                         volname) == 0)
196                                 return volnum;
197                 }
198         }
199
200         return -1;
201 }
202
203 static int ubi_get_devnum_by_devname(const char *devname)
204 {
205         int devnum;
206         int ret;
207
208         ret = sscanf(devname + sizeof(UBI_DEV_START) - 1, "%d", &devnum);
209         if (ret != 1)
210                 return -1;
211
212         return devnum;
213 }
214
215 static const char *ubi_get_volume_devname(const char *devname,
216                                           const char *volname)
217 {
218         char *volume_devname;
219         int volnum;
220         int devnum;
221         int ret;
222
223         devnum = ubi_get_devnum_by_devname(devname);
224         if (devnum < 0)
225                 return NULL;
226
227         volnum = ubi_get_volnum_by_name(devnum, volname);
228         if (volnum < 0)
229                 return NULL;
230
231         ret = asprintf(&volume_devname, "%s_%d", devname, volnum);
232         if (ret < 0)
233                 return NULL;
234
235 #ifdef DEBUG
236         fprintf(stderr, "Found ubi volume \"%s:%s\" -> %s\n",
237                 devname, volname, volume_devname);
238 #endif
239
240         return volume_devname;
241 }
242
243 static void ubi_check_dev(unsigned int dev_id)
244 {
245         char *devname = (char *)DEVNAME(dev_id);
246         char *pname;
247         const char *volname = NULL;
248         const char *volume_devname;
249
250         if (!is_ubi_devname(DEVNAME(dev_id)))
251                 return;
252
253         IS_UBI(dev_id) = 1;
254
255         for (pname = devname; *pname != '\0'; pname++) {
256                 if (*pname == ':') {
257                         *pname = '\0';
258                         volname = pname + 1;
259                         break;
260                 }
261         }
262
263         if (volname) {
264                 /* Let's find real volume device name */
265                 volume_devname = ubi_get_volume_devname(devname, volname);
266                 if (!volume_devname) {
267                         fprintf(stderr, "Didn't found ubi volume \"%s\"\n",
268                                 volname);
269                         return;
270                 }
271
272                 free(devname);
273                 DEVNAME(dev_id) = volume_devname;
274         }
275 }
276
277 static int ubi_update_start(int fd, int64_t bytes)
278 {
279         if (ioctl(fd, UBI_IOCVOLUP, &bytes))
280                 return -1;
281         return 0;
282 }
283
284 static int ubi_read(int fd, void *buf, size_t count)
285 {
286         ssize_t ret;
287
288         while (count > 0) {
289                 ret = read(fd, buf, count);
290                 if (ret > 0) {
291                         count -= ret;
292                         buf += ret;
293
294                         continue;
295                 }
296
297                 if (ret == 0) {
298                         /*
299                          * Happens in case of too short volume data size. If we
300                          * return error status we will fail it will be treated
301                          * as UBI device error.
302                          *
303                          * Leave catching this error to CRC check.
304                          */
305                         fprintf(stderr, "Warning: end of data on ubi volume\n");
306                         return 0;
307                 } else if (errno == EBADF) {
308                         /*
309                          * Happens in case of corrupted volume. The same as
310                          * above, we cannot return error now, as we will still
311                          * be able to successfully write environment later.
312                          */
313                         fprintf(stderr, "Warning: corrupted volume?\n");
314                         return 0;
315                 } else if (errno == EINTR) {
316                         continue;
317                 }
318
319                 fprintf(stderr, "Cannot read %u bytes from ubi volume, %s\n",
320                         (unsigned int)count, strerror(errno));
321                 return -1;
322         }
323
324         return 0;
325 }
326
327 static int ubi_write(int fd, const void *buf, size_t count)
328 {
329         ssize_t ret;
330
331         while (count > 0) {
332                 ret = write(fd, buf, count);
333                 if (ret <= 0) {
334                         if (ret < 0 && errno == EINTR)
335                                 continue;
336
337                         fprintf(stderr, "Cannot write %u bytes to ubi volume\n",
338                                 (unsigned int)count);
339                         return -1;
340                 }
341
342                 count -= ret;
343                 buf += ret;
344         }
345
346         return 0;
347 }
348
349 static int flash_io(int mode);
350 static int parse_config(struct env_opts *opts);
351
352 #if defined(CONFIG_FILE)
353 static int get_config(char *);
354 #endif
355
356 static char *skip_chars(char *s)
357 {
358         for (; *s != '\0'; s++) {
359                 if (isblank(*s) || *s == '=')
360                         return s;
361         }
362         return NULL;
363 }
364
365 static char *skip_blanks(char *s)
366 {
367         for (; *s != '\0'; s++) {
368                 if (!isblank(*s))
369                         return s;
370         }
371         return NULL;
372 }
373
374 /*
375  * s1 is either a simple 'name', or a 'name=value' pair.
376  * s2 is a 'name=value' pair.
377  * If the names match, return the value of s2, else NULL.
378  */
379 static char *envmatch(char *s1, char *s2)
380 {
381         if (s1 == NULL || s2 == NULL)
382                 return NULL;
383
384         while (*s1 == *s2++)
385                 if (*s1++ == '=')
386                         return s2;
387         if (*s1 == '\0' && *(s2 - 1) == '=')
388                 return s2;
389         return NULL;
390 }
391
392 /**
393  * Search the environment for a variable.
394  * Return the value, if found, or NULL, if not found.
395  */
396 char *fw_getenv(char *name)
397 {
398         char *env, *nxt;
399
400         for (env = environment.data; *env; env = nxt + 1) {
401                 char *val;
402
403                 for (nxt = env; *nxt; ++nxt) {
404                         if (nxt >= &environment.data[ENV_SIZE]) {
405                                 fprintf(stderr, "## Error: "
406                                         "environment not terminated\n");
407                                 return NULL;
408                         }
409                 }
410                 val = envmatch(name, env);
411                 if (!val)
412                         continue;
413                 return val;
414         }
415         return NULL;
416 }
417
418 /*
419  * Search the default environment for a variable.
420  * Return the value, if found, or NULL, if not found.
421  */
422 char *fw_getdefenv(char *name)
423 {
424         char *env, *nxt;
425
426         for (env = default_environment; *env; env = nxt + 1) {
427                 char *val;
428
429                 for (nxt = env; *nxt; ++nxt) {
430                         if (nxt >= &default_environment[ENV_SIZE]) {
431                                 fprintf(stderr, "## Error: "
432                                         "default environment not terminated\n");
433                                 return NULL;
434                         }
435                 }
436                 val = envmatch(name, env);
437                 if (!val)
438                         continue;
439                 return val;
440         }
441         return NULL;
442 }
443
444 /*
445  * Print the current definition of one, or more, or all
446  * environment variables
447  */
448 int fw_printenv(int argc, char *argv[], int value_only, struct env_opts *opts)
449 {
450         int i, rc = 0;
451
452         if (value_only && argc != 1) {
453                 fprintf(stderr,
454                         "## Error: `-n'/`--noheader' option requires exactly one argument\n");
455                 return -1;
456         }
457
458         if (!opts)
459                 opts = &default_opts;
460
461         if (fw_env_open(opts))
462                 return -1;
463
464         if (argc == 0) {        /* Print all env variables  */
465                 char *env, *nxt;
466                 for (env = environment.data; *env; env = nxt + 1) {
467                         for (nxt = env; *nxt; ++nxt) {
468                                 if (nxt >= &environment.data[ENV_SIZE]) {
469                                         fprintf(stderr, "## Error: "
470                                                 "environment not terminated\n");
471                                         return -1;
472                                 }
473                         }
474
475                         printf("%s\n", env);
476                 }
477                 fw_env_close(opts);
478                 return 0;
479         }
480
481         for (i = 0; i < argc; ++i) {    /* print a subset of env variables */
482                 char *name = argv[i];
483                 char *val = NULL;
484
485                 val = fw_getenv(name);
486                 if (!val) {
487                         fprintf(stderr, "## Error: \"%s\" not defined\n", name);
488                         rc = -1;
489                         continue;
490                 }
491
492                 if (value_only) {
493                         puts(val);
494                         break;
495                 }
496
497                 printf("%s=%s\n", name, val);
498         }
499
500         fw_env_close(opts);
501
502         return rc;
503 }
504
505 int fw_env_flush(struct env_opts *opts)
506 {
507         if (!opts)
508                 opts = &default_opts;
509
510         if (!environment.dirty)
511                 return 0;
512
513         /*
514          * Update CRC
515          */
516         *environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
517
518         /* write environment back to flash */
519         if (flash_io(O_RDWR)) {
520                 fprintf(stderr, "Error: can't write fw_env to flash\n");
521                 return -1;
522         }
523
524         return 0;
525 }
526
527 /*
528  * Set/Clear a single variable in the environment.
529  * This is called in sequence to update the environment
530  * in RAM without updating the copy in flash after each set
531  */
532 int fw_env_write(char *name, char *value)
533 {
534         int len;
535         char *env, *nxt;
536         char *oldval = NULL;
537         int deleting, creating, overwriting;
538
539         /*
540          * search if variable with this name already exists
541          */
542         for (nxt = env = environment.data; *env; env = nxt + 1) {
543                 for (nxt = env; *nxt; ++nxt) {
544                         if (nxt >= &environment.data[ENV_SIZE]) {
545                                 fprintf(stderr, "## Error: "
546                                         "environment not terminated\n");
547                                 errno = EINVAL;
548                                 return -1;
549                         }
550                 }
551                 oldval = envmatch(name, env);
552                 if (oldval)
553                         break;
554         }
555
556         deleting = (oldval && !(value && strlen(value)));
557         creating = (!oldval && (value && strlen(value)));
558         overwriting = (oldval && (value && strlen(value) &&
559                                   strcmp(oldval, value)));
560
561         /* check for permission */
562         if (deleting) {
563                 if (env_flags_validate_varaccess(name,
564                     ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
565                         printf("Can't delete \"%s\"\n", name);
566                         errno = EROFS;
567                         return -1;
568                 }
569         } else if (overwriting) {
570                 if (env_flags_validate_varaccess(name,
571                     ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
572                         printf("Can't overwrite \"%s\"\n", name);
573                         errno = EROFS;
574                         return -1;
575                 } else if (env_flags_validate_varaccess(name,
576                            ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
577                         const char *defval = fw_getdefenv(name);
578
579                         if (defval == NULL)
580                                 defval = "";
581                         if (strcmp(oldval, defval)
582                             != 0) {
583                                 printf("Can't overwrite \"%s\"\n", name);
584                                 errno = EROFS;
585                                 return -1;
586                         }
587                 }
588         } else if (creating) {
589                 if (env_flags_validate_varaccess(name,
590                     ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
591                         printf("Can't create \"%s\"\n", name);
592                         errno = EROFS;
593                         return -1;
594                 }
595         } else
596                 /* Nothing to do */
597                 return 0;
598
599         environment.dirty = 1;
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 == -1) {
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 += rc;
960                 if (rc != readlen) {
961                         fprintf(stderr,
962                                 "Warning on %s: Attempted to read %zd bytes but got %d\n",
963                                 DEVNAME(dev), readlen, rc);
964                         readlen -= rc;
965                         block_seek += rc;
966                 } else {
967                         blockstart += blocklen;
968                         readlen = min(blocklen, count - processed);
969                         block_seek = 0;
970                 }
971         }
972
973         return processed;
974 }
975
976 /*
977  * Write count bytes from begin of environment, but stay within
978  * ENVSECTORS(dev) sectors of
979  * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
980  * erase and write the whole data at once.
981  */
982 static int flash_write_buf(int dev, int fd, void *buf, size_t count)
983 {
984         void *data;
985         struct erase_info_user erase;
986         size_t blocklen;        /* length of NAND block / NOR erase sector */
987         size_t erase_len;       /* whole area that can be erased - may include
988                                    bad blocks */
989         size_t erasesize;       /* erase / write length - one block on NAND,
990                                    whole area on NOR */
991         size_t processed = 0;   /* progress counter */
992         size_t write_total;     /* total size to actually write - excluding
993                                    bad blocks */
994         off_t erase_offset;     /* offset to the first erase block (aligned)
995                                    below offset */
996         off_t block_seek;       /* offset inside the erase block to the start
997                                    of the data */
998         loff_t blockstart;      /* running start of the current block -
999                                    MEMGETBADBLOCK needs 64 bits */
1000         int was_locked = 0;     /* flash lock flag */
1001         int rc;
1002
1003         /*
1004          * For mtd devices only offset and size of the environment do matter
1005          */
1006         if (DEVTYPE(dev) == MTD_ABSENT) {
1007                 blocklen = count;
1008                 erase_len = blocklen;
1009                 blockstart = DEVOFFSET(dev);
1010                 block_seek = 0;
1011                 write_total = blocklen;
1012         } else {
1013                 blocklen = DEVESIZE(dev);
1014
1015                 erase_offset = DEVOFFSET(dev);
1016
1017                 /* Maximum area we may use */
1018                 erase_len = environment_end(dev) - erase_offset;
1019
1020                 blockstart = erase_offset;
1021
1022                 /* Offset inside a block */
1023                 block_seek = DEVOFFSET(dev) - erase_offset;
1024
1025                 /*
1026                  * Data size we actually write: from the start of the block
1027                  * to the start of the data, then count bytes of data, and
1028                  * to the end of the block
1029                  */
1030                 write_total = ((block_seek + count + blocklen - 1) /
1031                                blocklen) * blocklen;
1032         }
1033
1034         /*
1035          * Support data anywhere within erase sectors: read out the complete
1036          * area to be erased, replace the environment image, write the whole
1037          * block back again.
1038          */
1039         if (write_total > count) {
1040                 data = malloc(erase_len);
1041                 if (!data) {
1042                         fprintf(stderr,
1043                                 "Cannot malloc %zu bytes: %s\n",
1044                                 erase_len, strerror(errno));
1045                         return -1;
1046                 }
1047
1048                 rc = flash_read_buf(dev, fd, data, write_total, erase_offset);
1049                 if (write_total != rc)
1050                         return -1;
1051
1052 #ifdef DEBUG
1053                 fprintf(stderr, "Preserving data ");
1054                 if (block_seek != 0)
1055                         fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
1056                 if (block_seek + count != write_total) {
1057                         if (block_seek != 0)
1058                                 fprintf(stderr, " and ");
1059                         fprintf(stderr, "0x%lx - 0x%lx",
1060                                 (unsigned long)block_seek + count,
1061                                 (unsigned long)write_total - 1);
1062                 }
1063                 fprintf(stderr, "\n");
1064 #endif
1065                 /* Overwrite the old environment */
1066                 memcpy(data + block_seek, buf, count);
1067         } else {
1068                 /*
1069                  * We get here, iff offset is block-aligned and count is a
1070                  * multiple of blocklen - see write_total calculation above
1071                  */
1072                 data = buf;
1073         }
1074
1075         if (DEVTYPE(dev) == MTD_NANDFLASH) {
1076                 /*
1077                  * NAND: calculate which blocks we are writing. We have
1078                  * to write one block at a time to skip bad blocks.
1079                  */
1080                 erasesize = blocklen;
1081         } else {
1082                 erasesize = erase_len;
1083         }
1084
1085         erase.length = erasesize;
1086
1087         /* This only runs once on NOR flash and SPI-dataflash */
1088         while (processed < write_total) {
1089                 rc = flash_bad_block(fd, DEVTYPE(dev), blockstart);
1090                 if (rc < 0)     /* block test failed */
1091                         return rc;
1092
1093                 if (blockstart + erasesize > environment_end(dev)) {
1094                         fprintf(stderr, "End of range reached, aborting\n");
1095                         return -1;
1096                 }
1097
1098                 if (rc) {       /* block is bad */
1099                         blockstart += blocklen;
1100                         continue;
1101                 }
1102
1103                 if (DEVTYPE(dev) != MTD_ABSENT) {
1104                         erase.start = blockstart;
1105                         was_locked = ioctl(fd, MEMISLOCKED, &erase);
1106                         /* treat any errors as unlocked flash */
1107                         if (was_locked < 0)
1108                                         was_locked = 0;
1109                         if (was_locked)
1110                                 ioctl(fd, MEMUNLOCK, &erase);
1111                         /* These do not need an explicit erase cycle */
1112                         if (DEVTYPE(dev) != MTD_DATAFLASH)
1113                                 if (ioctl(fd, MEMERASE, &erase) != 0) {
1114                                         fprintf(stderr,
1115                                                 "MTD erase error on %s: %s\n",
1116                                                 DEVNAME(dev), strerror(errno));
1117                                         return -1;
1118                                 }
1119                 }
1120
1121                 if (lseek(fd, blockstart, SEEK_SET) == -1) {
1122                         fprintf(stderr,
1123                                 "Seek error on %s: %s\n",
1124                                 DEVNAME(dev), strerror(errno));
1125                         return -1;
1126                 }
1127 #ifdef DEBUG
1128                 fprintf(stderr, "Write 0x%llx bytes at 0x%llx\n",
1129                         (unsigned long long)erasesize,
1130                         (unsigned long long)blockstart);
1131 #endif
1132                 if (write(fd, data + processed, erasesize) != erasesize) {
1133                         fprintf(stderr, "Write error on %s: %s\n",
1134                                 DEVNAME(dev), strerror(errno));
1135                         return -1;
1136                 }
1137
1138                 if (DEVTYPE(dev) != MTD_ABSENT) {
1139                         if (was_locked)
1140                                 ioctl(fd, MEMLOCK, &erase);
1141                 }
1142
1143                 processed += erasesize;
1144                 block_seek = 0;
1145                 blockstart += erasesize;
1146         }
1147
1148         if (write_total > count)
1149                 free(data);
1150
1151         return processed;
1152 }
1153
1154 /*
1155  * Set obsolete flag at offset - NOR flash only
1156  */
1157 static int flash_flag_obsolete(int dev, int fd, off_t offset)
1158 {
1159         int rc;
1160         struct erase_info_user erase;
1161         char tmp = ENV_REDUND_OBSOLETE;
1162         int was_locked; /* flash lock flag */
1163
1164         erase.start = DEVOFFSET(dev);
1165         erase.length = DEVESIZE(dev);
1166         /* This relies on the fact, that ENV_REDUND_OBSOLETE == 0 */
1167         rc = lseek(fd, offset, SEEK_SET);
1168         if (rc < 0) {
1169                 fprintf(stderr, "Cannot seek to set the flag on %s\n",
1170                         DEVNAME(dev));
1171                 return rc;
1172         }
1173         was_locked = ioctl(fd, MEMISLOCKED, &erase);
1174         /* treat any errors as unlocked flash */
1175         if (was_locked < 0)
1176                 was_locked = 0;
1177         if (was_locked)
1178                 ioctl(fd, MEMUNLOCK, &erase);
1179         rc = write(fd, &tmp, sizeof(tmp));
1180         if (was_locked)
1181                 ioctl(fd, MEMLOCK, &erase);
1182         if (rc < 0)
1183                 perror("Could not set obsolete flag");
1184
1185         return rc;
1186 }
1187
1188 static int flash_write(int fd_current, int fd_target, int dev_target)
1189 {
1190         int rc;
1191
1192         switch (environment.flag_scheme) {
1193         case FLAG_NONE:
1194                 break;
1195         case FLAG_INCREMENTAL:
1196                 (*environment.flags)++;
1197                 break;
1198         case FLAG_BOOLEAN:
1199                 *environment.flags = ENV_REDUND_ACTIVE;
1200                 break;
1201         default:
1202                 fprintf(stderr, "Unimplemented flash scheme %u\n",
1203                         environment.flag_scheme);
1204                 return -1;
1205         }
1206
1207 #ifdef DEBUG
1208         fprintf(stderr, "Writing new environment at 0x%llx on %s\n",
1209                 DEVOFFSET(dev_target), DEVNAME(dev_target));
1210 #endif
1211
1212         if (IS_UBI(dev_target)) {
1213                 if (ubi_update_start(fd_target, CUR_ENVSIZE) < 0)
1214                         return -1;
1215                 return ubi_write(fd_target, environment.image, CUR_ENVSIZE);
1216         }
1217
1218         rc = flash_write_buf(dev_target, fd_target, environment.image,
1219                              CUR_ENVSIZE);
1220         if (rc < 0)
1221                 return rc;
1222
1223         if (environment.flag_scheme == FLAG_BOOLEAN) {
1224                 /* Have to set obsolete flag */
1225                 off_t offset = DEVOFFSET(dev_current) +
1226                     offsetof(struct env_image_redundant, flags);
1227 #ifdef DEBUG
1228                 fprintf(stderr,
1229                         "Setting obsolete flag in environment at 0x%llx on %s\n",
1230                         DEVOFFSET(dev_current), DEVNAME(dev_current));
1231 #endif
1232                 flash_flag_obsolete(dev_current, fd_current, offset);
1233         }
1234
1235         return 0;
1236 }
1237
1238 static int flash_read(int fd)
1239 {
1240         int rc;
1241
1242         if (IS_UBI(dev_current)) {
1243                 DEVTYPE(dev_current) = MTD_ABSENT;
1244
1245                 return ubi_read(fd, environment.image, CUR_ENVSIZE);
1246         }
1247
1248         rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
1249                             DEVOFFSET(dev_current));
1250         if (rc != CUR_ENVSIZE)
1251                 return -1;
1252
1253         return 0;
1254 }
1255
1256 static int flash_open_tempfile(const char **dname, const char **target_temp)
1257 {
1258         char *dup_name = strdup(DEVNAME(dev_current));
1259         char *temp_name = NULL;
1260         int rc = -1;
1261
1262         if (!dup_name)
1263                 return -1;
1264
1265         *dname = dirname(dup_name);
1266         if (!*dname)
1267                 goto err;
1268
1269         rc = asprintf(&temp_name, "%s/XXXXXX", *dname);
1270         if (rc == -1)
1271                 goto err;
1272
1273         rc = mkstemp(temp_name);
1274         if (rc == -1) {
1275                 /* fall back to in place write */
1276                 fprintf(stderr,
1277                         "Can't create %s: %s\n", temp_name, strerror(errno));
1278                 free(temp_name);
1279         } else {
1280                 *target_temp = temp_name;
1281                 /* deliberately leak dup_name as dname /might/ point into
1282                  * it and we need it for our caller
1283                  */
1284                 dup_name = NULL;
1285         }
1286
1287 err:
1288         if (dup_name)
1289                 free(dup_name);
1290
1291         return rc;
1292 }
1293
1294 static int flash_io_write(int fd_current)
1295 {
1296         int fd_target = -1, rc, dev_target;
1297         const char *dname, *target_temp = NULL;
1298
1299         if (have_redund_env) {
1300                 /* switch to next partition for writing */
1301                 dev_target = !dev_current;
1302                 /* dev_target: fd_target, erase_target */
1303                 fd_target = open(DEVNAME(dev_target), O_RDWR);
1304                 if (fd_target < 0) {
1305                         fprintf(stderr,
1306                                 "Can't open %s: %s\n",
1307                                 DEVNAME(dev_target), strerror(errno));
1308                         rc = -1;
1309                         goto exit;
1310                 }
1311         } else {
1312                 struct stat sb;
1313
1314                 if (fstat(fd_current, &sb) == 0 && S_ISREG(sb.st_mode)) {
1315                         /* if any part of flash_open_tempfile() fails we fall
1316                          * back to in-place writes
1317                          */
1318                         fd_target = flash_open_tempfile(&dname, &target_temp);
1319                 }
1320                 dev_target = dev_current;
1321                 if (fd_target == -1)
1322                         fd_target = fd_current;
1323         }
1324
1325         rc = flash_write(fd_current, fd_target, dev_target);
1326
1327         if (fsync(fd_current) && !(errno == EINVAL || errno == EROFS)) {
1328                 fprintf(stderr,
1329                         "fsync failed on %s: %s\n",
1330                         DEVNAME(dev_current), strerror(errno));
1331         }
1332
1333         if (fd_current != fd_target) {
1334                 if (fsync(fd_target) &&
1335                     !(errno == EINVAL || errno == EROFS)) {
1336                         fprintf(stderr,
1337                                 "fsync failed on %s: %s\n",
1338                                 DEVNAME(dev_current), strerror(errno));
1339                 }
1340
1341                 if (close(fd_target)) {
1342                         fprintf(stderr,
1343                                 "I/O error on %s: %s\n",
1344                                 DEVNAME(dev_target), strerror(errno));
1345                         rc = -1;
1346                 }
1347
1348                 if (rc >= 0 && target_temp) {
1349                         int dir_fd;
1350
1351                         dir_fd = open(dname, O_DIRECTORY | O_RDONLY);
1352                         if (dir_fd == -1)
1353                                 fprintf(stderr,
1354                                         "Can't open %s: %s\n",
1355                                         dname, strerror(errno));
1356
1357                         if (rename(target_temp, DEVNAME(dev_target))) {
1358                                 fprintf(stderr,
1359                                         "rename failed %s => %s: %s\n",
1360                                         target_temp, DEVNAME(dev_target),
1361                                         strerror(errno));
1362                                 rc = -1;
1363                         }
1364
1365                         if (dir_fd != -1 && fsync(dir_fd))
1366                                 fprintf(stderr,
1367                                         "fsync failed on %s: %s\n",
1368                                         dname, strerror(errno));
1369
1370                         if (dir_fd != -1 && close(dir_fd))
1371                                 fprintf(stderr,
1372                                         "I/O error on %s: %s\n",
1373                                         dname, strerror(errno));
1374                 }
1375         }
1376  exit:
1377         return rc;
1378 }
1379
1380 static int flash_io(int mode)
1381 {
1382         int fd_current, rc;
1383
1384         /* dev_current: fd_current, erase_current */
1385         fd_current = open(DEVNAME(dev_current), mode);
1386         if (fd_current < 0) {
1387                 fprintf(stderr,
1388                         "Can't open %s: %s\n",
1389                         DEVNAME(dev_current), strerror(errno));
1390                 return -1;
1391         }
1392
1393         if (mode == O_RDWR) {
1394                 rc = flash_io_write(fd_current);
1395         } else {
1396                 rc = flash_read(fd_current);
1397         }
1398
1399         if (close(fd_current)) {
1400                 fprintf(stderr,
1401                         "I/O error on %s: %s\n",
1402                         DEVNAME(dev_current), strerror(errno));
1403                 return -1;
1404         }
1405
1406         return rc;
1407 }
1408
1409 /*
1410  * Prevent confusion if running from erased flash memory
1411  */
1412 int fw_env_open(struct env_opts *opts)
1413 {
1414         int crc0, crc0_ok;
1415         unsigned char flag0;
1416         void *addr0 = NULL;
1417
1418         int crc1, crc1_ok;
1419         unsigned char flag1;
1420         void *addr1 = NULL;
1421
1422         int ret;
1423
1424         struct env_image_single *single;
1425         struct env_image_redundant *redundant;
1426
1427         if (!opts)
1428                 opts = &default_opts;
1429
1430         if (parse_config(opts)) /* should fill envdevices */
1431                 return -EINVAL;
1432
1433         addr0 = calloc(1, CUR_ENVSIZE);
1434         if (addr0 == NULL) {
1435                 fprintf(stderr,
1436                         "Not enough memory for environment (%ld bytes)\n",
1437                         CUR_ENVSIZE);
1438                 ret = -ENOMEM;
1439                 goto open_cleanup;
1440         }
1441
1442         /* read environment from FLASH to local buffer */
1443         environment.image = addr0;
1444
1445         if (have_redund_env) {
1446                 redundant = addr0;
1447                 environment.crc = &redundant->crc;
1448                 environment.flags = &redundant->flags;
1449                 environment.data = redundant->data;
1450         } else {
1451                 single = addr0;
1452                 environment.crc = &single->crc;
1453                 environment.flags = NULL;
1454                 environment.data = single->data;
1455         }
1456
1457         dev_current = 0;
1458         if (flash_io(O_RDONLY)) {
1459                 ret = -EIO;
1460                 goto open_cleanup;
1461         }
1462
1463         crc0 = crc32(0, (uint8_t *)environment.data, ENV_SIZE);
1464
1465         crc0_ok = (crc0 == *environment.crc);
1466         if (!have_redund_env) {
1467                 if (!crc0_ok) {
1468                         fprintf(stderr,
1469                                 "Warning: Bad CRC, using default environment\n");
1470                         memcpy(environment.data, default_environment,
1471                                sizeof(default_environment));
1472                         environment.dirty = 1;
1473                 }
1474         } else {
1475                 flag0 = *environment.flags;
1476
1477                 dev_current = 1;
1478                 addr1 = calloc(1, CUR_ENVSIZE);
1479                 if (addr1 == NULL) {
1480                         fprintf(stderr,
1481                                 "Not enough memory for environment (%ld bytes)\n",
1482                                 CUR_ENVSIZE);
1483                         ret = -ENOMEM;
1484                         goto open_cleanup;
1485                 }
1486                 redundant = addr1;
1487
1488                 /*
1489                  * have to set environment.image for flash_read(), careful -
1490                  * other pointers in environment still point inside addr0
1491                  */
1492                 environment.image = addr1;
1493                 if (flash_io(O_RDONLY)) {
1494                         ret = -EIO;
1495                         goto open_cleanup;
1496                 }
1497
1498                 /* Check flag scheme compatibility */
1499                 if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1500                     DEVTYPE(!dev_current) == MTD_NORFLASH) {
1501                         environment.flag_scheme = FLAG_BOOLEAN;
1502                 } else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1503                            DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1504                         environment.flag_scheme = FLAG_INCREMENTAL;
1505                 } else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1506                            DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1507                         environment.flag_scheme = FLAG_BOOLEAN;
1508                 } else if (DEVTYPE(dev_current) == MTD_UBIVOLUME &&
1509                            DEVTYPE(!dev_current) == MTD_UBIVOLUME) {
1510                         environment.flag_scheme = FLAG_INCREMENTAL;
1511                 } else if (DEVTYPE(dev_current) == MTD_ABSENT &&
1512                            DEVTYPE(!dev_current) == MTD_ABSENT &&
1513                            IS_UBI(dev_current) == IS_UBI(!dev_current)) {
1514                         environment.flag_scheme = FLAG_INCREMENTAL;
1515                 } else {
1516                         fprintf(stderr, "Incompatible flash types!\n");
1517                         ret = -EINVAL;
1518                         goto open_cleanup;
1519                 }
1520
1521                 crc1 = crc32(0, (uint8_t *)redundant->data, ENV_SIZE);
1522
1523                 crc1_ok = (crc1 == redundant->crc);
1524                 flag1 = redundant->flags;
1525
1526                 /*
1527                  * environment.data still points to ((struct
1528                  * env_image_redundant *)addr0)->data. If the two
1529                  * environments differ, or one has bad crc, force a
1530                  * write-out by marking the environment dirty.
1531                  */
1532                 if (memcmp(environment.data, redundant->data, ENV_SIZE) ||
1533                     !crc0_ok || !crc1_ok)
1534                         environment.dirty = 1;
1535
1536                 if (crc0_ok && !crc1_ok) {
1537                         dev_current = 0;
1538                 } else if (!crc0_ok && crc1_ok) {
1539                         dev_current = 1;
1540                 } else if (!crc0_ok && !crc1_ok) {
1541                         fprintf(stderr,
1542                                 "Warning: Bad CRC, using default environment\n");
1543                         memcpy(environment.data, default_environment,
1544                                sizeof(default_environment));
1545                         environment.dirty = 1;
1546                         dev_current = 0;
1547                 } else {
1548                         switch (environment.flag_scheme) {
1549                         case FLAG_BOOLEAN:
1550                                 if (flag0 == ENV_REDUND_ACTIVE &&
1551                                     flag1 == ENV_REDUND_OBSOLETE) {
1552                                         dev_current = 0;
1553                                 } else if (flag0 == ENV_REDUND_OBSOLETE &&
1554                                            flag1 == ENV_REDUND_ACTIVE) {
1555                                         dev_current = 1;
1556                                 } else if (flag0 == flag1) {
1557                                         dev_current = 0;
1558                                 } else if (flag0 == 0xFF) {
1559                                         dev_current = 0;
1560                                 } else if (flag1 == 0xFF) {
1561                                         dev_current = 1;
1562                                 } else {
1563                                         dev_current = 0;
1564                                 }
1565                                 break;
1566                         case FLAG_INCREMENTAL:
1567                                 if (flag0 == 255 && flag1 == 0)
1568                                         dev_current = 1;
1569                                 else if ((flag1 == 255 && flag0 == 0) ||
1570                                          flag0 >= flag1)
1571                                         dev_current = 0;
1572                                 else    /* flag1 > flag0 */
1573                                         dev_current = 1;
1574                                 break;
1575                         default:
1576                                 fprintf(stderr, "Unknown flag scheme %u\n",
1577                                         environment.flag_scheme);
1578                                 return -1;
1579                         }
1580                 }
1581
1582                 /*
1583                  * If we are reading, we don't need the flag and the CRC any
1584                  * more, if we are writing, we will re-calculate CRC and update
1585                  * flags before writing out
1586                  */
1587                 if (dev_current) {
1588                         environment.image = addr1;
1589                         environment.crc = &redundant->crc;
1590                         environment.flags = &redundant->flags;
1591                         environment.data = redundant->data;
1592                         free(addr0);
1593                 } else {
1594                         environment.image = addr0;
1595                         /* Other pointers are already set */
1596                         free(addr1);
1597                 }
1598 #ifdef DEBUG
1599                 fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1600 #endif
1601         }
1602         return 0;
1603
1604  open_cleanup:
1605         if (addr0)
1606                 free(addr0);
1607
1608         if (addr1)
1609                 free(addr1);
1610
1611         return ret;
1612 }
1613
1614 /*
1615  * Simply free allocated buffer with environment
1616  */
1617 int fw_env_close(struct env_opts *opts)
1618 {
1619         if (environment.image)
1620                 free(environment.image);
1621
1622         environment.image = NULL;
1623
1624         return 0;
1625 }
1626
1627 static int check_device_config(int dev)
1628 {
1629         struct stat st;
1630         int32_t lnum = 0;
1631         int fd, rc = 0;
1632
1633         /* Fills in IS_UBI(), converts DEVNAME() with ubi volume name */
1634         ubi_check_dev(dev);
1635
1636         fd = open(DEVNAME(dev), O_RDONLY);
1637         if (fd < 0) {
1638                 fprintf(stderr,
1639                         "Cannot open %s: %s\n", DEVNAME(dev), strerror(errno));
1640                 return -1;
1641         }
1642
1643         rc = fstat(fd, &st);
1644         if (rc < 0) {
1645                 fprintf(stderr, "Cannot stat the file %s\n", DEVNAME(dev));
1646                 goto err;
1647         }
1648
1649         if (IS_UBI(dev)) {
1650                 rc = ioctl(fd, UBI_IOCEBISMAP, &lnum);
1651                 if (rc < 0) {
1652                         fprintf(stderr, "Cannot get UBI information for %s\n",
1653                                 DEVNAME(dev));
1654                         goto err;
1655                 }
1656         } else if (S_ISCHR(st.st_mode)) {
1657                 struct mtd_info_user mtdinfo;
1658                 rc = ioctl(fd, MEMGETINFO, &mtdinfo);
1659                 if (rc < 0) {
1660                         fprintf(stderr, "Cannot get MTD information for %s\n",
1661                                 DEVNAME(dev));
1662                         goto err;
1663                 }
1664                 if (mtdinfo.type != MTD_NORFLASH &&
1665                     mtdinfo.type != MTD_NANDFLASH &&
1666                     mtdinfo.type != MTD_DATAFLASH &&
1667                     mtdinfo.type != MTD_UBIVOLUME) {
1668                         fprintf(stderr, "Unsupported flash type %u on %s\n",
1669                                 mtdinfo.type, DEVNAME(dev));
1670                         goto err;
1671                 }
1672                 DEVTYPE(dev) = mtdinfo.type;
1673                 if (DEVESIZE(dev) == 0 && ENVSECTORS(dev) == 0 &&
1674                     mtdinfo.type == MTD_NORFLASH)
1675                         DEVESIZE(dev) = mtdinfo.erasesize;
1676                 if (DEVESIZE(dev) == 0)
1677                         /* Assume the erase size is the same as the env-size */
1678                         DEVESIZE(dev) = ENVSIZE(dev);
1679         } else {
1680                 uint64_t size;
1681                 DEVTYPE(dev) = MTD_ABSENT;
1682                 if (DEVESIZE(dev) == 0)
1683                         /* Assume the erase size to be 512 bytes */
1684                         DEVESIZE(dev) = 0x200;
1685
1686                 /*
1687                  * Check for negative offsets, treat it as backwards offset
1688                  * from the end of the block device
1689                  */
1690                 if (DEVOFFSET(dev) < 0) {
1691                         rc = ioctl(fd, BLKGETSIZE64, &size);
1692                         if (rc < 0) {
1693                                 fprintf(stderr,
1694                                         "Could not get block device size on %s\n",
1695                                         DEVNAME(dev));
1696                                 goto err;
1697                         }
1698
1699                         DEVOFFSET(dev) = DEVOFFSET(dev) + size;
1700 #ifdef DEBUG
1701                         fprintf(stderr,
1702                                 "Calculated device offset 0x%llx on %s\n",
1703                                 DEVOFFSET(dev), DEVNAME(dev));
1704 #endif
1705                 }
1706         }
1707
1708         if (ENVSECTORS(dev) == 0)
1709                 /* Assume enough sectors to cover the environment */
1710                 ENVSECTORS(dev) = DIV_ROUND_UP(ENVSIZE(dev), DEVESIZE(dev));
1711
1712         if (DEVOFFSET(dev) % DEVESIZE(dev) != 0) {
1713                 fprintf(stderr,
1714                         "Environment does not start on (erase) block boundary\n");
1715                 errno = EINVAL;
1716                 return -1;
1717         }
1718
1719         if (ENVSIZE(dev) > ENVSECTORS(dev) * DEVESIZE(dev)) {
1720                 fprintf(stderr,
1721                         "Environment does not fit into available sectors\n");
1722                 errno = EINVAL;
1723                 return -1;
1724         }
1725
1726  err:
1727         close(fd);
1728         return rc;
1729 }
1730
1731 static int parse_config(struct env_opts *opts)
1732 {
1733         int rc;
1734
1735         if (!opts)
1736                 opts = &default_opts;
1737
1738 #if defined(CONFIG_FILE)
1739         /* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1740         if (get_config(opts->config_file)) {
1741                 fprintf(stderr, "Cannot parse config file '%s': %m\n",
1742                         opts->config_file);
1743                 return -1;
1744         }
1745 #else
1746         DEVNAME(0) = DEVICE1_NAME;
1747         DEVOFFSET(0) = DEVICE1_OFFSET;
1748         ENVSIZE(0) = ENV1_SIZE;
1749
1750         /* Set defaults for DEVESIZE, ENVSECTORS later once we
1751          * know DEVTYPE
1752          */
1753 #ifdef DEVICE1_ESIZE
1754         DEVESIZE(0) = DEVICE1_ESIZE;
1755 #endif
1756 #ifdef DEVICE1_ENVSECTORS
1757         ENVSECTORS(0) = DEVICE1_ENVSECTORS;
1758 #endif
1759
1760 #ifdef HAVE_REDUND
1761         DEVNAME(1) = DEVICE2_NAME;
1762         DEVOFFSET(1) = DEVICE2_OFFSET;
1763         ENVSIZE(1) = ENV2_SIZE;
1764
1765         /* Set defaults for DEVESIZE, ENVSECTORS later once we
1766          * know DEVTYPE
1767          */
1768 #ifdef DEVICE2_ESIZE
1769         DEVESIZE(1) = DEVICE2_ESIZE;
1770 #endif
1771 #ifdef DEVICE2_ENVSECTORS
1772         ENVSECTORS(1) = DEVICE2_ENVSECTORS;
1773 #endif
1774         have_redund_env = 1;
1775 #endif
1776 #endif
1777         rc = check_device_config(0);
1778         if (rc < 0)
1779                 return rc;
1780
1781         if (have_redund_env) {
1782                 rc = check_device_config(1);
1783                 if (rc < 0)
1784                         return rc;
1785
1786                 if (ENVSIZE(0) != ENVSIZE(1)) {
1787                         fprintf(stderr,
1788                                 "Redundant environments have unequal size\n");
1789                         return -1;
1790                 }
1791         }
1792
1793         usable_envsize = CUR_ENVSIZE - sizeof(uint32_t);
1794         if (have_redund_env)
1795                 usable_envsize -= sizeof(char);
1796
1797         return 0;
1798 }
1799
1800 #if defined(CONFIG_FILE)
1801 static int get_config(char *fname)
1802 {
1803         FILE *fp;
1804         int i = 0;
1805         int rc;
1806         char *line = NULL;
1807         size_t linesize = 0;
1808         char *devname;
1809
1810         fp = fopen(fname, "r");
1811         if (fp == NULL)
1812                 return -1;
1813
1814         while (i < 2 && getline(&line, &linesize, fp) != -1) {
1815                 /* Skip comment strings */
1816                 if (line[0] == '#')
1817                         continue;
1818
1819                 rc = sscanf(line, "%ms %lli %lx %lx %lx",
1820                             &devname,
1821                             &DEVOFFSET(i),
1822                             &ENVSIZE(i), &DEVESIZE(i), &ENVSECTORS(i));
1823
1824                 if (rc < 3)
1825                         continue;
1826
1827                 DEVNAME(i) = devname;
1828
1829                 /* Set defaults for DEVESIZE, ENVSECTORS later once we
1830                  * know DEVTYPE
1831                  */
1832
1833                 i++;
1834         }
1835         free(line);
1836         fclose(fp);
1837
1838         have_redund_env = i - 1;
1839         if (!i) {               /* No valid entries found */
1840                 errno = EINVAL;
1841                 return -1;
1842         } else
1843                 return 0;
1844 }
1845 #endif