xref: /openbmc/u-boot/tools/env/fw_env.c (revision 22f4442d12a3833e29b6580f6cf9bc0e55340504)
1 /*
2  * (C) Copyright 2000-2010
3  * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
4  *
5  * (C) Copyright 2008
6  * Guennadi Liakhovetski, DENX Software Engineering, lg@denx.de.
7  *
8  * See file CREDITS for list of people who contributed to this
9  * project.
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License as
13  * published by the Free Software Foundation; either version 2 of
14  * the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
24  * MA 02111-1307 USA
25  */
26 
27 #include <errno.h>
28 #include <env_flags.h>
29 #include <fcntl.h>
30 #include <linux/stringify.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <stddef.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #include <sys/ioctl.h>
37 #include <sys/stat.h>
38 #include <unistd.h>
39 
40 #ifdef MTD_OLD
41 # include <stdint.h>
42 # include <linux/mtd/mtd.h>
43 #else
44 # define  __user	/* nothing */
45 # include <mtd/mtd-user.h>
46 #endif
47 
48 #include "fw_env.h"
49 
50 #define WHITESPACE(c) ((c == '\t') || (c == ' '))
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 	char devname[16];		/* Device name */
60 	ulong 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 };
66 
67 static struct envdev_s envdevices[2] =
68 {
69 	{
70 		.mtd_type = MTD_ABSENT,
71 	}, {
72 		.mtd_type = MTD_ABSENT,
73 	},
74 };
75 static int dev_current;
76 
77 #define DEVNAME(i)    envdevices[(i)].devname
78 #define DEVOFFSET(i)  envdevices[(i)].devoff
79 #define ENVSIZE(i)    envdevices[(i)].env_size
80 #define DEVESIZE(i)   envdevices[(i)].erase_size
81 #define ENVSECTORS(i) envdevices[(i)].env_sectors
82 #define DEVTYPE(i)    envdevices[(i)].mtd_type
83 
84 #define CUR_ENVSIZE ENVSIZE(dev_current)
85 
86 #define ENV_SIZE      getenvsize()
87 
88 struct env_image_single {
89 	uint32_t	crc;	/* CRC32 over data bytes    */
90 	char		data[];
91 };
92 
93 struct env_image_redundant {
94 	uint32_t	crc;	/* CRC32 over data bytes    */
95 	unsigned char	flags;	/* active or obsolete */
96 	char		data[];
97 };
98 
99 enum flag_scheme {
100 	FLAG_NONE,
101 	FLAG_BOOLEAN,
102 	FLAG_INCREMENTAL,
103 };
104 
105 struct environment {
106 	void			*image;
107 	uint32_t		*crc;
108 	unsigned char		*flags;
109 	char			*data;
110 	enum flag_scheme	flag_scheme;
111 };
112 
113 static struct environment environment = {
114 	.flag_scheme = FLAG_NONE,
115 };
116 
117 static int HaveRedundEnv = 0;
118 
119 static unsigned char active_flag = 1;
120 /* obsolete_flag must be 0 to efficiently set it on NOR flash without erasing */
121 static unsigned char obsolete_flag = 0;
122 
123 #define DEFAULT_ENV_INSTANCE_STATIC
124 #include <env_default.h>
125 
126 static int flash_io (int mode);
127 static char *envmatch (char * s1, char * s2);
128 static int parse_config (void);
129 
130 #if defined(CONFIG_FILE)
131 static int get_config (char *);
132 #endif
133 static inline ulong getenvsize (void)
134 {
135 	ulong rc = CUR_ENVSIZE - sizeof(long);
136 
137 	if (HaveRedundEnv)
138 		rc -= sizeof (char);
139 	return rc;
140 }
141 
142 static char *fw_string_blank(char *s, int noblank)
143 {
144 	int i;
145 	int len = strlen(s);
146 
147 	for (i = 0; i < len; i++, s++) {
148 		if ((noblank && !WHITESPACE(*s)) ||
149 			(!noblank && WHITESPACE(*s)))
150 			break;
151 	}
152 	if (i == len)
153 		return NULL;
154 
155 	return s;
156 }
157 
158 /*
159  * Search the environment for a variable.
160  * Return the value, if found, or NULL, if not found.
161  */
162 char *fw_getenv (char *name)
163 {
164 	char *env, *nxt;
165 
166 	for (env = environment.data; *env; env = nxt + 1) {
167 		char *val;
168 
169 		for (nxt = env; *nxt; ++nxt) {
170 			if (nxt >= &environment.data[ENV_SIZE]) {
171 				fprintf (stderr, "## Error: "
172 					"environment not terminated\n");
173 				return NULL;
174 			}
175 		}
176 		val = envmatch (name, env);
177 		if (!val)
178 			continue;
179 		return val;
180 	}
181 	return NULL;
182 }
183 
184 /*
185  * Search the default environment for a variable.
186  * Return the value, if found, or NULL, if not found.
187  */
188 char *fw_getdefenv(char *name)
189 {
190 	char *env, *nxt;
191 
192 	for (env = default_environment; *env; env = nxt + 1) {
193 		char *val;
194 
195 		for (nxt = env; *nxt; ++nxt) {
196 			if (nxt >= &default_environment[ENV_SIZE]) {
197 				fprintf(stderr, "## Error: "
198 					"default environment not terminated\n");
199 				return NULL;
200 			}
201 		}
202 		val = envmatch(name, env);
203 		if (!val)
204 			continue;
205 		return val;
206 	}
207 	return NULL;
208 }
209 
210 /*
211  * Print the current definition of one, or more, or all
212  * environment variables
213  */
214 int fw_printenv (int argc, char *argv[])
215 {
216 	char *env, *nxt;
217 	int i, n_flag;
218 	int rc = 0;
219 
220 	if (fw_env_open())
221 		return -1;
222 
223 	if (argc == 1) {		/* Print all env variables  */
224 		for (env = environment.data; *env; env = nxt + 1) {
225 			for (nxt = env; *nxt; ++nxt) {
226 				if (nxt >= &environment.data[ENV_SIZE]) {
227 					fprintf (stderr, "## Error: "
228 						"environment not terminated\n");
229 					return -1;
230 				}
231 			}
232 
233 			printf ("%s\n", env);
234 		}
235 		return 0;
236 	}
237 
238 	if (strcmp (argv[1], "-n") == 0) {
239 		n_flag = 1;
240 		++argv;
241 		--argc;
242 		if (argc != 2) {
243 			fprintf (stderr, "## Error: "
244 				"`-n' option requires exactly one argument\n");
245 			return -1;
246 		}
247 	} else {
248 		n_flag = 0;
249 	}
250 
251 	for (i = 1; i < argc; ++i) {	/* print single env variables   */
252 		char *name = argv[i];
253 		char *val = NULL;
254 
255 		for (env = environment.data; *env; env = nxt + 1) {
256 
257 			for (nxt = env; *nxt; ++nxt) {
258 				if (nxt >= &environment.data[ENV_SIZE]) {
259 					fprintf (stderr, "## Error: "
260 						"environment not terminated\n");
261 					return -1;
262 				}
263 			}
264 			val = envmatch (name, env);
265 			if (val) {
266 				if (!n_flag) {
267 					fputs (name, stdout);
268 					putc ('=', stdout);
269 				}
270 				puts (val);
271 				break;
272 			}
273 		}
274 		if (!val) {
275 			fprintf (stderr, "## Error: \"%s\" not defined\n", name);
276 			rc = -1;
277 		}
278 	}
279 
280 	return rc;
281 }
282 
283 int fw_env_close(void)
284 {
285 	/*
286 	 * Update CRC
287 	 */
288 	*environment.crc = crc32(0, (uint8_t *) environment.data, ENV_SIZE);
289 
290 	/* write environment back to flash */
291 	if (flash_io(O_RDWR)) {
292 		fprintf(stderr,
293 			"Error: can't write fw_env to flash\n");
294 			return -1;
295 	}
296 
297 	return 0;
298 }
299 
300 
301 /*
302  * Set/Clear a single variable in the environment.
303  * This is called in sequence to update the environment
304  * in RAM without updating the copy in flash after each set
305  */
306 int fw_env_write(char *name, char *value)
307 {
308 	int len;
309 	char *env, *nxt;
310 	char *oldval = NULL;
311 	int deleting, creating, overwriting;
312 
313 	/*
314 	 * search if variable with this name already exists
315 	 */
316 	for (nxt = env = environment.data; *env; env = nxt + 1) {
317 		for (nxt = env; *nxt; ++nxt) {
318 			if (nxt >= &environment.data[ENV_SIZE]) {
319 				fprintf(stderr, "## Error: "
320 					"environment not terminated\n");
321 				errno = EINVAL;
322 				return -1;
323 			}
324 		}
325 		if ((oldval = envmatch (name, env)) != NULL)
326 			break;
327 	}
328 
329 	deleting = (oldval && !(value && strlen(value)));
330 	creating = (!oldval && (value && strlen(value)));
331 	overwriting = (oldval && (value && strlen(value)));
332 
333 	/* check for permission */
334 	if (deleting) {
335 		if (env_flags_validate_varaccess(name,
336 		    ENV_FLAGS_VARACCESS_PREVENT_DELETE)) {
337 			printf("Can't delete \"%s\"\n", name);
338 			errno = EROFS;
339 			return -1;
340 		}
341 	} else if (overwriting) {
342 		if (env_flags_validate_varaccess(name,
343 		    ENV_FLAGS_VARACCESS_PREVENT_OVERWR)) {
344 			printf("Can't overwrite \"%s\"\n", name);
345 			errno = EROFS;
346 			return -1;
347 		} else if (env_flags_validate_varaccess(name,
348 		    ENV_FLAGS_VARACCESS_PREVENT_NONDEF_OVERWR)) {
349 			const char *defval = fw_getdefenv(name);
350 
351 			if (defval == NULL)
352 				defval = "";
353 			if (strcmp(oldval, defval)
354 			    != 0) {
355 				printf("Can't overwrite \"%s\"\n", name);
356 				errno = EROFS;
357 				return -1;
358 			}
359 		}
360 	} else if (creating) {
361 		if (env_flags_validate_varaccess(name,
362 		    ENV_FLAGS_VARACCESS_PREVENT_CREATE)) {
363 			printf("Can't create \"%s\"\n", name);
364 			errno = EROFS;
365 			return -1;
366 		}
367 	} else
368 		/* Nothing to do */
369 		return 0;
370 
371 	if (deleting || overwriting) {
372 		if (*++nxt == '\0') {
373 			*env = '\0';
374 		} else {
375 			for (;;) {
376 				*env = *nxt++;
377 				if ((*env == '\0') && (*nxt == '\0'))
378 					break;
379 				++env;
380 			}
381 		}
382 		*++env = '\0';
383 	}
384 
385 	/* Delete only ? */
386 	if (!value || !strlen(value))
387 		return 0;
388 
389 	/*
390 	 * Append new definition at the end
391 	 */
392 	for (env = environment.data; *env || *(env + 1); ++env);
393 	if (env > environment.data)
394 		++env;
395 	/*
396 	 * Overflow when:
397 	 * "name" + "=" + "val" +"\0\0"  > CUR_ENVSIZE - (env-environment)
398 	 */
399 	len = strlen (name) + 2;
400 	/* add '=' for first arg, ' ' for all others */
401 	len += strlen(value) + 1;
402 
403 	if (len > (&environment.data[ENV_SIZE] - env)) {
404 		fprintf (stderr,
405 			"Error: environment overflow, \"%s\" deleted\n",
406 			name);
407 		return -1;
408 	}
409 
410 	while ((*env = *name++) != '\0')
411 		env++;
412 	*env = '=';
413 	while ((*++env = *value++) != '\0')
414 		;
415 
416 	/* end is marked with double '\0' */
417 	*++env = '\0';
418 
419 	return 0;
420 }
421 
422 /*
423  * Deletes or sets environment variables. Returns -1 and sets errno error codes:
424  * 0	  - OK
425  * EINVAL - need at least 1 argument
426  * EROFS  - certain variables ("ethaddr", "serial#") cannot be
427  *	    modified or deleted
428  *
429  */
430 int fw_setenv(int argc, char *argv[])
431 {
432 	int i, len;
433 	char *name;
434 	char *value = NULL;
435 
436 	if (argc < 2) {
437 		errno = EINVAL;
438 		return -1;
439 	}
440 
441 	if (fw_env_open()) {
442 		fprintf(stderr, "Error: environment not initialized\n");
443 		return -1;
444 	}
445 
446 	name = argv[1];
447 
448 	if (env_flags_validate_env_set_params(argc, argv) < 0)
449 		return 1;
450 
451 	len = 0;
452 	for (i = 2; i < argc; ++i) {
453 		char *val = argv[i];
454 		size_t val_len = strlen(val);
455 
456 		if (value)
457 			value[len - 1] = ' ';
458 		value = realloc(value, len + val_len + 1);
459 		if (!value) {
460 			fprintf(stderr,
461 				"Cannot malloc %zu bytes: %s\n",
462 				len, strerror(errno));
463 			return -1;
464 		}
465 
466 		memcpy(value + len, val, val_len);
467 		len += val_len;
468 		value[len++] = '\0';
469 	}
470 
471 	fw_env_write(name, value);
472 
473 	free(value);
474 
475 	return fw_env_close();
476 }
477 
478 /*
479  * Parse  a file  and configure the u-boot variables.
480  * The script file has a very simple format, as follows:
481  *
482  * Each line has a couple with name, value:
483  * <white spaces>variable_name<white spaces>variable_value
484  *
485  * Both variable_name and variable_value are interpreted as strings.
486  * Any character after <white spaces> and before ending \r\n is interpreted
487  * as variable's value (no comment allowed on these lines !)
488  *
489  * Comments are allowed if the first character in the line is #
490  *
491  * Returns -1 and sets errno error codes:
492  * 0	  - OK
493  * -1     - Error
494  */
495 int fw_parse_script(char *fname)
496 {
497 	FILE *fp;
498 	char dump[1024];	/* Maximum line length in the file */
499 	char *name;
500 	char *val;
501 	int lineno = 0;
502 	int len;
503 	int ret = 0;
504 
505 	if (fw_env_open()) {
506 		fprintf(stderr, "Error: environment not initialized\n");
507 		return -1;
508 	}
509 
510 	if (strcmp(fname, "-") == 0)
511 		fp = stdin;
512 	else {
513 		fp = fopen(fname, "r");
514 		if (fp == NULL) {
515 			fprintf(stderr, "I cannot open %s for reading\n",
516 				 fname);
517 			return -1;
518 		}
519 	}
520 
521 	while (fgets(dump, sizeof(dump), fp)) {
522 		lineno++;
523 		len = strlen(dump);
524 
525 		/*
526 		 * Read a whole line from the file. If the line is too long
527 		 * or is not terminated, reports an error and exit.
528 		 */
529 		if (dump[len - 1] != '\n') {
530 			fprintf(stderr,
531 			"Line %d not corrected terminated or too long\n",
532 				lineno);
533 			ret = -1;
534 			break;
535 		}
536 
537 		/* Drop ending line feed / carriage return */
538 		while (len > 0 && (dump[len - 1] == '\n' ||
539 				dump[len - 1] == '\r')) {
540 			dump[len - 1] = '\0';
541 			len--;
542 		}
543 
544 		/* Skip comment or empty lines */
545 		if ((len == 0) || dump[0] == '#')
546 			continue;
547 
548 		/*
549 		 * Search for variable's name,
550 		 * remove leading whitespaces
551 		 */
552 		name = fw_string_blank(dump, 1);
553 		if (!name)
554 			continue;
555 
556 		/* The first white space is the end of variable name */
557 		val = fw_string_blank(name, 0);
558 		len = strlen(name);
559 		if (val) {
560 			*val++ = '\0';
561 			if ((val - name) < len)
562 				val = fw_string_blank(val, 1);
563 			else
564 				val = NULL;
565 		}
566 
567 #ifdef DEBUG
568 		fprintf(stderr, "Setting %s : %s\n",
569 			name, val ? val : " removed");
570 #endif
571 
572 		if (env_flags_validate_type(name, val) < 0) {
573 			ret = -1;
574 			break;
575 		}
576 
577 		/*
578 		 * If there is an error setting a variable,
579 		 * try to save the environment and returns an error
580 		 */
581 		if (fw_env_write(name, val)) {
582 			fprintf(stderr,
583 			"fw_env_write returns with error : %s\n",
584 				strerror(errno));
585 			ret = -1;
586 			break;
587 		}
588 
589 	}
590 
591 	/* Close file if not stdin */
592 	if (strcmp(fname, "-") != 0)
593 		fclose(fp);
594 
595 	ret |= fw_env_close();
596 
597 	return ret;
598 
599 }
600 
601 /*
602  * Test for bad block on NAND, just returns 0 on NOR, on NAND:
603  * 0	- block is good
604  * > 0	- block is bad
605  * < 0	- failed to test
606  */
607 static int flash_bad_block (int fd, uint8_t mtd_type, loff_t *blockstart)
608 {
609 	if (mtd_type == MTD_NANDFLASH) {
610 		int badblock = ioctl (fd, MEMGETBADBLOCK, blockstart);
611 
612 		if (badblock < 0) {
613 			perror ("Cannot read bad block mark");
614 			return badblock;
615 		}
616 
617 		if (badblock) {
618 #ifdef DEBUG
619 			fprintf (stderr, "Bad block at 0x%llx, "
620 				 "skipping\n", *blockstart);
621 #endif
622 			return badblock;
623 		}
624 	}
625 
626 	return 0;
627 }
628 
629 /*
630  * Read data from flash at an offset into a provided buffer. On NAND it skips
631  * bad blocks but makes sure it stays within ENVSECTORS (dev) starting from
632  * the DEVOFFSET (dev) block. On NOR the loop is only run once.
633  */
634 static int flash_read_buf (int dev, int fd, void *buf, size_t count,
635 			   off_t offset, uint8_t mtd_type)
636 {
637 	size_t blocklen;	/* erase / write length - one block on NAND,
638 				   0 on NOR */
639 	size_t processed = 0;	/* progress counter */
640 	size_t readlen = count;	/* current read length */
641 	off_t top_of_range;	/* end of the last block we may use */
642 	off_t block_seek;	/* offset inside the current block to the start
643 				   of the data */
644 	loff_t blockstart;	/* running start of the current block -
645 				   MEMGETBADBLOCK needs 64 bits */
646 	int rc;
647 
648 	blockstart = (offset / DEVESIZE (dev)) * DEVESIZE (dev);
649 
650 	/* Offset inside a block */
651 	block_seek = offset - blockstart;
652 
653 	if (mtd_type == MTD_NANDFLASH) {
654 		/*
655 		 * NAND: calculate which blocks we are reading. We have
656 		 * to read one block at a time to skip bad blocks.
657 		 */
658 		blocklen = DEVESIZE (dev);
659 
660 		/*
661 		 * To calculate the top of the range, we have to use the
662 		 * global DEVOFFSET (dev), which can be different from offset
663 		 */
664 		top_of_range = ((DEVOFFSET(dev) / blocklen) +
665 				ENVSECTORS (dev)) * blocklen;
666 
667 		/* Limit to one block for the first read */
668 		if (readlen > blocklen - block_seek)
669 			readlen = blocklen - block_seek;
670 	} else {
671 		blocklen = 0;
672 		top_of_range = offset + count;
673 	}
674 
675 	/* This only runs once on NOR flash */
676 	while (processed < count) {
677 		rc = flash_bad_block (fd, mtd_type, &blockstart);
678 		if (rc < 0)		/* block test failed */
679 			return -1;
680 
681 		if (blockstart + block_seek + readlen > top_of_range) {
682 			/* End of range is reached */
683 			fprintf (stderr,
684 				 "Too few good blocks within range\n");
685 			return -1;
686 		}
687 
688 		if (rc) {		/* block is bad */
689 			blockstart += blocklen;
690 			continue;
691 		}
692 
693 		/*
694 		 * If a block is bad, we retry in the next block at the same
695 		 * offset - see common/env_nand.c::writeenv()
696 		 */
697 		lseek (fd, blockstart + block_seek, SEEK_SET);
698 
699 		rc = read (fd, buf + processed, readlen);
700 		if (rc != readlen) {
701 			fprintf (stderr, "Read error on %s: %s\n",
702 				 DEVNAME (dev), strerror (errno));
703 			return -1;
704 		}
705 #ifdef DEBUG
706 		fprintf(stderr, "Read 0x%x bytes at 0x%llx on %s\n",
707 			 rc, blockstart + block_seek, DEVNAME(dev));
708 #endif
709 		processed += readlen;
710 		readlen = min (blocklen, count - processed);
711 		block_seek = 0;
712 		blockstart += blocklen;
713 	}
714 
715 	return processed;
716 }
717 
718 /*
719  * Write count bytes at offset, but stay within ENVSECTORS (dev) sectors of
720  * DEVOFFSET (dev). Similar to the read case above, on NOR and dataflash we
721  * erase and write the whole data at once.
722  */
723 static int flash_write_buf (int dev, int fd, void *buf, size_t count,
724 			    off_t offset, uint8_t mtd_type)
725 {
726 	void *data;
727 	struct erase_info_user erase;
728 	size_t blocklen;	/* length of NAND block / NOR erase sector */
729 	size_t erase_len;	/* whole area that can be erased - may include
730 				   bad blocks */
731 	size_t erasesize;	/* erase / write length - one block on NAND,
732 				   whole area on NOR */
733 	size_t processed = 0;	/* progress counter */
734 	size_t write_total;	/* total size to actually write - excluding
735 				   bad blocks */
736 	off_t erase_offset;	/* offset to the first erase block (aligned)
737 				   below offset */
738 	off_t block_seek;	/* offset inside the erase block to the start
739 				   of the data */
740 	off_t top_of_range;	/* end of the last block we may use */
741 	loff_t blockstart;	/* running start of the current block -
742 				   MEMGETBADBLOCK needs 64 bits */
743 	int rc;
744 
745 	blocklen = DEVESIZE (dev);
746 
747 	top_of_range = ((DEVOFFSET(dev) / blocklen) +
748 					ENVSECTORS (dev)) * blocklen;
749 
750 	erase_offset = (offset / blocklen) * blocklen;
751 
752 	/* Maximum area we may use */
753 	erase_len = top_of_range - erase_offset;
754 
755 	blockstart = erase_offset;
756 	/* Offset inside a block */
757 	block_seek = offset - erase_offset;
758 
759 	/*
760 	 * Data size we actually have to write: from the start of the block
761 	 * to the start of the data, then count bytes of data, and to the
762 	 * end of the block
763 	 */
764 	write_total = ((block_seek + count + blocklen - 1) /
765 						blocklen) * blocklen;
766 
767 	/*
768 	 * Support data anywhere within erase sectors: read out the complete
769 	 * area to be erased, replace the environment image, write the whole
770 	 * block back again.
771 	 */
772 	if (write_total > count) {
773 		data = malloc (erase_len);
774 		if (!data) {
775 			fprintf (stderr,
776 				 "Cannot malloc %zu bytes: %s\n",
777 				 erase_len, strerror (errno));
778 			return -1;
779 		}
780 
781 		rc = flash_read_buf (dev, fd, data, write_total, erase_offset,
782 				     mtd_type);
783 		if (write_total != rc)
784 			return -1;
785 
786 #ifdef DEBUG
787 		fprintf(stderr, "Preserving data ");
788 		if (block_seek != 0)
789 			fprintf(stderr, "0x%x - 0x%lx", 0, block_seek - 1);
790 		if (block_seek + count != write_total) {
791 			if (block_seek != 0)
792 				fprintf(stderr, " and ");
793 			fprintf(stderr, "0x%lx - 0x%x",
794 				block_seek + count, write_total - 1);
795 		}
796 		fprintf(stderr, "\n");
797 #endif
798 		/* Overwrite the old environment */
799 		memcpy (data + block_seek, buf, count);
800 	} else {
801 		/*
802 		 * We get here, iff offset is block-aligned and count is a
803 		 * multiple of blocklen - see write_total calculation above
804 		 */
805 		data = buf;
806 	}
807 
808 	if (mtd_type == MTD_NANDFLASH) {
809 		/*
810 		 * NAND: calculate which blocks we are writing. We have
811 		 * to write one block at a time to skip bad blocks.
812 		 */
813 		erasesize = blocklen;
814 	} else {
815 		erasesize = erase_len;
816 	}
817 
818 	erase.length = erasesize;
819 
820 	/* This only runs once on NOR flash and SPI-dataflash */
821 	while (processed < write_total) {
822 		rc = flash_bad_block (fd, mtd_type, &blockstart);
823 		if (rc < 0)		/* block test failed */
824 			return rc;
825 
826 		if (blockstart + erasesize > top_of_range) {
827 			fprintf (stderr, "End of range reached, aborting\n");
828 			return -1;
829 		}
830 
831 		if (rc) {		/* block is bad */
832 			blockstart += blocklen;
833 			continue;
834 		}
835 
836 		erase.start = blockstart;
837 		ioctl (fd, MEMUNLOCK, &erase);
838 
839 		/* Dataflash does not need an explicit erase cycle */
840 		if (mtd_type != MTD_DATAFLASH)
841 			if (ioctl (fd, MEMERASE, &erase) != 0) {
842 				fprintf (stderr, "MTD erase error on %s: %s\n",
843 					 DEVNAME (dev),
844 					 strerror (errno));
845 				return -1;
846 			}
847 
848 		if (lseek (fd, blockstart, SEEK_SET) == -1) {
849 			fprintf (stderr,
850 				 "Seek error on %s: %s\n",
851 				 DEVNAME (dev), strerror (errno));
852 			return -1;
853 		}
854 
855 #ifdef DEBUG
856 		fprintf(stderr, "Write 0x%x bytes at 0x%llx\n", erasesize,
857 			blockstart);
858 #endif
859 		if (write (fd, data + processed, erasesize) != erasesize) {
860 			fprintf (stderr, "Write error on %s: %s\n",
861 				 DEVNAME (dev), strerror (errno));
862 			return -1;
863 		}
864 
865 		ioctl (fd, MEMLOCK, &erase);
866 
867 		processed  += blocklen;
868 		block_seek = 0;
869 		blockstart += blocklen;
870 	}
871 
872 	if (write_total > count)
873 		free (data);
874 
875 	return processed;
876 }
877 
878 /*
879  * Set obsolete flag at offset - NOR flash only
880  */
881 static int flash_flag_obsolete (int dev, int fd, off_t offset)
882 {
883 	int rc;
884 	struct erase_info_user erase;
885 
886 	erase.start  = DEVOFFSET (dev);
887 	erase.length = DEVESIZE (dev);
888 	/* This relies on the fact, that obsolete_flag == 0 */
889 	rc = lseek (fd, offset, SEEK_SET);
890 	if (rc < 0) {
891 		fprintf (stderr, "Cannot seek to set the flag on %s \n",
892 			 DEVNAME (dev));
893 		return rc;
894 	}
895 	ioctl (fd, MEMUNLOCK, &erase);
896 	rc = write (fd, &obsolete_flag, sizeof (obsolete_flag));
897 	ioctl (fd, MEMLOCK, &erase);
898 	if (rc < 0)
899 		perror ("Could not set obsolete flag");
900 
901 	return rc;
902 }
903 
904 static int flash_write (int fd_current, int fd_target, int dev_target)
905 {
906 	int rc;
907 
908 	switch (environment.flag_scheme) {
909 	case FLAG_NONE:
910 		break;
911 	case FLAG_INCREMENTAL:
912 		(*environment.flags)++;
913 		break;
914 	case FLAG_BOOLEAN:
915 		*environment.flags = active_flag;
916 		break;
917 	default:
918 		fprintf (stderr, "Unimplemented flash scheme %u \n",
919 			 environment.flag_scheme);
920 		return -1;
921 	}
922 
923 #ifdef DEBUG
924 	fprintf(stderr, "Writing new environment at 0x%lx on %s\n",
925 		DEVOFFSET (dev_target), DEVNAME (dev_target));
926 #endif
927 	rc = flash_write_buf(dev_target, fd_target, environment.image,
928 			      CUR_ENVSIZE, DEVOFFSET(dev_target),
929 			      DEVTYPE(dev_target));
930 	if (rc < 0)
931 		return rc;
932 
933 	if (environment.flag_scheme == FLAG_BOOLEAN) {
934 		/* Have to set obsolete flag */
935 		off_t offset = DEVOFFSET (dev_current) +
936 			offsetof (struct env_image_redundant, flags);
937 #ifdef DEBUG
938 		fprintf(stderr,
939 			"Setting obsolete flag in environment at 0x%lx on %s\n",
940 			DEVOFFSET (dev_current), DEVNAME (dev_current));
941 #endif
942 		flash_flag_obsolete (dev_current, fd_current, offset);
943 	}
944 
945 	return 0;
946 }
947 
948 static int flash_read (int fd)
949 {
950 	struct mtd_info_user mtdinfo;
951 	int rc;
952 
953 	rc = ioctl (fd, MEMGETINFO, &mtdinfo);
954 	if (rc < 0) {
955 		perror ("Cannot get MTD information");
956 		return -1;
957 	}
958 
959 	if (mtdinfo.type != MTD_NORFLASH &&
960 	    mtdinfo.type != MTD_NANDFLASH &&
961 	    mtdinfo.type != MTD_DATAFLASH) {
962 		fprintf (stderr, "Unsupported flash type %u\n", mtdinfo.type);
963 		return -1;
964 	}
965 
966 	DEVTYPE(dev_current) = mtdinfo.type;
967 
968 	rc = flash_read_buf(dev_current, fd, environment.image, CUR_ENVSIZE,
969 			     DEVOFFSET (dev_current), mtdinfo.type);
970 
971 	return (rc != CUR_ENVSIZE) ? -1 : 0;
972 }
973 
974 static int flash_io (int mode)
975 {
976 	int fd_current, fd_target, rc, dev_target;
977 
978 	/* dev_current: fd_current, erase_current */
979 	fd_current = open (DEVNAME (dev_current), mode);
980 	if (fd_current < 0) {
981 		fprintf (stderr,
982 			 "Can't open %s: %s\n",
983 			 DEVNAME (dev_current), strerror (errno));
984 		return -1;
985 	}
986 
987 	if (mode == O_RDWR) {
988 		if (HaveRedundEnv) {
989 			/* switch to next partition for writing */
990 			dev_target = !dev_current;
991 			/* dev_target: fd_target, erase_target */
992 			fd_target = open (DEVNAME (dev_target), mode);
993 			if (fd_target < 0) {
994 				fprintf (stderr,
995 					 "Can't open %s: %s\n",
996 					 DEVNAME (dev_target),
997 					 strerror (errno));
998 				rc = -1;
999 				goto exit;
1000 			}
1001 		} else {
1002 			dev_target = dev_current;
1003 			fd_target = fd_current;
1004 		}
1005 
1006 		rc = flash_write (fd_current, fd_target, dev_target);
1007 
1008 		if (HaveRedundEnv) {
1009 			if (close (fd_target)) {
1010 				fprintf (stderr,
1011 					"I/O error on %s: %s\n",
1012 					DEVNAME (dev_target),
1013 					strerror (errno));
1014 				rc = -1;
1015 			}
1016 		}
1017 	} else {
1018 		rc = flash_read (fd_current);
1019 	}
1020 
1021 exit:
1022 	if (close (fd_current)) {
1023 		fprintf (stderr,
1024 			 "I/O error on %s: %s\n",
1025 			 DEVNAME (dev_current), strerror (errno));
1026 		return -1;
1027 	}
1028 
1029 	return rc;
1030 }
1031 
1032 /*
1033  * s1 is either a simple 'name', or a 'name=value' pair.
1034  * s2 is a 'name=value' pair.
1035  * If the names match, return the value of s2, else NULL.
1036  */
1037 
1038 static char *envmatch (char * s1, char * s2)
1039 {
1040 	if (s1 == NULL || s2 == NULL)
1041 		return NULL;
1042 
1043 	while (*s1 == *s2++)
1044 		if (*s1++ == '=')
1045 			return s2;
1046 	if (*s1 == '\0' && *(s2 - 1) == '=')
1047 		return s2;
1048 	return NULL;
1049 }
1050 
1051 /*
1052  * Prevent confusion if running from erased flash memory
1053  */
1054 int fw_env_open(void)
1055 {
1056 	int crc0, crc0_ok;
1057 	unsigned char flag0;
1058 	void *addr0;
1059 
1060 	int crc1, crc1_ok;
1061 	unsigned char flag1;
1062 	void *addr1;
1063 
1064 	struct env_image_single *single;
1065 	struct env_image_redundant *redundant;
1066 
1067 	if (parse_config ())		/* should fill envdevices */
1068 		return -1;
1069 
1070 	addr0 = calloc(1, CUR_ENVSIZE);
1071 	if (addr0 == NULL) {
1072 		fprintf(stderr,
1073 			"Not enough memory for environment (%ld bytes)\n",
1074 			CUR_ENVSIZE);
1075 		return -1;
1076 	}
1077 
1078 	/* read environment from FLASH to local buffer */
1079 	environment.image = addr0;
1080 
1081 	if (HaveRedundEnv) {
1082 		redundant = addr0;
1083 		environment.crc		= &redundant->crc;
1084 		environment.flags	= &redundant->flags;
1085 		environment.data	= redundant->data;
1086 	} else {
1087 		single = addr0;
1088 		environment.crc		= &single->crc;
1089 		environment.flags	= NULL;
1090 		environment.data	= single->data;
1091 	}
1092 
1093 	dev_current = 0;
1094 	if (flash_io (O_RDONLY))
1095 		return -1;
1096 
1097 	crc0 = crc32 (0, (uint8_t *) environment.data, ENV_SIZE);
1098 	crc0_ok = (crc0 == *environment.crc);
1099 	if (!HaveRedundEnv) {
1100 		if (!crc0_ok) {
1101 			fprintf (stderr,
1102 				"Warning: Bad CRC, using default environment\n");
1103 			memcpy(environment.data, default_environment, sizeof default_environment);
1104 		}
1105 	} else {
1106 		flag0 = *environment.flags;
1107 
1108 		dev_current = 1;
1109 		addr1 = calloc(1, CUR_ENVSIZE);
1110 		if (addr1 == NULL) {
1111 			fprintf(stderr,
1112 				"Not enough memory for environment (%ld bytes)\n",
1113 				CUR_ENVSIZE);
1114 			return -1;
1115 		}
1116 		redundant = addr1;
1117 
1118 		/*
1119 		 * have to set environment.image for flash_read(), careful -
1120 		 * other pointers in environment still point inside addr0
1121 		 */
1122 		environment.image = addr1;
1123 		if (flash_io (O_RDONLY))
1124 			return -1;
1125 
1126 		/* Check flag scheme compatibility */
1127 		if (DEVTYPE(dev_current) == MTD_NORFLASH &&
1128 		    DEVTYPE(!dev_current) == MTD_NORFLASH) {
1129 			environment.flag_scheme = FLAG_BOOLEAN;
1130 		} else if (DEVTYPE(dev_current) == MTD_NANDFLASH &&
1131 			   DEVTYPE(!dev_current) == MTD_NANDFLASH) {
1132 			environment.flag_scheme = FLAG_INCREMENTAL;
1133 		} else if (DEVTYPE(dev_current) == MTD_DATAFLASH &&
1134 			   DEVTYPE(!dev_current) == MTD_DATAFLASH) {
1135 			environment.flag_scheme = FLAG_BOOLEAN;
1136 		} else {
1137 			fprintf (stderr, "Incompatible flash types!\n");
1138 			return -1;
1139 		}
1140 
1141 		crc1 = crc32 (0, (uint8_t *) redundant->data, ENV_SIZE);
1142 		crc1_ok = (crc1 == redundant->crc);
1143 		flag1 = redundant->flags;
1144 
1145 		if (crc0_ok && !crc1_ok) {
1146 			dev_current = 0;
1147 		} else if (!crc0_ok && crc1_ok) {
1148 			dev_current = 1;
1149 		} else if (!crc0_ok && !crc1_ok) {
1150 			fprintf (stderr,
1151 				"Warning: Bad CRC, using default environment\n");
1152 			memcpy (environment.data, default_environment,
1153 				sizeof default_environment);
1154 			dev_current = 0;
1155 		} else {
1156 			switch (environment.flag_scheme) {
1157 			case FLAG_BOOLEAN:
1158 				if (flag0 == active_flag &&
1159 				    flag1 == obsolete_flag) {
1160 					dev_current = 0;
1161 				} else if (flag0 == obsolete_flag &&
1162 					   flag1 == active_flag) {
1163 					dev_current = 1;
1164 				} else if (flag0 == flag1) {
1165 					dev_current = 0;
1166 				} else if (flag0 == 0xFF) {
1167 					dev_current = 0;
1168 				} else if (flag1 == 0xFF) {
1169 					dev_current = 1;
1170 				} else {
1171 					dev_current = 0;
1172 				}
1173 				break;
1174 			case FLAG_INCREMENTAL:
1175 				if (flag0 == 255 && flag1 == 0)
1176 					dev_current = 1;
1177 				else if ((flag1 == 255 && flag0 == 0) ||
1178 					 flag0 >= flag1)
1179 					dev_current = 0;
1180 				else /* flag1 > flag0 */
1181 					dev_current = 1;
1182 				break;
1183 			default:
1184 				fprintf (stderr, "Unknown flag scheme %u \n",
1185 					 environment.flag_scheme);
1186 				return -1;
1187 			}
1188 		}
1189 
1190 		/*
1191 		 * If we are reading, we don't need the flag and the CRC any
1192 		 * more, if we are writing, we will re-calculate CRC and update
1193 		 * flags before writing out
1194 		 */
1195 		if (dev_current) {
1196 			environment.image	= addr1;
1197 			environment.crc		= &redundant->crc;
1198 			environment.flags	= &redundant->flags;
1199 			environment.data	= redundant->data;
1200 			free (addr0);
1201 		} else {
1202 			environment.image	= addr0;
1203 			/* Other pointers are already set */
1204 			free (addr1);
1205 		}
1206 #ifdef DEBUG
1207 		fprintf(stderr, "Selected env in %s\n", DEVNAME(dev_current));
1208 #endif
1209 	}
1210 	return 0;
1211 }
1212 
1213 
1214 static int parse_config ()
1215 {
1216 	struct stat st;
1217 
1218 #if defined(CONFIG_FILE)
1219 	/* Fills in DEVNAME(), ENVSIZE(), DEVESIZE(). Or don't. */
1220 	if (get_config (CONFIG_FILE)) {
1221 		fprintf (stderr,
1222 			"Cannot parse config file: %s\n", strerror (errno));
1223 		return -1;
1224 	}
1225 #else
1226 	strcpy (DEVNAME (0), DEVICE1_NAME);
1227 	DEVOFFSET (0) = DEVICE1_OFFSET;
1228 	ENVSIZE (0) = ENV1_SIZE;
1229 	/* Default values are: erase-size=env-size, #sectors=1 */
1230 	DEVESIZE (0) = ENVSIZE (0);
1231 	ENVSECTORS (0) = 1;
1232 #ifdef DEVICE1_ESIZE
1233 	DEVESIZE (0) = DEVICE1_ESIZE;
1234 #endif
1235 #ifdef DEVICE1_ENVSECTORS
1236 	ENVSECTORS (0) = DEVICE1_ENVSECTORS;
1237 #endif
1238 
1239 #ifdef HAVE_REDUND
1240 	strcpy (DEVNAME (1), DEVICE2_NAME);
1241 	DEVOFFSET (1) = DEVICE2_OFFSET;
1242 	ENVSIZE (1) = ENV2_SIZE;
1243 	/* Default values are: erase-size=env-size, #sectors=1 */
1244 	DEVESIZE (1) = ENVSIZE (1);
1245 	ENVSECTORS (1) = 1;
1246 #ifdef DEVICE2_ESIZE
1247 	DEVESIZE (1) = DEVICE2_ESIZE;
1248 #endif
1249 #ifdef DEVICE2_ENVSECTORS
1250 	ENVSECTORS (1) = DEVICE2_ENVSECTORS;
1251 #endif
1252 	HaveRedundEnv = 1;
1253 #endif
1254 #endif
1255 	if (stat (DEVNAME (0), &st)) {
1256 		fprintf (stderr,
1257 			"Cannot access MTD device %s: %s\n",
1258 			DEVNAME (0), strerror (errno));
1259 		return -1;
1260 	}
1261 
1262 	if (HaveRedundEnv && stat (DEVNAME (1), &st)) {
1263 		fprintf (stderr,
1264 			"Cannot access MTD device %s: %s\n",
1265 			DEVNAME (1), strerror (errno));
1266 		return -1;
1267 	}
1268 	return 0;
1269 }
1270 
1271 #if defined(CONFIG_FILE)
1272 static int get_config (char *fname)
1273 {
1274 	FILE *fp;
1275 	int i = 0;
1276 	int rc;
1277 	char dump[128];
1278 
1279 	fp = fopen (fname, "r");
1280 	if (fp == NULL)
1281 		return -1;
1282 
1283 	while (i < 2 && fgets (dump, sizeof (dump), fp)) {
1284 		/* Skip incomplete conversions and comment strings */
1285 		if (dump[0] == '#')
1286 			continue;
1287 
1288 		rc = sscanf (dump, "%s %lx %lx %lx %lx",
1289 			     DEVNAME (i),
1290 			     &DEVOFFSET (i),
1291 			     &ENVSIZE (i),
1292 			     &DEVESIZE (i),
1293 			     &ENVSECTORS (i));
1294 
1295 		if (rc < 3)
1296 			continue;
1297 
1298 		if (rc < 4)
1299 			/* Assume the erase size is the same as the env-size */
1300 			DEVESIZE(i) = ENVSIZE(i);
1301 
1302 		if (rc < 5)
1303 			/* Default - 1 sector */
1304 			ENVSECTORS (i) = 1;
1305 
1306 		i++;
1307 	}
1308 	fclose (fp);
1309 
1310 	HaveRedundEnv = i - 1;
1311 	if (!i) {			/* No valid entries found */
1312 		errno = EINVAL;
1313 		return -1;
1314 	} else
1315 		return 0;
1316 }
1317 #endif
1318