flashrom.c 53.1 KB
Newer Older
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1
/*
2
 * This file is part of the flashrom project.
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
3
 *
4 5
 * Copyright (C) 2000 Silicon Integrated System Corporation
 * Copyright (C) 2004 Tyan Corp <yhlu@tyan.com>
6
 * Copyright (C) 2005-2008 coresystems GmbH
7
 * Copyright (C) 2008,2009 Carl-Daniel Hailfinger
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
8
 *
9 10 11 12
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
13
 *
14 15 16 17
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
18
 *
19 20 21
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
22 23
 */

24
#include <stdio.h>
25
#include <sys/types.h>
26 27
#ifndef __LIBPAYLOAD__
#include <fcntl.h>
28
#include <sys/stat.h>
29
#endif
Ronald G. Minnich's avatar
Ronald G. Minnich committed
30
#include <string.h>
Ronald G. Minnich's avatar
Ronald G. Minnich committed
31
#include <stdlib.h>
32
#include <ctype.h>
33
#include <getopt.h>
34 35 36
#if HAVE_UTSNAME == 1
#include <sys/utsname.h>
#endif
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
37
#include "flash.h"
38
#include "flashchips.h"
39
#include "programmer.h"
40
#include "hwaccess.h"
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
41

42
const char flashrom_version[] = FLASHROM_VERSION;
Ronald G. Minnich's avatar
Ronald G. Minnich committed
43
char *chip_to_probe = NULL;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
44 45
int verbose_screen = MSG_INFO;
int verbose_logfile = MSG_DEBUG2;
46

47
static enum programmer programmer = PROGRAMMER_INVALID;
48

49
static char *programmer_param = NULL;
50

51
/*
52 53 54
 * Programmers supporting multiple buses can have differing size limits on
 * each bus. Store the limits for each bus in a common struct.
 */
55 56 57 58
struct decode_sizes max_rom_decode;

/* If nonzero, used as the start address of bottom-aligned flash. */
unsigned long flashbase;
59

60 61 62
/* Is writing allowed with this programmer? */
int programmer_may_write;

63
const struct programmer_entry programmer_table[] = {
64
#if CONFIG_INTERNAL == 1
65
	{
66
		.name			= "internal",
67 68
		.type			= OTHER,
		.devs.note		= NULL,
69
		.init			= internal_init,
70 71
		.map_flash_region	= physmap,
		.unmap_flash_region	= physunmap,
72
		.delay			= internal_delay,
73
	},
74
#endif
75

76
#if CONFIG_DUMMY == 1
77
	{
78
		.name			= "dummy",
79 80 81
		.type			= OTHER,
					/* FIXME */
		.devs.note		= "Dummy device, does nothing and logs all accesses\n",
82
		.init			= dummy_init,
83 84
		.map_flash_region	= dummy_map,
		.unmap_flash_region	= dummy_unmap,
85
		.delay			= internal_delay,
86
	},
87
#endif
88

89
#if CONFIG_NIC3COM == 1
90
	{
91
		.name			= "nic3com",
92 93
		.type			= PCI,
		.devs.pci		= nics_3com,
94
		.init			= nic3com_init,
95 96
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
97
		.delay			= internal_delay,
98
	},
99
#endif
100

101
#if CONFIG_NICREALTEK == 1
102
	{
103
		/* This programmer works for Realtek RTL8139 and SMC 1211. */
104
		.name			= "nicrealtek",
105 106
		.type			= PCI,
		.devs.pci		= nics_realtek,
107 108 109 110
		.init			= nicrealtek_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
111 112 113
	},
#endif

114 115
#if CONFIG_NICNATSEMI == 1
	{
116
		.name			= "nicnatsemi",
117 118
		.type			= PCI,
		.devs.pci		= nics_natsemi,
119 120 121 122
		.init			= nicnatsemi_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
123 124
	},
#endif
125

126
#if CONFIG_GFXNVIDIA == 1
127 128
	{
		.name			= "gfxnvidia",
129 130
		.type			= PCI,
		.devs.pci		= gfx_nvidia,
131 132 133 134 135 136 137
		.init			= gfxnvidia_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
	},
#endif

138
#if CONFIG_DRKAISER == 1
139 140
	{
		.name			= "drkaiser",
141 142
		.type			= PCI,
		.devs.pci		= drkaiser_pcidev,
143 144 145 146 147
		.init			= drkaiser_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
	},
148
#endif
149

150
#if CONFIG_SATASII == 1
151
	{
152
		.name			= "satasii",
153 154
		.type			= PCI,
		.devs.pci		= satas_sii,
155
		.init			= satasii_init,
156 157
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
158
		.delay			= internal_delay,
159
	},
160
#endif
161

162
#if CONFIG_ATAHPT == 1
163 164
	{
		.name			= "atahpt",
165 166
		.type			= PCI,
		.devs.pci		= ata_hpt,
167 168 169 170 171 172 173
		.init			= atahpt_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
	},
#endif

174
#if CONFIG_FT2232_SPI == 1
175
	{
176
		.name			= "ft2232_spi",
177 178
		.type			= USB,
		.devs.usb		= devs_ft2232spi,
179
		.init			= ft2232_spi_init,
180 181
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
182 183
		.delay			= internal_delay,
	},
184
#endif
185

186
#if CONFIG_SERPROG == 1
187
	{
188
		.name			= "serprog",
189 190 191
		.type			= OTHER,
					/* FIXME */
		.devs.note		= "All programmer devices speaking the serprog protocol\n",
192 193 194 195 196
		.init			= serprog_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= serprog_delay,
	},
197
#endif
198

199
#if CONFIG_BUSPIRATE_SPI == 1
200
	{
201
		.name			= "buspirate_spi",
202 203 204
		.type			= OTHER,
					/* FIXME */
		.devs.note		= "Dangerous Prototypes Bus Pirate\n",
205 206 207 208 209 210 211
		.init			= buspirate_spi_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
	},
#endif

212
#if CONFIG_DEDIPROG == 1
213 214
	{
		.name			= "dediprog",
215 216 217
		.type			= OTHER,
					/* FIXME */
		.devs.note		= "Dediprog SF100\n",
218 219 220 221 222 223 224
		.init			= dediprog_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
	},
#endif

225 226 227
#if CONFIG_RAYER_SPI == 1
	{
		.name			= "rayer_spi",
228 229 230
		.type			= OTHER,
					/* FIXME */
		.devs.note		= "RayeR parallel port programmer\n",
231 232 233 234 235 236 237
		.init			= rayer_spi_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
	},
#endif

238 239 240
#if CONFIG_PONY_SPI == 1
	{
		.name			= "pony_spi",
241 242 243
		.type			= OTHER,
					/* FIXME */
		.devs.note		= "Programmers compatible with SI-Prog, serbang or AJAWe\n",
244 245 246 247
		.init			= pony_spi_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
248
	},
249 250
#endif

251 252 253
#if CONFIG_NICINTEL == 1
	{
		.name			= "nicintel",
254 255
		.type			= PCI,
		.devs.pci		= nics_intel,
256 257 258 259 260 261 262
		.init			= nicintel_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
	},
#endif

263 264
#if CONFIG_NICINTEL_SPI == 1
	{
265
		.name			= "nicintel_spi",
266 267
		.type			= PCI,
		.devs.pci		= nics_intel_spi,
268 269 270 271
		.init			= nicintel_spi_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
272 273 274
	},
#endif

275 276
#if CONFIG_OGP_SPI == 1
	{
277
		.name			= "ogp_spi",
278 279
		.type			= PCI,
		.devs.pci		= ogp_spi,
280 281 282 283
		.init			= ogp_spi_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
284 285 286
	},
#endif

287 288 289
#if CONFIG_SATAMV == 1
	{
		.name			= "satamv",
290 291
		.type			= PCI,
		.devs.pci		= satas_mv,
292 293 294 295 296 297 298
		.init			= satamv_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
	},
#endif

299 300 301
#if CONFIG_LINUX_SPI == 1
	{
		.name			= "linux_spi",
302 303
		.type			= OTHER,
		.devs.note		= "Device files /dev/spidev*.*\n",
304 305 306 307 308 309 310
		.init			= linux_spi_init,
		.map_flash_region	= fallback_map,
		.unmap_flash_region	= fallback_unmap,
		.delay			= internal_delay,
	},
#endif

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
311
	{0}, /* This entry corresponds to PROGRAMMER_INVALID. */
312
};
313

314
#define SHUTDOWN_MAXFN 32
315 316
static int shutdown_fn_count = 0;
struct shutdown_func_data {
317
	int (*func) (void *data);
318
	void *data;
319 320 321 322 323
} static shutdown_fn[SHUTDOWN_MAXFN];
/* Initialize to 0 to make sure nobody registers a shutdown function before
 * programmer init.
 */
static int may_register_shutdown = 0;
324

325
static int check_block_eraser(const struct flashctx *flash, int k, int log);
326

327 328 329 330 331 332 333 334
/* Register a function to be executed on programmer shutdown.
 * The advantage over atexit() is that you can supply a void pointer which will
 * be used as parameter to the registered function upon programmer shutdown.
 * This pointer can point to arbitrary data used by said function, e.g. undo
 * information for GPIO settings etc. If unneeded, set data=NULL.
 * Please note that the first (void *data) belongs to the function signature of
 * the function passed as first parameter.
 */
335
int register_shutdown(int (*function) (void *data), void *data)
336 337
{
	if (shutdown_fn_count >= SHUTDOWN_MAXFN) {
338
		msg_perr("Tried to register more than %i shutdown functions.\n",
339 340 341
			 SHUTDOWN_MAXFN);
		return 1;
	}
342 343 344 345 346
	if (!may_register_shutdown) {
		msg_perr("Tried to register a shutdown function before "
			 "programmer init.\n");
		return 1;
	}
347 348 349 350 351 352 353
	shutdown_fn[shutdown_fn_count].func = function;
	shutdown_fn[shutdown_fn_count].data = data;
	shutdown_fn_count++;

	return 0;
}

354
int programmer_init(enum programmer prog, char *param)
355
{
356
	int ret;
357 358 359 360 361 362

	if (prog >= PROGRAMMER_INVALID) {
		msg_perr("Invalid programmer specified!\n");
		return -1;
	}
	programmer = prog;
363 364 365 366 367 368
	/* Initialize all programmer specific data. */
	/* Default to unlimited decode sizes. */
	max_rom_decode = (const struct decode_sizes) {
		.parallel	= 0xffffffff,
		.lpc		= 0xffffffff,
		.fwh		= 0xffffffff,
369
		.spi		= 0xffffffff,
370 371 372 373 374
	};
	/* Default to top aligned flash at 4 GB. */
	flashbase = 0;
	/* Registering shutdown functions is now allowed. */
	may_register_shutdown = 1;
375 376
	/* Default to allowing writes. Broken programmers set this to 0. */
	programmer_may_write = 1;
377 378 379 380

	programmer_param = param;
	msg_pdbg("Initializing %s programmer\n",
		 programmer_table[programmer].name);
381 382 383 384 385 386 387
	ret = programmer_table[programmer].init();
	if (programmer_param && strlen(programmer_param)) {
		msg_perr("Unhandled programmer parameters: %s\n",
			 programmer_param);
		/* Do not error out here, the init itself was successful. */
	}
	return ret;
388 389 390 391
}

int programmer_shutdown(void)
{
392 393
	int ret = 0;

394 395 396 397
	/* Registering shutdown functions is no longer allowed. */
	may_register_shutdown = 0;
	while (shutdown_fn_count > 0) {
		int i = --shutdown_fn_count;
398
		ret |= shutdown_fn[i].func(shutdown_fn[i].data);
399
	}
Stefan Tauner's avatar
Stefan Tauner committed
400
	programmer_param = NULL;
401
	return ret;
402 403 404 405 406 407 408 409 410 411 412 413 414 415
}

void *programmer_map_flash_region(const char *descr, unsigned long phys_addr,
				  size_t len)
{
	return programmer_table[programmer].map_flash_region(descr,
							     phys_addr, len);
}

void programmer_unmap_flash_region(void *virt_addr, size_t len)
{
	programmer_table[programmer].unmap_flash_region(virt_addr, len);
}

416
void chip_writeb(const struct flashctx *flash, uint8_t val, chipaddr addr)
417
{
418
	flash->pgm->par.chip_writeb(flash, val, addr);
419 420
}

421
void chip_writew(const struct flashctx *flash, uint16_t val, chipaddr addr)
422
{
423
	flash->pgm->par.chip_writew(flash, val, addr);
424 425
}

426
void chip_writel(const struct flashctx *flash, uint32_t val, chipaddr addr)
427
{
428
	flash->pgm->par.chip_writel(flash, val, addr);
429 430
}

431 432
void chip_writen(const struct flashctx *flash, uint8_t *buf, chipaddr addr,
		 size_t len)
433
{
434
	flash->pgm->par.chip_writen(flash, buf, addr, len);
435 436
}

437
uint8_t chip_readb(const struct flashctx *flash, const chipaddr addr)
438
{
439
	return flash->pgm->par.chip_readb(flash, addr);
440 441
}

442
uint16_t chip_readw(const struct flashctx *flash, const chipaddr addr)
443
{
444
	return flash->pgm->par.chip_readw(flash, addr);
445 446
}

447
uint32_t chip_readl(const struct flashctx *flash, const chipaddr addr)
448
{
449
	return flash->pgm->par.chip_readl(flash, addr);
450 451
}

452 453
void chip_readn(const struct flashctx *flash, uint8_t *buf, chipaddr addr,
		size_t len)
454
{
455
	flash->pgm->par.chip_readn(flash, buf, addr, len);
456 457
}

458 459 460 461 462
void programmer_delay(int usecs)
{
	programmer_table[programmer].delay(usecs);
}

463
void map_flash_registers(struct flashctx *flash)
464
{
465
	size_t size = flash->chip->total_size * 1024;
466
	/* Flash registers live 4 MByte below the flash. */
467
	/* FIXME: This is incorrect for nonstandard flashbase. */
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
468
	flash->virtual_registers = (chipaddr)programmer_map_flash_region("flash chip registers", (0xFFFFFFFF - 0x400000 - size + 1), size);
469 470
}

471 472
int read_memmapped(struct flashctx *flash, uint8_t *buf, unsigned int start,
		   int unsigned len)
473
{
474
	chip_readn(flash, buf, flash->virtual_memory + start, len);
475

476 477 478
	return 0;
}

479 480 481 482 483
int min(int a, int b)
{
	return (a < b) ? a : b;
}

484 485 486 487 488
int max(int a, int b)
{
	return (a > b) ? a : b;
}

489 490 491 492 493 494 495 496 497
int bitcount(unsigned long a)
{
	int i = 0;
	for (; a != 0; a >>= 1)
		if (a & 1)
			i++;
	return i;
}

498 499 500 501 502 503
void tolower_string(char *str)
{
	for (; *str != '\0'; str++)
		*str = (char)tolower((unsigned char)*str);
}

504 505 506
char *strcat_realloc(char *dest, const char *src)
{
	dest = realloc(dest, strlen(dest) + strlen(src) + 1);
507 508
	if (!dest) {
		msg_gerr("Out of memory!\n");
509
		return NULL;
510
	}
511 512 513 514
	strcat(dest, src);
	return dest;
}

515
/* This is a somewhat hacked function similar in some ways to strtok().
516 517 518
 * It will look for needle with a subsequent '=' in haystack, return a copy of
 * needle and remove everything from the first occurrence of needle to the next
 * delimiter from haystack.
519
 */
520
char *extract_param(char **haystack, const char *needle, const char *delim)
521
{
522 523 524
	char *param_pos, *opt_pos, *rest;
	char *opt = NULL;
	int optlen;
525
	int needlelen;
526

527 528 529 530 531 532 533 534 535
	needlelen = strlen(needle);
	if (!needlelen) {
		msg_gerr("%s: empty needle! Please report a bug at "
			 "flashrom@flashrom.org\n", __func__);
		return NULL;
	}
	/* No programmer parameters given. */
	if (*haystack == NULL)
		return NULL;
536 537 538 539
	param_pos = strstr(*haystack, needle);
	do {
		if (!param_pos)
			return NULL;
540 541 542 543 544 545 546 547 548 549
		/* Needle followed by '='? */
		if (param_pos[needlelen] == '=') {
			
			/* Beginning of the string? */
			if (param_pos == *haystack)
				break;
			/* After a delimiter? */
			if (strchr(delim, *(param_pos - 1)))
				break;
		}
550 551 552 553
		/* Continue searching. */
		param_pos++;
		param_pos = strstr(param_pos, needle);
	} while (1);
554

555
	if (param_pos) {
556 557 558 559 560 561
		/* Get the string after needle and '='. */
		opt_pos = param_pos + needlelen + 1;
		optlen = strcspn(opt_pos, delim);
		/* Return an empty string if the parameter was empty. */
		opt = malloc(optlen + 1);
		if (!opt) {
562
			msg_gerr("Out of memory!\n");
563 564
			exit(1);
		}
565 566 567 568 569 570 571
		strncpy(opt, opt_pos, optlen);
		opt[optlen] = '\0';
		rest = opt_pos + optlen;
		/* Skip all delimiters after the current parameter. */
		rest += strspn(rest, delim);
		memmove(param_pos, rest, strlen(rest) + 1);
		/* We could shrink haystack, but the effort is not worth it. */
572 573
	}

574
	return opt;
575 576
}

577
char *extract_programmer_param(const char *param_name)
578 579 580 581
{
	return extract_param(&programmer_param, param_name, ",");
}

582
/* Returns the number of well-defined erasers for a chip. */
583
static unsigned int count_usable_erasers(const struct flashctx *flash)
584 585 586 587 588 589 590 591 592 593
{
	unsigned int usable_erasefunctions = 0;
	int k;
	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
		if (!check_block_eraser(flash, k, 0))
			usable_erasefunctions++;
	}
	return usable_erasefunctions;
}

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
int compare_range(uint8_t *wantbuf, uint8_t *havebuf, unsigned int start, unsigned int len)
{
	int ret = 0, failcount = 0;
	unsigned int i;
	for (i = 0; i < len; i++) {
		if (wantbuf[i] != havebuf[i]) {
			/* Only print the first failure. */
			if (!failcount++)
				msg_cerr("FAILED at 0x%08x! Expected=0x%02x, Found=0x%02x,",
					 start + i, wantbuf[i], havebuf[i]);
		}
	}
	if (failcount) {
		msg_cerr(" failed byte count from 0x%08x-0x%08x: 0x%x\n",
			 start, start + len - 1, failcount);
		ret = -1;
	}
	return ret;
}

614
/* start is an offset to the base address of the flash chip */
615 616
int check_erased_range(struct flashctx *flash, unsigned int start,
		       unsigned int len)
617 618 619 620 621
{
	int ret;
	uint8_t *cmpbuf = malloc(len);

	if (!cmpbuf) {
622
		msg_gerr("Could not allocate memory!\n");
623 624 625
		exit(1);
	}
	memset(cmpbuf, 0xff, len);
626
	ret = verify_range(flash, cmpbuf, start, len);
627 628 629 630
	free(cmpbuf);
	return ret;
}

631
/*
632
 * @cmpbuf	buffer to compare against, cmpbuf[0] is expected to match the
633
 *		flash content at location start
634 635 636 637
 * @start	offset to the base address of the flash chip
 * @len		length of the verified area
 * @return	0 for success, -1 for failure
 */
638
int verify_range(struct flashctx *flash, uint8_t *cmpbuf, unsigned int start, unsigned int len)
639
{
640
	uint8_t *readbuf = malloc(len);
641
	int ret = 0;
642 643 644 645

	if (!len)
		goto out_free;

646
	if (!flash->chip->read) {
647
		msg_cerr("ERROR: flashrom has no read function for this flash chip.\n");
648 649
		return 1;
	}
650
	if (!readbuf) {
651
		msg_gerr("Could not allocate memory!\n");
652 653 654
		exit(1);
	}

655
	if (start + len > flash->chip->total_size * 1024) {
656
		msg_gerr("Error: %s called with start 0x%x + len 0x%x >"
657
			" total_size 0x%x\n", __func__, start, len,
658
			flash->chip->total_size * 1024);
659 660 661
		ret = -1;
		goto out_free;
	}
662

663
	ret = flash->chip->read(flash, readbuf, start, len);
664 665 666 667 668 669
	if (ret) {
		msg_gerr("Verification impossible because read failed "
			 "at 0x%x (len 0x%x)\n", start, len);
		return ret;
	}

670
	ret = compare_range(cmpbuf, readbuf, start, len);
671 672 673 674 675
out_free:
	free(readbuf);
	return ret;
}

676
/*
677 678 679
 * Check if the buffer @have can be programmed to the content of @want without
 * erasing. This is only possible if all chunks of size @gran are either kept
 * as-is or changed from an all-ones state to any other state.
680 681 682
 *
 * Warning: This function assumes that @have and @want point to naturally
 * aligned regions.
683 684 685
 *
 * @have        buffer with current content
 * @want        buffer with desired content
686
 * @len		length of the checked area
687 688 689
 * @gran	write granularity (enum, not count)
 * @return      0 if no erase is needed, 1 otherwise
 */
690
int need_erase(uint8_t *have, uint8_t *want, unsigned int len, enum write_granularity gran)
691
{
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
692
	int result = 0;
693
	unsigned int i, j, limit;
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712

	switch (gran) {
	case write_gran_1bit:
		for (i = 0; i < len; i++)
			if ((have[i] & want[i]) != want[i]) {
				result = 1;
				break;
			}
		break;
	case write_gran_1byte:
		for (i = 0; i < len; i++)
			if ((have[i] != want[i]) && (have[i] != 0xff)) {
				result = 1;
				break;
			}
		break;
	case write_gran_256bytes:
		for (j = 0; j < len / 256; j++) {
			limit = min (256, len - j * 256);
713
			/* Are 'have' and 'want' identical? */
714 715 716 717
			if (!memcmp(have + j * 256, want + j * 256, limit))
				continue;
			/* have needs to be in erased state. */
			for (i = 0; i < limit; i++)
718
				if (have[j * 256 + i] != 0xff) {
719 720 721 722 723 724 725
					result = 1;
					break;
				}
			if (result)
				break;
		}
		break;
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
	default:
		msg_cerr("%s: Unsupported granularity! Please report a bug at "
			 "flashrom@flashrom.org\n", __func__);
	}
	return result;
}

/**
 * Check if the buffer @have needs to be programmed to get the content of @want.
 * If yes, return 1 and fill in first_start with the start address of the
 * write operation and first_len with the length of the first to-be-written
 * chunk. If not, return 0 and leave first_start and first_len undefined.
 *
 * Warning: This function assumes that @have and @want point to naturally
 * aligned regions.
 *
 * @have	buffer with current content
 * @want	buffer with desired content
 * @len		length of the checked area
 * @gran	write granularity (enum, not count)
746 747 748 749 750
 * @first_start	offset of the first byte which needs to be written (passed in
 *		value is increased by the offset of the first needed write
 *		relative to have/want or unchanged if no write is needed)
 * @return	length of the first contiguous area which needs to be written
 *		0 if no write is needed
751 752 753 754 755
 *
 * FIXME: This function needs a parameter which tells it about coalescing
 * in relation to the max write length of the programmer and the max write
 * length of the chip.
 */
756 757 758
static unsigned int get_next_write(uint8_t *have, uint8_t *want, unsigned int len,
			  unsigned int *first_start,
			  enum write_granularity gran)
759
{
760 761 762
	int need_write = 0;
	unsigned int rel_start = 0, first_len = 0;
	unsigned int i, limit, stride;
763 764 765 766

	switch (gran) {
	case write_gran_1bit:
	case write_gran_1byte:
767
		stride = 1;
768 769
		break;
	case write_gran_256bytes:
770
		stride = 256;
771 772 773 774
		break;
	default:
		msg_cerr("%s: Unsupported granularity! Please report a bug at "
			 "flashrom@flashrom.org\n", __func__);
775 776 777 778
		/* Claim that no write was needed. A write with unknown
		 * granularity is too dangerous to try.
		 */
		return 0;
779
	}
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
	for (i = 0; i < len / stride; i++) {
		limit = min(stride, len - i * stride);
		/* Are 'have' and 'want' identical? */
		if (memcmp(have + i * stride, want + i * stride, limit)) {
			if (!need_write) {
				/* First location where have and want differ. */
				need_write = 1;
				rel_start = i * stride;
			}
		} else {
			if (need_write) {
				/* First location where have and want
				 * do not differ anymore.
				 */
				break;
			}
		}
	}
798
	if (need_write)
799
		first_len = min(i * stride - rel_start, len);
800
	*first_start += rel_start;
801
	return first_len;
802 803
}

804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
/* This function generates various test patterns useful for testing controller
 * and chip communication as well as chip behaviour.
 *
 * If a byte can be written multiple times, each time keeping 0-bits at 0
 * and changing 1-bits to 0 if the new value for that bit is 0, the effect
 * is essentially an AND operation. That's also the reason why this function
 * provides the result of AND between various patterns.
 *
 * Below is a list of patterns (and their block length).
 * Pattern 0 is 05 15 25 35 45 55 65 75 85 95 a5 b5 c5 d5 e5 f5 (16 Bytes)
 * Pattern 1 is 0a 1a 2a 3a 4a 5a 6a 7a 8a 9a aa ba ca da ea fa (16 Bytes)
 * Pattern 2 is 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f (16 Bytes)
 * Pattern 3 is a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad ae af (16 Bytes)
 * Pattern 4 is 00 10 20 30 40 50 60 70 80 90 a0 b0 c0 d0 e0 f0 (16 Bytes)
 * Pattern 5 is 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f (16 Bytes)
 * Pattern 6 is 00 (1 Byte)
 * Pattern 7 is ff (1 Byte)
 * Patterns 0-7 have a big-endian block number in the last 2 bytes of each 256
 * byte block.
 *
 * Pattern 8 is 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11... (256 B)
 * Pattern 9 is ff fe fd fc fb fa f9 f8 f7 f6 f5 f4 f3 f2 f1 f0 ef ee... (256 B)
 * Pattern 10 is 00 00 00 01 00 02 00 03 00 04... (128 kB big-endian counter)
 * Pattern 11 is ff ff ff fe ff fd ff fc ff fb... (128 kB big-endian downwards)
 * Pattern 12 is 00 (1 Byte)
 * Pattern 13 is ff (1 Byte)
 * Patterns 8-13 have no block number.
 *
 * Patterns 0-3 are created to detect and efficiently diagnose communication
 * slips like missed bits or bytes and their repetitive nature gives good visual
 * cues to the person inspecting the results. In addition, the following holds:
 * AND Pattern 0/1 == Pattern 4
 * AND Pattern 2/3 == Pattern 5
 * AND Pattern 0/1/2/3 == AND Pattern 4/5 == Pattern 6
 * A weakness of pattern 0-5 is the inability to detect swaps/copies between
 * any two 16-byte blocks except for the last 16-byte block in a 256-byte bloc.
 * They work perfectly for detecting any swaps/aliasing of blocks >= 256 bytes.
 * 0x5 and 0xa were picked because they are 0101 and 1010 binary.
 * Patterns 8-9 are best for detecting swaps/aliasing of blocks < 256 bytes.
 * Besides that, they provide for bit testing of the last two bytes of every
 * 256 byte block which contains the block number for patterns 0-6.
 * Patterns 10-11 are special purpose for detecting subblock aliasing with
 * block sizes >256 bytes (some Dataflash chips etc.)
 * AND Pattern 8/9 == Pattern 12
 * AND Pattern 10/11 == Pattern 12
 * Pattern 13 is the completely erased state.
 * None of the patterns can detect aliasing at boundaries which are a multiple
 * of 16 MBytes (but such chips do not exist anyway for Parallel/LPC/FWH/SPI).
 */
int generate_testpattern(uint8_t *buf, uint32_t size, int variant)
{
	int i;

	if (!buf) {
858
		msg_gerr("Invalid buffer!\n");
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
		return 1;
	}

	switch (variant) {
	case 0:
		for (i = 0; i < size; i++)
			buf[i] = (i & 0xf) << 4 | 0x5;
		break;
	case 1:
		for (i = 0; i < size; i++)
			buf[i] = (i & 0xf) << 4 | 0xa;
		break;
	case 2:
		for (i = 0; i < size; i++)
			buf[i] = 0x50 | (i & 0xf);
		break;
	case 3:
		for (i = 0; i < size; i++)
			buf[i] = 0xa0 | (i & 0xf);
		break;
	case 4:
		for (i = 0; i < size; i++)
			buf[i] = (i & 0xf) << 4;
		break;
	case 5:
		for (i = 0; i < size; i++)
			buf[i] = i & 0xf;
		break;
	case 6:
		memset(buf, 0x00, size);
		break;
	case 7:
		memset(buf, 0xff, size);
		break;
	case 8:
		for (i = 0; i < size; i++)
			buf[i] = i & 0xff;
		break;
	case 9:
		for (i = 0; i < size; i++)
			buf[i] = ~(i & 0xff);
		break;
	case 10:
		for (i = 0; i < size % 2; i++) {
			buf[i * 2] = (i >> 8) & 0xff;
			buf[i * 2 + 1] = i & 0xff;
		}
		if (size & 0x1)
			buf[i * 2] = (i >> 8) & 0xff;
		break;
	case 11:
		for (i = 0; i < size % 2; i++) {
			buf[i * 2] = ~((i >> 8) & 0xff);
			buf[i * 2 + 1] = ~(i & 0xff);
		}
		if (size & 0x1)
			buf[i * 2] = ~((i >> 8) & 0xff);
		break;
	case 12:
		memset(buf, 0x00, size);
		break;
	case 13:
		memset(buf, 0xff, size);
		break;
	}

	if ((variant >= 0) && (variant <= 7)) {
		/* Write block number in the last two bytes of each 256-byte
		 * block, big endian for easier reading of the hexdump.
		 * Note that this wraps around for chips larger than 2^24 bytes
		 * (16 MB).
		 */
		for (i = 0; i < size / 256; i++) {
			buf[i * 256 + 254] = (i >> 8) & 0xff;
			buf[i * 256 + 255] = i & 0xff;
		}
	}

	return 0;
}

940 941 942
int check_max_decode(enum chipbustype buses, uint32_t size)
{
	int limitexceeded = 0;
943 944

	if ((buses & BUS_PARALLEL) && (max_rom_decode.parallel < size)) {
945
		limitexceeded++;
946
		msg_pdbg("Chip size %u kB is bigger than supported "
947 948 949 950
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.parallel / 1024, "Parallel");
951
	}
952
	if ((buses & BUS_LPC) && (max_rom_decode.lpc < size)) {
953
		limitexceeded++;
954
		msg_pdbg("Chip size %u kB is bigger than supported "
955 956 957 958
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.lpc / 1024, "LPC");
959
	}
960
	if ((buses & BUS_FWH) && (max_rom_decode.fwh < size)) {
961
		limitexceeded++;
962
		msg_pdbg("Chip size %u kB is bigger than supported "
963 964 965 966
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.fwh / 1024, "FWH");
967
	}
968
	if ((buses & BUS_SPI) && (max_rom_decode.spi < size)) {
969
		limitexceeded++;
970
		msg_pdbg("Chip size %u kB is bigger than supported "
971 972 973 974
			 "size %u kB of chipset/board/programmer "
			 "for %s interface, "
			 "probe/read/erase/write may fail. ", size / 1024,
			 max_rom_decode.spi / 1024, "SPI");
975 976 977 978 979 980 981
	}
	if (!limitexceeded)
		return 0;
	/* Sometimes chip and programmer have more than one bus in common,
	 * and the limit is not exceeded on all buses. Tell the user.
	 */
	if (bitcount(buses) > limitexceeded)
982
		/* FIXME: This message is designed towards CLI users. */
983
		msg_pdbg("There is at least one common chip/programmer "
984 985
			 "interface which can support a chip of this size. "
			 "You can try --force at your own risk.\n");
986 987 988
	return 1;
}

989
int probe_flash(struct registered_programmer *pgm, int startchip, struct flashctx *flash, int force)
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
990
{
991
	const struct flashchip *chip;
992
	unsigned long base = 0;
993
	char location[64];
994 995
	uint32_t size;
	enum chipbustype buses_common;
996
	char *tmp;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
997

998 999
	for (chip = flashchips + startchip; chip && chip->name; chip++) {
		if (chip_to_probe && strcmp(chip->name, chip_to_probe) != 0)
1000
			continue;
1001
		buses_common = pgm->buses_supported & chip->bustype;
1002
		if (!buses_common)
1003
			continue;
1004 1005 1006
		msg_gdbg("Probing for %s %s, %d kB: ", chip->vendor, chip->name, chip->total_size);
		if (!chip->probe && !force) {
			msg_gdbg("failed! flashrom has no probe function for this flash chip.\n");
1007 1008
			continue;
		}
Stefan Reinauer's avatar
Stefan Reinauer committed
1009

1010
		size = chip->total_size * 1024;
1011
		check_max_decode(buses_common, size);
Stefan Reinauer's avatar
Stefan Reinauer committed
1012

1013
		/* Start filling in the dynamic data. */
1014 1015 1016 1017 1018 1019 1020
		flash->chip = calloc(1, sizeof(struct flashchip));
		if (!flash->chip) {
			msg_gerr("Out of memory!\n");
			exit(1);
		}
		memcpy(flash->chip, chip, sizeof(struct flashchip));
		flash->pgm = pgm;
1021

1022
		base = flashbase ? flashbase : (0xffffffff - size + 1);
1023
		flash->virtual_memory = (chipaddr)programmer_map_flash_region("flash chip", base, size);
1024

1025 1026 1027
		/* We handle a forced match like a real match, we just avoid probing. Note that probe_flash()
		 * is only called with force=1 after normal probing failed.
		 */
1028 1029 1030
		if (force)
			break;

1031
		if (flash->chip->probe(flash) != 1)
1032 1033
			goto notfound;

1034 1035
		/* If this is the first chip found, accept it.
		 * If this is not the first chip found, accept it only if it is
Stefan Tauner's avatar
Stefan Tauner committed
1036 1037 1038 1039
		 * a non-generic match. SFDP and CFI are generic matches.
		 * startchip==0 means this call to probe_flash() is the first
		 * one for this programmer interface and thus no other chip has
		 * been found on this interface.
1040
		 */
1041
		if (startchip == 0 && flash->chip->model_id == SFDP_DEVICE_ID) {
Stefan Tauner's avatar
Stefan Tauner committed
1042 1043 1044
			msg_cinfo("===\n"
				  "SFDP has autodetected a flash chip which is "
				  "not natively supported by flashrom yet.\n");
1045
			if (count_usable_erasers(flash) == 0)
Stefan Tauner's avatar
Stefan Tauner committed
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
				msg_cinfo("The standard operations read and "
					  "verify should work, but to support "
					  "erase, write and all other "
					  "possible features");
			else
				msg_cinfo("All standard operations (read, "
					  "verify, erase and write) should "
					  "work, but to support all possible "
					  "features");

1056 1057 1058 1059 1060
			msg_cinfo(" we need to add them manually.\n"
				  "You can help us by mailing us the output of the following command to "
				  "flashrom@flashrom.org:\n"
				  "'flashrom -VV [plus the -p/--programmer parameter]'\n"
				  "Thanks for your help!\n"
Stefan Tauner's avatar
Stefan Tauner committed
1061 1062 1063
				  "===\n");
		}

1064 1065
		/* First flash chip detected on this bus. */
		if (startchip == 0)
1066
			break;
1067 1068 1069 1070
		/* Not the first flash chip detected on this bus, but not a generic match either. */
		if ((flash->chip->model_id != GENERIC_DEVICE_ID) && (flash->chip->model_id != SFDP_DEVICE_ID))
			break;
		/* Not the first flash chip detected on this bus, and it's just a generic match. Ignore it. */
1071
notfound:
1072 1073 1074 1075
		programmer_unmap_flash_region((void *)flash->virtual_memory, size);
		flash->virtual_memory = (chipaddr)NULL;
		free(flash->chip);
		flash->chip = NULL;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1076
	}
Uwe Hermann's avatar
Uwe Hermann committed
1077

1078
	if (!flash->chip)
1079
		return -1;
1080

1081 1082
#if CONFIG_INTERNAL == 1
	if (programmer_table[programmer].map_flash_region == physmap)
1083
		snprintf(location, sizeof(location), "at physical address 0x%lx", base);
1084 1085
	else
#endif
1086 1087
		snprintf(location, sizeof(location), "on %s", programmer_table[programmer].name);

1088 1089 1090
	tmp = flashbuses_to_text(flash->chip->bustype);
	msg_cinfo("%s %s flash chip \"%s\" (%d kB, %s) %s.\n", force ? "Assuming" : "Found",
		  flash->chip->vendor, flash->chip->name, flash->chip->total_size, tmp, location);
1091
	free(tmp);
1092

1093 1094 1095 1096
	/* Flash registers will not be mapped if the chip was forced. Lock info
	 * may be stored in registers, so avoid lock info printing.
	 */
	if (!force)
1097 1098
		if (flash->chip->printlock)
			flash->chip->printlock(flash);
1099

1100
	/* Return position of matching chip. */
1101
	return chip - flashchips;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1102 1103
}

1104 1105
int read_buf_from_file(unsigned char *buf, unsigned long size,
		       const char *filename)
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
{
	unsigned long numbytes;
	FILE *image;
	struct stat image_stat;

	if ((image = fopen(filename, "rb")) == NULL) {
		perror(filename);
		return 1;
	}
	if (fstat(fileno(image), &image_stat) != 0) {
		perror(filename);
		fclose(image);
		return 1;
	}
	if (image_stat.st_size != size) {
1121 1122
		msg_gerr("Error: Image size (%ld B) doesn't match the flash chip's size (%ld B)!\n",
			 image_stat.st_size, size);
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
		fclose(image);
		return 1;
	}
	numbytes = fread(buf, 1, size, image);
	if (fclose(image)) {
		perror(filename);
		return 1;
	}
	if (numbytes != size) {
		msg_gerr("Error: Failed to read complete file. Got %ld bytes, "
			 "wanted %ld!\n", numbytes, size);
		return 1;
	}
	return 0;
}

1139 1140
int write_buf_to_file(unsigned char *buf, unsigned long size,
		      const char *filename)
1141 1142 1143
{
	unsigned long numbytes;
	FILE *image;
1144 1145

	if (!filename) {
1146
		msg_gerr("No filename specified.\n");
1147 1148
		return 1;
	}
1149
	if ((image = fopen(filename, "wb")) == NULL) {
1150
		perror(filename);
1151
		return 1;
1152
	}
1153 1154 1155

	numbytes = fwrite(buf, 1, size, image);
	fclose(image);
1156 1157 1158
	if (numbytes != size) {
		msg_gerr("File %s could not be written completely.\n",
			 filename);
1159
		return 1;
1160
	}
1161 1162 1163
	return 0;
}

1164
int read_flash_to_file(struct flashctx *flash, const char *filename)
1165
{
1166
	unsigned long size = flash->chip->total_size * 1024;
1167 1168 1169 1170 1171 1172 1173 1174 1175
	unsigned char *buf = calloc(size, sizeof(char));
	int ret = 0;

	msg_cinfo("Reading flash... ");
	if (!buf) {
		msg_gerr("Memory allocation failed!\n");
		msg_cinfo("FAILED.\n");
		return 1;
	}
1176
	if (!flash->chip->read) {
1177 1178 1179 1180
		msg_cerr("No read function available for this flash chip.\n");
		ret = 1;
		goto out_free;
	}
1181
	if (flash->chip->read(flash, buf, 0, size)) {
1182 1183 1184 1185 1186
		msg_cerr("Read operation failed!\n");
		ret = 1;
		goto out_free;
	}

Stefan Tauner's avatar
Stefan Tauner committed
1187
	ret = write_buf_to_file(buf, size, filename);
1188 1189 1190 1191 1192 1193
out_free:
	free(buf);
	msg_cinfo("%s.\n", ret ? "FAILED" : "done");
	return ret;
}

1194 1195
/* This function shares a lot of its structure with erase_and_write_flash() and
 * walk_eraseregions().
1196 1197
 * Even if an error is found, the function will keep going and check the rest.
 */
1198
static int selfcheck_eraseblocks(const struct flashchip *chip)
1199
{
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1200 1201
	int i, j, k;
	int ret = 0;
1202 1203 1204

	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
		unsigned int done = 0;
1205
		struct block_eraser eraser = chip->block_erasers[k];
1206 1207 1208 1209 1210 1211 1212 1213

		for (i = 0; i < NUM_ERASEREGIONS; i++) {
			/* Blocks with zero size are bugs in flashchips.c. */
			if (eraser.eraseblocks[i].count &&
			    !eraser.eraseblocks[i].size) {
				msg_gerr("ERROR: Flash chip %s erase function "
					"%i region %i has size 0. Please report"
					" a bug at flashrom@flashrom.org\n",
1214
					chip->name, k, i);
1215
				ret = 1;
1216 1217 1218 1219 1220 1221 1222
			}
			/* Blocks with zero count are bugs in flashchips.c. */
			if (!eraser.eraseblocks[i].count &&
			    eraser.eraseblocks[i].size) {
				msg_gerr("ERROR: Flash chip %s erase function "
					"%i region %i has count 0. Please report"
					" a bug at flashrom@flashrom.org\n",
1223
					chip->name, k, i);
1224
				ret = 1;
1225 1226 1227 1228
			}
			done += eraser.eraseblocks[i].count *
				eraser.eraseblocks[i].size;
		}
1229 1230
		/* Empty eraseblock definition with erase function.  */
		if (!done && eraser.block_erase)
1231
			msg_gspew("Strange: Empty eraseblock definition with "
1232
				  "non-empty erase function. Not an error.\n");
1233 1234
		if (!done)
			continue;
1235
		if (done != chip->total_size * 1024) {
1236 1237 1238
			msg_gerr("ERROR: Flash chip %s erase function %i "
				"region walking resulted in 0x%06x bytes total,"
				" expected 0x%06x bytes. Please report a bug at"
1239 1240
				" flashrom@flashrom.org\n", chip->name, k,
				done, chip->total_size * 1024);
1241
			ret = 1;
1242
		}
1243 1244 1245 1246 1247 1248
		if (!eraser.block_erase)
			continue;
		/* Check if there are identical erase functions for different
		 * layouts. That would imply "magic" erase functions. The
		 * easiest way to check this is with function pointers.
		 */
1249
		for (j = k + 1; j < NUM_ERASEFUNCTIONS; j++) {
1250
			if (eraser.block_erase ==
1251
			    chip->block_erasers[j].block_erase) {
1252 1253 1254
				msg_gerr("ERROR: Flash chip %s erase function "
					"%i and %i are identical. Please report"
					" a bug at flashrom@flashrom.org\n",
1255
					chip->name, k, j);
1256 1257
				ret = 1;
			}
1258
		}
1259
	}
1260
	return ret;
1261 1262
}

1263
static int erase_and_write_block_helper(struct flashctx *flash,
1264
					unsigned int start, unsigned int len,
1265
					uint8_t *curcontents,
1266
					uint8_t *newcontents,
1267
					int (*erasefn) (struct flashctx *flash,
1268 1269 1270
							unsigned int addr,
							unsigned int len))
{
1271 1272
	unsigned int starthere = 0, lenhere = 0;
	int ret = 0, skip = 1, writecount = 0;
1273 1274
	enum write_granularity gran = write_gran_256bytes; /* FIXME */

1275
	/* curcontents and newcontents are opaque to walk_eraseregions, and
1276 1277
	 * need to be adjusted here to keep the impression of proper abstraction
	 */
1278
	curcontents += start;
1279 1280 1281
	newcontents += start;
	msg_cdbg(":");
	/* FIXME: Assume 256 byte granularity for now to play it safe. */
1282
	if (need_erase(curcontents, newcontents, len, gran)) {
1283 1284 1285 1286
		msg_cdbg("E");
		ret = erasefn(flash, start, len);
		if (ret)
			return ret;
1287 1288 1289 1290
		if (check_erased_range(flash, start, len)) {
			msg_cerr("ERASE FAILED!\n");
			return -1;
		}
1291 1292
		/* Erase was successful. Adjust curcontents. */
		memset(curcontents, 0xff, len);
1293 1294
		skip = 0;
	}
1295 1296 1297 1298
	/* get_next_write() sets starthere to a new value after the call. */
	while ((lenhere = get_next_write(curcontents + starthere,
					 newcontents + starthere,
					 len - starthere, &starthere, gran))) {
1299 1300 1301
		if (!writecount++)
			msg_cdbg("W");
		/* Needs the partial write function signature. */
1302
		ret = flash->chip->write(flash, newcontents + starthere,
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
				   start + starthere, lenhere);
		if (ret)
			return ret;
		starthere += lenhere;
		skip = 0;
	}
	if (skip)
		msg_cdbg("S");
	return ret;
}

1314 1315
static int walk_eraseregions(struct flashctx *flash, int erasefunction,
			     int (*do_something) (struct flashctx *flash,
1316
						  unsigned int addr,
1317 1318 1319 1320
						  unsigned int len,
						  uint8_t *param1,
						  uint8_t *param2,
						  int (*erasefn) (
1321
							struct flashctx *flash,
1322 1323 1324
							unsigned int addr,
							unsigned int len)),
			     void *param1, void *param2)
1325 1326
{
	int i, j;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1327 1328
	unsigned int start = 0;
	unsigned int len;
1329
	struct block_eraser eraser = flash->chip->block_erasers[erasefunction];
1330

1331 1332 1333 1334 1335 1336
	for (i = 0; i < NUM_ERASEREGIONS; i++) {
		/* count==0 for all automatically initialized array
		 * members so the loop below won't be executed for them.
		 */
		len = eraser.eraseblocks[i].size;
		for (j = 0; j < eraser.eraseblocks[i].count; j++) {
1337 1338 1339 1340
			/* Print this for every block except the first one. */
			if (i || j)
				msg_cdbg(", ");
			msg_cdbg("0x%06x-0x%06x", start,
1341
				     start + len - 1);
1342 1343
			if (do_something(flash, start, len, param1, param2,
					 eraser.block_erase)) {
1344
				return 1;
1345
			}
1346 1347 1348
			start += len;
		}
	}
1349
	msg_cdbg("\n");
1350 1351 1352
	return 0;
}

1353
static int check_block_eraser(const struct flashctx *flash, int k, int log)
1354
{
1355
	struct block_eraser eraser = flash->chip->block_erasers[k];
1356 1357 1358 1359 1360 1361 1362 1363 1364

	if (!eraser.block_erase && !eraser.eraseblocks[0].count) {
		if (log)
			msg_cdbg("not defined. ");
		return 1;
	}
	if (!eraser.block_erase && eraser.eraseblocks[0].count) {
		if (log)
			msg_cdbg("eraseblock layout is known, but matching "
Stefan Tauner's avatar
Stefan Tauner committed
1365
				 "block erase function is not implemented. ");
1366 1367 1368 1369 1370
		return 1;
	}
	if (eraser.block_erase && !eraser.eraseblocks[0].count) {
		if (log)
			msg_cdbg("block erase function found, but "
Stefan Tauner's avatar
Stefan Tauner committed
1371
				 "eraseblock layout is not defined. ");
1372 1373
		return 1;
	}
1374
	// TODO: Once erase functions are annotated with allowed buses, check that as well.
1375 1376 1377
	return 0;
}

1378
int erase_and_write_flash(struct flashctx *flash, uint8_t *oldcontents,
1379
			  uint8_t *newcontents)
1380
{
1381
	int k, ret = 1;
1382
	uint8_t *curcontents;
1383
	unsigned long size = flash->chip->total_size * 1024;
1384
	unsigned int usable_erasefunctions = count_usable_erasers(flash);
1385 1386

	msg_cinfo("Erasing and writing flash chip... ");
1387 1388 1389 1390 1391
	curcontents = malloc(size);
	if (!curcontents) {
		msg_gerr("Out of memory!\n");
		exit(1);
	}
1392 1393
	/* Copy oldcontents to curcontents to avoid clobbering oldcontents. */
	memcpy(curcontents, oldcontents, size);
1394 1395

	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
1396 1397
		if (k != 0)
			msg_cdbg("Looking for another erase function.\n");
1398 1399 1400 1401
		if (!usable_erasefunctions) {
			msg_cdbg("No usable erase functions left.\n");
			break;
		}
1402 1403
		msg_cdbg("Trying erase function %i... ", k);
		if (check_block_eraser(flash, k, 1))
1404
			continue;
1405
		usable_erasefunctions--;
1406 1407
		ret = walk_eraseregions(flash, k, &erase_and_write_block_helper,
					curcontents, newcontents);
1408 1409 1410
		/* If everything is OK, don't try another erase function. */
		if (!ret)
			break;
1411
		/* Write/erase failed, so try to find out what the current chip
1412 1413
		 * contents are. If no usable erase functions remain, we can
		 * skip this: the next iteration will break immediately anyway.
1414
		 */
1415 1416
		if (!usable_erasefunctions)
			continue;
1417 1418 1419 1420
		/* Reading the whole chip may take a while, inform the user even
		 * in non-verbose mode.
		 */
		msg_cinfo("Reading current flash chip contents... ");
1421
		if (flash->chip->read(flash, curcontents, 0, size)) {
1422
			/* Now we are truly screwed. Read failed as well. */
1423
			msg_cerr("Can't read anymore! Aborting.\n");
1424 1425 1426 1427 1428
			/* We have no idea about the flash chip contents, so
			 * retrying with another erase function is pointless.
			 */
			break;
		}
1429
		msg_cinfo("done. ");
1430
	}
1431 1432
	/* Free the scratchpad. */
	free(curcontents);
1433

1434
	if (ret) {
1435
		msg_cerr("FAILED!\n");
1436
	} else {
1437
		msg_cinfo("Erase/write done.\n");
1438 1439
	}
	return ret;
1440 1441
}

1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
void nonfatal_help_message(void)
{
	msg_gerr("Writing to the flash chip apparently didn't do anything.\n"
		"This means we have to add special support for your board, "
		  "programmer or flash chip.\n"
		"Please report this on IRC at irc.freenode.net (channel "
		  "#flashrom) or\n"
		"mail flashrom@flashrom.org!\n"
		"-------------------------------------------------------------"
		  "------------------\n"
		"You may now reboot or simply leave the machine running.\n");
}

1455
void emergency_help_message(void)
1456
{
1457
	msg_gerr("Your flash chip is in an unknown state.\n"
1458
		"Get help on IRC at chat.freenode.net (channel #flashrom) or\n"
1459 1460
		"mail flashrom@flashrom.org with the subject \"FAILED: <your board name>\"!\n"
		"-------------------------------------------------------------------------------\n"
1461 1462 1463
		"DO NOT REBOOT OR POWEROFF!\n");
}

1464
/* The way to go if you want a delimited list of programmers */
1465
void list_programmers(const char *delim)
1466 1467 1468
{
	enum programmer p;
	for (p = 0; p < PROGRAMMER_INVALID; p++) {
1469
		msg_ginfo("%s", programmer_table[p].name);
1470
		if (p < PROGRAMMER_INVALID - 1)
1471
			msg_ginfo("%s", delim);
1472
	}
1473
	msg_ginfo("\n");	
1474 1475
}

1476 1477 1478
void list_programmers_linebreak(int startcol, int cols, int paren)
{
	const char *pname;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1479 1480
	int pnamelen;
	int remaining = 0, firstline = 1;
1481
	enum programmer p;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1482
	int i;
1483 1484 1485 1486 1487 1488 1489 1490

	for (p = 0; p < PROGRAMMER_INVALID; p++) {
		pname = programmer_table[p].name;
		pnamelen = strlen(pname);
		if (remaining - pnamelen - 2 < 0) {
			if (firstline)
				firstline = 0;
			else
1491
				msg_ginfo("\n");
1492
			for (i = 0; i < startcol; i++)
1493
				msg_ginfo(" ");
1494 1495
			remaining = cols - startcol;
		} else {
1496
			msg_ginfo(" ");
1497 1498 1499
			remaining--;
		}
		if (paren && (p == 0)) {
1500
			msg_ginfo("(");
1501 1502
			remaining--;
		}
1503
		msg_ginfo("%s", pname);
1504 1505
		remaining -= pnamelen;
		if (p < PROGRAMMER_INVALID - 1) {
1506
			msg_ginfo(",");
1507 1508 1509
			remaining--;
		} else {
			if (paren)
1510
				msg_ginfo(")");
1511 1512 1513 1514
		}
	}
}

1515 1516
void print_sysinfo(void)
{
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
#ifdef _WIN32
	SYSTEM_INFO si;
	OSVERSIONINFOEX osvi;

	memset(&si, 0, sizeof(SYSTEM_INFO));
	memset(&osvi, 0, sizeof(OSVERSIONINFOEX));
	msg_ginfo(" on Windows");
	/* Tell Windows which version of the structure we want. */
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	if (GetVersionEx((OSVERSIONINFO*) &osvi))
		msg_ginfo(" %lu.%lu", osvi.dwMajorVersion, osvi.dwMinorVersion);
	else
		msg_ginfo(" unknown version");
	GetSystemInfo(&si);
	switch (si.wProcessorArchitecture) {
	case PROCESSOR_ARCHITECTURE_AMD64:
		msg_ginfo(" (x86_64)");
		break;
	case PROCESSOR_ARCHITECTURE_INTEL:
		msg_ginfo(" (x86)");
		break;
	default:
		msg_ginfo(" (unknown arch)");
		break;
	}
#elif HAVE_UTSNAME == 1
1543 1544
	struct utsname osinfo;

1545
	uname(&osinfo);
1546 1547 1548 1549 1550
	msg_ginfo(" on %s %s (%s)", osinfo.sysname, osinfo.release,
		  osinfo.machine);
#else
	msg_ginfo(" on unknown machine");
#endif
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1551 1552 1553 1554 1555
}

void print_buildinfo(void)
{
	msg_gdbg("flashrom was built with");
1556 1557
#if NEED_PCI == 1
#ifdef PCILIB_VERSION
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1558
	msg_gdbg(" libpci %s,", PCILIB_VERSION);
1559
#else
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1560
	msg_gdbg(" unknown PCI library,");
1561 1562 1563
#endif
#endif
#ifdef __clang__
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1564
	msg_gdbg(" LLVM Clang");
1565
#ifdef __clang_version__
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1566
	msg_gdbg(" %s,", __clang_version__);
1567
#else
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1568
	msg_gdbg(" unknown version (before r102686),");
1569
#endif
1570
#elif defined(__GNUC__)
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1571
	msg_gdbg(" GCC");
1572
#ifdef __VERSION__
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1573
	msg_gdbg(" %s,", __VERSION__);
1574
#else
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1575
	msg_gdbg(" unknown version,");
1576
#endif
1577
#else
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1578
	msg_gdbg(" unknown compiler,");
1579
#endif
1580
#if defined (__FLASHROM_LITTLE_ENDIAN__)
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1581
	msg_gdbg(" little endian");
1582
#elif defined (__FLASHROM_BIG_ENDIAN__)
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1583
	msg_gdbg(" big endian");
1584 1585
#else
#error Endianness could not be determined
1586
#endif
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1587
	msg_gdbg("\n");
1588 1589
}

1590 1591
void print_version(void)
{
1592
	msg_ginfo("flashrom v%s", flashrom_version);
1593
	print_sysinfo();
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1594
	msg_ginfo("\n");
1595 1596
}

1597 1598 1599
void print_banner(void)
{
	msg_ginfo("flashrom is free software, get the source code at "
1600
		  "http://www.flashrom.org\n");
1601 1602 1603
	msg_ginfo("\n");
}

1604 1605
int selfcheck(void)
{
1606
	const struct flashchip *chip;
1607 1608
	int i;
	int ret = 0;
1609 1610 1611 1612

	/* Safety check. Instead of aborting after the first error, check
	 * if more errors exist.
	 */
1613
	if (ARRAY_SIZE(programmer_table) - 1 != PROGRAMMER_INVALID) {
1614
		msg_gerr("Programmer table miscompilation!\n");
1615
		ret = 1;
1616
	}
1617 1618 1619 1620 1621 1622 1623 1624 1625
	for (i = 0; i < PROGRAMMER_INVALID; i++) {
		const struct programmer_entry p = programmer_table[i];
		if (p.name == NULL) {
			msg_gerr("All programmers need a valid name, but the one with index %d does not!\n", i);
			ret = 1;
			/* This might hide other problems with this programmer, but allows for better error
			 * messages below without jumping through hoops. */
			continue;
		}
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
		switch (p.type) {
		case USB:
		case PCI:
		case OTHER:
			if (p.devs.note == NULL) {
				if (strcmp("internal", p.name) == 0)
					break; /* This one has its device list stored separately. */
				msg_gerr("Programmer %s has neither a device list nor a textual description!\n",
					 p.name);
				ret = 1;
			}
			break;
		default:
			msg_gerr("Programmer %s does not have a valid type set!\n", p.name);
			ret = 1;
			break;
		}
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
		if (p.init == NULL) {
			msg_gerr("Programmer %s does not have a valid init function!\n", p.name);
			ret = 1;
		}
		if (p.delay == NULL) {
			msg_gerr("Programmer %s does not have a valid delay function!\n", p.name);
			ret = 1;
		}
		if (p.map_flash_region == NULL) {
			msg_gerr("Programmer %s does not have a valid map_flash_region function!\n", p.name);
			ret = 1;
		}
		if (p.unmap_flash_region == NULL) {
			msg_gerr("Programmer %s does not have a valid unmap_flash_region function!\n", p.name);
			ret = 1;
		}
	}
1660
	/* It would be favorable if we could also check for correct termination
1661
	 * of the following arrays, but we don't know their sizes in here...
1662 1663 1664 1665 1666 1667 1668
	 * For 'flashchips' we check the first element to be non-null. In the
	 * other cases there exist use cases where the first element can be
	 * null. */
	if (flashchips == NULL || flashchips[0].vendor == NULL) {
		msg_gerr("Flashchips table miscompilation!\n");
		ret = 1;
	}
1669 1670
	for (chip = flashchips; chip && chip->name; chip++)
		if (selfcheck_eraseblocks(chip))
1671
			ret = 1;
1672 1673 1674 1675 1676 1677

#if CONFIG_INTERNAL == 1
	if (chipset_enables == NULL) {
		msg_gerr("Chipset enables table does not exist!\n");
		ret = 1;
	}
1678
	if (board_matches == NULL) {
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
		msg_gerr("Board enables table does not exist!\n");
		ret = 1;
	}
	if (boards_known == NULL) {
		msg_gerr("Known boards table does not exist!\n");
		ret = 1;
	}
	if (laptops_known == NULL) {
		msg_gerr("Known laptops table does not exist!\n");
		ret = 1;
	}
1690
#endif
1691
	return ret;
1692 1693
}

1694
void check_chip_supported(const struct flashchip *chip)
1695
{
1696
	if (chip->feature_bits & FEATURE_OTP) {
1697 1698 1699 1700 1701 1702
		msg_cdbg("This chip may contain one-time programmable memory. "
			 "flashrom cannot read\nand may never be able to write "
			 "it, hence it may not be able to completely\n"
			 "clone the contents of this chip (see man page for "
			 "details).\n");
	}
1703
	if (TEST_OK_MASK != (chip->tested & TEST_OK_MASK)) {
1704
		msg_cinfo("===\n");
1705
		if (chip->tested & TEST_BAD_MASK) {
1706
			msg_cinfo("This flash part has status NOT WORKING for operations:");
1707
			if (chip->tested & TEST_BAD_PROBE)
1708
				msg_cinfo(" PROBE");
1709
			if (chip->tested & TEST_BAD_READ)
1710
				msg_cinfo(" READ");
1711
			if (chip->tested & TEST_BAD_ERASE)
1712
				msg_cinfo(" ERASE");
1713
			if (chip->tested & TEST_BAD_WRITE)
1714 1715
				msg_cinfo(" WRITE");
			msg_cinfo("\n");
1716
		}
1717 1718 1719 1720
		if ((!(chip->tested & TEST_BAD_PROBE) && !(chip->tested & TEST_OK_PROBE)) ||
		    (!(chip->tested & TEST_BAD_READ) && !(chip->tested & TEST_OK_READ)) ||
		    (!(chip->tested & TEST_BAD_ERASE) && !(chip->tested & TEST_OK_ERASE)) ||
		    (!(chip->tested & TEST_BAD_WRITE) && !(chip->tested & TEST_OK_WRITE))) {
1721
			msg_cinfo("This flash part has status UNTESTED for operations:");
1722
			if (!(chip->tested & TEST_BAD_PROBE) && !(chip->tested & TEST_OK_PROBE))
1723
				msg_cinfo(" PROBE");
1724
			if (!(chip->tested & TEST_BAD_READ) && !(chip->tested & TEST_OK_READ))
1725
				msg_cinfo(" READ");
1726
			if (!(chip->tested & TEST_BAD_ERASE) && !(chip->tested & TEST_OK_ERASE))
1727
				msg_cinfo(" ERASE");
1728
			if (!(chip->tested & TEST_BAD_WRITE) && !(chip->tested & TEST_OK_WRITE))
1729 1730
				msg_cinfo(" WRITE");
			msg_cinfo("\n");
1731
		}
1732
		/* FIXME: This message is designed towards CLI users. */
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
		msg_cinfo("The test status of this chip may have been updated "
			    "in the latest development\n"
			  "version of flashrom. If you are running the latest "
			    "development version,\n"
			  "please email a report to flashrom@flashrom.org if "
			    "any of the above operations\n"
			  "work correctly for you with this flash part. Please "
			    "include the flashrom\n"
			  "output with the additional -V option for all "
			    "operations you tested (-V, -Vr,\n"
Paul Menzel's avatar
Paul Menzel committed
1743
			  "-VE, -Vw), and mention which mainboard or "
1744
			    "programmer you tested.\n"
1745 1746
			  "Please mention your board in the subject line. "
			    "Thanks for your help!\n");
1747 1748 1749
	}
}

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1750 1751
/* FIXME: This function signature needs to be improved once doit() has a better
 * function signature.
1752
 */
1753 1754
int chip_safety_check(const struct flashctx *flash, int force, int read_it, int write_it, int erase_it,
		      int verify_it)
1755
{
1756 1757
	const struct flashchip *chip = flash->chip;

1758 1759 1760 1761 1762 1763
	if (!programmer_may_write && (write_it || erase_it)) {
		msg_perr("Write/erase is not working yet on your programmer in "
			 "its current configuration.\n");
		/* --force is the wrong approach, but it's the best we can do
		 * until the generic programmer parameter parser is merged.
		 */
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1764
		if (!force)
1765
			return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1766
		msg_cerr("Continuing anyway.\n");
1767 1768
	}

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1769 1770
	if (read_it || erase_it || write_it || verify_it) {
		/* Everything needs read. */
1771
		if (chip->tested & TEST_BAD_READ) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1772 1773
			msg_cerr("Read is not working on this chip. ");
			if (!force)
1774
				return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1775
			msg_cerr("Continuing anyway.\n");
1776
		}
1777
		if (!chip->read) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1778 1779
			msg_cerr("flashrom has no read function for this "
				 "flash chip.\n");
1780
			return 1;
1781
		}
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1782 1783 1784
	}
	if (erase_it || write_it) {
		/* Write needs erase. */
1785
		if (chip->tested & TEST_BAD_ERASE) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1786 1787
			msg_cerr("Erase is not working on this chip. ");
			if (!force)
1788
				return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1789
			msg_cerr("Continuing anyway.\n");
1790
		}
1791
		if(count_usable_erasers(flash) == 0) {
1792 1793 1794 1795
			msg_cerr("flashrom has no erase function for this "
				 "flash chip.\n");
			return 1;
		}
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1796 1797
	}
	if (write_it) {
1798
		if (chip->tested & TEST_BAD_WRITE) {
1799
			msg_cerr("Write is not working on this chip. ");
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1800
			if (!force)
1801
				return 1;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1802
			msg_cerr("Continuing anyway.\n");
1803
		}
1804
		if (!chip->write) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1805 1806
			msg_cerr("flashrom has no write function for this "
				 "flash chip.\n");
1807 1808
			return 1;
		}
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1809 1810 1811 1812 1813 1814 1815 1816
	}
	return 0;
}

/* This function signature is horrible. We need to design a better interface,
 * but right now it allows us to split off the CLI code.
 * Besides that, the function itself is a textbook example of abysmal code flow.
 */
1817 1818
int doit(struct flashctx *flash, int force, const char *filename, int read_it,
	 int write_it, int erase_it, int verify_it)
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1819
{
1820 1821
	uint8_t *oldcontents;
	uint8_t *newcontents;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1822
	int ret = 0;
1823
	unsigned long size = flash->chip->total_size * 1024;
1824

1825
	if (chip_safety_check(flash, force, read_it, write_it, erase_it, verify_it)) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1826
		msg_cerr("Aborting.\n");
1827 1828
		ret = 1;
		goto out_nofree;
1829 1830
	}

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1831 1832 1833
	/* Given the existence of read locks, we want to unlock for read,
	 * erase and write.
	 */
1834 1835
	if (flash->chip->unlock)
		flash->chip->unlock(flash);
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1836 1837 1838

	if (read_it) {
		ret = read_flash_to_file(flash, filename);
1839
		goto out_nofree;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1840
	}
1841

1842 1843 1844 1845 1846
	oldcontents = malloc(size);
	if (!oldcontents) {
		msg_gerr("Out of memory!\n");
		exit(1);
	}
1847 1848
	/* Assume worst case: All bits are 0. */
	memset(oldcontents, 0x00, size);
1849 1850 1851 1852 1853
	newcontents = malloc(size);
	if (!newcontents) {
		msg_gerr("Out of memory!\n");
		exit(1);
	}
1854 1855 1856 1857 1858 1859 1860 1861
	/* Assume best case: All bits should be 1. */
	memset(newcontents, 0xff, size);
	/* Side effect of the assumptions above: Default write action is erase
	 * because newcontents looks like a completely erased chip, and
	 * oldcontents being completely 0x00 means we have to erase everything
	 * before we can write.
	 */

Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1862
	if (erase_it) {
1863 1864 1865 1866 1867 1868
		/* FIXME: Do we really want the scary warning if erase failed?
		 * After all, after erase the chip is either blank or partially
		 * blank or it has the old contents. A blank chip won't boot,
		 * so if the user wanted erase and reboots afterwards, the user
		 * knows very well that booting won't work.
		 */
1869
		if (erase_and_write_flash(flash, oldcontents, newcontents)) {
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1870
			emergency_help_message();
1871
			ret = 1;
1872
		}
1873
		goto out;
Carl-Daniel Hailfinger's avatar
Carl-Daniel Hailfinger committed
1874 1875 1876
	}

	if (write_it || verify_it) {
1877
		if (read_buf_from_file(newcontents, size, filename)) {
1878 1879
			ret = 1;
			goto out;
1880 1881
		}

1882
#if CONFIG_INTERNAL == 1
1883 1884 1885 1886 1887 1888
		if (programmer == PROGRAMMER_INTERNAL && cb_check_image(newcontents, size) < 0) {
			if (force_boardmismatch) {
				msg_pinfo("Proceeding anyway because user forced us to.\n");
			} else {
				msg_perr("Aborting. You can override this with "
					 "-p internal:boardmismatch=force.\n");
1889 1890 1891
				ret = 1;
				goto out;
			}
1892
		}
1893
#endif
1894
	}
Ronald G. Minnich's avatar
Ronald G. Minnich committed
1895

1896 1897 1898 1899 1900 1901
	/* Read the whole chip to be able to check whether regions need to be
	 * erased and to give better diagnostics in case write fails.
	 * The alternative would be to read only the regions which are to be
	 * preserved, but in that case we might perform unneeded erase which
	 * takes time as well.
	 */
1902
	msg_cinfo("Reading old flash chip contents... ");
1903
	if (flash->chip->read(flash, oldcontents, 0, size)) {
1904
		ret = 1;
1905
		msg_cinfo("FAILED.\n");
1906
		goto out;
1907
	}
1908
	msg_cinfo("done.\n");
1909

1910 1911
	// This should be moved into each flash part's code to do it 
	// cleanly. This does the job.
1912
	handle_romentries(flash, oldcontents, newcontents);
1913

1914
	// ////////////////////////////////////////////////////////////
1915

1916
	if (write_it) {
1917 1918 1919
		if (erase_and_write_flash(flash, oldcontents, newcontents)) {
			msg_cerr("Uh oh. Erase/write failed. Checking if "
				 "anything changed.\n");
1920
			if (!flash->chip->read(flash, newcontents, 0, size)) {
1921 1922 1923 1924
				if (!memcmp(oldcontents, newcontents, size)) {
					msg_cinfo("Good. It seems nothing was "
						  "changed.\n");
					nonfatal_help_message();
1925 1926
					ret = 1;
					goto out;
1927 1928
				}
			}
1929
			emergency_help_message();
1930 1931
			ret = 1;
			goto out;
1932 1933
		}
	}
1934

1935
	if (verify_it) {
1936 1937 1938 1939
		msg_cinfo("Verifying flash... ");

		if (write_it) {
			/* Work around chips which need some time to calm down. */
1940
			programmer_delay(1000*1000);
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
			ret = verify_range(flash, newcontents, 0, size);
			/* If we tried to write, and verification now fails, we
			 * might have an emergency situation.
			 */
			if (ret)
				emergency_help_message();
		} else {
			ret = compare_range(newcontents, oldcontents, 0, size);
		}
		if (!ret)
			msg_cinfo("VERIFIED.\n");
1952
	}
1953

1954 1955 1956 1957
out:
	free(oldcontents);
	free(newcontents);
out_nofree:
1958
	programmer_shutdown();
Stefan Reinauer's avatar
Stefan Reinauer committed
1959
	return ret;
Ronald G. Minnich's avatar
Dammit  
Ronald G. Minnich committed
1960
}